package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
zenoh-cli
zenoh-cliA command line tool for interacting with a Zenoh sessionTypical use cases include:TestsInvestigationsProbingAs part of a bash pipelinezenoh-climakes use ofcodecsfor encoding and decoding to and from the wire payloads on the zenoh network bus. By default,zenoh-clibundles the following codecs:textbase64JSONA plugin system is in place to allow for easily extending the available codecs inzenoh-cli, see below.Installationpip install zenoh-cliUsageusage: zenoh [-h] [--mode {peer,client}] [--connect CONNECT] [--listen LISTEN] [--config CONFIG] [--log-level LOG_LEVEL] {info,network,scout,delete,put,subscribe,get} ... Zenoh command-line client application positional arguments: {info,network,scout,delete,put,subscribe,get} options: -h, --help show this help message and exit --mode {peer,client} --connect CONNECT Endpoints to connect to. (default: None) --listen LISTEN Endpoints to listen on. (default: None) --config CONFIG A path to a configuration file. (default: None) --log-level LOG_LEVELExample output ofzenoh networkExtending with codecs for encoding/decoding valueszenoh-clicomes with a plugin system for easily extending it with custom encoders and decoders (codecs) for the data values. The plugin system makes use of the entrypoints provided by setuptools, seeherefor details.zenoh-cligather plugins from two custom "groups":zenoh-cli.codecs.encoderszenoh-cli.codecs.decodersFor an example, seeexample_plugin
zenoh-ros-type
zenoh-ros-type-pythonThe repository contains common class for ROS 2 messages used by Zenoh.The messages come from:common_interface: Common-used ROS messagercl_interface: Common interface in RCLautoware_auto_msgs: messages used in Autowaretier4_autoware_msgs: messages used in AutowareUsageYou can download the packages viaPyPI.python3-mpipinstallzenoh-ros-type
zenomatic
Shows the Zen of Python in your ApplicationsAuthor:Chris MaillefaudVersion:1.0.0Python Version:2.7, 3.5 and 3.6Date:October, 16, 2017Install and UseInstall with pip:pip install zenomaticUseRun from command line:Options:‘random’: show a random quote‘seed <number>’: show numbererd quote‘all’: show all quotesExample:zenomatic randomRun inside application:from zenomatic import get_quote()ret, quote = get_quote(1)if ret:print(quote)Avaliable commandsget_quote(number)Get specific quote from 0 to 18get_quotes()Get all quotes
zenoml
Zeno is a general-purpose framework for evaluating machine learning models. It combines aPython APIwith aninteractive UIto allow users to discover, explore, and analyze the performance of their models across diverse use cases. Zeno can be used for any data type or task withmodular viewsfor everything from object detection to audio transcription.DemosImage ClassificationAudio TranscriptionImage GenerationDataset ChatbotSensor ClassificationImagenetteSpeech Accent ArchiveDiffusionDBLangChain + NotionMotionSensecodecodecodecodecodehttps://user-images.githubusercontent.com/4563691/220689691-1ad7c184-02db-4615-b5ac-f52b8d5b8ea3.mp4QuickstartInstall the Zeno Python package from PyPI:pipinstallzenomlCommand LineTo get started, run the following command to initialize a Zeno project. It will walk you through creating thezeno.tomlconfiguration file:zenoinitTake a look at theconfiguration documentationfor additionaltomlfile options like adding model functions.Start Zeno withzeno zeno.toml.Jupyter NotebookYou can also run Zeno directly from Jupyter notebooks or lab. Thezenocommand takes a dictionary of configuration options as input. Seethe docsfor a full list of options. In this example we pass the minimum options for exploring a non-tabular dataset:importpandasaspdfromzenoimportzenodf=pd.read_csv("/path/to/metadata/file.csv")zeno({"metadata":df,# Pandas DataFrame with a row for each instance"view":"audio-transcription",# The type of view for this data/task"data_path":"/path/to/raw/data/",# The folder with raw data (images, audio, etc.)"data_column":"id"# The column in the metadata file that contains the relative paths of files in data_path})You can pass a list of decorated function references directly Zeno as you add models and metrics.CitationPlease reference ourCHI'23 paper@inproceedings{cabrera23zeno,author={Cabrera, Ángel Alexander and Fu, Erica and Bertucci, Donald and Holstein, Kenneth and Talwalkar, Ameet and Hong, Jason I. and Perer, Adam},title={Zeno: An Interactive Framework for Behavioral Evaluation of Machine Learning},year={2023},isbn={978-1-4503-9421-5/23/04},publisher={Association for Computing Machinery},address={New York, NY, USA},url={https://doi.org/10.1145/3544548.3581268},doi={10.1145/3544548.3581268},booktitle={CHI Conference on Human Factors in Computing Systems},location={Hamburg, Germany},series={CHI '23}}CommunityChat with us on ourDiscord channelor leave an issue on this repository if you run into any issues or have a request!
zenoml-audio-transcription
Zeno View for Audio TranscriptionDevelopmentFirst, build the frontend:cdfrontend npminstall npmrunbuildInstallInstall the package from PyPI:pip install zenoml_audio_transcriptionAnd pass as thetaskargument to a Zeno.tomlfile.Follow the documentation to get started
zenoml-image-classification
Zeno View for Image ClassificationInstallInstall the package from PyPI:pip install zenoml_image_classificationAnd pass as thetaskargument to a Zeno.tomlfile.Follow the documentation to get started
zenoml-image-segmentation
Zeno View for Image SegmentationDevelopmentFirst, build the frontend:cdfrontend npminstall npmrunbuildInstallInstall the package from PyPI:pip install zenoml_image_segmentationAnd pass as thetaskargument to a Zeno.tomlfile.Follow the documentation to get started
zenoml-text-classification
Zeno View for Text ClassificationDevelopmentFirst, build the frontend:cdfrontend npminstall npmrunbuildInstallInstall the package from PyPI:pip install zenoml_text_classificationAnd pass as thetaskargument to a Zeno.tomlfile.Follow the documentation to get started
zenon
No description available on PyPI.
zenopy
CI/CDCode Coverage and QualityTechnical SupportFoundationzenopyAn open-source Python library for Zenodo REST APIOVERVIEWzenopy provides a comprehensive Python library for productivity allowing scientists and engineers to publish their work on Zenodo in compliance with FAIR principles.INSTALLATIONThe installation procedure can be as easy as running the following command in a terminalpipinstallzenopy
zeno-sliceline
Sliceline is a Python library for fast slice finding for Machine Learning model debugging.It is an implementation ofSliceLine: Fast, Linear-Algebra-based Slice Finding for ML Model Debugging, from Svetlana Sagadeeva and Matthias Boehm of Graz University of Technology.👉 Getting startedGiven an input datasetXand a model error vectorerrors, SliceLine finds the top slices inXthat identify where a ML model performs significantly worse.You can use sliceline as follows:fromsliceline.slicefinderimportSlicefinderslice_finder=Slicefinder()slice_finder.fit(X,errors)print(slice_finder.top_slices_)X_trans=slice_finder.transform(X)We invite you to check thedemo notebooksfor a more thorough tutorial:Implementing Sliceline on Titanic datasetImplementing Sliceline on California housing dataset🛠 InstallationSliceline is intended to work withPython 3.7 or above. Installation can be done withpip:pipinstallslicelineThere arewheels availablefor Linux, MacOS, and Windows, which means that you most probably won’t have to build Sliceline from source.You can install the latest development version from GitHub as so:pipinstallgit+https://github.com/DataDome/sliceline--upgradeOr, through SSH:pipinstallgit+ssh://[email protected]/datadome/sliceline.git--upgrade🔗 Useful linksDocumentationPackage releasesSliceLine paper👐 ContributingFeel free to contribute in any way you like, we’re always open to new ideas and approaches.Open a discussionif you have any question or enquiry whatsoever. It’s more useful to ask your question in public rather than sending us a private email. It’s also encouraged to open a discussion before contributing, so that everyone is aligned and unnecessary work is avoided.Feel welcome toopen an issueif you think you’ve spotted a bug or a performance issue.Please check out thecontribution guidelinesif you want to bring modifications to the code base.📝 LicenseSliceline is free and open-source software licensed under the3-clause BSD license.
zenoss
UNKNOWN
zenoss-fork
UNKNOWN
zenoss-hipchat
Command suitable in use for Zenoss notification commands for sending events to hipchat.InstallationSimply install using your preferred python package manager with either:pip installzenoss-hipchatfor the latest release, orpip install-egit+https://github.com/carsongee/zenoss-hipchat#egg=zenoss-hipchatfor the latest development version.ConfigurationIn Zenoss go toEvents->Triggersand create a trigger with the rules for which you want to send events to hipchat. Of course you can use an existing trigger as well. For more detailed guide on triggers and notifications see thecommunity documentation.After you have a trigger you wish to use, go tonotificationsand create a new notification. Set theIdto something memorable likeHipChatErrorsor similar and chooseCommandas the action.After creating the notification, edit it. On theNotificationtab configure it as you see fit, but you are generally going to want to make sure it is enabled, and that you have added the Trigger you created earlier. The command does support clear messages, so go ahead and check that option if you like.Now on theContenttab of the notification paste the following into theCommandfield:zenoss-hipchat--device="${evt/device}"--info=${evt/summary}--component="${evt/component}"--severity=${evt/severity}--url="${urls/eventUrl}"--message=${evt/message}And if you want to use the clear option, for the clear command:zenoss-hipchat--device="${evt/device}"--info=${evt/summary}--component="${evt/component}"--severity=${evt/severity}--url="${urls/eventUrl}"--message=${evt/message}--cleared-by="${evt/clearid}"--clearYou also need to provide the room and API token using theEnvironment variablesfield with something like:HIPCHAT_TOKEN=<APIv1Token>;HIPCHAT_ROOM=<RoomName(orID)topostto>replacing the values with ones appropriate for you.Additional Environment VariablesIn addition toHIPCHAT_TOKENandHIPCHAT_ROOMwhich are required, you can also override other options with the following optional environment variables:HIPCHAT_API_V1_ENDPOINT- Allows you to override the API endpoint if you are using private HipChatHIPCHAT_FROM- Defaults to Zenoss, and determines who the messages appear to be coming from.HIPCHAT_TIMEOUT- Defaults to 3 seconds, but if you have a slow connection to the HipChat server it can be increased or decreased.HIPCHAT_NOTIFY_SEVERITY- Defaults to Error and above (4), but can raised or lowered and determines which events trigger the HipChat notification.
zenoss-snmp-module
This project provides a Net-SNMP pass_persist script for monitoring Zenoss. If you aren’t familiar with Net-SNMP’s pass_persist option, it allows an external script to provide responses for all GET and GETNEXT requires under a configured base OID.Currently zenoss-snmp-module provides support for the provided ZENOSS-PROCESS- MIB. See the following snmptranslate command for what the MIB provides:$ snmptranslate -Tp ZENOSS-PROCESS-MIB::zenossProcessMIB +--zenossProcessMIB(3) | +--zenSystemTable(1) | | | +--zenSystemEntry(1) | | Index: zenSystemName | | | +-- -R-- String zenSystemName(1) | Textual Convention: DisplayString | Size: 0..255 | +--zenProcessTable(2) | | | +--zenProcessEntry(1) | | Index: zenSystemName, zenProcessName | | | +-- -R-- String zenProcessName(1) | Textual Convention: DisplayString | Size: 0..255 | +--zenProcessMetricTable(3) | +--zenProcessMetricEntry(1) | Index: zenSystemName, zenProcessName, zenProcessMetricName | +-- -R-- String zenProcessMetricName(1) | Textual Convention: DisplayString | Size: 0..255 +-- -R-- String zenProcessMetricValue(2) | Textual Convention: DisplayString | Size: 0..255 +-- -R-- String zenProcessMetricCyclesSinceUpdate(3) Textual Convention: DisplayString Size: 0..255 $ snmpwalk -v2c -c public localhost ZENOSS-PROCESS-MIB::zenossProcessMIB ZENOSS-PROCESS-MIB::zenSystemName."localhost" = STRING: localhost ZENOSS-PROCESS-MIB::zenProcessName."localhost"."zenhub" = STRING: zenhub ZENOSS-PROCESS-MIB::zenProcessName."localhost"."zenwebtx" = STRING: zenwebtx ZENOSS-PROCESS-MIB::zenProcessName."localhost"."zencommand" = STRING: zencommand ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenhub"."services" = STRING: services ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenhub"."totalTime" = STRING: totalTime ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenhub"."totalEvents" = STRING: totalEvents ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenhub"."invalidations" = STRING: invalidations ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenhub"."totalCallTime" = STRING: totalCallTime ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenhub"."workListLength" = STRING: workListLength ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenwebtx"."devices" = STRING: devices ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenwebtx"."dataPoints" = STRING: dataPoints ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenwebtx"."eventCount" = STRING: eventCount ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenwebtx"."cyclePoints" = STRING: cyclePoints ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenwebtx"."queuedTasks" = STRING: queuedTasks ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenwebtx"."runningTasks" = STRING: runningTasks ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zenwebtx"."eventQueueLength" = STRING: eventQueueLength ZENOSS-PROCESS-MIB::zenProcessMetricName."localhost"."zencommand"."eventQueueLength" = STRING: eventQueueLength ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."devices" = STRING: 0.0 ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."dataPoints" = STRING: 0.0 ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."eventCount" = STRING: 0.0 ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."cyclePoints" = STRING: 0.0 ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."queuedTasks" = STRING: 0.0 ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."runningTasks" = STRING: 0.0 ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."eventQueueLength" = STRING: 0.0 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenhub"."services" = STRING: 2.35 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenhub"."totalTime" = STRING: 2.35 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenhub"."totalEvents" = STRING: 2.35 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenhub"."invalidations" = STRING: 2.35 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenhub"."totalCallTime" = STRING: 2.35 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenhub"."workListLength" = STRING: 2.35 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenwebtx"."devices" = STRING: 0.48 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenwebtx"."dataPoints" = STRING: 0.48 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenwebtx"."eventCount" = STRING: 0.48 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenwebtx"."cyclePoints" = STRING: 0.48 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenwebtx"."queuedTasks" = STRING: 0.48 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenwebtx"."runningTasks" = STRING: 0.48 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zenwebtx"."eventQueueLength" = STRING: 0.45 ZENOSS-PROCESS-MIB::zenProcessMetricCyclesSinceUpdate."localhost"."zencommand"."eventQueueLength" = STRING: 0.12UsageTo install zenoss-snmp-module you must run the following command:sudo easy_install -U zenoss-snmp-moduleOnce installed, thezenoss-snmp-modulescript provides built-in support for helping you configure it. See the following command examples for installing the associated MIB and configuring snmpd:# Install ZENOSS-PROCESS-MIB. zenoss-snmp-module --mib | sudo tee /usr/share/snmp/mibs/ZENOSS-PROCESS-MIB.txt # Add pass_persist line to snmpd.conf. zenoss-snmp-module --snmpd | sudo tee -a /etc/snmp/snmpd.conf # Restart snmpd service. sudo service snmpd restartAfter changing snmpd.conf you must restart the snmpd service. Then you should be able to test with the following command:# Walk the entire zenossProcessMIB. snmpwalk -mALL -v2c -c public localhost zenossProcessMIBTry snmpwalk commands like the following to get more specific results:# Only show metric values for the zenwebtx proces on the localhost collector. snmpwalk -mALL -v2c -c public localhost 'zenProcessMetricValue."localhost"."zenwebtx"' # Show how many cycles it's been since each metric was updated. snmpwalk -mALL -v2c -c public localhost 'zenProcessMetricCyclesSinceUpdate."localhost"'You will need to know the OIDs for these values to poll them with Zenoss. Use a command like the following to discover the OID for a given value. Note that because these OIDs are just encoded system, process and metric names, they will return the expected data from any system and can be considered permanent:# Translate from name to OID. snmptranslate -On 'ZENOSS-PROCESS-MIB::zenProcessMetricValue."localhost"."zenwebtx"."queuedTasks"'TroubleshootingNormally zenoss-snmp-module is run from within snmpd. This makes it difficult to troubleshoot problems. To test the script outside of snmpd, you can runzenoss-snmp-moduleas root. If things are working properly, this will appear to do nothing.See the following session as an example:# zenoss-snmp-module PING PONG DUMP {'1.1.1.9.108.111.99.97.108.104.111.115.116': {'type': 'STRING', 'value': 'localhost'}, ... snipped ...It can also be useful to stop the snmpd service and run it in the foreground with just the useful debugging enabled:sudo service snmpd stop sudo snmpd -fV -Lo -Ducd-snmp/pass_persist -DoutputBe sure to start the snmpd service once you’re done testing.
zenoss.toolbox
zenoss.toolboxCurrent version: 0.5.2Utilities for analyzing/debugging Zenoss environments as well as tools to increase/maintain performance.How do I Install and Use the zenoss.toolbox Package?https://support.zenoss.com/hc/en-us/articles/203117595Tools IncludedzodbscanHow do I use zodbscan to Scan zodb for Dangling References?https://support.zenoss.com/hc/en-us/articles/203118175findposkeyerrorHow do I use findposkeyerror to detect and fix POSKeyErrors in zodb?https://support.zenoss.com/hc/en-us/articles/203117795zenrelationscanHow do I use zenrelationscan to scan/fix ZenRelationshttps://support.zenoss.com/hc/en-us/articles/203121165zencatalogscanHow do I use zencatalogscan to detect and fix unresolvable object references in catalogs?https://support.zenoss.com/hc/en-us/articles/203118075zenindextoolHow to use zenindextool to reindex top-level organizershttps://support.zenoss.com/hc/en-us/articles/203263689zennetworkcleanHow to use zennetworkclean to remove unused network informationhttps://support.zenoss.com/hc/en-us/articles/203263699Author: Brian Bibeault ([email protected])Changelog0.5.2Fixed ZEN-16133: First draft for the ZenDesk zennetworkclean documentFixed ZEN-16126: First draft for the ZenDesk zenindextool documentFixed ZEN-16108: Changes to the ZenDesk findposkeyerror documentFixed ZEN-16106: Changes to the ZenDesk zencatalogscan documentFixed ZEN-16104: Changes to the ZenDesk zodbscan documentFixed ZEN-16103: Changes to the ZenDesk toolbox overview documentFixed ZEN-16102: Changes to the ZenDesk zenrelationscan documentFixed ZEN-16092: Add copyright notice to all toolbox toolsFixed ZEN-16040: zennetworkclean has output message that refers to zencatalogscanFixed ZEN-16039: zenindextool changes to call dmd._p_jar.sync()Fixed ZEN-16017: zencatalogscan has incorrect template catalog referenceFixed ZEN-15225: Add new catalogs to zencatalogscanFixed ZEN-15082: zencatalogscan has incorrect mibsearch catalogFixed ZEN-14953: Not all zenoss toolbox scripts use the zenoss user’s pythonFixed ZEN-14744: All tools need updated documentation links for the new ZenDesk0.5.1Fixed ZEN-13192: add tool to clean/remove old unused ip addresses/iprealmss0.5.0Fixed ZEN-14586: Create zenindextool (break apart reIndex functionality from zencatalogscan)Fixed ZEN-14454: zenrelationscan won’t execute like other toolbox tools0.4.0Adding in an early alpha of zenrelationscan to the zenoss toolbox (for testing purposes)0.3.2Fixed ZEN-14078: findposkeyerror fails on fixable (no dmd reference)0.3.1Fixed ZEN-13951: zencatalogscan not properly scanning jobs catalogFixed ZEN-13952: findposkeyerror failing against zenoss core0.3.0Fixed ZEN-13191: zencatalogscan - add eventClassSearch, rrdtemplatesearch, mibsearch catalogsFixed ZEN-13429: zencatalogscan zenoss.toolbox get_lock logging incorrectFixed ZEN-13433: zencatalogscan customer feedback needs integratedFixed ZEN-13524: zencatalogscan progress bars should show last updated timestampFixed ZEN-13592: zencatalogscan logs missing catalogs as ERROR, not INFOFixed ZEN-13596: zencatalogscan needs to use rotating log filesFixed ZEN-13597: findposkeyerror needs to use rotating log filesFixed ZEN-13598: zodbscan needs to use rotating log filesFixed ZEN-13599: findposkeyerror progress bars should show last updated timestampFixed ZEN-13600: zodbscan progress bars should show last updated timestampFixed ZEN-13636: zencatalogscan needs option for doing just reindexFixed ZEN-13666: zodbscan zenoss.toolbox get_lock logging incorrectFixed ZEN-13667: findposkeyerror zenoss.toolbox get_lock logging incorrectFixed ZEN-13757: findposkeyerror reports 3 getDatabase tracebacksFixed ZEN-13925: zodbscan should log command line parameters to log fileFixed ZEN-13924: findposkeyerror should log command line parameters to log fileFixed ZEN-13923: zencatalogscan should log command line parameters to log file0.2.3Fixed ZEN-13425: findposkeyerror local variable ‘name’ referenced before assignmentFixed ZEN-12325: findposkeyerror memory growth continues unbounded until finish0.2.2Fixed ZEN-13194: zencatalogscan should output progress during device dmd reindexFixed ZEN-13106: findposkeyerror script is missing dmd contextFixed ZEN-12718: findposkeyerror.py UnboundLocalError referencing ‘e’Fixed ZEN-12683: findposkeyerror tracebacks on ZenPack.zenoss.AdvancedSearch on CoreFixed ZEN-12406: findposkeyerror must print full exceptions and log output to fileFixed ZEN-12328: findposkeyerror needs to mention log file, show absolute start timeFixed ZEN-12327: findposkeyerror missing return code (zero/one)Fixed ZEN-12326: findposkeyerror should check to see if tools already runningFixed ZEN-11587: findposkeyerror script needs to show progress as it runsFixed ZEN-10807: findposkeyerror ComponentSearchFixer() not included in _fixits()0.2.1Fixed ZEN-12671: zencatalogscan should locate log in $ZENHOME/log/toolboxFixed ZEN-12637: zodbscan - remove scanning of zodb_sessionFixed ZEN-12409: zodbscan should only recommend zenossdbpack if threshold exceededFixed ZEN-12405: zodbscan must print full exceptions and log output to fileFixed ZEN-12404: zodbscan should check to see if tools already runningFixed ZEN-12403: zodbscan needs to mention log file, show absolute start timeFixed ZEN-12402: zodbscan missing return code (zero/one)Fixed ZEN-12160: zodbscan fails on import of ZenStatus0.2.0Fixed ZEN-12049: zencatalogscan doesn’t process additional catalogsFixed ZEN-12167: zencatalogscan memory growth continues unbounded until finishFixed ZEN-12230: zencatalogscan missing return code (zero/one)Fixed ZEN-12265: zencatalogscan should check to see if tools already runningFixed ZEN-12165: zencatalogscan needs to show progress bar ASAP per catalogFixed ZEN-12183: zencatalogscan needs to mention log file, show absolute start timeUpdated README.rst to reference the published Zenoss KB articles for each tool0.1.9Fixed ZEN-10556: findposkeyerror has broken easy install entry scriptFixed ZEN-11700: zodbscan in zenoss.toolbox is downlevel (missing memory optimization)Fixed ZEN-11679: zencatalogscan needs an option to only scan a certain catalogFixed ZEN-10793: zencatalogscan reindex can fail for dmd.Devices.reIndex()Fixed ZEN-10579: zencatalogscan doesn’t reindex component catalogsFixed ZEN-10580: zencatalogscan must print full exceptions and log output to fileFixed ZEN-10567: zencatalogscan should cycle until it fixes all issues0.1.8Fixed ZEN-10555: zencatalogscan not fixing with –fix option0.1.7Added zencatalogscan - replaces cleancatalog and support’s fixCatalogs.py0.1.6Added findposkeyerror, which finds/fixes relationships having POSKeyErrors0.1.5Added cleancatalog, which cleans stale objects from the catalog0.1.0Added zodbscan, which detects and reports on POSKeyErrors
zenpad
InstallThe most easy way via pypi:pip install zenpador:easy_install zenpadOr you can install from sources:python setup.py build sudo python setup.py installOr run directly from sources without any install:./zenpad.pyAlso you need PyQt4 to be installed.UsageSimply run:zenpadLinkssite:http://zenpad.ru/repo:http://bitbucket.org/imbolc/zenpad/google group:http://groups.google.com/group/zenpadrussian docs:http://about.zenpad.ru/
zenpass
ZenpassTo generate random and strong passwords.Installationpip install -U zenpassUsageusage: zenpass [options] optional arguments: -h, --help show this help message and exit -v, --version show version number and exit. to customize Password: -l , --length to set length to the password -n , --ignore to ignore unwanted characters to the password -i , --include to include characters to the password -o , --only to create password only using wanted characters -s , --separator the separator character -c , --seplen the length of characters between separator --repeat to repeat the characters in the password (default : False) --separation to separate password characters using separator (default : False) --show to show password (default : False) keywords: [alphabets, uppercase, lowercase, numbers, symbols] can be given as input for following params: ignore, include, onlyPython ScriptTo generate a random password.from zenpass import PasswordGenerator pg = PasswordGenerator() pg.generate()Command LineTo generate a random password.$ zenpass Password copied to clipboard.To set the password length, Default password length is8-16.$ zenpass -l 10 --show Password: Q3m/vro|uR Password copied to clipboard.Whether the characters in passwords repeat or not, Default value ofrepeatisFalse.$ zenpass -r --show Password: 96Ndl;1D$jQu4Z2 Password copied to clipboard.To include, ignore or use only'alphabets','numbers','uppercase','lowercase','symbols'andrandom charactersin generating password.To ignorenumbersin passwords.$ zenpass -n numbers --show Password: uyMXP‘$!ZSCYqzj Password copied to clipboard.To ignore charactersa,b,c,d,e$ zenpass -n abcde --show Password: ~}t"R‘jF'ksG8~E Password copied to clipboard.To create a password only usingspecial characters.$ zenpass -o symbols -l 15 --show Password: ?)".=-_^[_‘~{.) Password copied to clipboard.To includea,b,c,d,echaracters in a password.$ zenpass -o numbers -i abcde -l 15 --show Password: 78713d1e3d926a3 Password copied to clipboard.To separate characters in a password using separator.$ zenpass -o uppercase --separation -l 16 --show Password: YNQC-RKBF-DMAT-UVIP Password copied to clipboard.To separate characters in a password using separator_with5characters between each separator.$ zenpass -o uppercase --separation -l 15 -s _ -c 5 --show Password: YNQCR_KBFDM_ATUVI Password copied to clipboard.Issues:If you encounter any problems, please file anissuealong with a detailed description.
zenpi
zenpiSimple Zenodo API Client Implementation
zen-publish
Link for project ishttps://github.com/Zen-Reportz/ZenPublishZen is command line package for Zen Reportz (https://zenreportz.com).There are three main method of package.createThis is used for storing credentials and url for zen reportupdateThis is used for updating credentials and url for zen reportpublish This is used for publishing report
zenpy
No description available on PyPI.
zen-py
No description available on PyPI.
zenpycbp
No description available on PyPI.
zenq
CLV packageFree software: MIT licenseInstallationTo install Zenq CLV Models Library, simply run the following command:pipinstallzenq-clv-modelsThe StoryIn order to provide marketing analysts and data scientists with a useful tool, the ZENQ package was developed. Because it is connected to a database, our product can be utilized by a wider variety of customers, including those who have a limited understanding of coding. Users are able to run scripts derived from the ZENQ package while the package works on data pertaining to customers. The data may be inserted into the database by users. It gives users the ability to study the behaviors of consumers based on how they engage with the company. Computations of CLV and RFM, in addition to forecasts, are the primary objective of the package. It features a Machine Learning component that makes an assumption as to whether the client will “die” or still be alive after a certain amount of time has passed. For the purpose of developing assumptions about the customers’ loyalness, ZENQ relies on the Pareto/NBD model. Because the package offers a number of different visualizations, it simplifies the process of comprehending the statistics and basing business decisions on those findings.Usage - Simple ExampleOnce installed, you can use the library in your Python scripts as follows:#run in terminal for postgres url creationdockerrun--namemy-postgres-db-ePOSTGRES_USER=master-ePOSTGRES_PASSWORD=pass-ePOSTGRES_DB=GLOBBING-p5432:5432-dpostgres# Initialize database with tablesfromzenq.api.prepare_dbimportdbm=db()m.main()# Insert data into databasefromzenq.api.endpointsimportinsert_factsinsert_facts('globbing.csv','Customer','Gender','InvoiceId','Date','Product_weight','Product_price')# Insert data of logging into LOGS tablefromzenq.api.endpointsimportupdate_logupdate_log()#define modelfromzenq.clvmodels.paretoimportModelmodel=Model()cltv=model.cltv_df()rfm=model.rfm_score()parameters=model.model_params()alive=model.customer_is_alive()#define Visualizationsfromzenq.visualizations.plotimportVisualsgender_price=visuals.gender_price()CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.
zen-quotes
zen_quotesA simple library that returns the Zen of Python quotes.Installationpip install zen_quotesUsage# import lib from zen_quotes.quote import Quotes# That will return you all quotes in English. Quotes().get_quotes()# Altogether there are 19 quotations, but if you need only one quotation, # then pass the quotation position number on the list. Quotes().get_quotes(quote=2) # this will return you the second quote on the list in English. Quotes().get_quotes(lang='pt', quote=2) # this will return you the second quote on the list in Portuguese.This lib searches the project data:https://github.com/ymussi/zen_of_pythonTODO[] add other languages
zenroom
Use Zenroom in Python3zenroom.py 🐍A Python3 wrapper ofZenroom, a secure and small virtual machine for crypto language processingThis library attempts to provide a very simple wrapper around the Zenroom (https://zenroom.dyne.org/) crypto virtual machine developed as part of the DECODE project (https://decodeproject.eu/), that aims to make the Zenroom virtual machine easier to call from normal Python code.Zenroom itself does have good cross platform functionality, so if you are interested in finding out more about the functionalities offered by Zenroom, then please visit the website linked to above to find out more.💾 InstallationpipinstallzenroomNOTE- the above command attempts to install the zenroom package, pulling in the Zenroom VM as a precompiled binary, so will only work on Linux and macOS machines.for the edge (syn to the latest commit on master) version please run:pipinstallzenroom--preThezenroompackage is just a wrapper around thezencode-executility. You also need to installzencode-exec, you can download if from the officialreleases on githubWhen after downloading you have to move it somewhere in your path:sudo cp zencode-exec /usr/local/bin/Warning: on Mac OS, the executable iszencode-exec.commandand you have to symlink it tozencode-execsudo cp zencode-exec.command /usr/local/bin/ cd /usr/local/bin sudo ln -s zencode-exec.command zencode-exec🎮 UsageTwo main calls are exposed, one to runzencodeand one forzenroom scripts.If you don't know whatzencodeis, you can start with this blogposthttps://decodeproject.eu/blog/smart-contracts-english-speakerThe official documentation is available onhttps://dev.zenroom.org/zencode/A good set of examples ofzencodecontracts could be found onzencode simple testszencode coconut tests🐍 Python wrapperthe wrapper exposes two simple calls:zenroom_execzencode_execas the names suggest are the two methods to execute zenroom (lua scripts) and zencode.argsBoth functions accept the same arguments:scriptstringthe lua script or the zencode script to be executedkeysstringthe optional keys string to pass in execution as documented in zenroom docsheredatastringthe optional data string to pass in execution as documented in zenroom docshereconfstringthe optional conf string to pass according to zen_configherereturnBoth functions return the same object resultZenResultthat have two attributes:stdoutstringholds the stdout of the script executionstderrstringholds the stderr of the script executionExamplesExample usage ofzencode_exec(script, keys=None, data=None, conf=None)fromzenroomimportzenroomcontract="""Scenario ecdh: Create a keypair"Given that I am known as 'identifier'When I create the keypairThen print my data"""result=zenroom.zencode_exec(contract)print(result.output)Example usage ofzenroom_exec(script, keys=None, data=None, conf=None)fromzenroomimportzenroomscript="print('Hello world')"result=zenroom.zenroom_exec(script)print(result.output)The same arguments and the same result are applied as thezencode_execcall.📋 TestingTests are made with pytests, just runpython setup.py testinzenroom_test.pyfile you'll find more usage examples of the wrapper🌐 Linkshttps://decodeproject.eu/https://zenroom.org/https://dev.zenroom.org/😍 AcknowledgementsCopyright (C) 2018-2022 byDyne.orgfoundation, AmsterdamOriginally designed and written by Sam Mulube.Designed, written and maintained by Puria Nafisi AziziRewritten by Danilo Spinella and David DashyanThis project is receiving funding from the European Union’s Horizon 2020 research and innovation programme under grant agreement nr. 732546 (DECODE).👥 ContributingPlease first take a look at theDyne.org - Contributor License Agreementthen🔀FORK ITCreate your feature branchgit checkout -b feature/branchCommit your changesgit commit -am 'Add some fooBar'Push to the branchgit push origin feature/branchCreate a new Pull Requestgh pr create -f🙏 Thank you💼 LicenseZenroom.py - a python wrapper of zenroom Copyright (c) 2018-2022 Dyne.org foundation, Amsterdam This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
zenroom-minimal
No description available on PyPI.
zenrows
ZenRows Python SDKSDK to accessZenRowsAPI directly from Python. ZenRows handles proxies rotation, headless browsers, and CAPTCHAs for you.InstallationInstall the SDK with pip.pipinstallzenrowsUsageStart using the API bycreating your API Key.The SDK usesrequestsfor HTTP requests. The client's response will be a requestsResponse.It also usesRetryto automatically retry failed requests (status codes 429, 500, 502, 503, and 504). Retries are not active by default; you need to specify the number of retries, as shown below. It already includes an exponential back-off retry delay between failed requests.fromzenrowsimportZenRowsClientclient=ZenRowsClient("YOUR-API-KEY",retries=1)url="https://www.zenrows.com/"response=client.get(url,params={# Our algorithm allows to automatically extract content from any website"autoparse":False,# CSS Selectors for data extraction (i.e. {"links":"a @href"} to get href attributes from links)"css_extractor":"",# Enable Javascript with a headless browser (5 credits)"js_render":False,# Use residential proxies (10 credits)"premium_proxy":False,# Make your request from a given country. Requires premium_proxy"proxy_country":"us",# Wait for a given CSS Selector to load in the DOM. Requires js_render"wait_for":".content",# Wait a fixed amount of time in milliseconds. Requires js_render"wait":2500,# Block specific resources from loading, check docs for the full list. Requires js_render"block_resources":"image,media,font",# Change the browser's window width and height. Requires js_render"window_width":1920,"window_height":1080,# Will automatically use either desktop or mobile user agents in the headers"device":"desktop",# Will return the status code returned by the website"original_status":False,},headers={"Referrer":"https://www.google.com","User-Agent":"MyCustomUserAgent",})print(response.text)You can also pass optionalparamsandheaders; the list above is a reference. For more info, check outthe documentation page.Sending headers to the target URL will overwrite our defaults. Be careful when doing it and contact us if there is any problem.POST RequestsThe SDK also offers POST requests by calling theclient.postmethod. It can receive a new parameterdatathat represents the data sent in, for example, a form.fromzenrowsimportZenRowsClientclient=ZenRowsClient("YOUR-API-KEY",retries=1)url="https://httpbin.org/anything"response=client.post(url,data={"key1":"value1","key2":"value2",})print(response.text)ConcurrencyTo limit the concurrency, it usesasyncio, which will simultaneously send a maximum of requests. The concurrency is determined by the plan you are in, so take a look at thepricingand set it accordingly. Take into account that each client instance will have its own limit, meaning that two different scripts will not share it, and 429 (Too Many Requests) errors might arise.The main difference with the sequential snippet above isclient.get_asyncinstead ofclient.get. The rest will work exactly the same, and we will support thegetfunction. But the async is necessary to parallelize calls and allow async/await syntax. Remember to run the scripts withasyncio.runor it will fail with acoroutine 'main' was never awaitederror.We useasyncio.gatherin the example below. It will wait for all the calls to finish, and the results are stored in aresponsesarray. The whole list of URLs will run, even if some fail. Then each response will have the status, request, response content, and other values as usual.fromzenrowsimportZenRowsClientimportasyncioclient=ZenRowsClient("YOUR-API-KEY",concurrency=5,retries=1)asyncdefmain():urls=["https://www.zenrows.com/",# ...]responses=awaitasyncio.gather(*[client.get_async(url)forurlinurls])forresponseinresponses:print(response.text)asyncio.run(main())ContributingPull requests are welcome. For significant changes, please open an issue first to discuss what you would like to change.LicenseMIT
zen-screw
Screw shape builder for ZenCAD
zen-screw-bolt
Screw bolt builder for ZenCAD
zen_scripts
This is a security placeholder package. If you want to claim this name for legitimate purposes, please contact us [email protected]@yandex-team.ru
zense
zenseEfficient Data Storage and Seamless Manipulation
zensectfpy
simple-vuln-py-libPython library that contains a snarky storage secret.Installationpip install --upgrade zensectfpyPublic-facing functionalityfromzensectfpy.rickrollimportprint_rickroll# Importing the `print_rickroll` functionnum_iterations:int=10# Number of times the Rickroll lyrics are to be printedprint_rickroll(num_iterations)# Calling the functionZense CTF ChallengeThere is some private functionality hidden in this repo. Access it, and you shall find the flag!
zensend
#
zenserp
Zenserp Python ClientZenserp Python Client is the official Python Wrapper around the zenserpAPI.InstallationInstall from pip:pipinstallzenserpInstall from code:pipinstallgit+https://github.com/zenserp/zenserp-python.gitUsageAll zenserp API requests are made using theClientclass. This class must be initialized with your API access key string.Where is my API access key?In your Python application, importzenserpand pass authentication information to initialize it:importzenserpclient=zenserp.Client('API_KEY')Retrieve Statusstatus=client.status()print(status['remaining_requests'])Retrieve SERPsparams=(('q','Pied Piper'),('location','United States'),('search_engine','google.com'),)result=client.search(params)print(result)Contact usAny feedback? Please feel free tocontact our team.
zen_sj_nester
UNKNOWN
zensols.actioncli
Action and Mnemonic command line libraryThis library intends to make command line execution and configuration easy. The library supports (among other features) an mnemonic centric way to tie a command line anactionto a Python 3 handler code segment. Features include:Better command line parsing thanoptparse. This a binding to from a command line option using an action mnemonic to invocation of a handler.Better application level support for configuration thanconfigparser. Specifically, optional configuration and configuration groups.ObtainingThe easiest way to obtain this package is viapip:pipinstallzensols.actioncliBinaries are also available onpypi.UsageTwo ways to use this project follow. The easiest way is to use the template method. Either way, first install the library viapiporeasyinstall.TemplateThe best way to get started is to template out this project with the following commands:# clone the boilerplate repogitclonehttps://github.com/plandes/template# download the boilerplate toolwgethttps://github.com/plandes/clj-mkproj/releases/download/v0.0.7/mkproj.jar# create a python template and build it outjava-jarmkproj.jarconfig-stemplate/python java-jarmkproj.jarStraight PythonIf you want to skip templating it out (i.e. don't like Java), create a command line module:fromzensols.actioncliimportOneConfPerActionOptionsClifromzensols.actioncliimportSimpleActionClifromzensols.toolsimportHelloWorldVERSION='0.1'classConfAppCommandLine(OneConfPerActionOptionsCli):def__init__(self):cnf={'executors':[{'name':'hello','executor':lambdaparams:HelloWorld(**params),'actions':[{'name':'doit','meth':'print_message','opts':[['-m','--message',True,# require argument{'dest':'message','metavar':'STRING','help':'a message to print'}]]}]}],# uncomment to add a configparse (ini format) configuration file# 'config_option': {'name': 'config',# 'opt': ['-c', '--config', False,# {'dest': 'config', 'metavar': 'FILE',# 'help': 'configuration file'}]},'whine':1}super(ConfAppCommandLine,self).__init__(cnf,version=VERSION)defmain():cl=ConfAppCommandLine()cl.invoke()This uses theOneConfPerActionOptionsCliEnvclass, which provides a data driven way of configuring the action based command line. An extention of this class is theOneConfPerActionOptionsCliEnvclass, which imports environment variables and allows adding to the configuration via adding a resource like file (i.e.~/.<program name>rc) type file. See theSee thecommand line test casesfor more examples.ChangelogAn extensive changelog is availablehere.LicenseCopyright (c) 2018 Paul LandesPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zensols.amr
AMR annotation and feature generationProvides support for AMR annotations and feature generation.Features:Annotation in AMR metadata. For example, sentence types found in the Proxy report AMR corpus.AMR token alignment asspaCycomponents.A scoring API that includesSmatchandWLK, which extends a more generalNLP scoring module.AMR parsing (amrlib) and AMR co-reference (amr_coref).Command line and API utilities for AMR graph Penman graphs, debugging and files.Tools for training and evaluating AMR parse models.Documentationfull documentation.API referenceObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.amrBinaries are also available onpypi.Usagefrompenman.graphimportGraphfromzensols.nlpimportFeatureDocument,FeatureDocumentParserfromzensols.amrimportAmrDocument,AmrSentence,ApplicationFactorysent:str="""He was George Washington and first president of the United States.He was born On February 22, 1732.""".replace('\n',' ').strip()# get the AMR document parserdoc_parser:FeatureDocumentParser=ApplicationFactory.get_doc_parser()# the parser creates a NLP centric feature document as provided in the# zensols.nlp packagedoc:FeatureDocument=doc_parser(sent)# the AMR object graph data structure is provided in the feature documentamr_doc:AmrDocument=doc.amr# dump a human readable output of the AMR documentamr_doc.write()# get the first AMR sentence instanceamr_sent:AmrSentence=amr_doc.sents[0]print('sentence:')print(' ',amr_sent.text)print('tuples:')# show the Penman graph representationpgraph:Graph=amr_sent.graphprint(f'variables:{", ".join(pgraph.variables())}')fortinpgraph.triples:print(' ',t)print('edges:')foreinpgraph.edges():print(' ',e)Per the example, thet5.confandgsii.confconfiguration show how to include configuration needed per AMR model. These files can also be used directly with theamrcommand using the--configoption.However, the other resources in the example must be imported unless you redefine them yourself.LibraryWhen adding theamrspaCy pipeline component, thedoc._.amrattribute is set on theDocinstance. You can either configure spaCy yourself, or you can use the configuration files intest-resourcesas an example using thezensols.util configuration framework. The command line application provides an example how to do this, along with thetest case.Command LineThis library is written mostly to be used by other program, but the command line utilityamris also available to demonstrate its usage and to generate ARM graphs on the command line.To parse:$amrparse-ctest-resources/t5.conf'This is a test of the AMR command line utility.'# ::snt This is a test of the AMR command line utility.(t/test-01:ARG1(u/utility:mod(c/command-line):name(n/name:op1"AMR":toki1"6"):toki1"9"):domain(t2/this:toki1"0"):toki1"3")To generate graphs in PDF format:$amrplot-ctest-resources/t5.conf'This is a test of the AMR command line utility.'wrote:amr-graph/this-is-a-test-of-the-amr-comm.pdfPerformance (Smatch)This repo is configured to download and train on the AMR bio-medical corpus. The results of the scores using amrlib's default smatch score is:CorpusModelPrecisionRecallF-scorebioamrlib t50.56136470228215420.47990297694707240.5174473330001563bioamrlib t5 + bio0.67921877591121430.61643726696786330.6463069704295633AttributionThis project, or reference model code, uses:Python 3spaCyfor natural language parsing.zensols.nlparsefor natural language features.amrlibfor AMR parsing.amr_coreffor AMR co-referenceSmatch(Cai and Knight. 2013) andWLK(Opitz et. al. 2021) for scoring.CitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2021 - 2023 Paul Landes
zensols.amr-coref
amr_corefA python library / model for creating co-references between AMR graph nodes.InstallTo install:pipinstallzensols.amr_corefAboutamr_coref is a python library and trained model designed to do co-referencing betweenAbstract Meaning Representationgraphs.The project follows the general approach of theneuralcoref projectand it's excellentblog on the co-referencing. However, the model is trained to do direct co-reference resolution between graph nodes and does not depend on the sentences the graphs were created from.The trained model achieves the following scoresMUC : R=0.647 P=0.779 F₁=0.706 B³ : R=0.633 P=0.638 F₁=0.630 CEAF_m: R=0.515 P=0.744 F₁=0.609 CEAF_e: R=0.200 P=0.734 F₁=0.306 BLANC : R=0.524 P=0.799 F₁=0.542 CoNLL-2012 average score: 0.548Project Status!! The following papers have GitHub projects/code that are better scoring and may be a preferable solution.See the uploaded file in#1for a quick view of scores.VGAE as Cheap Supervision for AMR Coreference ResolutionEnd-to-end AMR Coreference ResolutionThis is a fork ofBrad Jascob'samr_corefrepository, and modified to address the multiprocessing issues on non-Debian style OSs. See#3for details on the issue.UsageTo turn multi-threading off, create theInterfaceinstance withuse_multithreading=False.Installation and usageThere is currently no pip installation. To use the library, simply clone the code and use it in place.The pre-trained model can be downloaded from the assets section inreleases.To use the model create adatadirectory and un-tar the model in it.The script40_Run_Inference.py, is an example of how to use the model.TrainingIf you'd like to train the model from scratch, you'll need a copy of theAMR corpus. To complete training, run the scripts in order.10_Build_Model_TData.py12_Build_Embeddings.py14_Build_Mention_Tokens.py30_Train_Model.py.You'll needamr_annotation_3.0andGloVe/glove.6B.50d.txtin yourdatadirectoryThe first few scripts will create the training data indata/tdataand the model training script will createdata/model. Training takes less than 4 hours.
zensols.amrspring
A Spring AMR service and clientA client and server that generates AMR graphs from natural language sentences. This repository has a Docker that compiles the [AMR SPRING parser] using the original settings of the authors.The Docker image was created because this parser has a very particular set of Python dependencies that do not compile under some platforms. Specificallytokenizers==0.7.0fails to compile from source on apipinstall because of a Rust (version) compiler misconfiguration.TheDocker imageprovides a very simple service written in [Flask] that uses the SPRING model for inferencing and returns the parsed AMRs.Features:Parse natural language sentence (batched) into AMRs.Results cached in memory or an SQLite database.Both a command line and Pythonic object oriented client API.InstallingFirst install the client:pip3installzensols.amrspringServerThere is a script to build a local server, but there is also a docker image.To build a local server:Clone this repo:git clone https://github.com/plandes/amrspringWorking directory:cd amrspringBuild out the server:src/bin/build-server.sh <python installation directory>Start it( cd server ; ./serverctl start )Test it( cd server ; ./serverctl test-server )Stop it( cd server ; ./serverctl top )DockerTo build the Docker image:Download the model(s) from the [AMR SPRING parser] repository.Build the image:cd docker ; make buildCheck for errors.Start the image:make upTest using a method fromusage.Of course, the server code can be run without docker by cloning the [AMR SPRING parser] repository and adding theserver code. See theDockerfilefor more information on how to do that.UsageThe package can be used from the command line or directly via a Python API.You can use a combination UNIX tools toPOSTdirectly to it:wget-q-O---post-data='{"sents": ["Obama was the 44th president."]}'\--header='Content-Type:application/json'\'http://localhost:8080/parse'|jq-r'.amrs."0"."graph"'# ::snt Obama was the 44th president.(z0/person:ord(z1/ordinal-entity:value44):ARG0-of(z2/have-org-role-91:ARG2(z3/president)):domain(z4/person:name(z5/name:op1"Obama")))It also offers a command line:$amrspring--levelwarnparse'Obama was the president.'sent:Obamawasthepresident. graph:# ::snt Obama was the president.(z0/person:ARG0-of(z1/have-org-role-91:ARG2(z2/president)):domain(z3/person:name(z4/name:op1"Obama")))The Python API is very straight forward as well:>>>fromzensols.amrspringimportAmrPrediction,ApplicationFactory>>>client=ApplicationFactory.get_client()>>>pred=tuple(client.parse(['Obama was the president.']))[0]2024-02-1919:41:03,659parsed1sentencesin3ms>>>print(pred.graph)# ::snt Obama was the president.(z0/person:ARG0-of(z1/have-org-role-91:ARG2(z2/president)):domain(z3/person:name(z4/name:op1"Obama")))DocumentationSee thefull documentation. TheAPI referenceis also available.ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2024 Paul Landes[AMR SPRING parser]: git clonehttps://github.com/SapienzaNLP/spring
zensols.bibstract
BibTeX Extract and PopulateThis utility extractsBibTeXreferences (a.k.amarkers) from a(La)TeXfile and copies entries from a source, which themaster BibTeX file. It also provides easy customization to massage the entries of the BibTeX files (seefeatures). The use case is exporting allBetterBibtexentries to a file on your file system, usually one that is updated as you add, remove and modify papers inZotero. While the use case was intended for use with Zoter and BetterBibtex, it will work on any BibTeX system.The program does the following:Parses some large master source BibTeX file.Parses a file or recursively all.tex,.sty, and.clsfiles recursively in a directory.Copies the matching entries from the master source BibTeX to standard out.The program makes the assumption that the BibTeX entry IDs are unique as the matches are very loose when parsing the (La)TeX file.FeaturesMany features relate to modifying older entries to accommodate newer systems (i.e.BibLATEX) or modifying newer entries to accommodate older systems (i.e.BibTex).Features:Replace or edit Unicode characters, which is useful when\usepackage[utf8]{inputenc}has no effect.Massage date strings.Remove certain entries that cause bibliography systems issues (useful forBibLATEX).Modify entries to normalizearXiventries.ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.bibstractBinaries are also available onpypi.UsageThis is a command line program written that has the following usage (also use--help):Print IDs in a master source file BibTeX file:bibstract showbib.Print cite references in a (La)TeX file:bibstract showtex <file|directory>Print IDs that will be exported from the BibTeX file:bibstract showexport <file|directory>Export the matching entries to standard out:bibstract export <file|directory>ConvertersA set ofconverterscan be specified in theconfiguration file, which modify each parsed BibTeX entry in succession. Currently there the following:date_year: Converts the year part of a date field to a year. This is useful when using Zotero's Better Biblatex extension that produces BibLatex formats, but you need BibTeX entries.copy: Copy or move one or more fields in the entry. This is useful when your bibliography style expects one key, but the output (i.e.BibLatex) outputs a different named field). Whendestructiveis set toTrue, this copy operation becomes a move.Converters can be set be set and configured in theconfiguration file. See thetest casesfor more examples.ConfigurationAconfiguration filemust be given, whose location is either given with a-ccommand line argument, or set in the environment variableBIBSTRACTRC.An exampleconfiguration fileis available, which has only one INI sectiondefaultwith optionmaster_bibwith the master BibTeX file.Example Configuration FileThe following example configuration file points to the a home directory file where you tell whereBetterBibtexto export. It then specifies to convert dates with years (deleting thedatefield after)when creating the output.In addition, it copies thejournaltitle(exported byBetterBibtex) tojournal, which is used by BibTeX. This converter, calledreplaceis configured thereplace_converterentry.[default]master_bib=${env:home}/.zotero-betterbib.bibconverters=date_year_destructive, replace[replace_converter]class_name=zensols.bibstract.CopyOrMoveConverterfields=dict: {'journaltitle': 'journal'}destructive=FalseDocumentationSee thefull documentation. TheAPI referenceis also available.ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseCopyright (c) 2020 - 2023 Paul LandesPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zensols.clojure
No description available on PyPI.
zensols.cnndmdb
CNN/DailyMail Dataset as SQLiteCreates a SQLite database if the CNN and DailyMail summarization dataset.DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.cnndmdbBinaries are also available onpypi.UsageFirst create the SQLite database file:cnndmdb loadand check to make sure the filedata/cnn.sqlite3was created. This takes a while since the entire corpus is first downloaded and then inserted into the SQLite file.Command LineThe SQLite database keys can be given:cnndmdbkeysThen the command line can also be used to print articles:cnndmdbshow-torg3b07f5102c69e3e609d73b2ccb0dc5549d4fbaf6The-t orgtells it to use the original corpus keys. This option also allows for selected SQLiterowidkeys or a Kth smallest article.APIThe corpus objects are accessible as mapped Python objects. For example:corpus:Corpus=ApplicationFactory.get_corpus()art:Article=next(iter(corpus.stash.values()))print(art.text)Data SourceThe data is sourced from aTensorflow dataset, which in turn uses theAbigail See GitHubrepository.@article{DBLP:journals/corr/SeeLM17,author={Abigail See andPeter J. Liu andChristopher D. Manning},title={Get To The Point: Summarization with Pointer-Generator Networks},journal={CoRR},volume={abs/1704.04368},year={2017},url={http://arxiv.org/abs/1704.04368},archivePrefix={arXiv},eprint={1704.04368},timestamp={Mon, 13 Aug 2018 16:46:08 +0200},biburl={https://dblp.org/rec/bib/journals/corr/SeeLM17},bibsource={dblp computer science bibliography, https://dblp.org}}@inproceedings{hermann2015teaching,title={Teaching machines to read and comprehend},author={Hermann, Karl Moritz and Kocisky, Tomas and Grefenstette, Edward and Espeholt, Lasse and Kay, Will and Suleyman, Mustafa and Blunsom, Phil},booktitle={Advances in neural information processing systems},pages={1693--1701},year={2015}}ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2023 Paul Landes
zensols.datdesc
Describe and optimize dataThis API and command line program describes data in tables with metadata and generate LaTeX tables in a.styfile from CSV files. The paths to the CSV files to create tables from and their metadata is given as a YAML configuration file. Paraemters are both files or both directories. When using directories, only files that match*-table.ymlare considered. In addition, the described data can be hyperparameter metadata, which can be optimized with thehyperparameter module.Features:Associate metadata with each column in a Pandas DataFrame.DataFrame metadata is used to format LaTeX data and exported to Excel as column header notes.Data and metadata is viewable in a nice format with paging in a web browser using theRender program.Usable as an API during data collection for research projects.DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.datdescBinaries are also available onpypi.UsageFirst create the table's configuration file. For example, to create a Latex.styfile from the CSV filetest-resources/section-id.csvusing the first column as the index (makes that column go away) using a variable size and placement, use:intercodertab:path:test-resources/section-id.csvcaption:>-Krippendorff’s ...size:VARplacement:VARsingle_column:trueuses:zentableread_kwargs:index_col:0write_kwargs:disable_numparse:truereplace_nan:''blank_columns:[0]bold_cells:[[0,0],[1,0],[2,0],[3,0]]Some of these fields include:placement: the placement (i.e.h!), whichVARmeans to create the command with a variable to use as the first parametersize: the font size (i.e.small), whichVARmeans to create the command with a variable to use as the second parameterindex_col: clears column 0 andbold_cells: make certain cells bolddisable_numparsetells thetabulatemodule not reformat numbersSee theTableclass for a full listing of options.HyperparametersHyperparameter metadata: access and documentation. This package was designed for the following purposes:Provide a basic scaffolding to update model hyperparameters such ashyperopt.Generate LaTeX tables of the hyperparamers and their descriptions for academic papers.Access to the hyperparameters via the API is done by calling thesetormodellevels with adotted path notationstring. For example,svm.Cfirst navigates to modelsvm, then to the hyperparameter namedC.A command line access to create LaTeX tables from the hyperparameter definitions is available with thehyperaction. An example of a hyperparameter set (a grouping of models that in turn have hyperparameters) follows:svm:doc:'supportvectormachine'params:kernel:type:choicechoices:[radial,linear]doc:'mapstheobservationsintosomefeaturespace'C:type:floatdoc:'regularizationparameter'max_iter:type:intdoc:'numberofiterations'value:20interval:[1,30]In the example, thesvmmodel has hyperparameterskernel,Candmax_iter. Thekerneltype is set as a choice, which is a string that has the constraints of matching a string in the list. TheChyperparameter is a floating point number, and themax_iteris an integer that must be between 1 and 30.In this next example, thek_meansmodel uses the stringk-meansin human readable documentation, which can be Python generated code in adataclass.k_means:desc:k-meansdoc:'k-meansclustering'params:n_clusters:type:intdoc:'numberofclusters'copy_x:type:boolvalue:Truedoc:'Whenpre-computingdistancesitismorenumericallyaccuratetocenterthedatafirst'strata:type:listdoc:'Anarrayofstratifiedhyperparameters(madeupfortestcases).'value:[1,2]kwargs:type:dictdoc:'Modelkeywordarguments(madeupfortestcases).'value:learning_rate:0.01epochs:3ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2023 Paul Landes
zensols.db
Database convenience utilities.A library of database convenience utilities, typically for creation of temporary files for processing large data.Features:DB-API Interface allows combined SQL rapid prototyping with backing programmatic usage.Java Beans like persistence.Integration withzensols.util stash.SQLiteintegration.PostgreSQLintegration with thedbutilpglibrary.Pandasdata frame creation, which is agnostic of database provider.DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easist way to install the command line program is via thepipinstaller:pip3installzensols.dbBinaries are also available onpypi.UsageA simple example is detailed below, and also found in therepo.SQL binding fileFirst, create the SQL file, which is used to create and access the database. Here we can replacename, agewith${cols}and call itperson.sql:-- meta=init_sections=create_tables,create_idx-- name=create_idxcreateindexperson_nameonperson(name);-- name=create_tablescreatetableperson(nametext,ageint);-- name=insert_personinsertintoperson(${cols})values(?,?);-- name=select_people; note that the order is needed for the unit tests onlyselect${cols},rowidasidfrompersonorderbyname;-- name=select_people_by_idselect${cols},rowidasidfrompersonwhereid=?;-- name=update_personupdatepersonsetname=?,age=?whererowid=?;-- name=delete_persondeletefrompersonwhererowid=?;PersisterNext, create the application context with a persister that is the SQL to client binding and call itapp.conf:# command line interaction[cli]class_name=zensols.cli.ActionCliManagerapps=list: app# the connection manager, which is the DB binding and in our case SQLite[sqlite_conn_manager]class_name=zensols.db.SqliteConnectionManagerdb_file=path: person.db# the persister binds the API to the SQL[person_persister]class_name=zensols.db.DataClassDbPersisterbean_class=class: app.Personsql_file=person.sqlconn_manager=instance: sqlite_conn_managerinsert_name=insert_personselect_name=select_peopleselect_by_id=select_people_by_idupdate_name=update_persondelete_name=delete_person# the application class invoked by the CLI[app]class_name=app.Applicationpersister=instance: person_persisterApplicationDefine thebean, which provides the metadata for the${cols}inperson.sqland can (but not must) be used with the API to CRUD rows:fromdataclassesimportdataclass,fieldfromzensols.dbimportBeanDbPersister@dataclassclassPerson(object):name:str=field()age:int=field()id:int=field(default=None)@dataclassclassApplication(object):"""A people database"""persister:BeanDbPersisterdefdemo(self):# create a row using an instance of a dataclass and return the unique# ID of the inserted rowpaul_id:int=self.persister.insert(Person('Paul',31))# we can also insert by columns in the order given in the dataclassjane_id:int=self.persister.insert_row('Jane',32)# print everyone in the databaseprint(self.persister.get())# delete a rowself.persister.delete(paul_id)print(self.persister.get())# update jane's ageself.persister.update_row(jane_id,'jane',36)# get the updated row we just setjane=self.persister.get_by_id(jane_id)print(f'jane:{jane}')# clean up, which for SQLite deletes the fileself.persister.conn_manager.drop()Create the entry point used on the command line and call itrun.py:fromzensols.cliimportCliHarnessCliHarness(app_config_resource='app.conf').run()Run$./run.py-h Usage:run.py[options]: Apeopledatabase. Options:-h,--helpshowthishelpmessageandexit--versionshowtheprogramversionandexit$./run.py(Person(name='Jane',age=32,id=2),Person(name='Paul',age=31,id=1))(Person(name='Jane',age=32,id=2),)jane:Person(name='jane',age=36,id=2)See theuse casesfor more detailed examples of how to use the API.ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2020 - 2023 Paul Landes
zensols.dbpg
A PostgreSQL implementation of the dbutil libraryAPostgreSQLimplementation of thedbutillibrary.DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easist way to install the command line program is via thepipinstaller:pip3installzensols.dbutilpgBinaries are also available onpypi.On macOS, usemake macosdep.ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2020 - 2023 Paul Landes
zensols.deeplearn
Deep Zensols Deep Learning FrameworkThis deep learning library was designed to provide consistent and reproducible results.See thefull documentation.See thepaperFeatures:Easy to configure and framework to allow for programmaticdebuggingof neural networks.Reproducibilityof resultsAllrandom seed stateis persisted in the trained model files.Persisting of keys and key order across train, validation and test sets.Analysis of results with complete metrics available.Avectorizationframework that allows for pickling tensors.Additionallayers:FullBiLSTM-CRFand stand-aloneCRFimplementation using easy to configure constituent layers.Easy to configureN[deep convolution layer] with automatic dimensionality calculation and configurable pooling and batch centering.Convolutional layer factorywith dimensionality calculation.Recurrent layersthat abstracts RNN, GRU and LSTM.Ndeeplinear layers.Each layer's configurable with activation, dropout and batch normalization.Pandasintegration todata load,easily managevectorized features, andreport results.Multi-process for time consuming CPU featurevectorizationrequiring little to no coding.Resource and tensor deallocation with memory management.Real-time performanceand loss metrics with plotting while training.Thoroughunit testcoverage.Debugginglayers using easy to configure Python logging module and control points.Much of the code provides convenience functionality toPyTorch. However, there is functionality that could be used for other deep learning APIs.DocumentationSee thefull documentation.ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.deeplearnBinaries are also available onpypi.WorkflowThis package provides a workflow for processing features, training and then testing a model. A high level outline of this process follows:Container objects are used to represent and access data as features.Instances ofdata pointswrap the container objects.Vectorize the features of each data point in to tensors.Store the vectorized tensor features to disk so they can be retrieved quickly and frequently.At train time, load the vectorized features in to memory and train.Test the model and store the results to disk.To jump right in, see theexamplessection. However, it is better to peruse the in depth explanation with theIris examplecode follows:The initialdata processing, which includes data representation to batch creation.Creating and configuring themodel.Using afacadeto train, validate and test the model.Analysis ofresults, including training/validation loss graphs and performance metrics.ExamplesTheIris example(also see theIris example configuration) is the most basic example of how to use this framework. This example is detailed in theworkflowdocumentation in detail.There are also examples in the form ofJuypternotebooks as well, which include the:Iris notebookdata set, which is a small data set of flower dimensions as a three label classification,MNIST notebookfor the handwritten digit data set,debugging notebook.AttributionThis project, or example code, uses:PyTorchas the underlying framework.Branched code fromTorch CRFfor theCRFclass.pycudafor Python integration withCUDA.scipyfor scientific utility.Pandasfor prediction output.matplotlibfor plotting loss curves.Corpora used include:Iris data setAdult data setMNIST data setTorch CRFTheCRFclass was taken and modified from Kemal Kurniawan'spytorch_crfGitHub repository. See theREADME.mdmodule documentation for more information. This module wasforked pytorch_crfwith modifications. However, the modifications were not merged and the project appears to be inactive.Important: This project will change to use it as a dependency pending merging of the changes needed by this project. Until then, it will remain as a separate class in this project, which is easier to maintain as the only class/code is theCRFclass.Thepytorch_crfrepository uses the same license as this repository, which theMIT License. For this reason, there are no software/package tainting issues.See AlsoThezensols deepnlpproject is a deep learning utility library for natural language processing that aids in feature engineering and embedding layers that builds on this project.CitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}ChangelogAn extensive changelog is availablehere.CommunityPlease star the project and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2020 - 2023 Paul Landes
zensols.deepnlp
DeepZensols Natural Language ProcessingDeep learning utility library for natural language processing that aids in feature engineering and embedding layers.See thefull documentation.See thepaperFeatures:Configurable layers with little to no need to write code.Natural language specific layers:Easily configurable word embedding layers forGlove,Word2Vec,fastText.Huggingface transformer (BERT) context based word vector layer.FullEmbedding+BiLSTM-CRFimplementation using easy to configure constituent layers.NLP specific vectorizersthat generatezensols deeplearnencoded and decodedbatched tensorsforspaCyparsed features, dependency tree features, overlapping text features and others.Easily swapable during runtime embedded layers asbatched tensorsand other linguistic vectorized features.Support for token, document and embedding level vectorized features.Transformer word piece to linguistic token mapping.Two full documented reference models provided as both command line andJupyter notebooks.Command line support for training, testing, debugging, and creating predictions.DocumentationFull documentationLayers: NLP specific layers such as embeddings and transformersVectorizers: specific vectorizers that digitize natural language text in to tensors ready asPyTorchinputAPI referenceReference ModelsObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.deepnlpBinaries are also available onpypi.UsageThe API can be used as is and manually configuring each component. However, this (like any Zensols API) was designed to instantiated with inverse of control usingresource libraries.ComponentComponents and out of the box models are available with little to no coding. However, thissimple examplethat uses the library's components is recommended for starters. The example is a command line application that in-lines a simple configuration needed to create deep learning NLP components.Similarly,this exampleis also a command line example, but uses a masked langauge model to fill in words.Reference ModelsIf you're in a rush, you can dive right in to theClickbate Text Classificationreference model, which is a working project that uses this library. However, you'll either end up reading up on thezensols deeplearnlibrary before or during the tutorial.The usage of this library is explained in terms of the reference models:TheClickbate Text Classificationis the best reference model to start with because the only code consists of is the corpus reader and a module to remove sentence segmentation (corpus are newline delimited headlines). It was also usesresource libraries, which greatly reduces complexity, where as the other reference models do not. Also see theJupyter clickbate classification notebook.TheMovie Review Sentimenttrained and tested on theStanford movie reviewandCornell sentiment polaritydata sets, which assigns a positive or negative score to a natural language movie review by critics. Also see theJupyter movie sentiment notebook.TheNamed Entity Recognizertrained and tested on theCoNLL 2003 data setto label named entities on natural language text. Also see theJupyter NER notebook.The unit test cases are also a good resource for the more detailed programming integration with various parts of the library.AttributionThis project, or reference model code, uses:GensimforGlove,Word2VecandfastTextword embeddings.Huggingface TransformersforBERTcontextual word embeddings.h5pyfor fast read access to word embedding vectors.zensols nlparsefor feature generation fromspaCyparsing.zensols deeplearnfor deep learning network libraries.Corpora used include:Stanford movie reviewCornell sentiment polarityCoNLL 2003 data setCitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2020 - 2023 Paul Landes
zensols.dltools
General deep learning toolsGeneral deep learing utility library. It contains a utilities I used in my own research that have some intersection with:Convolution layer dimensionality calculationPyTorchconvolution factoryUnrelated (to deep learning) plotting utilities.ObtainingThe easist way to install the command line program is via thepipinstaller:pip3installzensols.dltoolsBinaries are also available onpypi.ChangelogAn extensive changelog is availablehere.LicenseCopyright (c) 2019 Paul LandesPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zensols.dsprov
Provenience of discharge summaries Pythonic accessThis library provides integrated MIMIC-III with discharge summary provenance of data annotations and Pythonic classes.DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3install--use-deprecated=legacy-resolverzensols.dsprovBinaries are also available onpypi.UsageThe package includes a command line interface, which is probably most useful by dumping selected admission annotations.Command line# help$dsprov-h# get two admission IDs (hadm_id)$dsprovids-l2# print out two admissions$dsprovshow-l2# print out admissions 139676$dsprovshow-d139676# output the JSON of two admissions with indent 4$dsprovshow-i4-fjson-d$(dsprovids-l2|awk'{print $1}'|paste-s-d,-)APIThe package can be used directly in your research to provide Python object oriented access to the annotations:>>>fromzensols.nlpimportFeatureDocument>>>fromzensols.dsprovimportApplicationFactory,AdmissionMatch>>>stash=ApplicationFactory.get_stash()>>>am:AdmissionMatch=next(iter(stash.values()))>>>doc:FeatureDocument=am.note_matches[0].discharge_summary.note.doc>>>print(f'hadm:{am.hadm_id}')>>>print(f'sentences:{len(doc.sents)}')>>>print(f'tokens:{doc.token_len}')>>>print(f'entities:{doc.entities}')hadm:120334sentences:46tokens:1039entities:(<Admission>,<Date>,<Discharge>,<Date>,<DateofBirth>,<Sex>,...)ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2023 Paul Landes
zensols.garmdown
Download Garmin Connect DataThis software downloads TCX files and accompanying activity metadata files from the Garmin Connect website. Since Garmin has discontinued its API to download your data this software was written to take its place. It is the opinion of the author that this data generated by the athlete should be accessible via an automated method and not constrained to a Web GUI interface.Features:Download Garmin activity data.Track data in anSQLitedatabase (avoid re-downloading).Sync duration statistics with GoogleSheets.Print basic information and statistics on previous activities.Convenient importing in your favorite analysis tool (i.e.GoldenCheetah).Table of ContentsObtainingData Life CycleHistoryUsageCommand LineChangelogLicenseObtainingThe easist way to install the command line program is via thepipinstaller:pipinstallzensols.garmdownBinaries are also available onpypi.Data Life CycleDownload activities. These are independent blocks of data that provide information used to later download the respective TCX file.Download the TCX file. The TCX file has all the information needed by workout analysis applications likeGoldenCheetah.Import TCX file. This step simply copies downloaded files to a directory that's easy to access by the workout analysis application.Ingest TCX files. Import all files in the import folder to your data workout analysis application. After this step you delete the folder as subsequent invocations of step 3 will regenerate it.Backup the activities database. In the rare case the binary database file (see below) might be corrupted, a backup is made everyNdays (whereNis specified in a configuration file).All state between all of these steps are recorded in an SQLite database, which is a binary file stored on the file system. If this doesn't make sense to you, it means that you shouldn't need to install anything special and itliveson your disk.HistoryThe activity download module was inspired byShannon's original project, which was used to navigate the convoluted Garmin client API.UsageThe easiest way to use the program is to use thesyncaction repeatedly until the program doesn't do anything, example:$garmdownsyncThis invokes alldata life cycle steps, meaning it imports activities in to the database, downloads the TCX files and creates a handy import directory (by default in your desktop directory~/Desktop/to-import).Command LineUsage:usage:garmdown<list|activity|backup|env|import|notdown|notimport|sheet|sync|tcx>[options]Options:--version show program's version number and exit-h,--help show this help message and exit-wNUMBER,--whine=NUMBERaddverbositytologging-cFILE,--config=FILEconfigurationfileActions:activityDownloadoutstandingactivites-l,--limit <int> the limitbackupBackup(force)theactivitesdatabaseenvPrintenvironment-d,--detail report details of missing dataimportImporttcxfile-l,--limit <int> the limitnotdownPrintactivitiesnotdownloaded-d,--detail report details of missing datanotimportPrintactivitiesnotimported-d,--detail report details of missing datasheetUpdategoogledocstrainingspreadsheetsyncDownloadalloutstandingdata-l,--limit <int> the limittcxDownloadoutstandingtcxfiles-l,--limit <int> the limitChangelogAn extensive changelog is availablehere.LicenseCopyright (c) 2019 Paul LandesPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zensols.grsync
GRSync: Persist create build out environmentsThis program captures your home directory and synchronize it with another host using Git repo metadata, symbolic links and persisted files.I wrote this because I couldn't find anything that creates repositories with the idea of having a portable and easy to recreate your home directory on another host. If I've reinvented the wheel, please let me know :)More specifically: it persists and creates build out environments in a nascent account. The programmemorizinga users home directory and building it out on another system (seeoverview). This is done by:Copying files, directories and git repos configuration.Creating a distribution compressed file.Uncompress on the destination system and create repos.A future release will also synchronize and manage multiple GitHub repositories.Autility scriptalso provided to do operations on all configured local git repositories.DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easist way to install the command line program is via thepipinstaller:pipinstallzensols.grsyncBinaries are also available onpypi.OverviewNot only is the aim to create a repproducable development (or like) environment, it is also to create acleanenvironment. This means we have temporary directories we might expect to exist for our process(es), and of course repositories cloned in their nascent state. These steps are summarized below:Freeze: This process captures the current host's setup and configuration (specified in theconfiguration file) and includes:Empty directories.Git repository meta data.Locations of files to copy, top level directories of files to recursively copy, where symlinks are considered files as well and currently not followed. Seecaveat.A sub-step of this process isdiscover, which reads the file system as indicated by the configuration file. This includes reading git repostiory metadata, identifying file metadata (i.e. permissions) etc.Bootstraping: create an Python virtual environment on the target machine that can be loaded with this program and depenedencies. This is not a necessary step as the program is available as apipinstall. However, if this step can be used to help automate new environments, after which, you could futher add/install software with tools such asPuppet.Thaw: This includes two steps:File Extraction: extracts the files from the distribution zip created in thefreezestep.Repo Cloning: this step recursively clones all repositories.UsageThe program has two phases:freezeandthaw(seeoverview). The command line program is used twice: first on thefreezeon the source system and thenthawon the target machine.Seeusagefor more information.ConfigurationThe configuration is used thefreezephase to create the distribution file. This fil contains all git repositories, files, empty directory paths on the current file system that is stored to bethawedon the target system.Seeconfigurationfor detailed documentation on configurationtest case yaml filefor an example of a simple configuration file to capture a set of git repositories and small set of files. The freeze/thaw/move test case usesthis configuration file, which is more comprehensive and up to date.Symbolic LinksAs mentioned in theusagesection, symbolic links pointing to any file in a repository arefroozen, which means that integrity at thaw time is ensured. However, linksnotpointing to a repository are persisted, but the files and directories they point to are not.A future release might have afollow symbolic linkstype functionality that allows this. However, for now, you must include both the link and the data it points to get this integrity.ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2020 - 2023 Paul Landes
zensols.hostcon
Simple program to connect to servers from a list.This is a simple program to load servers from a file, list them, then allow you to login, SSH mount, etc.Features provided by a terse command line syntax:Login using a terminal instance on the command line via SSH.Invoke an xterm on a configured host.Mount and unmount aSSH Fusedirectory.Invoke aEmacssession via SSH.Print environment in abashexportformat for scripting.Output a bourne shell script that does what the script would do for a particular environment (per-noption).Other commands are easily configurable incli.py.ObtainingThe easist way to install the command line program is via thepipinstaller:pipinstallzensols.hostconBinaries are also available onpypi.UsageFirst, create a configuration file. Examples used by the test cases are givenhere. Below is a simple example that declares an SSH hostjoveon the (default) port 22 withSSH Fusemount options convenient for a MacOS client.[default]host_name=jovessh_port=22ssh_switches=-X -Ymount_options=reconnect,sshfs_sync,no_readahead,sync_read,cache=no,noreadahead,noubc,noappledouble,noapplexattrSave this example to~/.hostconrcor anywhere else specified in environment variableHOSTCONRC. Now we can get include this as environment:$hostconenvexportDOMAIN=NoneexportHOST_NAME=joveexportSSH_PORT=22exportUSER_NAME=someuserStart an XTerm on the host:$hostcon invokingssh-X-Y-f-p22someuser@jove/usr/bin/xtermSee thetest casesfor more examples of how to configure andaliashost information.HelpThe usage is given with-h:$hostcon-hUsage:hostcon<list|...>[options]Options:--version show program's version number and exit-h,--help show this help message and exit-s,--short short output for list-wNUMBER,--whine=NUMBERaddverbositytologging-nHOST_NAME,--hostname=HOST_NAMEthehosttoconnectto-d,--dryrun dry run to not actually connect, but act like itChangelogAn extensive changelog is availablehere.LicenseCopyright © 2018 Paul LandesApache License version 2.0Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
zensols.install
Downloads and installs filesSimple light API to download and install files. If the file appears to be a compressed file by ending withzip,tar.gz,tgzetc, then also un-compress the file after it is downloaded. The process flow follows:Check to see if the installed file exists. If not download it.Otherwise, if the file has been downloaded uncompress it.If the file could not be downloaded, uncompressed, or a file from the uncompressed file isn't found an error is thrown.A destination location can be specified in the configuration. It is also possible to install it in the~/.cache/<package name>wherepackage nameis the name the installed package. For example, that would bezensols.installfor the package installed for this repository.DocumentationFull documentationAPI referenceObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.installBinaries are also available onpypi.UsageThe below code is given in theexample.First create the installer configuration with each file to be installed as a resource as a fileinstall.conf:[zip_resource]class_name=zensols.install.Resourceurl=https://github.com/plandes/zenbuild/archive/refs/tags/general_build.zip# we have to give the name of the diretory in the zip file so the program knows# what to unzip; otherwise it is named from the section, or file if `None`name=zenbuild-general_build# uncomment below to keep the `zenbuild-general_build.zip` zip file#clean_up = False[downloader]class_name=zensols.install.Downloader#use_progress_bar = False[installer]class_name=zensols.install.Installerdownloader=instance: downloader# uncomment the below line, then comment out `base_directory` to use the# package name (using the zensols.cli.ApplicationFactory--see example); using# `package_resource` will in install a ~/.<package name> install directorybase_directory=path: install_dir#package_resource = ${package:name}resources=instance: list: zip_resourceNow use the configuration to create the installer and call it:importloggingfromzensols.configimportIniConfig,ImportConfigFactoryfromzensols.installimportInstallerlogging.basicConfig(level=logging.INFO)fac=ImportConfigFactory(IniConfig('install.conf'))installer:Installer=fac.instance('installer')installer.install()This code creates a new directory with the un-zipped files ininstall_dir:INFO:zensols.install.installer:installing zenbuild-general_build to install_dir/zenbuild-general_build INFO:zensols.install.download:creating directory: install_dir INFO:zensols.install.download:downloading https://github.com/plandes/zenbuild/archive/refs/tags/general_build.zip to install_dir/zenbuild-general_build.zip general_build.zip: 16.4kB [00:00, 40.1kB/s] INFO:zensols.install.installer:uncompressing install_dir/zenbuild-general_build.zip to install_dir patool: Extracting install_dir/zenbuild-general_build.zip ... patool: ... install_dir/zenbuild-general_build.zip extracted to `install_dir'. INFO:zensols.install.installer:cleaning up downloaded file: install_dir/zenbuild-general_build.zipFirst the program checks to see if the target directory (nameproperty in thezip_resourcesection) exists. It then downloads it when it can't find either the target directory or the downloaded file.If the program is run a second time, there will be no output since the installed directory now exists.ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2021 - 2023 Paul Landes
zensols.medcat
Medicaloncept Annotation ToolMedCAT can be used to extract information from Electronic Health Records (EHRs) and link it to biomedical ontologies like SNOMED-CT and UMLS. Paper onarXiv.Official DocshereDiscussion ForumdiscourseNewsNew Downloader [15. March 2022]: You can nowdownloadthe latest SNOMED-CT and UMLS model packs via UMLS user authentication.New Feature and Tutorial [7. December 2021]:Exploring Electronic Health Records with MedCAT and Neo4jNew Minor Release [20. October 2021]Introducing model packs, new faster multiprocessing for large datasets (100M+ documents) and improved MetaCAT.New Release [1. August 2021]: Upgraded MedCAT to use spaCy v3, new scispaCy models have to be downloaded - all old CDBs (compatble with MedCAT v1) will work without any changes.New Feature and Tutorial [8. July 2021]:Integrating 🤗 Transformers with MedCAT for biomedical NER+LGeneral [1. April 2021]: MedCAT is upgraded to v1, unforunately this introduces breaking changes with older models (MedCAT v0.4), as well as potential problems with all code that used the MedCAT package. MedCAT v0.4 is available on the legacy branch and will still be supported until 1. July 2021 (with respect to potential bug fixes), after it will still be available but not updated anymore.Paper:What’s in a Summary? Laying the Groundwork for Advances in Hospital-Course Summarization(more...)DemoA demo application is available atMedCAT. This was trained on MIMIC-III and all of SNOMED-CT.TutorialsA guide on how to use MedCAT is available atMedCAT Tutorials. Read more about MedCAT onTowards Data Science.Available ModelsAvailable modelshereAcknowledgementsEntity extraction was trained onMedMentionsIn total it has ~ 35K entites from UMLSThe vocabulary was compiled fromWiktionaryIn total ~ 800K unique wordsPowered ByA big thank you goes tospaCyandHugging Face- who made life a million times easier.Citation@ARTICLE{Kraljevic2021-ln, title="Multi-domain clinical natural language processing with {MedCAT}: The Medical Concept Annotation Toolkit", author="Kraljevic, Zeljko and Searle, Thomas and Shek, Anthony and Roguski, Lukasz and Noor, Kawsar and Bean, Daniel and Mascio, Aurelie and Zhu, Leilei and Folarin, Amos A and Roberts, Angus and Bendayan, Rebecca and Richardson, Mark P and Stewart, Robert and Shah, Anoop D and Wong, Wai Keong and Ibrahim, Zina and Teo, James T and Dobson, Richard J B", journal="Artif. Intell. Med.", volume=117, pages="102083", month=jul, year=2021, issn="0933-3657", doi="10.1016/j.artmed.2021.102083" }
zensols.mednlp
Medical natural language parsing and utility libraryA natural language medical domain parsing library. This library:Provides an interface to theUTS(UMLSTerminology Services) RESTful service with data caching (NIH login needed).Wraps theMedCATlibrary by parsing medical and clinical text into first class Python objects reflecting the structure of the natural language complete withUMLSentity linking withCUIsand other domain specific features.Combines non-medical (such as POS and NER tags) and medical features (such asCUIs) in one API and resulting data structure and/or as aPandasdata frame.Providescui2vecas aword embedding modelfor either fast indexing and access or to use directly as features in aZensols Deep NLP embedding layermodel.Provides access tocTAKESusing as a dictionary likeStashabstraction.Includes a command line program to access all of these features without having to write any code.DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easiest way to install the command line program is via thepipinstaller.pip3installzensols.mednlpBinaries are also available onpypi.UsageTo parse text, create features, and extract clinical concept identifiers:>>>fromzensols.mednlpimportApplicationFactory>>>doc_parser=ApplicationFactory.get_doc_parser()>>>doc=doc_parser('John was diagnosed with kidney failure')>>>fortokindoc.tokens:print(tok.norm,tok.pos_,tok.tag_,tok.cui_,tok.detected_name_)JohnPROPNNNP-<N>--<N>-wasAUXVBD-<N>--<N>-diagnosedVERBVBN-<N>--<N>-withADPIN-<N>--<N>-kidneyNOUNNNC0035078kidney~failurefailureNOUNNNC0035078kidney~failure>>>print(doc.entities)(<John>,<kidneyfailure>)See thefull example, and for other functionality, see theexamples.MedCAT ModelsBy default, this library the small MedCAT model used fortutorials, and is not sufficient for any serious project. To get the UMLS trained model,theMedCAT UMLS request formfrom be filled out (see theMedCATrepository).After you obtain access and download the new model, add the following to~/.mednlprcwith the following:[medcat_status_resource]url=file:///location/to/the/downloaded/file/umls_sm_wstatus_2021_oct.zip'AttributionThis API utilizes the following frameworks:MedCAT: used to extract information from Electronic Health Records (EHRs) and link it to biomedical ontologies like SNOMED-CT and UMLS.cTAKES: a natural language processing system for extraction of information from electronic medical record clinical free-text.cui2vec: a new set of (like word) embeddings for medical concepts learned using an extremely large collection of multimodal medical data.Zensols Deep NLP library: a deep learning utility library for natural language processing that aids in feature engineering and embedding layers.ctakes-parser: parsescTAKESoutput in to aPandasdata frame.CitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}CommunityPlease star the project and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2021 - 2023 Paul Landes
zensols.mimic
MIMIC III Corpus ParsingA utility library for parsing theMIMIC-IIIcorpus. This usesspaCyand extends thezensols.mednlpto parse theMIMIC-IIImedical note dataset. Features include:Creates both natural language and medical features from medical notes. The latter is generated using linked entity concepts parsed withMedCATviazensols.mednlp.Modifies thespaCytokenizer to chunk masked tokens. For example,[,**,First,Name**]becomes[**First Name**].Provides a clean Pythonic object oriented representation of MIMIC-III admissions and medical notes.Interfaces MIMIC-III data as a relational database (either PostgreSQL or SQLite).DocumentationSee thefull documentation. TheAPI referenceis also available.ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.mimicBinaries are also available onpypi.InstallationInstall the package:pip3 install zensols.mimicInstall the database (either PostgreSQL or SQLite).MedCAT ModelsThe dependencyzensols.mednlppackage uses thedefault MedCAT model.SQLite ConfigurationSQLite is the default database used for MIMIC-III access, but, it is slower and not as well tested compared to thePostgreSQLdriver. See theSQLite database fileusing theSQLite instructionsto create the SQLite file from MIMIC-III if you need database access.Once you create the file, configure it with the API using the following additional configuration in the--configfile is also necessary (or in~/.mimicrc):[mimic_sqlite_conn_manager]db_file=path: <some directory>/mimic3.sqlite3PostgreSQLPostgreSQL is the preferred way to access MIMIC-II for this API. The MIMIC-III database can be loaded by following thePostgreSQL instructions, or consider thePostgreSQL Docker image. Then configure the database by adding the following to~/.mimicrc:[mimic_default]resources_dir=resource(zensols.mimic): resourcessql_resources=${resources_dir}/postgresconn_manager=mimic_postgres_conn_manager[mimic_db]database=<needs a value>host=<needs a value>port=<needs a value>user=<needs a value>password=<needs a value>The Python PostgreSQL client package is also needed, which can be installed with:pip3installzensols.dbpgUsageTheCorpusclass is the data access object used to read and parse the corpus:# get the MIMIC-III corpus data acceess object>>>fromzensols.mimicimportApplicationFactory>>>corpus=ApplicationFactory.get_corpus()# get an admission by hadm_id>>>adm=corpus.hospital_adm_stash['165315']# get the first discharge note (some have admissions have addendums)>>>fromzensols.mimic.regexnoteimportDischargeSummaryNote>>>ds=adm.notes_by_category[DischargeSummaryNote.CATEGORY][0]# dump the note as a human readable section-by-section>>>ds.write()row_id:12144category:Dischargesummarydescription:Reportannotator:regular_expression----------------------0:chief-complaint(CHIEFCOMPLAINT)-----------------------Unresponsiveness-----------1:history-of-present-illness(HISTORYOFPRESENTILLNESS)------------Thepatientisa...# get features of the note useful in ML models as a Pandas dataframe>>>df=ds.feature_dataframe# get only medical features (CUI, entity, NER and POS tag) for the HPI section>>>df[(df['section']=='history-of-present-illness')&(df['cui_']!='-<N>-')]['norm cui_ detected_name_ ent_ tag_'.split()]normcui_detected_name_ent_tag_15historyC0455527history~of~hypertensionconceptNNSee theapplication example, which gives a fine grain way of configuring the API.Medical Note SegmentationThis package uses regular expressions to segment notes. However, thezensols.mimicsiduses annotations and a model trained by clinical informatics physicians. Using this package gives this enhanced segmentation without any API changes.CitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2022 - 2024 Paul Landes
zensols.mimicsid
MIMIC-III corpus parsing and section prediction with MedSecIdThis repository contains the a Python package to automatically segment and identify sections of clinical notes, such as electronic health record (EHR) medical documents. It also provides access to the MedSecId section annotations with MIMIC-III corpus parsing from the paperA New Public Corpus for Clinical Section Identification: MedSecId. See themedsecid repositoryto reproduce the results from the paper.This package provides the following:The same access to MIMIC-III data as provided in themimic package.Access to the annotated MedSecId notes as an easy to use Python object graph.The pretrained model inferencing, which produces a similar Python object graph to the annotations (provides the classPredictedNoteinstead of anAnnotatedNoteclass.Table of ContentsObtainingDocumentationInstallationUsagePrediction UsageAnnotation AccessDifferences from the Paper RepositoryTrainingPreprocessing StepTraining and TestingTraining Production ModelsModelsMedCAT ModelsPerformance MetricsVersion 0.0.2Version 0.0.3CitationDockerChangelogCommunityLicenseObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.mimicsidBinaries are also available onpypi.Adockerimage is now available as well.DocumentationSee thefull documentation. TheAPI referenceis also available.InstallationIf you only want to predict sections using the pretrained model, you need only toinstallthe package. However, if you want to access the annotated notes, you must install a Postgres MIMIC-III database asmimic package install section.UsageThis package provides models to predict sections of a medical note and access to the MIMIC-III section annotations available onZenodo. The first time it is run it will take a while to download the annotation set and the pretrained models.See theexamplesfor the complete code and additional documentation.Prediction UsageTheSectionPredictorclass creates section annotation span IDs/types and header token spans. See the example below:fromzensols.nlpimportFeatureTokenfromzensols.mimicimportSectionfromzensols.mimicsidimportPredictedNote,ApplicationFactoryfromzensols.mimicsid.predimportSectionPredictorif(__name__=='__main__'):# get the section predictor from the application context in the appsection_predictor:SectionPredictor=ApplicationFactory.section_predictor()# read in a test note to predictwithopen('../../test-resources/note.txt')asf:content:str=f.read().strip()# predict the sections of read in note and print itnote:PredictedNote=section_predictor.predict([content])[0]note.write()# iterate through the note object graphsec:Sectionforsecinnote.sections.values():print(sec.id,sec.name)# concepts or special MIMIC tokens from the addendum sectionsec=note.sections_by_name['addendum'][0]tok:FeatureTokenfortokinsec.body_doc.token_iter():print(tok,tok.mimic_,tok.cui_)Annotation AccessAnnotated notes are provided as a PythonNote class, which contains most of the MIMIC-III data from theNOTEEVENTStable. This includes not only the text, but parsedFeatureDocumentinstances. However, you must build a Postgres database and provide a login to it in the application as detailed below:fromzensols.configimportIniConfigfromzensols.mimicimportSectionfromzensols.mimicsidimportApplicationFactoryfromzensols.mimicimportNotefromzensols.mimicsidimportAnnotatedNote,NoteStashif(__name__=='__main__'):# create a configuration with the Postgres database loginconfig=IniConfig('db.conf')# get the `dict` like data structure that has notes by `row_id`note_stash:NoteStash=ApplicationFactory.note_stash(**config.get_options(section='mimic_postgres_conn_manager'))# get a note by `row_id`note:Note=note_stash[14793]# iterate through the note object graphsec:Sectionforsecinnote.sections.values():print(sec.id,sec.name)Differences from the Paper RepositoryThe papermedsecid repositoryhas quite a few differences, mostly around reproducibility. However, this repository is designed to be a package used for research that applies the model. To reproduce the results of the paper, please refer to the [medsicid repository]. To use the best performing model (BiLSTM-CRF token model) from that paper, then use this repository.Perhaps the largest difference is that this repository has a pretrained model and code for header tokens. This is a separate model whose header token predictions are "merged" with the section ID/type predictions.The differences in performance between the section ID/type models and metrics reported involve several factors. The primary difference being that released models were trained on the test data with only validation performance metrics reported to increase the pretrained model performance. Other changes include:Uses themednlp package, which usesMedCATto parse clinical medical text. This includes changes such as fixing misspellings and expanding acronyms.Uses themimic package, which builds on themednlp packageand parses [MIMIC-III] text by configuring thespaCytokenizer to deal with pseudo tokens (i.e.[**First Name**]). This is a significant change given how these tokens are treated between the models and term mapping (Pt.becomespatient). This was changed so the model will work well on non-MIMIC data.Feature sets differences such as provided by theZensols Deep NLP package.Model changes include LSTM hidden layer parameter size and activation function.White space tokens are removed inmedsecid repositoryand added back in this package to give additional cues to the model on when to break a section. However, this might have had the opposite effect.There are also changes in the libraries used:PyTorch was upgraded from 1.9.1 to 1.12.1spaCywas upgraded from 3.0.7 to 3.2.4Python version 3.9 to 3.10.TrainingThis document explains how to create and package models for distribution.Preprocessing StepTo train the model, first install the MIMIC-III Postgres database per themimic packageinstructions in theInstallationsection.Add the MIMIC-III Postgres credentials and database configuration toetc/batch.conf.Comment out the lineresource(zensols.mimicsid): resources/model/adm.confinresources/app.conf.Vectorize the batches using the preprocessing script:$ ./src/bin/preprocess.sh. This also creates cached hospital admission and spaCy data parse files.Training and TestingTo get performance metrics on the test set by training on the training, use the command:./mimicsid traintest -c models/glove300.conffor the section ID model. The configuration file can be any of those in themodelsdirectory. For the header model use:./mimicsidtraintest-cmodels/glove300.conf--overridemimicsid_default.model_type=headerTraining Production ModelsTo train models used in your projects, train the model on both the training and test sets. This still leaves the validation set to inform when to save for epochs where the loss decreases:Update thedeeplearn_model_packer:versioninresources/app.conf.Preprocess (see thepreprocessing) section.Run the script that trains the models and packages them:src/bin/package.sh.Check for errors and verify models:$ ./src/bin/verify-model.py.Don't forget to revert filesetc/batch.confandresources/app.conf.ModelsYou can mix and match models across section vs. header models (seePerformance Metrics). By default the package uses the best performing models but you can select the model you want by adding a configuration file and specifying it on the command line with-c:[mimicsid_default]section_prediction_model=bilstm-crf-tok-fasttextheader_prediction_model=bilstm-crf-tok-glove-300dThe resources live onZenodoand are automatically downloaded on the first time the program is used in the~/.cachedirectory (or similar home directory on Windows).MedCAT ModelsThe dependencymednlp packagepackage uses thedefault MedCAT model.Performance MetricsThe distributed models add in the test set to the training set to improve the performance for inferencing, which is why only the validation metrics are given. The validation set performance of the pretrained models are given below, where:wF1is the weighted F1mF1is the micro F1Mf1is the macro F1accis the accuracyFundamental API changes have necessitated subsequent versions of the model. Each version of this package is tied to a model version. While some minor changes of each version might present language parsing differences such as sentence chunking, metrics are most likely statistically insignificant.Version 0.0.2NameTypeIdwF1mF1MF1accBiLSTM-CRF_tok (fastText)Sectionbilstm-crf-tok-fasttext-section-type0.9180.9250.7970.925BiLSTM-CRF_tok (GloVE 300D)Sectionbilstm-crf-tok-glove-300d-section-type0.9170.9220.8090.922BiLSTM-CRF_tok (fastText)Headerbilstm-crf-tok-fasttext-header0.9960.9960.9590.996BiLSTM-CRF_tok (GloVE 300D)Headerbilstm-crf-tok-glove-300d-header0.9960.9960.9620.996Version 0.0.3NameTypeIdwF1mF1MF1accBiLSTM-CRF_tok (fastText)Sectionbilstm-crf-tok-fasttext-section-type0.9110.9170.7920.917BiLSTM-CRF_tok (GloVE 300D)Sectionbilstm-crf-tok-glove-300d-section-type0.9290.9330.8100.933BiLSTM-CRF_tok (fastText)Headerbilstm-crf-tok-fasttext-header0.9960.9960.9650.996BiLSTM-CRF_tok (GloVE 300D)Headerbilstm-crf-tok-glove-300d-header0.9960.9960.9620.996CitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2022-new,title="A New Public Corpus for Clinical Section Identification: {M}ed{S}ec{I}d",author="Landes, Paul andPatel, Kunal andHuang, Sean S. andWebb, Adam andDi Eugenio, Barbara andCaragea, Cornelia",booktitle="Proceedings of the 29th International Conference on Computational Linguistics",month=oct,year="2022",address="Gyeongju, Republic of Korea",publisher="International Committee on Computational Linguistics",url="https://aclanthology.org/2022.coling-1.326",pages="3709--3721"}Also please cite theZensols Framework:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}DockerAdockerimage is now available as well.To use the docker image, do the following:Create (or obtain) thePostgres docker imageClone this repositorygit clone --recurse-submodules https://github.com/plandes/mimicsidSet the working directory to the repo:cd mimicsidCopy the configuration from the installedmimicdbimage configuration:make -C docker/mimicdb SRC_DIR=<cloned mimicdb directory> cpconfigStart the container:make -C docker/app upTest sectioning a document:make -C docker/app testdumpsecLog in to the container:make -C docker/app devloginOutput a note to a temporary file:mimic note 1118471 > note.txtPredict the sections on the note:mimicsid predict note.txtLook at the section predictions:cat preds/note-pred.txtChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2022 - 2024 Paul Landes
zensols.ngramdb
Create an SQLite database from the Google ngrams database.Creates an SQLite database of the one millionn-gramdatasets from Google. This code downloads then-gram data setscorpus and then creates anSQLitedatabase file with the contents. It also provides a simple API forn-gramlook ups.Table of ContentsInstallationData SizeUsageCommand LineProgrammatic InterfaceData Analysis with PandasObtainingChangelogLicenseInstallationTo make life easier, installGNU Make. If you do not, you'll need to follow the steps given in themakefile.Download the 1 millionn-gram data sets:make download. This should take a few minutes with a good Internet connection.Un-compress the load files:make uncompress.Create and load theSQLitedatabase from the downloaded corpus:make load. Depending on the processor speed, this should take about an hour and creates a file indata/eng-1gram.dbthat takes 18G on disk.Install from the command line either from source (make install) or frompip.If you want to use the program on the command line (as opposed to an API), create a the following file in~/.ngramdbrcwith the contents:[default][ngram_db]data_dir=${HOME}/path/to/eng-1gram.dbData SizeAs mentioned, theSQLitedatabase file take 18G on disk. This is because it keeps occurrences over several decades. In many cases, older n-grams are not needed and queries can take a while given the size of the data. The data can be minimized with the following SQL in anySQLiteinterface (i.e. MacOS hassqlite3on the command line):deletefromngramwhereyr<1990;In this example, all n-grams recorded from publications before the year 1990 are expunged.UsageThis project can be used either from the command line or as an API.Command LineTo use from the command line:%ngramdbquery-gthe-y20056313626900.56880%This gives the number of unigrams (assuming unigrams were built) found since 2005 and the percentage of that unigram to all words in the corpus.Programmatic InterfaceAs in theinstallationsection, create the~/.ngramdbrcconfiguration file. Also note that the API is configured to easily work with other Python projects that use thezensols.actioncliconfiguration API.fromzensols.ngramdbimportAppConfig,Queryconf=AppConfig.instance().app_configquery=Query(conf)stash=query.stashn_occurs=stash['The']print(f'{n_occurs}{100*n_occurs/len(stash):.5f}%')=>6313626900.56880%Data Analysis with PandasThestash accessis nice for specific use cases where a subset of the corpus counts are necessary. However, the intention of creating a selectable data format was to allow for data analysis as well. Here's an example of howPandascan be used directly against the createdSQLitefile learn about the corpus:fromzensols.actioncli.timeimporttimeimportpandasaspdimportsqlite3ass# "connect" to the SQLite database filedb='/path/to/data/directory/eng-1gram.db'conn=s.connect(db)# create a dataframe with all entries on or after 1990sql='select grams, match_count as cnt from ngram where yr >= 1990'withtime('{rc}rows read'):df=pd.read_sql_query(sql,conn)rc=len(df)#=> 28150989 rows read finished in 60.8s# create a data frame with a ngram text and number of match counts per rowwithtime('groupby of{rc}rows'):dfg=df.groupby(['grams'],as_index=False).agg({'cnt':'sum'})rc=len(df)#=> group of 28150989 rows finished in 7.6s# get the number of counts on 'the'dfg[dfg['grams']=='the']#=> grams cnt#=> 2819462 the 621594750# all token occurrencesall_cnt=df['cnt'].sum()all_cnt#=> 13269089201# calculate at the poulation of a few wordsforwordin'the The . cat dog phone iPhone'.split():occ=dfg[dfg['grams']==word].cnt.item()pop=occ/all_cntprint(f'word\'{word}\'found{occ}times, which is{pop*100:.5f}% of the corpus')#=> word 'the' found 621594750 times, which is 4.68453% of the corpus#=> word 'The' found 77576794 times, which is 0.58464% of the corpus#=> word '.' found 641792317 times, which is 4.83675% of the corpus#=> word 'cat' found 247075 times, which is 0.00186% of the corpus#=> word 'dog' found 453789 times, which is 0.00342% of the corpus#=> word 'phone' found 522190 times, which is 0.00394% of the corpus#=> word 'iPhone' found 178 times, which is 0.00000% of the corpuswithtime('pickled data frame'):df.to_pickle('df.dat')#=> pickled data frame finished in 8.0swithtime('write to csv'):df.to_csv('df.csv')#=> write to csv finished in 44.3swithtime('read data from'):df=pd.read_pickle('df.dat')#=> read data from finished in 2.4sObtainingThe easist way to install the command line program is via thepipinstaller:pip3installzensols.ngramdbBinaries are also available onpypi.ChangelogAn extensive changelog is availablehere.LicenseCopyright (c) 2019 Paul LandesPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zensols.nlp
Zensols Natural Language ParsingThis framework wraps thespaCyframework and creates light weight features in a classhierarchythat reflects the structure of natural language. The motivation is to generate features from the parsed text in an object oriented fashion that is fast and easy to pickle.See thefull documentation.Paper onarXiv.Other features include:Parse and normalizea stream of tokens as stop words, punctuation filters, up/down casing, porter stemming andothers.Detached featuresthat are safe and easy to pickle to disk.Configuration drive parsing and token normalization usingconfiguration factories.Pretty print functionality for easy natural language feature selection.A comprehensivescoring moduleincluding following scoring methods:RougeBleuSemEval-2013 Task 9.1Levenshtein distanceExact matchDocumentationFramework documentationNatural Language ParsingList Token Normalizers and MappersObtaining / InstallingThe easiest way to install the command line program is via thepipinstaller. Since the package needs at least one spaCy module, the second command downloads the smallest model.pip3install--use-deprecated=legacy-resolverzensols.nlp python-mspacydownloaden_core_web_smBinaries are also available onpypi.UsageA parser using the default configuration can be obtained by:fromzensols.nlpimportFeatureDocumentParserparser:FeatureDocumentParser=FeatureDocumentParser.default_instance()doc=parser('Obama was the 44th president of the United States.')fortokindoc.tokens:print(tok.norm,tok.pos_,tok.tag_)print(doc.entities)>>>ObamaPROPNNNPwasAUXVBDtheDETDT45thADJJJpresidentNOUNNNofADPINtheUnitedStatesDETDT.PUNCT.(<Obama>,<45th>,<theUnitedStates>)However, minimal effort is needed to configure the parser using aresource library:fromioimportStringIOfromzensols.configimportImportIniConfig,ImportConfigFactoryfromzensols.nlpimportFeatureDocument,FeatureDocumentParserCONFIG="""# import the `zensols.nlp` library[import]config_file = resource(zensols.nlp): resources/obj.conf# override the parse to keep only the norm, ent[doc_parser]token_feature_ids = set: ent_, tag_"""if(__name__=='__main__'):fac=ImportConfigFactory(ImportIniConfig(StringIO(CONFIG)))doc_parser:FeatureDocumentParser=fac('doc_parser')sent='He was George Washington and first president of the United States.'doc:FeatureDocument=doc_parser(sent)fortokindoc.tokens:tok.write()This uses aresource libraryto source in the configuration from this package so minimal configuration is necessary. More advanced configurationexamplesare also available.See thefeature documentsfor more information.ScoringCertain scores in thescoring moduleneed additional Python packages. These are installed with:pipinstall-Rsrc/python/requirements-score.txtAttributionThis project, or example code, uses:spaCyfor natural language parsingmsgpackandsmart-openfor Python disk serializationnltkfor theporter stemmerfunctionalityCitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2020 - 2023 Paul Landes
zensols.propbankdb
Failed to fetch description. HTTP Status Code: 404
zensols.pybuild
Inspect and iterate on git tags and invoke setup utilsInspect and iterate on git tags. This manages tags in a git repository and invokes setup utils. This is used in thezen build setupas well.DocumentationSee thefull documentation.ObtainingThe easist way to install the command line program is via thepipinstaller:pipinstallzensols.pybuildBinaries are also available onpypi.UsageSee thezotsite setup.pyfile for an example of how to use it as in setup tools.ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2018 - 2020 Paul Landes
zensols.rbak
Mount file systems and backup directories.This program copiessourcepaths optionally mountabletargets. You can configure whether or not a target is mountable or not. If it is, the program mounts the file system by looking for ainfo.conffile and mounts if the file is not found. The program only looks to see if this file exists and does not do anything with the contents.Features:Mounts file systems only when necessaryUnmounts only file systems mountedCustomizable rsync (and mount/umount) commands.Easy/intuitive configuration.Need not bersync, you can customize the backup to whatever you want.Table of ContentsUsageConfigurationHelpObtainingChangelogLicenseUsageInstallthe library, which also installs the command.Create a configuration file (default is/etc/rbak.confif-cis not given): See thetest case configuration filefor an example.Check your configuration:$ rbak infoBackup using a dry run (i.e. careful withrsync's--delete):$ rbak --dryrun backupStart the backup:$ rbak backupConfigurationSee thetest case configuration file, which has the explains each line of configuration in detail.Here's a sample:## default section has configuration shared with all targets and sources[default]# name of file to look for in targets to determine if mountedinfo_file=info.conf# default name of backup directory for each target--this gets appended to the# target's pathbackup_dir=bak# commands for mounting, un-mounting and backing upmount_cmd=/bin/mount -L {name} {path}umount_cmd=/bin/umount {path}backup_cmd=rsync -rltpgoDuv --delete {source.path}/ {target.backup_path}/{source.basename}# list of targets and sources, each of which need their own sectionstargets=extbak2tsources=git## target `extbak2t` is an example of a mountable file system (i.e. USB drive)[extbak2t]# declare this to be a mountable file systemmountable=true# path resolves to /mnt/extbak2t ({name} is the target/section name)path=/mnt/{name}## the one and only source for this configuration[git]# path of where files will be copied frompath=/opt/var/git# override the basenme target backup directorybasename_dir=other/gitpathThebackup_cmdneed not be anrsynccommand, it can be anything and you can use any property of the source and target that are generated at runtime, but it can also by any property of these classes.The globaldefaultsection'sbackup_dirvariable is shared with all targets and sources. This variable is appended to the target's path so the program can differentiate between the mount point and the path to back up files.Thebasename_dirproperty in sources overrides thesource.basenmeproperty inbackup_cmd. If this is not given it defaults to the basename of the source'spathproperty.This program was written KISS (keep it simple) philosophy. If you have a transitive backup situation (i.e. backup A -> B, then B -> C), it's better to break this out into two separate configuration files and two separate backup invocations. That said, in some cases you may be able to utilize the--sourcesoption to set which sources to backup.HelpThe usage is given with-h:$rbak-hUsage:rbak<list|...>[options]Options:--version show program's version number and exit-h,--help show this help message and exit-s,--short short output for list-wNUMBER,--whine=NUMBERaddverbositytologging-cFILE,--config=FILEconfigurationfileUsage:rbakbackup[additionaloptions]RunthebackupOptions:-d,--dryrun dry run to not actually connect, but act like it-n,--sources override the sources property in the config-h,--help show this help message and exitUsage:rbakmount[additionaloptions]MountalltargetsOptions:-d,--dryrun dry run to not actually connect, but act like it-h,--help show this help message and exitUsage:rbakumount[additionaloptions]Un-mountalltargetsOptions:-d,--dryrun dry run to not actually connect, but act like it-h,--help show this help message and exitObtainingThe easist way to install the command line program is via thepipinstaller:pipinstallzensols.rbakBinaries are also available onpypi.ChangelogAn extensive changelog is availablehere.LicenseCopyright (c) 2018 Paul LandesPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zensols.rend
Invoke native applications to view filesInvoke native applications to view and render data from files.Features:UsesDashto render Excel, CSV and TSV files.Render PDF and HTML in the default web browser.Features on macOS:Default web browser used for HTML,Preview.appused for PDF files.Resize the window and a per display basis.Go to a specified page inPreview.app.Multiple file rendering in browser tabs.The features on macOS areneeded for other operating systems.UsageCreate aconfiguration filewith the dimensions of each of the screens you work with and where you wantPreview.appto be displayed. You can validate these configurations by having the application echo them back at you:$rendconfigCommand LineInvoke the application to show the file and display it:$rendexample.pdfSee theconfiguration fileexample.From PythonThe package is designed to be easy invoke from Python as well (note the parenthesis needed to make the instance):fromzensols.rendimportApplicationFactoryif(__name__=='__main__'):app=ApplicationFactory().get_instance()app('test-resources/sample.pdf')PandasDataFrames can be rendered using the browser API (note the lack of parenthesis as it is called as a class method):fromzensols.rendimportBrowserManager,ApplicationFactoryimportpandasaspdif(__name__=='__main__'):mng:BrowserManager=ApplicationFactory.get_browser_manager()url='https://raw.githubusercontent.com/scpike/us-state-county-zip/master/geo-data.csv'df=pd.read_csv(url)mng.show(df)ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.rendBinaries are also available onpypi.DocumentationSee thefull documentation. TheAPI referenceis also available.ContributingCurrently the more advanced features are only available on macOS. However, the API is written to easily add other operating systems as plugins. If you would like to write one for other operating systems, please contact and/or submit a pull request.ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2022 - 2023 Paul Landes
zensols.showfile
Invoke native applications to view filesInvoke native applications to view files. On macOS, the default web browser and Preview.app are used to view HTML and PDF files respectively. On all other operating systems the default web browser is used to view files.UsageCreate aconfiguration filewith the dimensions of each of the screens you work with and where you want Preview.app to be displayed. You can validate these configurations by having the application echo them back at you:$showfileconfigCommand LineInvoke the application to show the file and display it:$showfileshowexample.pdfSee theconfiguration fileexample.From PythonThe package is designed to be easy invoke from Python as well:fromzensols.showfileimportApplicationFactoryapp=ApplicationFactory().get_instance()app('test-resources/showfile.conf')ObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.showfileBinaries are also available onpypi.DocumentationSee thefull documentation. TheAPI referenceis also available.ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2022 Paul Landes
zensols.spanmatch
Unsupervised Position-Based Semantic MatchingAn API to match spans of semantically similar text across documents. Each match is a span of text in a source document and another span of text in a target document that are both tied together.Table of ContentsIntroductionDocumentationUsageCitationObtainingChangelogLicenseIntroductionSpans are formed by a weighted combination of the semantic similarity of the each document's text and the token position. Hyperparameters are used to control which take precedent (semantic similarity or token position for longer contiguous token spans).This is done using position embeddings on a third (see Figure 1) axis shows data blue word embeddings moving from cluster 1 to cluster 2. Cluster spans the discharge summaries (orange), the note antecedent (green) and arrows connecting the tokens to word points.Figure 1For more information, see "Hybrid Semantic Positional Token Clustering" in our paperHospital Discharge Summarization Data Provenance.DocumentationSee thefull documentation. TheAPI referenceis also available.Usagefromzensols.cliimportCliHarnessfromzensols.nlpimportFeatureDocument,FeatureDocumentParserfromzensols.spanmatchimportMatch,MatchResult,Matcher,ApplicationFactorySOURCE="""\Johannes Gutenberg (1398 – 1468) was a German goldsmith and publisher whointroduced printing to Europe. His introduction of mechanical movable typeprinting to Europe started the Printing Revolution and is widely regarded as themost important event of the modern period. It played a key role in thescientific revolution and laid the basis for the modern knowledge-based economyand the spread of learning to the masses.Gutenberg many contributions to printing are: the invention of a process formass-producing movable type, the use of oil-based ink for printing books,adjustable molds, and the use of a wooden printing press. His truly epochalinvention was the combination of these elements into a practical system thatallowed the mass production of printed books and was economically viable forprinters and readers alike."""SUMMARY="""\The German Johannes Gutenberg introduced printing in Europe. His invention had adecisive contribution in spread of mass-learning and in building the basis ofthe modern society."""harness:CliHarness=ApplicationFactory.create_harness()doc_parser:FeatureDocumentParser=harness['spanmatch_doc_parser']matcher:Matcher=harness['spanmatch_matcher']source:FeatureDocument=doc_parser(SOURCE)summary:FeatureDocument=doc_parser(SUMMARY)# shorten source doc span length by scaling up positional importancematcher.hyp.source_position_scale=2.5# elongate summary doc span length by scaling up positional importancematcher.hyp.target_position_scale=0.9res:MatchResult=matcher(source,summary)match:Matchfori,matchinenumerate(res.matches[:5]):match.write(include_flow=False)Output:2023-06-1108:22:38,39224matchesfoundsource(0,55):JohannesGutenberg(1398–1468)wasaGermangoldsmithtarget(4,29):GermanJohannesGutenbergsource(524,631):type,theuseofoil-basedinkforprintingbooks,adjustablemolds,andtheuseofawoodenprintingpresstarget(4,59):GermanJohannesGutenbergintroducedprintinginEuropesource(301,421):scientificrevolutionandlaidthebasisforthemodernknowledge-basedeconomyandthespreadoflearningtothemassestarget(106,177):spreadofmass-learningandinbuildingthebasisofthemodernsocietysource(516,585):movabletype,theuseofoil-basedinkforprintingbooks,adjustabletarget(116,169):mass-learningandinbuildingthebasisofthemodernsource(168,199):startedthePrintingRevolutiontarget(106,145):spreadofmass-learningandinbuildingObtainingThe easiest way to install the command line program is via thepipinstaller:pip3install--use-deprecated=legacy-resolverzensols.spanmatchBinaries are also available onpypi.CitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-dsprov,title="{{Hospital Discharge Summarization Data Provenance}}",author="Landes, Paul andChaise, Aaron J. andPatel, Kunal P. andHuang, Sean S. andDi Eugenio, Barbara",booktitle="Proceedings of the 21st {{Workshop}} on {{Biomedical Language Processing}}",month=jul,year="2023",day=9,address="Toronto, Canada",publisher="{{Association for Computational Linguistics}}"}ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2023 Paul Landes
zensols.util
Zensols UtilitiesCommand line, configuration and persistence utilities generally used for any more than basic application. This general purpose library is small, has few dependencies, and helpful across many applications.See thefull documentation.Paper onarXiv.Some features include:AHydraorJava Springlike application level support forconfigurationthanconfigparser.Construct objects using configuration files (both INI and YAML).Parse primitives, dictionaries, file system objects, instances of classes.Acommand action libraryusing an action mnemonic to invocation of a handler that is integrated with a the configuration API. This supports long and short GNU style options as provided byoptparse.Streamline in memory and on diskpersistence.Multi-processing work with apersistence layer.A secondary goal of the API is to make prototyping Python code quick and easy using the REPL. Examples include reloading modules in theconfiguration factory.DocumentationFull documentationConfiguration: powerful but simple configuration system much likeHydraorJava SpringCommand line: automagically creates a fully functional command with help from a PythondataclassPersistence: cache intermediate data(structures) to the file systemAPI referenceObtainingThe easiest way to install the command line program is via thepipinstaller:pip3installzensols.utilCommand Line UsageThis library contains a full persistence layer and other utilities. However, a quick and dirty example that uses the configuration and command line functionality is given below. See the otherexamplesto learn how else to use it.fromdataclassesimportdataclassfromenumimportEnum,autoimportosfromioimportStringIOfromzensols.cliimportCliHarnessCONFIG="""# configure the command line[cli]apps = list: app# define the application, whose code is given below[app]class_name = fsinfo.Application"""classFormat(Enum):short=auto()long=auto()@dataclassclassApplication(object):"""Toy application example that provides file system information."""defls(self,format:Format=Format.short):"""List the contents of the directory.:param format: the output format"""cmd=['ls']ifformat==Format.long:cmd.append('-l')os.system(' '.join(cmd))if(__name__=='__main__'):harnes=CliHarness(app_config_resource=StringIO(CONFIG))harnes.run()The framework automatically links each command line action mnemonic (i.e.ls) to the data classApplicationmethodlsand command line help. For example:$python./fsinfo.py-h Usage:fsinfo.py[options]: Listthecontentsofthedirectory. Options:-h,--helpshowthishelpmessageandexit--versionshowtheprogramversionandexit-f,--format<long|short>shorttheoutputformat $python./fsinfo.py-fshort __pycache__fsinfo.pySee thefull examplethat demonstrates more complex command line handling, documentation and explanation.TemplateThe easiest to get started is totemplateout this project is to create your own boilerplate project with themkprojutility. This requires aJava installation, and easy to create a Python boilerplate with the following commands:# clone the boilerplate repogitclonehttps://github.com/plandes/template# download the boilerplate toolwgethttps://github.com/plandes/clj-mkproj/releases/download/v0.0.7/mkproj.jar# create a python template and build it outjava-jarmkproj.jarconfig-stemplate/python java-jarmkproj.jarThis creates a project customized with your organization's name, author, and other details about the project. In addition, it also creates a sample configuration file and command line that is ready to be invoked by either a Python REPL or from the command line viaGNU make.If you don't want to bother installing this program, the following sections have generated code as examples from which you can copy/paste.CitationIf you use this project in your research please use the following BibTeX entry:@inproceedings{landes-etal-2023-deepzensols,title="{D}eep{Z}ensols: A Deep Learning Natural Language Processing Framework for Experimentation and Reproducibility",author="Landes, Paul andDi Eugenio, Barbara andCaragea, Cornelia",editor="Tan, Liling andMilajevs, Dmitrijs andChauhan, Geeticka andGwinnup, Jeremy andRippeth, Elijah",booktitle="Proceedings of the 3rd Workshop for Natural Language Processing Open Source Software (NLP-OSS 2023)",month=dec,year="2023",address="Singapore, Singapore",publisher="Empirical Methods in Natural Language Processing",url="https://aclanthology.org/2023.nlposs-1.16",pages="141--146"}ChangelogAn extensive changelog is availablehere.LicenseMIT LicenseCopyright (c) 2020 - 2023 Paul Landes
zensols.zotsite
Zotsite: A Zotero Export UtilityThis project exports your localZoterolibrary to a usable HTML website. This generated website has the following features:Easily access your papers, site snapshots, notes from a navigation tree.Provides metadata from collections and attachments (i.e. referenes etc).Display PDF papers and website snapshot (the latter as framed).Search function dynamically narrows down the papers you're looking for.Embed links to a specific collection, article, item, note etc.Export only a portion of your collection with regular expressions using the collection name.BetterBibtexintegration.Snazzy look and feel from the latestBootstrapCSS/Javascript library.DocumentationSee thefull documentation.ObtainingThe easist way to install the command line program is via thepipinstaller:pip3installzensols.zotsiteBinaries are also available onpypi.ProcessThe tool does the following:Exports the meta data (directory structure, references, notes, etc) from yourZoterolibrary. On MacOS, this is done by querying the file system SQLite DB files.Copies a static site that enables traversal of the exported data.Copies yourZoterostored papers, snapshot (sites) etc.Generates a navigation tree to easily find your papers/content.Sample Site DemonstrationSee thelive demo, which provides a variety of resources found in my own library.Note:To my knowledge, all of these resources are free to distribute and violate no laws. If I've missed one, pleasecreate an issue.RequirementsBetterBibtexplugin for Zotero.UsageThe command line program has two modes: show configuration (a good first step) and to create the web site. You can see what the program is parsing from yourZoterolibrary:zotsiteprintTo create the stand-alone site, run the program (without the angle brackets):zotsiteexportIf your library is not in the default $HOME/zotero directory you will need to change that path by making a zotsite.conf config file:zotsiteexport--collectionzotsite.confThis will create the html files in the directory ./zotsiteSeeusagefor more information.Configuration FileEither an environment variableZOTSITERCmust be set or a-cconfiguration option must be given and point to a file to customize how the program works. See the testconfiguration filefor an example and inline comments for more detail on how and what can be configured.Ubuntu and Linux Systems with Python 3.5 or Previous VersionPleaseread this issueif you are installing a Ubuntu or any Linux system with Python 3.5 or previous version.Command Line HelpCommand line usage as provided with the--helpoption:Usage:zotsite[list|export|print][options]: ThisprojectexportsyourlocalZoterolibrarytoausableHTMLwebsite. Options:-h,--help[actions]showthishelpmessageandexit--versionshowtheprogramversionandexit--levelXtheapplicationloggerlevel,Xisoneof:debug,err,info,warn-c,--configFILEtheconfigurationfile Actions: listlistallactionsandhelp--lstfmt<json|name|text>texttheoutputformatfortheactionlistingexport(default)generateandexportthezoterowebsite--collectionREGEXaregularexpressionusedtofilter"collection"nodes-o,--outputdirDIRthedirectorytodumpthesite;defaulttoconfigurationfile-s,--showwhethertobrowsetothecreatedsite(needs"pip install zensols.showfile")printprint(sub)collectionsandpapersinthosecollectionsasatree--collectionREGEXaregularexpressionusedtofilter"collection"nodesAttributionThis software uses:Python 3jQueryversion 3DataTablesversion 1.12Bootstrapversion 4Tree Viewfor BootstrapPopperfor tooltipsCopy to ClipboardfunctionScreenshotAlso see thelive demo.TodoMake the site portion a proper Javascript site. Right now, all themins are added in the distribution to same directory as themain navigation/contentfile.Add functionality to the disabledViewbutton that drills down in a paper and finds a PDF or site to view withouth the user having to do this.Use something like zotxt to make this work with a plugin rather than directly against the SQLite DB.Zotero Plugin ListingThis is listed as apluginon the Zotero site.ChangelogAn extensive changelog is availablehere.CommunityPlease star this repository and let me know how and where you use this API. Contributions as pull requests, feedback and any input is welcome.LicenseMIT LicenseCopyright (c) 2019 - 2023 Paul Landes
zen-spring
3D printed springs builder for ZenCAD
zensvi
ZenSVIThis package handles downloading, cleaning, analyzing street view imageryInstallation$pipinstallzensviUsageTODOContributingInterested in contributing? Check out the contributing guidelines. Please note that this project is released with a Code of Conduct. By contributing to this project, you agree to abide by its terms.Licensezensviwas created by koito19960406. It is licensed under the terms of the MIT license.Creditszensviwas created withcookiecutterand thepy-pkgs-cookiecuttertemplate.
zentables
ZenTables - Stress-Free Descriptive Tables in PythonZenTablestransforms yourpandasDataFrames into beautiful, publishable tables in one line of code, which you can then transfer into Google Docs and other word processors with one click. Supercharge your workflow when you are writing papers and reports.importzentablesaszendf.zen.pretty()FeaturesBeautiful tables in one lineGoogle Docs/Word ready in one clickDescriptive statistics at varying levels of aggregationControl table aesthetics globallyand many more to come....InstallationViapipfrom PyPI:pipinstallzentablesViapipfrom GitHub directlypipinstall-Ugit+https://github.com/thepolicylab/ZenTablesHow to useZenTables1. How to format anyDataFrameFirst, import the package alongsidepandas:importpandasaspdimportzentablesaszenThen, to format anyDataFrame, simply use:df.zen.pretty()And this is the result:Click on theCopy Tablebutton to transfer the table to Google Docs and Word. Formatting will be preserved.Results in Google Docs (Tested on Chrome, Firefox, and Safari):Results in Microsoft Word:2. How to control my tables' appearance?ZenTablesprovides two ways to control the aesthetics of the tables. You can use global settings to control the font and font size of the tables via:zen.set_options(font_family="Times New Roman, serif",font_size=12)Note:Whenfont_sizeis specified as anint, it will be interpreted as points (pt). All other CSS units are accepted as astr.Or you can override any global options by specifyingfont_familyandfont_sizeinzen.pretty()method:df.zen.pretty(font_family="Times New Roman, serif",font_size="12pt")Both will result in a table that looks like thisWe are working on adding more customization options in a future release.3. How to create common descriptive tables usingZenTables?3.1. Frequency TablesUsedf.zen.freq_tables()to create simple frequency tables:freq_table=df.zen.freq_table(index=["Segment","Region"],columns=["Category"],values="Order ID",props="index",totals=True,subtotals=True,totals_names="Total"subtotals_names="Subtotal",)freq_table.zen.pretty()# You can also chain the methodsUsepropsto control whether to add percentages of counts. Whenpropsis not set (the default), no percentages will be added. You can also specifypropsto calculate percentages over"index"(rows),"columns", or"all"(over the totals of the immediate top level).Usetotalsandsubtotalsparameters to specify whether totals and subtotals will be added. Note that whenpropsis notNone, bothtotalsandsubtotalswill beTrue, and whensubtotalsis set toTrue, this will also overridetotalssettings toTrue.Additionally, you can control the names of the total and subtotal categories usingtotals_namesandsubtotals_namesparameters.3.2. Mean and standard deviation tablesUsedf.zen.mean_sd_table()to create descriptives with n, mean, and standard deviation:mean_sd_table=df.zen.mean_sd_table(index=["Segment","Region"],columns=["Category"],values="Sales",margins=True,margins_name="All",submargins=True,submargins_name="All Regions",)mean_sd_table.zen.pretty()# You can also chain the methodsSimilar tofreq_tables, you can usemarginsandsubmarginsparameters to specify whether aggregations at the top and intermediate levels will be added. Additionally, you can control the names of the total and subtotal categories usingmargins_namesandsubmargins_namesparameters.3.3 Other descriptive statistics tablesFor all other types of tables,ZenTablesprovides its owndf.zen.pivot_table()method:mean_median_table=df.zen.pivot_table(index=["Segment","Region"],columns=["Category"],values="Sales",aggfunc=["count","mean","median"],margins=True,margins_name="All",submargins=True,submargins_name="All Regions",).rename(# rename columnscolumns={"count":"n","mean":"Mean","median":"Median",})mean_median_table.zen.pretty().format(precision=1)# Specify level of precisionThere are two differences between thispivot_table()method and thepandaspivot_tablemethod. First, likemean_sd_table(), it providessubmarginsandsubmargins_namesfor creating intermediate-level aggregations. Second, results are grouped byvalues,columns, andaggfuncs, instead ofaggfuncs,values, andcolumns. This provides more readability than what thepandasversion provides.4. Tips and tricksdf.zen.pretty()returns a subclass ofpandasStyler, which means you can chain all other methods afterdf.style.format()in the previous section is an example. For more formatting options, please seethis page inpandasdocumentationAll other methods inZenTablesreturns a regularDataFramethat can be modified further.The names of the index and columns are by default hidden. You can get them back by doing this:df.zen.pretty().show_index_names().show_column_names()You can also disable theCopy Tablebutton like this:df.zen.pretty().hide_copy_button()TODOMore tests on compatibility withStylerinpandasMore options for customizationA theming systemMore to come...ContributingContributions are welcome, and they are greatly appreciated! If you have a new idea for a simple table that we should add, please submit an issue.ContributorsPrincipally written by Paul Xu atThe Policy Lab. Other contributors:Kevin H. WilsonEdward HuhSpecial thanksAll the members ofThe Policy Labat Brown University for their feedbackThesidetablepackagefor ideas and inspiration.
zentinel
No description available on PyPI.
zentool
No description available on PyPI.
zentra
Zentra Python ClientA simple client for interacting with the backend.
zentrit
No description available on PyPI.
zentropi
Zentropi Agent Framework: Script Your WorldFree software: BSD 3-Clause LicenseInstallationpip install zentropiYou can also install the in-development version with:pip install https://github.com/zentropi/python-zentropi/archive/master.zipDocumentationhttps://zentropi.readthedocs.io/DevelopmentTo run the all tests run:toxNote, to combine the coverage data from all the tox environments run:Windowsset PYTEST_ADDOPTS=--cov-append toxOtherPYTEST_ADDOPTS=--cov-append toxChangelog2020.0.1 (2020-03-06)First release on PyPI.
z.entry
Usefromz.entryimportentry@entrydefmain():print('hello world')
zentuxlog-client
UtilisationDans un script, une classe, un module, ...fromzentuxlog_client.clientimportClientAPIKEY="hkhfds56dfsdfjhdjk"APISECRET="KAP0dika43iH7"USERNAME="John"PASSWORD="Mypassauth={'client_id':APIKEY,'client_secret':APISECRET,'username':USERNAME,'password':PASSWORD}c=Client(auth=auth)c.send(data="information à logguer",method="POST",path="logs/")Dans une exception personnaliséefromzentuxlog_client.clientimportClientAPIKEY="hkhfds56dfsdfjhdjk"APISECRET="KAP0dika43iH7"USERNAME="John"PASSWORD="Mypass"auth={'client_id':APIKEY,'client_secret':APISECRET,'username':USERNAME,'password':PASSWORD}c=Client(auth=auth)classMyCustomError(Exception):"""Erreur générique."""def__init__(self,msg=''):self.msg=msgifmsg:c.send(msg,method="POST",path="logs/")def__str__(self):returnself.msg
zentx
coming soon
zen-util
Zen UtilitiesHelpful utility functions/decorators.@handle_pluralThis decorator is designed to be added to functions, automatically expands pased dicts/lists into the function it wraps.This function does not return values for most operations, it is designed to be used within a class where the wrapped function sets class attributes.NoDupFlatListEssentially a dumb set, but is a list so is orderedpretty_printA function designed to print complex data structures in a nice mannerreplace_file_lineReplaces a line in a filedef replace_file_line(file_path, old_line, new_line):update_initUsed by@add_thread, appends the passed function to the init of a class.walk_dictTakes two dicts as args, walks the first dict using the structure of the second dict. Iffail_safeis set, returns none when keys can't be found.check_dictThis decorator can be added to a function to check for the presence or lack of a dict item.By default, it will print an error message, but will use self.logger if it exists in the class whose method is decorated. This logger will be created automatically if the clsss is wrapped with @loggify.The first arg (key) is required. Thevalidate_dictarg is initially unset, and allows the dict which is being checked to be changed.Ifkeyis a dict, the structure will be used to walk thevalidate_dict.The decorator will read args[0] at runtime, and if this is a dict, it will use that ifvalidate_dictis not set. Functionally, this readsselfand allows this decorator to be used to check for dict items within a class with a__dict__value_argDefines the value to compare found keys against.containsIs a boolean that enables checking for thevalue_argas the name of a key invalidate_dict.unsetIs a boolean used to make validation pass if thekeyis not found.raise_exceptionCauses a ValueError to be rasied instead of printing an error message.log_level(10) Defines the log level to send the message to.return_val(False) Defines the default return value to use when validation fails.return_argReturn this argument (by number) when validation fails.messageSet the vailidation failure message.Additional arguments exist to set a value to compare found keys against
zenutils
zenutilsCollection of simple utils.Installpip install zenutilsExtra packages requiresFor python3.2 and python2.x, requires extra package: inspect2~=0.1.2For user who is using xxhash methods with hashutils, requires extra package: xxhashFor user who is using sm3 methods with hashutils, requires extra package: sm3utils.If your python installation's hashlib already support sm3 hash method, you don't have to install sm3utils.xxhash and sm3utils are not put into this package's requirements, you need to install them by your self.NoticeThe hashutils' hash methods are different on different python installations. The list below is based on Python 3.10.6 x86_64 on windows. Mostly md5, sha1, sha224, sha256, sha384, sha512 methods are supported.The hashutils' DEFAULT_HASH_METHOD is sm3 and DEFAULT_PASSWORD_HASH_METHOD is ssm3, so if your python installation is not support sm3 hash method, you need to install sm3utils by yourself.Utilszenutils.base64utilsa85decodea85encodeb16decodeb16encodeb32decodeb32encodeb32hexdecodeb32hexencodeb64decodeb64encodeb85decodeb85encodedecodedecodebytesencodeencodebytesstandard_b64decodestandard_b64encodeurlsafe_b64decodeurlsafe_b64encodezenutils.baseutilsNullzenutils.cacheutilsReqIdCachecacheget_cached_valuesimple_cachezenutils.cipherutilsBase64EncoderCipherBaseDecryptFailedEncoderBaseHexlifyEncoderIvCipherIvfCipherMappingCipherRawDataEncoderS12CipherS1CipherS2CipherSafeBase64EncoderUtf8Encoderzenutils.dateutilsget_daysget_monthsget_yearszenutils.dictutilsHttpHeadersDictObjectattrgetorsetattrsetchangechangesdeep_mergedifffix_objectignore_none_itemprefix_keyselectto_objecttouchupdatezenutils.errorutilsAccessDeniedAccountDisabledErrorAccountLockedErrorAccountRemovedErrorAccountStatusErrorAccountTemporaryLockedErrorAnotherServiceErrorAppAuthFailedAuthErrorBadParameterBadParameterTypeBadResponseContentBadUserTokenBizErrorBizErrorBaseCacheErrorCaptchaOnlyAllowedOnceCaptchaRequiredCaptchaValidateFailedCastFailedErrorCastToBooleanFailedCastToFloatFailedCastToIntegerFailedCastToNumbericFailedCastToStringFailedClientLostErrorConfigErrorDataErrorDatabaseErrorEventNotRegisteredFormErrorHttpErrorInformalRequestErrorInformalResultPackageInformalResultPackageLogicErrorLoginRequiredMessageQueueErrorMissingConfigItemMissingFieldMissingParameterNetworkErrorNoAccessPermissionErrorNoDeletePermissionErrorNoMatchingRouteFoundNoPermissionErrorNoPermissionToCleanCacheErrorNoReadPermissionErrorNoUpstreamServerAvailabeNoWritePermissionErrorNotSupportedHttpMethodNotSupportedTypeToCastOKParamErrorParseJsonErrorPermissionErrorRepeatedlySubmitFormReqeustForbiddenReqidDuplicateErrorRequestExpiredSYSTEM_ERROR_CODE_MAPPINGServiceErrorStringTooLongStringTooShortSysErrorTargetNotFoundTooLargeRequestErrorTsExpiredErrorTypeErrorUndefinedErrorUserDoesNotExistUserPasswordErrorValueExceedsMaxLimitValueLessThanMinLimitWrongFieldTypeWrongParameterTypeclean_language_nameget_error_infoget_languageset_error_infoset_languagezenutils.fsutilsTemporaryFilecopyexpandfile_content_replacefilecopyfirst_exists_fileget_application_config_filepathget_application_config_pathsget_safe_filenameget_size_deviationget_size_displayget_swap_filenameget_temp_workspaceget_unit_sizeinfomkdirmovepathjoinreadfilerenamermsafe_writesize_unit_namessize_unit_upper_limittouchtreecopywritezenutils.funcutilsBunchCallableChainableProxycall_with_injectchainclasspropertyget_all_builtin_exceptionsget_builtins_dictget_class_nameget_default_valuesget_inject_paramsget_method_helpget_method_signatureinspectis_a_classisclassmcall_with_injectsignaturetry_again_on_errorzenutils.hashutilsBase64ResultEncoderBlake2BHexlifyPasswordHashBlake2BPbkdf2PasswordHashBlake2BPbkdf2PasswordHashColonBlake2BSimplePasswordHashBlake2BSimpleSaltPasswordHashBlake2SHexlifyPasswordHashBlake2SPbkdf2PasswordHashBlake2SPbkdf2PasswordHashColonBlake2SSimplePasswordHashBlake2SSimpleSaltPasswordHashDigestResultEncoderHexlifyPasswordHashBaseHexlifyResultEncoderMd5HexlifyPasswordHashMd5Pbkdf2PasswordHashMd5Pbkdf2PasswordHashColonMd5SimplePasswordHashMd5SimpleSaltPasswordHashPasswordHashMethodBasePasswordHashMethodNotSupportErrorPbkdf2PasswordHashBaseResultEncoderBaseSha1HexlifyPasswordHashSha1Pbkdf2PasswordHashSha1Pbkdf2PasswordHashColonSha1SimplePasswordHashSha1SimpleSaltPasswordHashSha224HexlifyPasswordHashSha224Pbkdf2PasswordHashSha224Pbkdf2PasswordHashColonSha224SimplePasswordHashSha224SimpleSaltPasswordHashSha256HexlifyPasswordHashSha256Pbkdf2PasswordHashSha256Pbkdf2PasswordHashColonSha256SimplePasswordHashSha256SimpleSaltPasswordHashSha384HexlifyPasswordHashSha384Pbkdf2PasswordHashSha384Pbkdf2PasswordHashColonSha384SimplePasswordHashSha384SimpleSaltPasswordHashSha3_224HexlifyPasswordHashSha3_224Pbkdf2PasswordHashSha3_224Pbkdf2PasswordHashColonSha3_224SimplePasswordHashSha3_224SimpleSaltPasswordHashSha3_256HexlifyPasswordHashSha3_256Pbkdf2PasswordHashSha3_256Pbkdf2PasswordHashColonSha3_256SimplePasswordHashSha3_256SimpleSaltPasswordHashSha3_384HexlifyPasswordHashSha3_384Pbkdf2PasswordHashSha3_384Pbkdf2PasswordHashColonSha3_384SimplePasswordHashSha3_384SimpleSaltPasswordHashSha3_512HexlifyPasswordHashSha3_512Pbkdf2PasswordHashSha3_512Pbkdf2PasswordHashColonSha3_512SimplePasswordHashSha3_512SimpleSaltPasswordHashSha512HexlifyPasswordHashSha512Pbkdf2PasswordHashSha512Pbkdf2PasswordHashColonSha512SimplePasswordHashSha512SimpleSaltPasswordHashShaHexlifyPasswordHashShaPbkdf2PasswordHashShaPbkdf2PasswordHashColonShaSimplePasswordHashShaSimpleSaltPasswordHashSimplePasswordHashBaseSimpleSaltPasswordHashBaseSm3HexlifyPasswordHashSm3Pbkdf2PasswordHashSm3Pbkdf2PasswordHashColonSm3SimplePasswordHashSm3SimpleSaltPasswordHashXxh128HexlifyPasswordHashXxh128Pbkdf2PasswordHashXxh128Pbkdf2PasswordHashColonXxh128SimplePasswordHashXxh128SimpleSaltPasswordHashXxh32HexlifyPasswordHashXxh32Pbkdf2PasswordHashXxh32Pbkdf2PasswordHashColonXxh32SimplePasswordHashXxh32SimpleSaltPasswordHashXxh64HexlifyPasswordHashXxh64Pbkdf2PasswordHashXxh64Pbkdf2PasswordHashColonXxh64SimplePasswordHashXxh64SimpleSaltPasswordHashalgorithms_availableget_blake2bget_blake2b_base64get_blake2b_digestget_blake2b_hexdigestget_blake2sget_blake2s_base64get_blake2s_digestget_blake2s_hexdigestget_file_blake2bget_file_blake2b_base64get_file_blake2b_digestget_file_blake2b_hexdigestget_file_blake2sget_file_blake2s_base64get_file_blake2s_digestget_file_blake2s_hexdigestget_file_hashget_file_hash_base64get_file_hash_hexdigestget_file_hash_resultget_file_md5get_file_md5_base64get_file_md5_digestget_file_md5_hexdigestget_file_shaget_file_sha1get_file_sha1_base64get_file_sha1_digestget_file_sha1_hexdigestget_file_sha224get_file_sha224_base64get_file_sha224_digestget_file_sha224_hexdigestget_file_sha256get_file_sha256_base64get_file_sha256_digestget_file_sha256_hexdigestget_file_sha384get_file_sha384_base64get_file_sha384_digestget_file_sha384_hexdigestget_file_sha3_224get_file_sha3_224_base64get_file_sha3_224_digestget_file_sha3_224_hexdigestget_file_sha3_256get_file_sha3_256_base64get_file_sha3_256_digestget_file_sha3_256_hexdigestget_file_sha3_384get_file_sha3_384_base64get_file_sha3_384_digestget_file_sha3_384_hexdigestget_file_sha3_512get_file_sha3_512_base64get_file_sha3_512_digestget_file_sha3_512_hexdigestget_file_sha512get_file_sha512_base64get_file_sha512_digestget_file_sha512_hexdigestget_file_sha_base64get_file_sha_digestget_file_sha_hexdigestget_file_sm3get_file_sm3_base64get_file_sm3_digestget_file_sm3_hexdigestget_file_xxh128get_file_xxh128_base64get_file_xxh128_digestget_file_xxh128_hexdigestget_file_xxh32get_file_xxh32_base64get_file_xxh32_digestget_file_xxh32_hexdigestget_file_xxh64get_file_xxh64_base64get_file_xxh64_digestget_file_xxh64_hexdigestget_hashget_hash_base64get_hash_digestget_hash_hexdigestget_hash_resultget_md5get_md5_base64get_md5_digestget_md5_hexdigestget_password_hashget_password_hash_methodsget_pbkdf2_blake2bget_pbkdf2_blake2sget_pbkdf2_hmacget_pbkdf2_md5get_pbkdf2_shaget_pbkdf2_sha1get_pbkdf2_sha224get_pbkdf2_sha256get_pbkdf2_sha384get_pbkdf2_sha3_224get_pbkdf2_sha3_256get_pbkdf2_sha3_384get_pbkdf2_sha3_512get_pbkdf2_sha512get_pbkdf2_sm3get_pbkdf2_xxh128get_pbkdf2_xxh32get_pbkdf2_xxh64get_salted_hash_base64get_shaget_sha1get_sha1_base64get_sha1_digestget_sha1_hexdigestget_sha224get_sha224_base64get_sha224_digestget_sha224_hexdigestget_sha256get_sha256_base64get_sha256_digestget_sha256_hexdigestget_sha384get_sha384_base64get_sha384_digestget_sha384_hexdigestget_sha3_224get_sha3_224_base64get_sha3_224_digestget_sha3_224_hexdigestget_sha3_256get_sha3_256_base64get_sha3_256_digestget_sha3_256_hexdigestget_sha3_384get_sha3_384_base64get_sha3_384_digestget_sha3_384_hexdigestget_sha3_512get_sha3_512_base64get_sha3_512_digestget_sha3_512_hexdigestget_sha512get_sha512_base64get_sha512_digestget_sha512_hexdigestget_sha_base64get_sha_digestget_sha_hexdigestget_sm3get_sm3_base64get_sm3_digestget_sm3_hexdigestget_xxh128get_xxh128_base64get_xxh128_digestget_xxh128_hexdigestget_xxh32get_xxh32_base64get_xxh32_digestget_xxh32_hexdigestget_xxh64get_xxh64_base64get_xxh64_digestget_xxh64_hexdigestis_the_same_hash_methodmethod_loadnewpbkdf2_hmacregister_hexlify_password_hashregister_password_hash_methodregister_pbkdf2_password_hashregister_simple_password_hashregister_simple_salt_password_hashsetup_hash_method_loadervalidate_password_hashvalidate_pbkdf2_blake2bvalidate_pbkdf2_blake2svalidate_pbkdf2_hmacvalidate_pbkdf2_md5validate_pbkdf2_shavalidate_pbkdf2_sha1validate_pbkdf2_sha224validate_pbkdf2_sha256validate_pbkdf2_sha384validate_pbkdf2_sha3_224validate_pbkdf2_sha3_256validate_pbkdf2_sha3_384validate_pbkdf2_sha3_512validate_pbkdf2_sha512validate_pbkdf2_sm3validate_pbkdf2_xxh128validate_pbkdf2_xxh32validate_pbkdf2_xxh64zenutils.httputilsdownloadget_sitenameget_url_filenameget_url_save_pathget_urlinfourlparsezenutils.importutilsget_caller_globalsget_caller_localsimport_from_stringimport_modulezenutils.jsonutilsSimpleJsonEncodermake_simple_json_encoderregister_global_encodersimple_json_dumpszenutils.listutilsappend_newchunkclean_nonecomparecompare_executefirstgroupignore_none_elementint_list_to_bytesis_orderedlist2dictpadreplacetopological_sorttopological_testuniquezenutils.logutilsget_console_handlerget_file_handlerget_simple_configsetupzenutils.nameutilsget_last_namesget_random_nameget_suggest_first_namesguess_lastnameguess_surnamezenutils.numericutils_infinitybinary_decomposebytes2intsdecimal_change_basefloat_splitfrom_bytesget_float_partinfinityint2bytesints2bytesis_infinityninfinitypinfinityzenutils.packutilsAbstractResultPackerRcmPackerzenutils.perfutilstimeitzenutils.randomutilsLcg31RandomRandomUuidGeneratorchoicesget_password_seed32uuid1uuid3uuid4uuid5zenutils.serviceutilsDebugServiceServiceBasezenutils.sixutilsBASESTRING_TYPESBYTESBYTES_TYPEINT_TO_BYTESNUMERIC_TYPESPY2PY3STR_TYPETEXTbcharbstr_to_arraybytes_to_arraycreate_new_classdefault_encodingdefault_encodingsforce_bytesforce_textunicodezenutils.socketserverutilsNStreamExchangeProtocolBaseServerEngineBaseServerHandlezenutils.strutilsBAIBASE64_CHARSHEXLIFY_CHARSQIANSHIStrUtilsURLSAFEB64_CHARSWANYIbinarifybytes2intscamelcaptital_numberchar_force_to_intchunkcleancombinationscombinations2decodabledefault_cn_digitsdefault_cn_float_placesdefault_cn_negativedefault_cn_placesdefault_cn_yuandefault_encodingdefault_encodingsdefault_quotesdefault_random_string_choicesdo_cleanencodableforce_floatforce_intforce_numbericforce_type_toformat_with_mappingget_all_substringsget_base64imageget_image_byteshtml_element_css_appendint2bytesints2bytesis_base64_decodableis_chinese_characteris_hex_digitsis_str_composed_by_the_choicesis_unhexlifiableis_urlsafeb64_decodableis_uuidjoin_linesno_mappingnone_to_empty_stringparse_base64imagerandom_stringremove_prefixremove_suffixreversesimple_cn_yuansimplesplitsmart_get_binary_datasplitsplit2str_composed_bystringlist_appendstrip_stringsubstringstext_display_lengthtext_display_shortenunbinarifyunquotewholestripzenutils.sysutilsdefault_timeout_killexecute_scriptget_current_thread_idget_node_ipget_random_script_nameget_worker_idpsutil_timeout_killzenutils.threadutilsConcurrentLimitJobQueueCounterFutureJobExecuteTimeoutJobQueueJobResultNotSetLoopIdleServiceServiceStopServiceTerminateSimpleConsumerSimpleProducerSimpleProducerConsumerServerSimpleServerStartOnTerminatedServicezenutils.treeutilsSimpleRouterTreebuild_treeprint_treeprint_tree_callbacktree_walkzenutils.typingutilsNumberSTRING_ENCODINGSregister_global_castersmart_castzenutils.xmlrpcutilsSimpleAuthMixinSimpleAuthSafeTransportSimpleAuthTransportCompatibilityTest passed with python versions:Python 2.7 passedPython 3.2 passedPython 3.3 passedPython 3.4 passedPython 3.5 passedPython 3.7 passedPython 3.8 passedPython 3.9 passedPython 3.10 passedPython 3.11 passedReleasev0.1.0First release.v0.2.0Add treeutils.SimpleRouterTree.Add randomutils.HashPrng.Add hashutils.get_password_hash and hashutils.validate_password_hash.Add dictutils.HttpHeadersDict.Add sysutils.get_node_ip.v0.3.1Add funcutils.retry.Fix hashutils.validate_password_hash problem.v0.3.2Add sm3 hash support in hashutils.Add xxhash hash support in hashutils.Export hashutils.pbkdf2_hmac to work with your self defined hash methods.Fix problem in sysutils.get_random_script_name on windows.Fix path string problem in tests.test_httputils on windows.v0.3.3Fix funcutils.isclass can not detect classes with metaclass. Use inspect.isclass instead.Add cacheutils.cache.v0.3.5Change default log file path frompwd/app.log topwd/logs/app.log.Add fsutils.get_swap_filename.Add fsutils.safe_write.Add fsutils.get_safe_filename.v0.3.6Add sixutils.create_new_class.Fix hashutils problem in python3.3 and below.Extend numericutils.int2bytes as int.to_bytes.V0.3.7Add randomutils.Lcg31Random.Add randomutils.get_password_seed32.v0.3.8Fix force_text in handling NON-STR type data.v0.3.9Add delete_script parameter in fsutils.execute_script.v0.3.12dictutils.Object add select method.Add errorutils.Add packutils.Add perfutils.Add serviceutils.v0.3.15Add serviceutils.ServerEngineBase.v0.3.16Rename serviceutils.ServerEngineBase to socketserverutils.ServerEngineBase.Add socketserverutils.NStreamExchangeProtocolBase.Add ServerHandle.v0.3.19Fix NStreamExchangeProtocolBase makefile buffering problem for py2.7.Fix log format problem in old version python.Add more exception classes in errorutils.Add dateutils.Add errorutils.AuthenticationRequired.v0.3.23Fix logger.error missing msg problem.Add threadutils.ConcurrentLimitJobQueue.v0.4.8Fix *args problem in call_with_inject.Change serviceutils.ServiceBase.register_to.Add cacheutils.ReqIdCache.Add xmlrpcutils.SimpleAuthTransport.Add xmlrpcutils.SimpleAuthSafeTransport.Add threadutils.JobQueue.Add threadutils.Future.Add funcutils.get_method_help.Add funcutils.get_method_signature.v0.4.9Add cacheutils.simple_cache.v0.4.10Fix readme document.Fix pylint warnings.Unit test problems fix.v0.5.0Add sixutils.unicode.v0.5.1Fix logutils default format missing space between thread and module fields.v0.5.2Add hashutils.get_hash_digest.Add log_to_console and log_to_file option in logutils.get_simple_config.
zenv
No description available on PyPI.
zenv-cli
ZenvZenv is container based virtual environments. The main goal of Zenv is to simplify access to applications inside container, making it seamless in use like native (host-machine) applicationsUsage>zenvinit Zenvcreated! ># run `ls` command inside contaner>zelsMotivationAs a developer, when set up a project locally, I usually need to install additional applications on the system. Of course, modern package managers such as poetry, pipenv, npm, cargo, ext, perfectly solve for us most of the problems with dependencies within a single stack of technologies. But they do not allow to solve the problem with the installation of system libraries. If you have a lot of projects that require different versions of system libraries, then you have problemsIn production, this problem has long been solved by container insulation, and as a rule, it is aDocker. Therefore, many of my colleagues use docker-images and docker-compose, not only to run services in a production environment but also to develop and debug programs on a local machineUnfortunately, there are several problems along the way:Some of your familiar utilities may not be preinstalled in the containerIf you try to install packages in the process, you will encounter the lack of necessary rightsForget about debugging withprintThe main thing is lost the usual experience, you can not use your favorite customized shellOf course, the problems described above are solved by creating a docker image specifically for developing a specific project,zenvjust helps to create such containers very simplyFeaturesSimplify: all interaction with the container occurs with one short command:zeZenv automatically forwarded current directory to the container with the same PWDZenv automatically forwarded current UserID, GroupID to containerTherefore, files created in the container have the same rights as those created in the native console and you can also usesudoto get privileges>sudoze<command>or>sudo!!Zenv can forwarded environment vars as is native>MYVAR=LIVE!!!!zeenvAnd of course your could combinate native and containerized commands in Unix pipes>zels|head-7|zetail-5Minimal performance impactCustomization: you can additionally control container parameters using ZenvfileInstallMake sure you have the latest version ofDockerinstalledFor linux, make sure you have your user’srights are allowedto interact with dokerMake sure that you have python version 3.6 or higherExecute:>sudopipinstallzenv-cli# or>sudopip3installzenv-cliHow It worksBy nature, zenv is a small automated layer over the official docker CLIinitCommandzenv initcreateZenvfilein current directory. This file describes the relationship with the docker image and container that will be created to execute isolated commands.By default, used image isubuntu: latest. But you can change it by setting-iflag. For example:>zenvinit-ipython:latestOr editZenvfilemanuallyExecuteCommandzenv exec <COMMAND>or it shot aliasze <COMMAND>run<COMMAND>in a container environment. When running the command:Zenv checks current container status (running, stopped, removed), and up container if need.The container run with the commandsleep infinity. Therefore it will be easily accessibleUID and GID that ran the command are pushed into the container. Therefor your could usesudo ze <COMMAND>When executing the command, the directory from the path where Zenvfile is located is forwarded to the container as is a current PWD. Therefor your could runzefrom deep into directories relative to ZenvfileEnvironment variables are also thrown into the container as a native.> MYVAR=SUPER ze envTo avoid conflicts between host and container variables, all installed system variables are placed in the blacklist when Zenvfile is created, from which editing can be removedOther commands>zenv--help Usage:zenv[OPTIONS]COMMAND[ARGS]...ZENV(Zen-env):ContainersmanagerfordeveloperenvironmentUsage:>zenvinit-icentos:latest&zecat/etc/redhat-release Options:--helpShowthismessageandexit. Commands:execCallsomecommandinsidethecontainerinfoShowcurrentcontainerinfoinitInitializeEnvironment:createZenvfilermRemovecontainer(willstopthecontainer,ifneed)stopStopcontainerstop-allStopallzenvcontainersExample install jupyter notebook>mkgirnotebooks >cdnotebooks >zenvinit-ipython:3.7.3After edit Zenvfile to explode notebook ports. Updateports = []toports = ["8888:8888"]> sudo ze pip install jupyter numpy scipy matplotlibRun notebook> ze jupyter notebook --ip 0.0.0.0launch your browser with url:http://localhost:8888Also you could add this commands to Zenvfile:[run]init_commands=[["__create_user__"],["pip", "install", "jupyter", "numpy", "scipy", "matplotlib"]][commands]notebook=["jupyter","notebook","--ip","0.0.0.0"]And launch notebook with command> ze notebookZenvfile[main]image="ubuntu:latest"name="zenv-project"# container namedebug=false# for show docker commands[run]command=["__sleep__",]init_commands=[["__create_user__",],][exec]env_file=""env_excludes=["TMPDIR",][run.options]volume=["{zenvfilepath}:{zenvfilepath}:rw",]detach="true"publish=[][commands]__sleep__=["sleep","365d",]__create_user__=["useradd","-m","-r","-u","{uid}","-g","{gid}","zenv",]
zenwarch
https://github.com/renzon/zenwarch/
zenyx
ZenyxThe best Python Object Notation library there is.--- documentation coming soon ---Installpython-mpipinstall--upgradezenyx
zenyxheic
zenyxheicConvert HEIC to png, jpg, gif
zenyxvm
zenyxvmThe zenyx version manager packageRequirementsMake sure you have apyproject.tomlfile in your project's root folderUse python 3.7 or newerHow to use?Run the manager:Windows:python-mzenyxvmLinux:python3-mzenyxvm
zeo_connector
IntroductionWrappers, which make working withZEOlittle bit nicer.By default, you have to do a lot of stuff, like create connection to database, maintain it, synchronize it (or running asyncore loop), handle reconnects and so on. Classes defined in this project makes all this work for you at the background.DocumentationThis module defines three classes:ZEOWrapperPrototypeZEOConfWrapperZEOWrapperZEOWrapperPrototypeZEOWrapperPrototypecontains methods and shared attributes, which may be used by derived classes.You can pretty much ignore this class, unless you want to make your own connector.ZEOConfWrapperZEOConfWrappermay be used to create connection to ZEO fromXML configuration file.Lets say you have file/tests/data/zeo_client.conf:<zeoclient>serverlocalhost:60985</zeoclient>You can now create theZEOConfWrapperobject:fromzeo_connectorimportZEOConfWrapperdb_obj=ZEOConfWrapper(conf_path="/tests/data/zeo_client.conf",project_key="Some project key",)and save the data to the database:importtransactionwithtransaction.manager:db_obj["data"]="some data"String"some data"is now saved underdb._connection.root()[project_key]["data"]path.ZEOWrapperZEOWrapperdoesn’t use XML configuration file, but direct server/port specification:fromzeo_connectorimportZEOWrapperdifferent_db_obj=ZEOWrapper(server="localhost",port=60985,project_key="Some project key",)So you can retreive the data you stored into the database:importtransactionwithtransaction.manager:printdifferent_db_obj["data"]Running the ZEO serverThe examples expects, that the ZEO server is running. To run the ZEO, look at the help page of therunzeoscript which is part of the ZEO bundle. This script requires commandline or XML configuration.You can generate the configuration files using providedzeo_connector_gen_defaults.pyscript, which is part of thezeo_connector_defaults <https://github.com/Bystroushaak/zeo_connector_defaults>package:$ zeo_connector_gen_defaults.py --help usage: zeo_connector_gen_defaults.py [-h] [-s SERVER] [-p PORT] [-C] [-S] [PATH] This program will create the default ZEO XML configuration files. positional arguments: PATH Path to the database on the server (used in server configuration only. optional arguments: -h, --help show this help message and exit -s SERVER, --server SERVER Server url. Default: localhost -p PORT, --port PORT Port of the server. Default: 60985 -C, --only-client Create only CLIENT configuration. -S, --only-server Create only SERVER configurationFor example:$ zeo_connector_gen_defaults.py /tmpwill createzeo.conffile with following content:<zeo>addresslocalhost:60985</zeo><filestorage>path/tmp/storage.fs</filestorage><eventlog>levelINFO<logfile>path/tmp/zeo.logformat%(asctime)s%(message)s</logfile></eventlog>andzeo_client.confcontaining:<zeoclient>serverlocalhost:60985</zeoclient>You can change the ports and address of the server using--serveror--portarguments.To run the ZEO with the server configuration file, run the following command:runzeo -C zeo.confTo run the client, you may useZEOConfWrapper, as was show above:fromzeo_connectorimportZEOConfWrapperdb_obj=ZEOConfWrapper(conf_path="./zeo_client.conf",project_key="Some project key",)InstallationModule ishosted at PYPI, and can be easily installed usingPIP:sudo pip install zeo_connectorSource codeProject is released under the MIT license. Source code can be found at GitHub:https://github.com/Bystroushaak/zeo_connectorUnittestsYou can run the tests using providedrun_tests.shscript, which can be found in the root of the project.If you have any trouble, just add--pdbswitch at the end of yourrun_tests.shcommand like this:./run_tests.sh--pdb. This will drop you toPDBshell.RequirementsThis script expects that packagepytestis installed. In case you don’t have it yet, it can be easily installed using following command:pip install --user pytestor for all users:sudo pip install pytestExample$ ./run_tests.sh ============================= test session starts ============================== platform linux2 -- Python 2.7.6 -- py-1.4.30 -- pytest-2.7.2 rootdir: /home/bystrousak/Plocha/Dropbox/c0d3z/python/libs/zeo_connector, inifile: plugins: cov collected 7 items tests/test_zeo_connector.py ....... =========================== 7 passed in 7.08 seconds ===========================Changelog0.4.8ZEO version un-pinned. Will continue inhttps://github.com/zopefoundation/ZEO/issues/770.4.7Pinned older version of ZEO.0.4.6Cleanup of metadata files.0.4.0 - 0.4.5Added@retry_and_resetdecorator for all internal dict-methods calls.Project key is now optional, so this object may be used to access the root of the database.PropertyASYNCORE_RUNNINGrenamed to_ASYNCORE_RUNNING.Implemented.pack().Added@transaction_manager.Addedexamples/database_handler.pyand tests.Added @wraps(fn) to decorators.Added requirement for zope.interface.Attempt to solvehttps://github.com/WebArchivCZ/WA-KAT/issues/860.3.0Environment generator and other shared parts moved tohttps://github.com/Bystroushaak/zeo_connector_defaultsREADME.rst improved, added more documentation and additional sections.0.2.0Added standard dict methods, like.__contains__(),.__delitem__(),.__iter__()and so on.0.1.0Project created.
zeo_connector_defaults
IntroductionDefault configuration files and configuration file generator forzeo_connector.DocumentationThis project provides generators of the testing environment for the ZEO-related tests. It also provides generator, for the basic ZEO configuration files.zeo_connector_gen_defaults.pyThis script simplifies the process of generation of ZEO configuration files.ZEO testsTypically, when you test your program which is using the ZEO database, you need to generate the database files, then run new thread withrunzeoprogram, do tests, cleanup and stop the thread.This module provides two functions, which do exactly this:zeo_connector_defaults.generate_environment()zeo_connector_defaults.cleanup_environment()generate_environmentThis function will create temporary directory in/tmpand copy template files for ZEO client and server into this directory. Then it starts new thread withrunzeoprogram using the temporary server configuration file.Names of the files may be resolved usingtmp_context_name()function.Note:This function works best, if added to setup part of your test environment.cleanup_environmentFunction, which stops the runningrunzeothread and delete all the temporary files.Note:This function works best, if added to setup part of your test environment.Context functionsThere is also twotemp environment access functions:tmp_context_name()tmp_context()Both of them take onefnargument and return name of the file (tmp_context_name()) or content of the file (tmp_context()) in context of random temporary directory.For example:tmp_context_name("zeo_client.conf")returns the absolute path to the filezeo_client.conf, which may be for example/tmp/tmp1r5keh/zeo_client.conf.You may also call it without the arguments, which will return just the name of the temporary directory:tmp_context_name()which should return something like/tmp/tmp1r5keh.Tests exampleHere is the example how your test may look like:#! /usr/bin/env python# -*- coding: utf-8 -*-## Interpreter version: python 2.7## Imports =====================================================================importpytestfromzeo_connector_defaultsimportgenerate_environmentfromzeo_connector_defaultsimportcleanup_environmentfromzeo_connector_defaultsimporttmp_context_name# Setup =======================================================================defsetup_module(module):generate_environment()defteardown_module(module):cleanup_environment()# Fixtures ====================================================================@pytest.fixturedefzeo_conf_wrapper():returnZEOConfWrapper(conf_path=tmp_context_name("zeo_client.conf"),...# Tests =======================================================================deftest_something(zeo_conf_wrapper):...InstallationModule ishosted at PYPI, and can be easily installed usingPIP:sudo pip install zeo_connector_defaultsSource codeProject is released under the MIT license. Source code can be found at GitHub:https://github.com/Bystroushaak/zeo_connector_defaultsChangelog0.2.2Small bugfix.Removed unused files.0.2.1Switched to complete randomly generated ZEO environment (random name in /tmp, and random ports for ZEO server process).0.2.0Bugfix of path parsing.0.1.0Project created.
zeoliteclusterizer
UNKNOWN
zeomega.recipe.mxodbcconnect
A buildout recipe to install eGenix mx.ODBCConnect.Client
zeonapi
UNKNOWN
zeo-utils
Utilities for ZEO++
zep2md
No description available on PyPI.
zepben.auth
Zepben Auth LibraryThis library provides Authentication mechanisms for Zepben SDKs used with Energy Workbench and other Zepben services.Typically this library will be used by the SDKs to plug into connection mechanisms. It is unlikely that end users will need to use this library directly.Usagefromzepben.auth.clientimportcreate_token_fetcherauthenticator=create_token_fetcher("https://localhost/auth")authenticator.token_request_data.update({{"grant_type":"password","username":"<username>","password":"<password>","scope":"offline_access openid profile email","client_id":"<client_id>"}})authenticator.refresh_request_data.update({"grant_type":"refresh_token","scope":"offline_access openid profile email","client_id":"<client_id>"})token=authenticator.fetch_token()
zepben.cimbend
Zepben Evolve Python SDKThe Python Evolve SDK contains everything necessary to communicate with aZepben EWB Server. See thearchitecturedocumentation for more details.ote this project is still a work in progress and unstable, and breaking changes may occur prior to 1.0.0.RequirementsPython 3.7 or laterpycryptodome, which requires a C/C++ compiler to be installed. On Linux, python headers (typicallypython-dev) is also necessary to build pycryptodome.On Windows systems:Download and runBuild Tools for Visual Studio 2019When in the installer, select and install:C++ build toolsWindows 10 SDKThe latest version of MSVC v142 x64/x86 build tools.After this you should be able topip install zepben.cimbendwithout issues.Installationpip install zepben.cimbendBuildingpython setup.py bdist_wheelDevelopingThis library depends on protobuf and gRPC for messaging. To set up for developing against this library, clone it first:git clone https://github.com/zepben/evolve-sdk-python.gitInstall as an editable install. It's recommended to install in aPython virtualenvcd evolve-sdk-python pip install -e .[test]Run the tests:python -m pytest
zepben.eas
Evolve App Server Python ClientThis library provides a wrapper to the Evolve App Server's API, allowing users of the evolve SDK to authenticate with the Evolve App Server and upload studies.UsagefromgeojsonimportFeatureCollectionfromzepben.easimportEasClient,Study,Result,Section,GeoJsonOverlayeas_client=EasClient(host="<host>",port=1234,client_id="<client_id>",username="<username>",password="<password>",client_secret="<client_secret>")eas_client.upload_study(Study(name="<study name>",description="<study description>",tags=["<tag>","<tag2>"],results=[Result(name="<result_name>",geo_json_overlay=GeoJsonOverlay(data=FeatureCollection(...),styles=["style1"]),sections=Section(type="TABLE",name="<table name>",description="<table description>",columns=[{"key":"<column 1 key>","name":"<column 1 name>"},{"key":"<column 2 key>","name":"<column 2 name>"},],data=[{"<column 1 key>":"<column 1 row 1 value>","<column 2 key>":"<column 2 row 1 value>"},{"<column 1 key>":"<column 1 row 2 value>","<column 2 key>":"<column 2 row 2 value>"}]))],styles=[{"id":"style1",# other Mapbox GL JS style properties}]))eas_client.close()AsyncIOAsyncio is also supported using aiohttp. A session will be created for you when you create an EasClient if not provided via thesessionparameter to EasClient.To use the asyncio API useasync_upload_studylike so:fromaiohttpimportClientSessionfromgeojsonimportFeatureCollectionfromzepben.easimportEasClient,Study,Result,Section,GeoJsonOverlayasyncdefupload():eas_client=EasClient(host="<host>",port=1234,client_id="<client_id>",username="<username>",password="<password>",client_secret="<client_secret>",session=ClientSession(...))awaiteas_client.async_upload_study(Study(name="<study name>",description="<study description>",tags=["<tag>","<tag2>"],results=[Result(name="<result_name>",geo_json_overlay=GeoJsonOverlay(data=FeatureCollection(...),styles=["style1"]),sections=Section(type="TABLE",name="<table name>",description="<table description>",columns=[{"key":"<column 1 key>","name":"<column 1 name>"},{"key":"<column 2 key>","name":"<column 2 name>"},],data=[{"<column 1 key>":"<column 1 row 1 value>","<column 2 key>":"<column 2 row 1 value>"},{"<column 1 key>":"<column 1 row 2 value>","<column 2 key>":"<column 2 row 2 value>"}]))],styles=[{"id":"style1",# other Mapbox GL JS style properties}]))awaiteas_client.aclose()
zepben.edith
Extension functions for interacting with the EWB
zepben.evolve
Zepben Evolve Python SDKThe Python Evolve SDK contains everything necessary to communicate with aZepben EWB Server. See the completeEvolve Python SDK Documentationfor more details.Note this project is still a work in progress and unstable, and breaking changes may occur prior to 1.0.0.RequirementsPython 3.7 or laterInstallationpip install zepben.evolveBuildingpython setup.py bdist_wheelUsageSeeEvolve Python SDK Documentation.
zepben.evolve.test-ci-central
Zepben Evolve Python SDKThe Python Evolve SDK contains everything necessary to communicate with aZepben EWB Server. See the completeEvolve Python SDK Documentationfor more details.Note this project is still a work in progress and unstable, and breaking changes may occur prior to 1.0.0.RequirementsPython 3.7 or laterInstallationpip install zepben.evolveBuildingpython setup.py bdist_wheelUsageSeeEvolve Python SDK Documentation.