package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
zpm
Supported Python versions: 2.6, 2.7, 3.3, and 3.4.ZPM is a package manger forZeroVM. You use it to create and deploy ZeroVM applications ontoZeroCloud.DocumentationThe documentation is hosted atdocs.zerovm.org.InstallationYou can installzpmusingpip:$ pip install zpmContactPlease use thezerovm mailing liston Google Groups for anything related to zpm. You are also welcome to come by#zerovm on irc.freenode.netwhere the developers can be found.Changelog0.3 (2014-10-22):This release adds new features and fixes bugs. The main change is that it is now possible to leave out theuikey from the zapp configuration. Before that would signal that the default web interface should be generated byzpm deploy, it now means no web interface. To get the default interface, specify–with-uiwhen runningzpm new.Issues closed since 0.2.1:#109: Add web frontend as an option ofzpm new, don’t generate it onzpm bundle.#131:zpm deploy -l debugshould include request/response data.#157: Ubuntu package: install requirespython-swiftclient.#158: Ubuntu package: update changelog for version 0.2.#167:index.htmltemplate rendering was broken.#173: Deduce auth version from environment variables.#177: Allow user to force deployment to a non-empty container withzpm deploy.#180: Add X-Nexe-Cdr-Line parsing and display.#183: Addzpm authcommand for getting storage url and auth token.0.2.1 (2014-07-20):This release fixes some minor packaging and distribution issues, as well as some of the behavior of thedeploycommand:python-swiftclientis now an explicit dependencysetup.pyusessetuptoolsinstead ofdistutilsdeploy: show full URL to the deployed index.htmldeploy: set correct content type for zapp filesdeploy: better management of containers (automatically create containers if not existing, don’t allow deployment to a non-empty container)0.2 (2014-06-30):This release drops support for Python 3.2 due to the lack ofu"..."literals in that version. Other issues fixed:#20: Set up Debian packaging for zpm.#31: Usepython-swiftclientinstead ofrequestsfor interacting with Swift.#37: Added azpm executecommand.#119:zpm bundledid not raise errors when files in the bundling list don’t exist.#122: Somezpm deployreferences were not rendering correctly in the documentation.#132: Only process UI files ending in.tmplas Jinja2 templates.0.1 (2014-05-21):First release.
zpodcli
Failed to fetch description. HTTP Status Code: 404
zpodsdk
Failed to fetch description. HTTP Status Code: 404
zpoolparty
zpoolparty: Execute ZFS dataset commands transparently across pools/hostsThe command syntax is the same as the standard “zfs” command, except that instead of specifying datasets in pool/filesystem[@snapshot] form, you can prepend host:. For example,$ zpoolparty snapshot bos:mypool/work@todayis translated into$ ssh bos zfs snapshotmypool/work@todayA single command can reference filesystems on multiple hosts. For example,$ zpoolparty get mountpoint mypool/foo bos:mypool/work lax:mypool/playis, in turn, translated into three commands, run sequentially:$ zfs get mountpoint mypool/foo $ ssh bos zfs get mountpoint mypool/work $ ssh lax zfs get mountpoint mypool/play
zpool-status
zpool-statusParse output from thezpool statusZFS command in Python.AboutThis project contains:A Python modulezpool_status.pythat convertszpool statusoutput into a Python datastructure.A Python scriptzpool-statusthat serves as a drop-in replacement for thezpool statuscommand that produces JSON output.InstallInstallzpool-statususing pip:$pipinstallzpool-statusCommand-line interfaceThezpool-statusscript provides a command-line interface that is identical to the one ofzpool-status(1). The only difference is thatzpool-statusproduces JSON output.zpool-status [-c [script1[,script2]...]] [-igLpPstv] [-T d|u] [pool] ... [interval [count]][!NOTE] The-Dand-xoptions are not supported.ExampleSuppose we get the following output fromzpool status:$ zpool status -v tank pool: tank state: UNAVAIL status: One or more devices are faulted in response to IO failures. action: Make sure the affected devices are connected, then run 'zpool clear'. see: http://www.sun.com/msg/ZFS-8000-HC scrub: scrub completed after 0h0m with 0 errors on Tue Feb 2 13:08:42 2010 config: NAME STATE READ WRITE CKSUM tank UNAVAIL 0 0 0 insufficient replicas c1t0d0 ONLINE 0 0 0 c1t1d0 UNAVAIL 4 1 0 cannot open errors: Permanent errors have been detected in the following files: /tank/data/aaa /tank/data/bbb /tank/data/cccThe following shell command line:$zpool-status-vtankis identical to the this Python code:importjsonfromzpool_statusimportZPoolzpool=ZPool("tank",options=["-v"])status=zpool.get_status()print(json.dumps(status,indent=2))Both produce this output:{"pool":"tank","state":"UNAVAIL","status":"One or more devices are faulted in response to IO failures.","action":"Make sure the affected devices are connected, then run 'zpool clear'.","see":"http://www.sun.com/msg/ZFS-8000-HC","scrub":"scrub completed after 0h0m with 0 errors on Tue Feb 2 13:08:42 2010","config":[{"name":"tank","state":"UNAVAIL","read":0,"write":0,"cksum":0,"message":"insufficient replicas","type":"pool","devices":[{"name":"c1t0d0","state":"ONLINE","read":0,"write":0,"cksum":0,"type":"device"},{"name":"c1t1d0","state":"UNAVAIL","read":4,"write":1,"cksum":0,"message":"cannot open","type":"device"}]}],"errors":["Permanent errors have been detected in the following files:","","/tank/data/aaa","/tank/data/bbb","/tank/data/ccc"]}
zpov
A minimalist note engine~500 lines of codeno javascriptusable on any browser, including on mobileno database, just a bare git repo for storage and synchttp basic authpages are markdown files in the git repo. earch “directory”musthave anindex.mdat the toptitle of each page is the top line of the markdown filesub-pages are sorted alphabeticallyedition is a text area containing the markdownUsagezpovis a python application built usingflask. refer to the flask documentation to learn about developement and/or debugging.zpovneeds a git repository and a configuration file to work. If public access is not wanted, users and passwords must be stored in the configuration file too.To ease up installation, azpov-adminCLI is provided in thezpovpackage:zpov-admin init [--public-access ] /path/to/empty/directory zpov-admin add-user --login LOGIN --name NAME --email EMAIL --password PASSWORD
zpp
zppThis is zpp, the Z Pre-Processor.Zpp transforms bash in a pre-processor for F90 source files. It offers a set of functions specifically tailored to build clean Fortran90 interfaces by generating code for all types, kinds, and array ranks supported by a given compiler.SyntaxZpp files are typically named*.F90.zpp.In these files, the lines that start with!$SHare interpreted as bash lines. Other lines are copied as-is, except that variable substitution is operated as in a double-quoted string, including bash commands${VAR}or$(command). If inside a bash control block (if,for, etc.), the output generation obeys the control statement.For example, this code:!$SH for GREETED in world universe multiverse ; do print *, "Hello ${GREETED}" !$SH doneWould produce the following result:print *, "Hello world" print *, "Hello universe" print *, "Hello multiverse"Support functionsPredefined bash functions, variable and code can be provided in.zpp.shfiles that can be included with#!SH source <filename>.zpp.sh.Beware: a file NEEDs to have the.zpp.shextension to be included from zpp.Zpp provides a standard library of functions tailored to build clean Fortran90 interfaces by generating code for all types, kinds, and array ranks supported by a given compiler.zpp_str_repeatFound inbase.zpp.shOutputs a string multiple times.Parameters:the string to Repeatthe lower bound of the iterations (inclusive)the upper bound of the iterations (inclusive)the string separatorthe string starterthe string enderRepeats string$1($3-$2+1) times, separated by string$4inside$5$6.If the number of repetitions is negative, the result is empty.If$1contains the '@N' substring, it will be replaced by the iteration number (from$2to$3).example:#!SH source base.zpp.sh zpp_str_repeat v@N 5 7 '...' '<<' '>>' zpp_str_repeat w@N 1 1 '...' '<<' '>>' zpp_str_repeat x@N 1 0 '...' '<<' '>>'output:<<v5...v6...v7>> <<w1>>zpp_str_repeat_reverseFound inbase.zpp.shOutputs a string multiple times in reverse order.Parameters:the string to Repeatthe upper bound of the iterations (inclusive)the lower bound of the iterations (inclusive)the string separatorthe string starterthe string enderRepeats string$1($2-$3+1) times, separated by string$4inside$5$6.If the number of repetitions is negative, the result is empty.If$1contains the '@N' substring, it will be replaced by the iteration number (from$2to$3, i.e. upper to lower).example:#!SH source base.zpp.sh zpp_str_repeat_reverse v@N 5 7 '...' '<<' '>>' zpp_str_repeat_reverse w@N 1 1 '...' '<<' '>>' zpp_str_repeat_reverse x@N 1 0 '...' '<<' '>>'output:<<v7...v6...v5>> <<w1>>ZPP_FORT_TYPESFound infortran.zpp.shThe list of types supported by the fortran compiler as zpp:typeIDs.The compiler ID should be provided inZPP_CONFIGasconfig.<ID>. The supported predefined IDs are:Gnu,Intel,PGIandXL. You can also provide definitions for an additional compiler by definingZPP_FORT_TYPESin a file namedconfig.<ID>.zpp.sh.If you use cmake, it will automatically generate such a file for your compiler and defineZPP_CONFIGso you don't have to handle it.zpp_fort_array_descFound infortran.zpp.shOutputs an assumed shaped array descriptor of the provided size.Parameters:the size of the assumed shaped arrayexample:#!SH source fortran.zpp.sh integer:: scalar$(zpp_fort_array_desc 0) integer:: array1d$(zpp_fort_array_desc 1) integer:: array2d$(zpp_fort_array_desc 2)output:integer:: scalar integer:: array1d(:) integer:: array2d(:,:)zpp_fort_ptypeFound infortran.zpp.shOutputs the type associated to a zpp:typeID.Parameters:a zpp:typeIDexample:#!SH source fortran.zpp.sh !$SH for T in ${ZPP_FORT_TYPES} ; do $(zpp_fort_ptype $1) !$SH doneexample output:CHARACTER COMPLEX COMPLEX INTEGER INTEGER INTEGER INTEGER LOGICAL REAL REALzpp_fort_kindFound infortran.zpp.shOutputs the kind associated to a zpp:typeID.Parameters:a zpp:typeIDexample:#!SH source fortran.zpp.sh !$SH for T in ${ZPP_FORT_TYPES} ; do $(zpp_fort_kind $1) !$SH doneexample output:1 4 8 1 2 4 8 1 4 8zpp_fort_typeFound infortran.zpp.shOutputs the full type (with kind included) associated to a zpp:typeID.Parameters:a zpp:typeIDadditional attributes for the typeexample:#!SH source fortran.zpp.sh !$SH for T in ${MY_CHAR_TYPES} ; do $(zpp_fort_type $1) $(zpp_fort_type $1 "len=5") !$SH doneexample output:CHARACTER(KIND=1) CHARACTER(KIND=1,len=5)zpp_fort_sizeofFound infortran.zpp.shOutputs the size in bits associated to a zpp:typeID.Parameters:a zpp:typeIDzpp_fort_io_formatFound infortran.zpp.shOutputs an IO descriptor suitable for a zpp:typeID.Parameters:a zpp:typeIDZPP_HDF5F_TYPESFound inhdf5_fortran.zpp.shA list of zpp:typeIDs supported by HDF5.hdf5_constantFound inhdf5_fortran.zpp.shOutputs the HDF5 type constant associated to a zpp:typeID.Parameters:a zpp:typeIDexample:#!SH source hdf5_fortran.zpp.sh !$SH for T in ${ZPP_HDF5F_TYPES} ; do $(hdf5_constant $1) !$SH doneexample output:H5T_NATIVE_INTEGER H5T_NATIVE_REAL H5T_NATIVE_REAL H5T_NATIVE_CHARACTERCommand-line interfaceZpp basic usage is as follow:Usage: zpp [Options...] <source> [<destination>] use `zpp -h' for more info Preprocesses BASH in-line commands in a source file Options: --version show program's version number and exit -h, --help show this help message and exit -I DIR Add DIR to search list for source directives -o FILE Place the preprocessed code in file FILE. -D OPTION=VALUE Set the value of OPTION to VALUECMake interfaceSupport is provided for using zpp from CMake based projects, but you can use it from plain Makefiles too.There are two ways you can use zpp from your CMake project:withadd_subdirectory: include zpp in your project and use it directly from there,withfind_package: install zpp and use it as an external dependency of your project.CMake subdirectory usageUsing zpp withadd_subdirectoryis very simple. Just copy thezppdirectory in your source and point to it withadd_subdirectory(zpp). Thezpp_preprocessthen becomes available to process zpp files.This is demonstrated inexample/cmake_subdirectory.CMake find usageUsing zpp withfind_packageis no more complex. If zpp is installed, just add afind_package(zpp REQUIRED). Thezpp_preprocessthen becomes available to process zpp files.This is demonstrated inexample/cmake_find.GMake usageUsing zpp from a GNU Makefile is slightly less powerful than from CMake. The types and kinds supported by the Fortran compiler will not be automatically detected. Predefined lists of supported types for well known compilers are provided instead.To use zpp from a Makefile, include theshare/zpp/zpp.mkfile (either from an installed location or from a subdirectory in your project). You can then set thezpp_COMPILER_IDvariable to the compiler you use and.F90files will be automatically generated from their.F90.zppequivalent. ThezppFLAGSvariable is automatically passed to zpp similarly toCFLAGSorCXXFLAGSforccandcxx.This is demonstrated inexample/cmake_makefile.InstallationZpp can be installed using the usual python way withsetup.py../setup.py --helpThe cmake approach is deprecated.FAQQ. Isn't zpp redundant with assumed type parameters?A. The assumed type parameters functionality allows to implement part of what can be done with zpp (support for all kinds of a type). However as of 2013 it was not correctly supported on most compilers installed on the supercomputers.In addition, many things can be done with zpp but not with assumed type parameters, such as support for variable array rank or small variations of the code depending on the kind.
zppan
UNKNOWN
zpp_args
zpp-argsInformationsModule pour le traitement des arguments d'une ligne de commande.Trois sources possibles:sys.argvune chaîne de caractèreune listePrérequisPython 3Installationpip install zpp_argsUtilisationConseil d'importation du modulefromzpp_argsimportparserInitialisation du parserparse=parser(SOURCE,error_lock=False)En paramètre supplémentaire, nous pouvons mettre:error_lock: Purge le retour de la fonction si une erreur s'est produite (Par défaut: False)Initialisation des argumentsparse.set_argument(NAME)L'initialisation doit prendre au moins un des deux paramètres suivants:shortcut: Pour les arguments courts (1 caractère)longname: Pour les arguments explicites (1 mot ou ensemble de mots séparés par le symbole _)Si non précisé, la fonction initialise shortcutEn paramètre supplémentaire, nous pouvons mettre:error_lock: Purge le retour de la fonction si une erreur s'est produite (Par défaut: )type: Pour forcer l'argument reçu à un str ou un digit (Par défaut: None)default: Pour choisir une valeur par défaut(Par défaut: None)description: Pour ajouter une description à l'argument à afficher lors de l'appel de la commande help(Par défaut: None)required: Choisir si cet argument est nécessaire (Par défaut: False)store: Choisir si l'argument' est un simple True/False ou s'il attends une variable (Par défaut: bool)category: Choisir une catégorie pour l'affichage du helpInitialisation des paramètresL'initialisation des paramètres va permettre d'agrémenter la commande help et de fixer une limite minimum lors de la récupération des paramètresparse.set_argument(NAME)En paramètre supplémentaire, nous pouvons mettre:description: Pour ajouter une description au paramètre à afficher lors de l'appel de la commande help(Par défaut: None)Execution du parseurargument,parameter=parse.load()Retourne une liste avec les paramètres et une classe (StoreArgument) avec les arguments La StoreArgument peut retourner un dictionnaire en appelant argument.list_all()Initialisation de la description de la commandeparse.set_description(DESCRIPTION)Affichage de l'aideparse.help()Désactiver le check sur les paramètresPour désactiver le check du nombre de paramètres à envoyer, il suffit d'appeler la fonction suivante.parse.disable_check()
zpp-browser
zpp-browserInformationsLibrairie pour l'utilisateur d'un explorateur de fichier en cli pour la sélection d'un fichierPrérequisPython 3Installationpip install zpp_browserUtilisationConseil d'importation du modulefromzpp_browserimportBrowserInitialisaton du browserc=Browser("Chemin_de_depart")En paramètre supplémentaire, nous pouvons mettre:Filter: Permet de filtrer sur une liste d'extension de fichier. (Par défaut: ne filtre pas)ShowHidden: Afficher les fichiers et dossiers cachés. True ou False (Par défaut: True)ShowDir: Afficher les dossiers. True ou False (Par défaut: True)ShowFirst: Choisir si on souhaite afficher les dossiers ou les fichiers en premier. dir, file ou None (Par défaut: dir)Color: Permet de configurer la colorisation des fichiers en fonction de l'extensions (Voir annexe pour la configuration)Pointer: Choisir un pointer custom (Par défaut: " >")Padding: Choisir la taille de la marge à gauche (Par defaut: 2)Configuration des couleursIl est possible d'envoyer à la fonction une liste de couleur pour permettre de customiser l'affichage des fichiers en fonction de leur extension. Pour cela, la fonction attends une liste à 2 dimensions contenant [extension, couleur du texte, couleur de fond]Pour l'extension il suffit de mettre le nom. Par exemple, .txt pour les fichiers txt Cas particulier pour la configuration de certains éléments:__default__: Pour la couleur par défaut__hidden__: Pour les fichiers et dossiers cachés__dir__: Pour les dossiers__selected__: Pour l'élément sélectionnéDans le cas où on veut configurer plusieurs extensions avec la même couleur, il suffit de mettre une virgule entre le nom des extensions. Exemple:['.crt,.pfx,.key,.txt','yellow','black']Exemple de liste de couleur[['__default__','white','black'],['__hidden__','red','black'],['__selected__','red','black'],['__dir__','green','black'],['.crt,.pfx,.key,.txt','yellow','black']]
zpp-color
zpp-colorInformationsLibrairie pour la colorisation de texte dans un terminal.Permet de modifier la couleur du texte, la couleur de fond et le style.Prise en charge de 256 couleurs.Sélection de la couleur avec le nom, l'id ou une combinaison RGBPrérequisPython 3Installationpip install zpp_colorUtilisationConseil d'importation du modulefromzpp_colorimportfg,bg,attrModification de la couleur du texteAvec le nomprint(f"{fg('blue')}Ceci est un texte en bleu{attr(0)}")Avec l'idprint(f"{fg(3)}Ceci est un texte en bleu{attr(0)}")Avec un code RGBprint(f"{fg('0,0,255')}Ceci est un texte en bleu{attr(0)}")NOTE:Toujours rajouter attr(0) à la fin du texte, sinon la couleur s'appliquera pour les lignes suivantes.Modification de la couleur de fondAvec le nomprint(f"{bg('red')}Ceci est un texte avec un fond rouge{attr(0)}")Avec l'idprint(f"{bg(1)}Ceci est un texte avec un fond rouge{attr(0)}")Avec un code RGBprint(f"{bg('255,0,0')}Ceci est un texte avec un fond rouge{attr(0)}")Modification du style du texteAvec le nomprint(f"{attr('italic')}Ceci est un texte en italic{attr(0)}")Avec l'idprint(f"{attr(3)}Ceci est un texte en italic{attr(0)}")Lister les possibilitésLister les couleurs possibleszpp_color.list_fg()zpp_color.list_bg()Lister les styles possibleszpp_color.list_attr()
zpp_config
zpp-configInformationsLibrairie pour l'utilisation et la modification de fichier de configuration:Charger un ou plusieurs paramètresModifier un paramètre existantAjout un paramètre ou une sectionSupprimer un paramètre ou une sectionLister les sections disponiblesLister les paramètres et/ou sections désactivésPrends en compte les paramètres commentés.Compatible avec les fichiers de configuration indentés.Traduit les paramètres pour les types str, int, float, bool, list, dictPrérequisPython 3Installationpip install zpp_configUtilisationConseil d'importation du modulefromzpp_configimportConfigExemple de fichier de config[section]value1=key1value2=key2value3=key3 [section2]value1=key1value2=key2value3=key3Initialisaton d'un fichier de configurationc=Config("conf.ini")En paramètre supplémentaire, nous pouvons mettre:separator: Définir le séparateur entre la clé et la valeur dans le fichier. (Par défaut: " = ")escape_line: Définir le caractère utilisé pour commenter une valeur ou une section. (Par défaut: "#")auto_create: Créer le fichier de configuration s'il n'existe pas. (Par défaut: "False")read_only: Ouvrir le fichier de configuration en lecture seule. (Par défaut: "False")Chargement de paramètreLa fonction renvoie la valeur si un unique paramètre a été trouvé, sinon renvoie un dictionnaire avec les différentes valeurs trouvées (classé par section) Renvoie un tableau vide si aucun paramètre n'a été trouvéChargement de tous les paramètresdata=c.load()Chargement d'une section du fichierdata=c.load(section='section_name')Chargement d'une valeur dans tout le fichierdata=c.load(val='value_name')Chargement d'une valeur dans une section spécifiquedata=c.load(val='value_name',section='section_name')En paramètre supplémentaire, nous pouvons mettre:default: Pour initialiser une valeur par défaut si aucun résultat est trouvéChangement de paramètreChangement d'une valeur dans tout le fichierc.change(val='value_name',key='key_value')Changement d'une valeur dans une section spécifiquec.change(val='value_name',key='key_value',section='section_name')Ajout de paramètre ou de sectionAjoute une section ou un paramètre dans le fichier de configuration. Dans le cas de l'ajout d'un paramètre, rajoute la section si elle n'existe pas.Ajout d'une sectionc.add(section='section_name')Ajout d'un paramètre dans une sectionc.add(val='value_name',key='key_value',section='section_name')Si aucune section est défini, rajoute le paramètre en dehors des sections.Suppression de paramètre ou de sectionSuppression d'une sectionc.delete(section='section_name')Suppression d'un paramètre dans une sectionc.delete(val='value_name',section='section_name')Si aucune section est défini, recherche le paramètre en dehors des sections.Liste des paramètres non pris en compteRetourne la liste des paramètres qui sont non pris en compte dans le fichier de configuration.data=c.disabled_line()Possibilité de préciser la section en utilisant le paramètre sectionListe les sections disponiblesdata=c.list_section()
zpp-logs
zpp-logsInformationsModule pour la gestion des logs (à l'image de logging) avec des tuning personnalisés par niveau de logsPrérequisPython 3Installationpip install zpp-logsUtilisationLoggerUn logger est un objet qui permet de définir des options (handler, formatter, filter) pour un log.fromzpp_logsimportLoggerlog=Logger()Il est possible de lui donner en paramètre un fichier de configuration au format yaml pour configurer directement les différentes optionsfromzpp_logsimportLoggerlog=Logger(configfile='config.yaml')Exemple de fichier yaml:formatters: standard: format: "%(fore:deep_sky_blue_3a)%[%(date:%d/%m/%Y %H:%M:%S)%]%(attr:0)% - %(fore:medium_purple_4)%%(levelname)%%(attr:0)% - %(fore:grey_46)%%(msg)%%(attr:0)%" test: format: "%(epoch)% - %(msg)%" filters: testfunc: test3.test handlers: console: class: zpp_logs.Console_handler level: zpp_logs.CRITICAL ops: "<" formatter: test output: sys.stdout logger: handlers: [console] filters: [testfunc]Dans un Logger, nous pouvons ajouter/supprimer des handler et des filtres, afficher le compteur de log et appeler les méthodes de log. Toutes ces options sont détaillées dans la suite.HandlerDifférents handler sont disponibles pour permettre d'envoyer les logs dans la console, dans un fichier ou par mail. Tous les handler disposent des méthodes:setFormatter()pour ajouter un formattercons.setFormatter(form)la méthode attend un objet FormattersetLevel()pour définir le niveau de log à appliquercons.setLevel(zpp_logs.DEBUG)la méthode attend un niveau de logs. Il est possible de lui envoyer un argument ops pour définir le comportement du handler. (Par défaut ==)cons.setLevel(zpp_logs.ERROR,ops="<=")le ops permet de comparaison pour trigger le handler. Dans l'exemple du dessus, le handler se déclenche si le log est de niveau ERROR ou inférieur.addFilter()pour ajouter un filtre. Le filter est soit un script (qui peut être une regex), soit une fonction (dans ce cas, le filter attends un retour True pour se déclencer)deftest(message):if"bjr"inmessage:returnTruereturnFalsecons.addFilter(MonModule.test)removeFilter()pour supprimer un filtre. Cette méthode permet de supprimer un filtre configuréConsole_handlerUn Console_handler permet d'envoyer des messages dans la console. Par défaut, le handler n'attend pas de paramètre mais peut recevoir:output: pour définir la destination (Par défaut sys.stdout)level: pour définir le niveau de logs attendu (Par défaut NOTSET)ops: pour définir le comportement du handler. (Par défaut ==) (Voir setLevel)log=Logger()cons=Console_handler()log.add_handler(cons)File_handlerUn File_handler permet d'envoyer des messages dans un fichier. Par défaut, le handler attend le chemin du fichier de destination. (Peut recevoir un nom de fichier dynamique avec la syntaxe des formatter)Il peut aussi recevoir:rewrite: pour définir si le handler réécrit sur un fichier existant (Par défaut False)level: pour définir le niveau de logs attendu (Par défaut NOTSET)ops: pour définir le comportement du handler. (Par défaut ==) (Voir setLevel)log=Logger()cons=File_handler('content.log')log.add_handler(cons)RotateFile_handlerUn RotateFile_handler permet d'envoyer des messages dans un fichier en prenant en charge une rotation de logs en fonction d'une taille max. Par défaut, le handler attend le chemin du fichier de destination. (Peut recevoir un nom de fichier dynamique avec la syntaxe des formatter)Il peut aussi recevoir:rewrite: pour définir si le handler réécrit sur un fichier existant (Par défaut False)level: pour définir le niveau de logs attendu (Par défaut NOTSET)ops: pour définir le comportement du handler. (Par défaut ==) (Voir setLevel)maxBytes: pour définir la taille max du fichier de logbackupCount: pour définir le nombre maximum de fichier de log. Si la limite est atteinte, il supprime le fichier le plus ancien.log=Logger()cons=RotateFile_handler('content.log')log.add_handler(cons)SMTP_handlerUn SMTP_handler permet d'envoyer des messages par mail. Par défaut, le handler attend les paramètres:smtphost: l'ip ou l'adresse du serveur SMTP sous forme de str. Possibilité de lui envoyer un tuple pour définir le port à utiliser (HOST, PORT)fromaddr: l'adresse mail de l'expéditeur sous forme de strtoaddrs: la/les adresses mail des destinataires sous forme de str pour un destination ou une liste pour plusieurssubject: l'objet du mail (Peut recevoir un objet dynamique avec la syntaxe des formatter)Il peut aussi recevoir:credentials: pour définir les login de connexion sous forme de liste ou tuple (USERNAME, PASSWORD)secure: pour définir si la connexion doit être sécurisée (Par défaut None)timeout: pour définir le temps timeout pour la réponse du serveur SMTP (Par défaut 5.0)level: pour définir le niveau de logs attendu (Par défaut NOTSET)ops: pour définir le comportement du handler. (Par défaut ==) (Voir setLevel)log=Logger()cons=SMTP_handler(smtphost='smtp.local.com',fromaddr='[email protected]',toaddrs=['[email protected]','[email protected]'],subject="Test de notification")log.add_handler(cons)FormatterUn formatter est un objet qui permet de définir le format du message de log envoyé Dans un formatter, les trigger doivent être de la forme%(trigger_name)%Si on veut formater un peu de texte pour aligner les logs, on peut définir un padding en ajoutant la taille avec le 2ème % Par exemple,%(trigger_name)5%Voici la liste des trigger disponiblesNameDescriptionasctimeDate au format %d/%m/%Y %H:%M:%S:%fdate: strftime_formatDate dans le format qu'on veutepochDate au format epochexc_infoRécupération du tracebacklevelnameNom du niveau de loglevelnoID du niveau de logmsgMessage de logfilenameNom du fichier d'exécutionfilepathRépertoire parent du fichier d'exécutionlinenoNuméro de la ligne du fichier d'exécutionfunctnameNom de la fonctionpathChemin actuelprocessNom du processprocessidPID du processusernameNom d'utilisateur qui exécute le scriptuiduid de l'utilisateur qui exécute le script (only linux)os_nameNom de l'OSos_versionVersion de l'OSos_archiArchitecture de l'OSmem_totalCapacité max de RAMmem_availableCapacité disponible de RAMmem_usedCapacité utilisée de RAMmem_freeCapacité disponible de RAMmem_percentCapacité utilisée de RAM en pourcentageswap_totalCapacité max de Swapswap_usedCapacité utilisée de Swapswap_freeCapacité disponible de Swapswap_percentCapacité utilisée de Swap en pourcentagecpu_countNombre de core physiquecpu_logical_countNombre de core logiquecpu_percentPourcentage de CPU utilisécurrent_disk_deviceNom du disque où se trouve le scriptcurrent_disk_mountpointPoint de montage du disque où se trouve le scriptcurrent_disk_fstypeFormat du disque où se trouve le scriptcurrent_disk_totalCapacité max du disque où se trouve le scriptcurrent_disk_usedCapacité utilisée du disque où se trouve le scriptcurrent_disk_freeCapacité disponible du disque où se trouve le scriptcurrent_disk_percentCapacité utilisée en pourcentage du disque où se trouve le scriptfore: colorCouleur de la police d'écritureback: colorCouleur du fond de la police d'écritureattr: attributeStyle de la police d'écriturePour son utilisation, il suffit de créer un objet Formatter et de l'ajouter dans un handler.fromzpp_logsimportLogger,Formatter,Console_handlerlog=Logger()form=Formatter("%(fore:deep_sky_blue_3a)%[%(date:%d/%m/%Y %H:%M:%S)%]%(attr:0)% - %(fore:medium_purple_4)%%(levelname)%%(attr:0)% - %(fore:grey_46)%%(msg)%%(attr:0)%")cons=Console_handler()cons.setFormatter(form)Envoi des logsLes méthodes pour envoyer des logs se déclinent en 7 niveaux:log(message): zpp_logs.NOTSETgood(message): zpp_logs.GOODdebug(message): zpp_logs.DEBUGinfo(message): zpp_logs.INFOwarning(message): zpp_logs.WARNINGerror(message): zpp_logs.ERRORcritical(message): zpp_logs.CRITICALCes méthodes peuvent être appelées soit en direct, soit depuis un logger.fromzpp_logsimportLoggerlogger=Logger(configfile="config.yaml")logger.warning("Test de logs")Compteur des logsIl est possible de récupérer un dictionnaire contenant le compteur des logs envoyés par un logger.>>>logger.count(){'CRITICAL':0,'ERROR':0,'WARNING':1,'INFO':0,'GOOD':0,'DEBUG':0,'NOTSET':0}
zpp-ManagedFile
zpp_ManagedFileInformationsSystème de fichier managé pour le contrôle des actions sur un fichier tels que la fermeture du fichier. Permet de créer plusieurs types de fichier:file: Ouverture d'un fichier présent sur le systèmestring: Simulation d'un fichierbytesio: Fichier bytes en mémoirestringio: Fichier en mémoiretempfile: Fichier temporaireInstallationpip install zpp_ManagedFileUtilisationfile=zpp_ManagedFile.ManagedFile()filename=None, mode='r', typefile="stringio", encoding=None, closable=TrueEn paramètre supplémentaire, nous pouvons mettre:filename = Chemin du fichier si typefile=filemode = Option sur le fichier (w/r/a) (default: r)typefile = type de fichier (file,string,bytesio,stringio,tempfile) (default: stringio)encoding = type d'encodage du fichierclosable = activer le blocage de la fermeture (True pour activer)Le fichier a les mêmes actions q'un fichier classique.Bloquer la fermeture du fichierIl est possible de bloquer la fermeture du fichier en utlisant la méthode isClosablefile.isClosable(True)Opération courantes sur les fichiersFermeture du fichierfile.close()Ecriture dans un fichierfile.write(data)Ecriture d'une liste dans un fichierfile.writelines(list)Flush des données du bufferfile.flush()Tronquer le fichierfile.truncate(size)size détermine la taille du fichier tronquéLecture d'un fichierfile.read(size)Si size est déterminé, lis seulement x bytes du fichierLecture d'une ligne d'un fichierfile.readline(size)Si size est déterminé, lis seulement x bytes du fichierRécupération du contenu du fichier sous forme de listefile.readlines()Déplacer le curseurfile.seek(offset,[mode])offset correspond au déplacement mode (optionnel) correspond à l'option de déplacement (0: déplacement depuis le début du fichier, 1: déplacement depuis la position actuelle, 2: déplacement depuis la fin du fichier)Connaitre la position du curseurfile.tell()
zpp_menu
py-menuInformationsGénérateur d'un menu à touches fléchées.Le choix dans le menu se fait à partir des touches fléchées pour la navigation et de la touche Enter pour la validation.Customisation des couleurs du menu et du curseur possibles.Retourne l'indice du choix sélectionnéPrérequisPython 3Installationpip install zpp_menuUtilisationchoice=zpp_menu.Menu(Title,OptionList)En paramètre supplémentaire, nous pouvons mettre:Background = Choisir la couleur de font du choix selectionnéForeground = Choisir la couleur du texte du choix selectionnéPointer = Choisir un pointeur à afficher avant le choixPadding = Choisir la taille du décalage entre le titre et les choixSelected = Choisir la position du curseur
zpp-serpent
py-serpentInformationsImplémentation de l'algorithme de chiffrement Serpent en python3, basé sur le travail de Frank StajanoChiffrement de bloc de 128bits avec une clés de 256bitsRemplissage de bloc incomplet avec utilisation du padding RFC2040 ou CipherText Stealing (pour ECB et CBC)Fonctionnement possible en ECB, CBC, PCBC et CFBHashage du mot de passe et du vecteur d'initialisation en pbkdf2_hmac sha256 avec un salt aléatoirePrérequisPython 3Module Python 3:bitstringInstallationpip install zpp_serpentUtilisationElectronic codebook (ECB)Chiffrementencrypted=zpp_serpent.encrypt_ECB(cleartext,password)Dechiffrementplain=zpp_serpent.decrypt_ECB(encrypted,password)En paramètre supplémentaire, nous pouvons mettre:hash_type = pour choisir l'algorithme de hashage utilisé pour la clélvl = 1 (pour padding RFC2040) ou 2 (pour CTS)Cipher block chaining (CBC)Chiffrementencrypted=zpp_serpent.encrypt_CBC(cleartext,password)Dechiffrementplain=zpp_serpent.decrypt_CBC(encrypted,password)En paramètre supplémentaire, nous pouvons mettre:hash_type = pour choisir l'algorithme de hashage utilisé pour la clélvl = 1 (pour padding RFC2040) ou 2 (pour CTS)Propagating cipher block chaining (PCBC)Chiffrementencrypted=zpp_serpent.encrypt_PCBC(cleartext,password)Dechiffrementplain=zpp_serpent.decrypt_PCBC(encrypted,password)En paramètre supplémentaire, nous pouvons mettre:hash_type = pour choisir l'algorithme de hashage utilisé pour la cléCipher feedback (CFB)Chiffrementencrypted=zpp_serpent.encrypt_CFB(cleartext,password)Dechiffrementplain=zpp_serpent.decrypt_CFB(encrypted,password)En paramètre supplémentaire, nous pouvons mettre:hash_type = pour choisir l'algorithme de hashage utilisé pour la cléTechnique de remplissagePadding RFC2040La méthode padding RFC2040 est une technique largement utilisé pour le remplissage de bloc imcomplet. Elle se base sur un modèle qui varie en fonction de la taille d'un bloc à remplir.Supposons qu'un bloc ne fasse que 112bits au lieu des 128bits nécessaire. Il faut donc trouver une méthode de combler le vide avec une modèle qui pourra être retiré lors du déchiffrement. Avec cette méthode, nous allons remplir la fin du bloc par autant d'octet que nécessaire, avec pour valeur le nombre d'octet que nous devons rajouter. Dans notre exemple, il nous manque 2 octets pour arriver à 128bits. Nous devons donc ajouter à la fin du bloc 2 Octets avec la valeur hexadécimal 02 pour remplir complètement ce bloc.Pour le déchiffrement, nous allons analyser les modèles en fin de bloc pour déterminer si ce sont des blocs qui ont été rajoutés et qui doivent être enlevés.CipherText Stealing (CTS)La méthode de vol de texte chiffré (CipherText Stealing) permet le remplissage de bloc incomplet tout en évitant d'augmenter la taille du texte comme peu le faire le padding RFC2040. De plus, elle limite les attaques dit Padding oracle attack qui est la faiblesse du padding RFC2040 sur du chiffrement ECB et CBC. Cette méthode se base sur le traitement des deux derniers blocs d'un message et sur le double chiffrement d'une partie d'un des deux blocs.
zpptomle
Failed to fetch description. HTTP Status Code: 404
zp-pycrc
本模块主要进行数据校验:支持查表法和直接法。支持crc16常用校验法和自定义校验。详细用法可参照代码。crc32仅仅实现了经典法。importunittestfromzp_pycrcimport*classcrc_test(unittest.TestCase):deftest_crc16(self):datas=b'\x01\x02\x03\x04\x05'print(len(datas),datas)crc=crc16_ccitt()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_ccitt_false()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_xmodem()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_x25()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_ibm()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_usb()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_maxim()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_modbus()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_dnp()print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16(0,0x8005,True,True,0)print(crc.__class__.__name__,"%04X"%(crc.cal(datas)))crc=crc16_ibm()print("crc16_ibm __call__",hex(crc(datas)))b=cal_crc16_classcial(datas,0,0x8005,True,True,0)print("cal_crc16_classcial",hex(b))print('*******crc ibm table*****')print([hex(i)foriincrc.crc_table])deftest_crc32(self):datas=b'\x01\x02\x03\x04\x05'r=cal_crc32_classcial(datas,0xffffffff,0x04c11db7,True,True,0xffffffff)print(hex(r))if__name__=='__main__':unittest.main()
zpretty
A tool to format in avery opinionatedway HTML, XML and text containing XML snippets.It satisfies a primary need: decrease the pain of diffing HTML/XML.For this reasonzprettyformats the markup following these rules of thumb:maximize the vertical space/decrease the line lengthattributes should be sorted consistentlyattribute sorting is first semantic and then alphabeticThis tool understands theTAL languageand has some features dedicated to it.This tool is not a linter! If you are looking for linters safe bets areTidyandxmllint.You may have parsing problems!zprettywill close for you some known self closing tags, likeinputandimg, that are allowed to be open in HTML.zprettyis not clever enough to understand correctly valueless attributes! Some work is ongoing, but it works best with "normal" attributes.Lack of feature/slowness are a known issue. For the moment the development focused in having a working tool. So it works fast enough: less than a second to format a ~100k file. New features are planned and also huge perfomance boost can be easily obtained. Anywayzprettyis not your option for formatting large files (> 1 MB).SeeTODO sectionto know what is forecast for the future.The source code and the issue tracker are hosted onGitHub.INSTALLThe suggested installation method is usingpip:python3-mpipinstall--userzprettyThe latest release ofzprettyrequires Python3. If you need to use Python2.7 usezpretty0.9.x.USAGEBasic usage:$zpretty-husage: zpretty [-h] [--encoding ENCODING] [-i] [-v] [-x] [-z] [--check][--include INCLUDE] [--exclude EXCLUDE][--extend-exclude EXTEND_EXCLUDE][paths ...]positional arguments:paths The list of files or directory to prettify (defaults tostdin). If a directory is passed, all files anddirectories matching the regular expression passed to--include will be prettified.options:-h, --help show this help message and exit--encoding ENCODING The file encoding (defaults to utf8)-i, --inplace Format files in place (overwrite existing file)-v, --version Show zpretty version number-x, --xml Treat the input file(s) as XML-z, --zcml Treat the input file(s) as XML. Follow the ZCMLstyleguide--check Return code 0 if nothing would be changed, 1 if somefiles would be reformatted--include INCLUDE A regular expression that matches files and directoriesthat should be included on recursive searches. An emptyvalue means all files are included regardless of thename. Use forward slashes for directories on allplatforms (Windows, too). Exclusions are calculatedfirst, inclusions later. [default:\.(html|pt|xml|zcml)$]--exclude EXCLUDE A regular expression that matches files and directoriesthat should be excluded on recursive searches. An emptyvalue means no paths are excluded. Use forward slashesfor directories on all platforms (Windows, too).Exclusions are calculated first, inclusions later.[default: /(\.direnv|\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|venv|\.svn|\.ipynb_checkpoints|_build|buck-out|build|dist|__pypackages__)/]--extend-exclude EXTEND_EXCLUDELike --exclude, but adds additional files anddirectories on top of the excluded ones. (Useful if yousimply want to add to the default)The default exclude pattern is: `/(\.direnv|\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|venv|\.svn|\.ipynb_checkpoints|_build|buck-out|build|dist|__pypackages__)/`Without parameters constraining the file type (e.g.-x,-z, ...)zprettywill try to guess the right options for you.Example:zpretty hello_world.htmlpre-commit supportzprettycan be used as apre-commithook. To do so, add the following to your.pre-commit-config.yaml:-repo:https://github.com/collective/zprettyrev:FIXMEhooks:-id:zprettyVSCode extensionThere is a VSCode extension that useszpretty:https://marketplace.visualstudio.com/items?itemName=erral.erral-zcmlLanguageConfigurationThanks to @erral for the work!DEVELOPgitclone...cdzpretty makeRUNNING TESTSmaketestChangelog3.1.0 (2023-06-30)No changes were made from the latest alpha version [ale-rt]3.1.0a2 (2023-05-09)Improve the regular expression that matches the entities (Fixes #130) [ale-rt]3.1.0a1 (2023-05-04)Add command line parameters to include/exclude files and folders (Implements #96) [ale-rt]Be tolerant with characters forbidden in XML when dealing with tal attributes (See #125) [ale-rt]3.0.4 (2023-04-20)Fix bogus ampersands in attributes (Fixes #116) [ale-rt]3.0.3 (2023-03-26)Handle HTML files with an XML preamble before the doctype. (Fixes #118) [ale-rt]3.0.2 (2023-02-26)Handle forbidden characters in attributes properly (Fixes #110) [ale-rt]Fix attribute with a value containing double quotes (Fixes #109) [ale-rt]3.0.1 (2023-02-09)Fix an issue with empty lines inside an attribute. (Fixes #106) [ale-rt]3.0.0 (2023-02-09)The pre-commit hook now modifies fixes the files instead of just checking if they should be fixed [ale-rt]Fix the check behavior when multiple files are passed [ale-rt]Improve the check that sniffs html files (Fixes #89) [ale-rt]2.4.1 (2022-10-25)XML files with newlines between attributes are properly formatted (Fixes #84) [ale-rt]Do not tamper attributes in XML as if they were a page template attribute (Fixes #85) [ale-rt]2.4.0 (2022-10-22)Prevent fiddling around with custom entity declaration (Fixes #80) [ale-rt]Add support for Python 3.11. [ale-rt]Drop support for Python 3.6. [ale-rt]2.3.1 (2022-09-30)Do not try to do anything on CDATAs (Fixes #76) [ale-rt]2.3.0 (2022-09-26)Added a -v/--version option [ale-rt]2.3.0a4 (2022-09-24)Remove custom tree builder which is not used anymore [ale-rt]Fix entity sustitution in XML (Fixes #48, Refs #71) [ale-rt]2.3.0a3 (2022-07-08)Do not escape entities inside the script and style tags (Fixes #57) [ale-rt]2.3.0a2 (2022-07-08)Fix release2.3.0a1 (2022-07-08)Preserve whitespace in XML documents andpreelements (Fixes #64) [ale-rt]Improve doctype handling [ale-rt]Do not kill XML documents with a doctype (Fixes #47) [ale-rt]Support Python 3.10 [ale-rt]2.2.0 (2021-12-06)Add a--checkcommand line parameter (Fixes #49) [ale-rt]Now the package ispre-commitcompatibile (Fixes #50) [ale-rt]2.1.0 (2021-02-12)Remove unusedautofixmethod [ale-rt]Do not render a spurious=""when new lines appear inside a tag (Refs. #35) [ale-rt]The attributes renderer knows about the element indentation and for indents the attributes consequently [ale-rt]The ZCML element has now its custom tag templates, this simplifies the code [ale-rt]Attributes content spanning multiple lines is not indented anymore (Refs. #17) [ale-rt]Improved sorting for zcml attributes (Refs. #11) [ale-rt]Code is compliant with black 20.8b1 [ale-rt]Switch to pytest for running tests [ale-rt]Upgrade dev requirements [ale-rt]Support Python 3.9 [ale-rt]2.0.0 (2020-05-28)Updated the list of self closing elements and boolean attributes [ale-rt]1.0.3 (2020-05-22)Fix unwanted newlines (#20)1.0.2 (2019-11-03)In Python3.8 quotes in attributes were escapedFix output again on file and stdout [ale-rt]1.0.1 (2019-10-28)Fix output on file [ale-rt]1.0.0 (2019-10-27)Support Python3 only [ale-rt]0.9.3 (2017-05-06)Last release that supports Python2.7Fix text methodPreserve entities in textAdded an--encodingparameterAdded an--xmlparameter to force xml parsingChoose the better parser according to the given filename if no parser is forcedProcess stdin if-is in the arguments or no arguments are passed [ale-rt]0.9.2 (2017-02-27)Small modification for the order of the zcml attributesAuto add a new line to the end of the prettified filesSelf heal open self closing tag. [ale-rt]0.9.1.1 (2017-02-18)Fixed bad release. [ale-rt]0.9.1 (2017-02-18)Initial support for zcml style guide (#3). [ale-rt]0.9.0 (2017-02-11)Initial release. [ale-rt]
zprint
Infozprint 2018-08-20Author: Zhao Mingming <[email protected]>Copyright: This module has been placed in the public domain.version:0.0.4add func zprint, print out the function list and time into stdoutadd func eprint, print out the function list and time into stderradd func zhelp, print demo scriptversion:0.0.7add func zprintrversion:0.0.7add func sys.stdout.flush()Functions:add func zprint, print out the function list and time into stdoutadd func eprint, print out the function list and time into stderrHow To Use This Module.. image:: funny.gif :height: 100px :width: 100px :alt: funny cat picture :align: centerexample code:.. code:: pythonfrom zprint import *def fun2(): zprint(" I am in fun2",0)def fun1(): zprint(" I am in fun1") fun2()ifname=="main": print 1 fun1()Refresh20180820
z-probability
No description available on PyPI.
zproc
ZProc is a thought experiment, in making multi-tasking easier and accessible to everyone.It focuses on automating various tasks related to message passing systems, for pythonistas. The eventual goal is to make Python a first-class language for doing multi-tasking.So thatyoudon't have to think about arcane details, like request-reply loops, reliable pub-sub, worker management, task distributiom, exception propagation, that kind of thing...Behold, the power of ZProc:importzproc## define "atomic" operations#@zproc.atomicdefeat_cookie(snapshot):snapshot["cookies"]-=1print("nom nom nom")@zproc.atomicdefbake_cookie(snapshot):snapshot["cookies"]+=1print("Here's a cookie!")## specify a process#defcookie_eater(ctx):state=ctx.create_state({'ready':True})# `start_time=0` accesses events from the very beginning.for_instate.get_when_change("cookies",start_time=0,count=5):eat_cookie(state)# boilerplatectx=zproc.Context(wait=True)state=ctx.create_state({"cookies":0})# create a "ready" handleready=state.get_when_available("ready")# spwan the processproc=ctx.spawn(cookie_eater)print(proc)# wait for readynext(ready)# finally, bake some cookies.for_inrange(5):bake_cookie(state)Result:Process - pid: 10815 target: '__main__.cookie_eater' ppid: 10802 is_alive: True exitcode: None Here's a cookie! Here's a cookie! nom nom nom Here's a cookie! nom nom nom Here's a cookie! nom nom nom Here's a cookie! nom nom nom nom nom nomThe framework does message passing for you.Thestate.get_when_change()iterator supplies thecookie_eaterprocess with events asynchronously, as the state is updated.The core ideaMessage passing is cumbersome, error prone, and tedius -- because there is a lot of manual wiring involved.The idea behind this project is to provide a pythonic API over widely accepted models in the message passing realm.It started out withembracingshared state (but not shared memory).Shared memory is frowned upon by almost everyone, due to the fact that memory is inherently dumb. Memory doesn't really care who's writing to it.Shared state brings it's own perils, because its really hard to keep track of changes.With the aid of the Actor Model, ZProc's state keeps a track of who's doing what. So much so, that it can act as a time-machine and give you state events from any defined time.It then evolved to do handle exceptions across processes, failover, worker swarms, event sourcing, and other very useful features realated to multi-tasking.The underlying architecture 100% message passing based, and hence scalable across many computers, with minimal modifications to the user code.Well why not just X?Each technology solution has it's place. Here is a rundown of why you would use ZProc over X.X == asyncioIt's kinda in the name. Asyncio is strictly for I/O based concurrency. And then there's the fact that it implies extreme levels of refactoring.To quote Joe Armstrong,I want one way to program computers, not many.Install$ pip install zprocMIT LicensePython 3.5+DocumentationRead the docsExamplesWishlistHere are some of the ideas that I wish were implemented in ZProc, but currently aren't.Redundant state-servers -- automatic selection/fallback.Green, Erlang-style processes. (requires Cpython internals)Processlinks, that automatically propagate errors across processes.Make namespaces horizontally scalable.Features🌠   Process managementRemembers to cleanup processes when exiting, for general peace. (even when they're nested)Keeps a record of processes created using ZProc.🔖[ZProc] Cleaning up 'python' (13652)...🌠   Worker/Process MapsAutomatically manages worker processes, and delegates tasks to them.🔖🌠Communicating sequential processes, at the core.No need for manual message passing.Watchfor changes in state, withoutbusy waiting.🔖.Deterministic state updates.Ships with a event messaging system that doesn't rely on flaky PUB/SUB.Go back in time, with aTimeMachine!.Distributed, by default.Scalable to multiple computers, with minimal refactoring.🌠   Atomic OperationsPerform an arbitrary number of operations on state as a single, atomic operation.🔖🌠 Detailed, humane error logging for Proceeses.[ZProc] Crash report: target: '__main__.p1' pid: 8959 ppid: 8944 Traceback (most recent call last): File "/home/dev/Projects/zproc/zproc/child.py", line 88, in main **self.target_kwargs File "/home/dev/Projects/zproc/zproc/child.py", line 65, in target_wrapper return self.target(*args, **kwargs) File "test.py", line 12, in p1 raise ValueError ValueErrorCaveatsThe state only gets updated if you do it at the highest level.This means that if you mutate objects deep down in the dict hirearchy, they wont be reflected in the global state.The state should be pickle-able.It runs an extra Processes for managing the state.They're fairly lightweight though, and shouldn't add too much weight to your application.FAQFast?Above all, ZProc is written for safety and the ease of use.However, since its written using ZMQ, it's plenty fast for most stuff.Stable?Mostly. However, since it's still in its development stage, you should expect some API changes.Production ready?Please don't use it in production right now.Windows compatible?Probably?Local development# get the code git clone https://github.com/pycampers/zproc.git # install dependencies cd zproc pipenv install pipenv install -d # activate virtualenv pipenv shell # install zproc, and run tests pip install -e . pytestBuild documentationcd docs ./build.sh # open docs google-chrome _build/index.html # start a build loop ./build.sh loopZProc in the wildOscilloscopeMuroThanksThanks toopen logosfor providing the wonderful ZProc logo.Thanks topieter hintjens, for his work on theZeroMQlibrary and for hisamazing book.Thanks totblib, ZProc can raise First-class Exceptions from the zproc server!Thanks topsutil, ZProc can handle nested procesess!Thanks to Kennith Rietz. His setup.py was used to host this project on pypi. Plus a lot of documentation structure is blatantly copied from his documentation on requestsZProc is short forZeroProcess.🐍🏕️
zprocess
zprocessA set of utilities for multiprocessing using zeromq. Includes process creation and management, output redirection, message passing, inter-process locks, logging, and a process-tree-wide event system.(view on pypi;view on Github)Installpython setup.py install.
zprofile
zprofileStatistical (sampling) CPU and wall-clock profilers for Python, derived fromgoogle-cloud-profiler.Google Cloud Python profiling agentPython profiling agent forGoogle Cloud Profiler.SeeGoogle Cloud Profiler profiling Python codefor detailed documentation.Supported OSLinux. Profiling Python applications is supported for Linux kernels whose standard C library is implemented withglibcor withmusl. For configuration information specific to Linux Alpine kernels, seeRunning on Linux Alpine.Supported Python VersionsPython >= 3.7 and <= 3.11Installation & usageInstall the profiler package using PyPI:pip3installzprofileEnable the profiler in your application:fromzprofile.cpu_profilerimportCPUProfilerp=CPUProfiler()pprof=p.profile(30)# secondswithopen("profile.pprof","wb")asf:f.write(pprof)View the profile with thepproftool:$ go tool pprof -http localhost:8080 profile.pprof
zproj
INTRODUCTIONThis project is a suite of tools designed to ease the process of developing assembly language apps for the TI-83 Plus series of calculators. Currently, it contains the following tools:zmake (inspired by qmake of qt), which produces a Makefile that describes the build process for a TI-83 Plus assembly language application, andzabc (Z80 Application Boilerplate Compiler), which generates an assembly language file that can be assembled into an application.It also includes some assembly language libraries and a sample application to build.INSTALLATION AND DEPENDENCIESCurrently, this project is only supported on Unix-like operating systems. It is a Python project located on PyPI, and can therefore be installed by running some variation ofpip install zproj(perhaps with root access).The following dependencies are required to use this project:Python 3. The tools are written in Python, and have not been designed with Python 2 in mind.peeker. This is a small Python package used by the tools included in this project.GNU make or equivalent. This program must be installed in order to use the Makefile generated by zmake.spasm. This is the assembler currently used and supported by the project, and must therefore be installed to perform builds.rabbitsign. TI-83 Plus applications must be digitally signed in order to be loaded onto calculators, and rabbitsign is the application signer currently supported by this project.EXAMPLEThis project ships with an example “Hello World” application that can be built using the tools contained in this project. After installing the project and the above dependencies, changing directories intoexamples/helloand runningzmakefollowed bymakeshould build a .8xk file that can be loaded onto an actual or simulated TI-83 Plus series calculator.
zps
zpsZeek PCAP Scalpel
zpspider
No description available on PyPI.
zpspython
No description available on PyPI.
zptess
zptessCommand line utility to calibrate TESS-W at LICAInstallationgitclonehttps://github.com/STARS4ALL/zptess.git sudopythonsetup.pyinstallorpipinstall--userzptessRunSeepython -m zptess --helpfor helpThe calibration processSamples from the reference TESS-W and the new TESS-W are taken and stored in circular buffers (default: 25 samples). An estimator of central tendency of frequencies is taken on each buffer (default estimator: median). The standard deviation from this estimator is also computed to asses the quality of readings. If this standard deviation is zero on either buffer, the whole process is discarded. Otherwise, we keep the estimated central tendency of reference and test frequencies and compute a candidate Zero Point.This process is repeated in a series of rounds (default: 5 rounds) and we select the "best" estimation of frequencies and Zero Point. The best freequency estimation is chosen as themodewith a fallback tomedianif mode does not exists.FormulaeMag[ref] = ZP[fict] - 2.5*log10(Freq[ref]) Mag[tst] = ZP[fict] - 2.5*log10(Freq[tst]) Offset = 2.5*log10(Freq[tst]/Freq[ref]) ZP[calibrated] = ZP[ref] + Offset where ZP[fict] is a ficticios zero point of 20.50 to compare readings with the TESS Windows utility by Cristobal García. ZP[ref] is the absolute Zero Point of the calibrated TESS-W (20.44) determined by LICA.
zptestlib
No description available on PyPI.
zptlint
zptlintScript that runs the pagetemplate parser and output errorsInstallationBecausezptlintdepends onzope.pagetemplate, it depends on a lot of other zope eggs.To avoid polluting you system python, you can installzptlintin avirtualenv:$ virtualenv --no-site-packages zptlint $ cd zptlint/ $ bin/easy_install zptlintThen make a link to the right script:$ ln -s MYPATH/zptlint/bin/zptlintConfiguration in .vimrc"page templates configuration autocmd BufNewFile,BufRead *.pt,*.cpt,*.zpt setfiletype zpt autocmd FileType zpt set makeprg=zptlint\ % autocmd FileType zpt set errorformat=%+P***\ Error\ in:\ %f,%Z%*\\s\\,\ at\ line\ %l\\,\ column\ %c,%E%*\\s%m,%-Q augroup filetype au BufWritePost,FileWritePost *.pt make au BufWritePost,FileWritePost *.cpt make au BufWritePost,FileWritePost *.zpt make augroup ENDBecause zpt is defined as a new file type, you may want to copysyntax/html.vimtosyntax/zpt.vimandftplugin/html.vimtoftplugin/zpt.vim.or usage from command-line in vim:set makeprg=zptlint\ % set errorformat=%+P***\ Error\ in:\ %f,%Z%*\\s\\,\ at\ line\ %l\\,\ column\ %c,%E%*\\s%m,%-QCreditscode by Balazs Ree, Greenfinityeggified by Godefroid Chapelle, BubbleNetChangelog for zptlint0.2.4 (2010-12-26)Fix url in setup.py [gotcha]0.2.3 (2009-12-18)Documentation fixes (suggested by Davide Moro) [gotcha]0.2.2 (2009-12-18)Testing multiple files was broken (reported by Wouter Vanden Hove) [gotcha]0.2.1 (2009-12-18)Remove RestrictedPython from dependencies [gotcha]0.2 (2009-12-18)Add provider expression support [gotcha]0.1 (2009-12-17)Proper source release [gotcha]0.1a (2008-06-16)First release to PyPI [gotcha]Initial code [ree]
zpy
Quickly encrypt files with your ssh identity.For more information, seegithub.com/sfstpala/zpy.
zpy-alert-manager
ZPy Telegram Alert NotifierZPy Alert ManagerZurck'z Py Telegram Bot Alert NotifierThis package contains some helpers features for build python microservices.RequirementsPython 3.9+InstallationUse the package managerpipto install py flask micro service core .pipinstallzpy-api-coreFeaturesContains some helper features.Telegram Bot ManagerSend message to specific chatBasic Usagenotifier=TelegramBot(data={})notifier.send('Hello',"12121")ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMITAuthorsNoé Cruz
zpy-api-core
ZPy Core, Layer for build microservicesZPy CoreZurck'z Py Flask Micro Services CoreThis package contains some helpers features for build python microservices using Flask frameworkZPy use the following packages:Flaskmarshmallowmarshmallow_objectsrequestsaws-lambda-wsgiRequirementsPython 3.6+InstallationUse the package managerpipto install py flask micro service core .pipinstallzpy-api-coreFeaturesContains some helper features.ApiApi BuilderResponse BuilderModelsHooksMiddlewaresExceptionsCloud ImplementationsAws Handler decoratorsSee: AWS PackageCLIDDD Project structure generatorBounded Context GeneratorUseCases generatorDatabaseSee: SQL Oracle & MySQLLoggerStreamUtilsCollectionselement finderDatesTime zonesTransformsCiphersSee: Crypto WrappersFunctionsParallelmap parallelrun parallelObjectsgzipBasic UsageGenerate project usingzpy CLI# Generate project with basic information. for more type: zpy --helpzpymake-pawesome-api-d"My awsome users api"-cUsers-ucUserSearcher-op ...cdawesome-apizpy will generate the project with the following structureawesome-api │ .env │ .gitignore │ CHANGELOG.md │ CHANGELOG.md │ README.md │ requirements.txt │ └───src │ │ di.py │ │ handler.py │ │ local_deploy.py │ │ │ └───┬api │ │ routes.py │ │ ... │ └contexts │ │ ... │ └───users │ │ ... │ └───┬application │ │ │ ... │ └───┬domain │ │ │ ... │ └───┬infraestructure │ │ ... └───tests │ user_searcher_test.pyDependencies file# 🛸 Generated by zPyfromzpy.utilsimportget_env_or_throwasvarfromzpy.app.usecaseimportUseCasefromtypingimportAny# * Setup Dependencies 📃fromcontexts.users.domain.repositoriesimportUserRepositoryfromcontexts.users.infraestructure.payment_repositoryimportAwesomeUserRepositoryfromcontexts.users.application.user_searcherimportUserSearcherrepository:UserRepository=AwesomeUserRepository()# Setup UseCasesuser_searcher_uc:UseCase[Any,None]=UserSearcher(repository)print("🚀 Dependencies loaded successfully...")routes.py# 🛸 Generated by zPyfromdiimportuser_searcher_ucfromflaskimportFlaskfromzpy.api.http.responseimportresponse_builderfromzpy.api.flaskimportcreate_appapp:Flask=create_app()@app.route("/api/users",methods=["GET"])@response_builderdefusers():returnuser_searcher_uc.execute(None)Use Case# 🛸 Generated by zPyfromtypingimportAnyfromzpy.app.usecaseimportUseCasefrom..domain.repositoriesimportUserRepositoryclassUserSearcher(UseCase[Any,Any]):"""Use Case description."""def__init__(self,repository:PaymentRepository)->None:self.repository=repositorydefexecute(self,data:Any,*args,**kwargs)->None:# TODO Do magic with business rules 😁returnself.repository.user_searcher(data)Local Dev Deploy# 🛸 Generated by zPyfromdotenvimportload_dotenvload_dotenv(dotenv_path="|3:\\projects\\demos\\awesome-api\\.env")fromapi.routesimportappif__name__=="__main__":app.run(host="127.0.0.1",port=5050,debug=True)handler.py configure for aws lambda and api gateway# 🛸 Generated by zPyfromzpy.api.cloud_handlersimportaws_lambdafromapi.routesimportappimportaws_lambda_wsgiasawsgi@aws_lambda()defhandle(event:dict,context:dict)->any:returnawsgi.response(app,event,context)ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMITAuthorsNoé Cruz
zpybox
python 编程工具该工具包含了python编程可能用到的一些工具包,比如写入日志,判断文本格式等等。运行依赖无编程示例其他说明有问题请联系[email protected]版本记录当前版本:0.0.10.0.1添加一个判断ip格式的函数
zpy-ciphers-utils
ZCrypto WrapperZPy Database CoreZurck'z PyThis package contains some helpers features for encrypt data .ZPy use the following packages:pycryptoRequirementsPython 3.6+InstallationUse the package managerpipto install py flask micro service core .pipinstallzpy pipinstallpackage_directorydirectory_to_installFeaturesContains some helper features with specific integrations.DatabaseOnly MySQL implementationFunctions executorStored Procedures executorAutocommit is false by defaultUtilsfuncsRoadmapActiveRecord implementationClusterBasic UsageBasic Configurationconfig={"user":"","password":"","database":"","host":"","port":3306}With single datasource# Create database mediator with single datasourcedb_manager=ZMediator.single(config,True)# Open connectiondb_conn=db_manager.default().new_connect()try:# Execute functionres=db_manager.default().exec("FN_GET_USER_BY_ID(%d)",list_params=[1],ret_type=DBTypes.cursor)print(res)exceptExceptionase:logging.exception(e)finally:# ⚠ Remember close opened connectiondb_conn.close()Multiple Datasources# Define db mediator# Setup base configuration in ZMediator()# The base configuration will be overwritten by add common valuesdb_mngr=ZMediator(config,False).add_common("DB_NAME_1","DB_USER","DB_PASSWORD",True)# Mark default ds.add_common("DB_NAME_2","DB_USER","DB_PASSWORD").add_common("DB_NAME_3","DB_USER","DB_PASSWORD")db_conn1=db_mngr.default().new_connect()db_conn2=db_mngr.get("DB_NAME_1").new_connect()db_conn3=db_mngr.get("DB_NAME_3").new_connect()try:# Execute functionres=db_mngr.default().exec("FN_GET_USER_BY_ID(%d)",list_params=[1],ret_type=DBTypes.cursor)print(res)# Execute functionres=db_mngr.get("DB_NAME_2").exec("FN_GET_USER_BY_ID(%d)",list_params=[1],ret_type=DBTypes.cursor)print(res)# Call spres=db_mngr.get("DB_NAME_3").call("SP_GET_DATA",ret_type=DBTypes.cursor)print(res)exceptExceptionase:logging.exception(e)finally:# ⚠ Remember close opened connectionsdb_conn1.close()db_conn2.close()db_conn3.close()ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMITAuthorsNoé Cruz
zpycli
Failed to fetch description. HTTP Status Code: 404
zpy-cloud-utils
ZPy Cloud Utils, Layer for build microservicesZPy Flask CoreZurck'z Py Flask Micro Services CoreThis package contains some helpers features for build python microservices using Flask frameworkZPy use the following packages:boto3ibm-sdkgcloudRequirementsPython 3.6+InstallationUse the package managerpipto install py flask micro service core .pipinstallboto3 pipinstallzpyFeaturesContains some helper features with specific integrations.ApiApi BuilderResponse BuilderModelsHooksMiddlewaresExceptionsRepositoriesOnly oracle repository implementation for functions calling.Cloud ImplementationsAWS ServicesS3SSMFirehoseSQSCustomPlugingsDatabaseOnly Oracle implementationFunctions executorLoggerStreamUtilsCollectionsCipherFunctionsgzipBasic UsageDefine restful resourcefromzpy.api.resourceimportZResource,HTTP_METHODSclassUserResource(ZResource):def__init__(self,**kwargs)->None:super().__init__()# Receive any dependency by keywords argumentsdefget(self):l,i=super().new_operation()try:returnself.success({"user":{"name":"Zurckz"}},logger=l)exceptExceptionase:returnself.handle_exceptions(e,l,i)Setup api# Define api@api(base='/v1',config=config)defcreate_api():# Set all supported resource for this web service.return[ZResource('/',UserResource)]Local Dev Deployfromapiimportcreate_apiapp=create_api()# 🚨 Only use it in local tests 💻if__name__=="__main__":app.run(host="localhost",debug=True)ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMITAuthorsNoé Cruz
zpy-database
zpy-database v0.1.1Zguillez| Guillermo de la IglesiaPyton database wrapperGetting StartedInstallpip install --upgrade zpy-databaseUsagefrom zpy_database import database as db db.connect({ 'conn': os.environ['DB_HOST'], 'database': os.environ['DB_NAME'], 'user': os.environ['DB_USER'], 'password': os.environ['DB_PASS'] })data = db.sql("SELECT id, name FROM my_table") print(data[0])data = db.dict("SELECT id, name FROM my_table", ['id', 'name']) print(data[0]['name'])db.close()Contributing and issuesContributors are welcome, please fork and send pull requests! If you have any ideas on how to make this project better then please submit an issue oremailme.License©2023 Zguillez.IOOriginal code licensed underMITOpen Source projects used within this project retain their original licenses.Changelogv0.1.1 (February 13, 2023)Initial commit
zpy-db-core
from zdb.mysql import ZMySQLZDB Core, Layer for connect to mysql, postgresql or oracle from pythonZPy Database CoreZurck'z PyThis package contains some helpers features for call function or stored procedures from python.ZPy use the following packages:mysql-connector-pythoncx-Oraclepsycopg2RequirementsPython 3.6+InstallationUse the package managerpipto install py flask micro service core .pipinstallzpy pipinstallpackage_directorydirectory_to_installFeaturesContains some helper features with specific integrations.DatabaseFunctions executorStored Procedures executorAutocommit is false by defaultUtilsContext Manager HelperRoadmapActiveRecord implementationClusterParallel parsedBasic UsageBasic Configurationconfig={"user":"","password":"","database":"","host":"","port":3306}With single MySQL datasourcefromzdb.mysqlimportZMySQLfromzdbimportZDBTransact# Create database instance for MySQLmysql_db=ZMySQL.from_of(user="",password="",host="",db_name="")# If you only execute one operation you can call directly# Connection automatically opened and commit and close[user]=mysql_db.call("FN_GET_USER_BY_ID",list_params=[1])# Open connection using Context ManagerwithZDBTransact(mysql_db)astr:payments=mysql_db.call("FN_GET_USER_PAYMENTS",list_params=[1],connection=tr.session)forpaymentinpayments:mysql_db.call("FN_UPDATE_PAYMENT",list_params=[payment['id']],connection=tr.session)Multiple Datasources# Define db mediator# Setup base configuration in ZMediator()# The base configuration will be overwritten by add common valuesdb_mngr=ZMediator(config,False).add_common("DB_NAME_1","DB_USER","DB_PASSWORD",True)# Mark default ds.add_common("DB_NAME_2","DB_USER","DB_PASSWORD").add_common("DB_NAME_3","DB_USER","DB_PASSWORD")db_conn1=db_mngr.default().new_connect()db_conn2=db_mngr.get("DB_NAME_1").new_connect()db_conn3=db_mngr.get("DB_NAME_3").new_connect()try:# Execute functionres=db_mngr.default().exec("FN_GET_USER_BY_ID(%d)",list_params=[1],ret_type=DBTypes.cursor)print(res)# Execute functionres=db_mngr.get("DB_NAME_2").exec("FN_GET_USER_BY_ID(%d)",list_params=[1],ret_type=DBTypes.cursor)print(res)# Call spres=db_mngr.get("DB_NAME_3").call("SP_GET_DATA",ret_type=DBTypes.cursor)print(res)exceptExceptionase:logging.exception(e)finally:# ⚠ Remember close opened connectionsdb_conn1.close()db_conn2.close()db_conn3.close()session=self.db.new_connect()try:count=self.db.call('SP_GENERIC_GET_ROWS',list_params=['TAROLES'],ret_type=DBTypes.integer,connection=session)returnPager.create(data.pagination,count)finally:session.close()ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMITAuthorsNoé Cruz
zpy-flask-msc
ZPy Flask MSC, Layer for build microservicesZPy Flask MSCZurck'z Py Flask Micro Services CoreThis package contains some helpers features for build python microservices using Flask frameworkZPy use the following packages:pycryptodomeFlaskmarshmallowcx-OracleRequirementsPython 3.6+Boto 3+Oracle ClientInstallationUse the package managerpipto install py flask micro service core .pipinstallboto3 pipinstallzpyFeaturesContains some helper features with specific integrations.ApiApi BuilderResponse BuilderModelsHooksMiddlewaresExceptionsRepositoriesOnly oracle repository implementation for functions calling.Cloud ImplementationsAWS ServicesS3SSMFirehoseSQSCustomPlugingsDatabaseOnly Oracle implementationFunctions executorLoggerStreamUtilsCollectionsCipherFunctionsgzipBasic UsageDefine restful resourcefromzpy.api.resourceimportZResource,HTTP_METHODSclassUserResource(ZResource):def__init__(self,**kwargs)->None:super().__init__()# Receive any dependency by keywords argumentsdefget(self):l,i=super().new_operation()try:returnself.success({"user":{"name":"Zurckz"}},logger=l)exceptExceptionase:returnself.handle_exceptions(e,l,i)Setup api#Define api@api(base='/v1',config=config)defcreate_api():#Set all supported resource for this web service.return\[ZResource('/',UserResource)]Local Dev Deployfromapiimportcreate_apiapp=create_api()# 🚨 Only use it in local tests 💻if__name__=="__main__":app.run(host="localhost",debug=True)ContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMITAuthorsNoé Cruz
zpylib
Zpy LibZpy Lib - Chinese programming lib快速开始通过pip安装pipinstallzpylib创建后缀为.zpy的文件(例:test.zpy)touchtest.zpy编写代码星星数 = 12 如果 星星数 % 2 != 1: 星星数 += 1 对于 层数 在 范围(舍入((星星数-1)/2)+1): 星星 = '*'*(层数*2+1) 打印(星星.center(星星数, " "))通过命令行运行文件zpyruntest.zpy编译成python文件zpybuildtest.zpy
zpyshell
Zpy shell=================![ZpyContent](https://github.com/albertaleksieiev/zpy/raw/content/img/screenshot-1.png)**Next level command line shell with script languages, like python or js. Work in shell with your favorite language.**```(Zpy) pwd | "Current folder %s" % z | catCurrent folder /Users/XXXX/pytho-nal(Zpy) j request = require('request')(Zpy) j ['New York', 'Paris', 'London', 'Berlin', 'San Francisco']|[for] j request(`http://weathers.co/api.php?city=${z}`, (err,res,body) => sync(JSON.parse(body).data))|j z.map((data) => `${data.location} has temperature ${data.temperature} °F`)|[for] echo $z >> weather.txt['', '', '', '', ''](Zpy) cat weather.txtNew York has temperature -7 °FParis has temperature -7 °FLondon has temperature -7 °FBerlin has temperature 4 °FSan Francisco has temperature 24 °F```### Demo![Zpy Demo](https://github.com/albertaleksieiev/zpy/raw/content/img/zpy_demo.gif)Combine Python and JavaScript together in the terminal is really easy! Just look at [Full Video](https://asciinema.org/a/3fam2wma6o16onjx01xdod0fe) with additional features!### PipelineZpy ideology says - pipeline make work in terminal great again! Pipeline play the major role in zpy. If you want to use every opportunity of Zpy you should know a few things about the pipeline. Input command will be splited by pipeline character, each of token will be evaluated by shell,python or js interpreter, and tokens will be chained into 1 chain. Zpy pass previous token evaluation result as stdin to next token and you have access to z-variable if token not expects to stdin. So Zpy pipes work like standard unix pipes.### SyntaxIf you want use Zpy you should a few rules.* Command will be evaluated by **unix system** if you add **`** symbol in begin of the token, or you command begin with [142 linux commands](http://www.mediacollege.com/linux/command/linux-command.html)* Command will be evaluated by [**javascript**](#javascript) language if you add `j` at begining of token.* Command will be evaluated by [**Chain Pool**](#chain-pool) if you add specific characters like `for` in the begin the line.* Command will be evaluated by [**python**](#python) command **in any other case**(by default just evaluate python code - python is default language)#### From Python to Unix```(Zpy) "\n".join(["Zpy so awesome #review #1e%s"%i for i in range(10)]) | grep "5\|6\|8"Zpy so awesome #review #1e5Zpy so awesome #review #1e6Zpy so awesome #review #1e8```Generate array with text joined with number from zero to ten, join it by using `\n` character, that we can use it in **unix pipe** cause grep use data splited by `\n` characher. Filtering results by using **grep** command, show only string which contrains 5,6 or 8 digits.```(Zpy) "%s.%s" % ('index','php') | cat $zcat: index.php: No such file or directory(Zpy) "%s.%s" % ('index','cpp') | touch $z```Generate "index.php" as z-value, and send it to next pipe. Last pipe will be evaluated by unix system, we have access to z-variable as like path variable or stdin. So you can write `$z` to access variable `...|touch $z` or stdin `...|grep "index"`.#### From Unix to Python```(Zpy) ls | z.split('\n') | filter(lambda x : 'index' in x, z) | list(z)['index.py']```Get current files, convert it into array and filter it by some conditionWe have access to z-variable as `z`.#### From (Unix or Python) to Js and backAs you can see abowe, we have access to `z` variable from unix or python just use `z` or `$z` variables, this rule works the same way in js.```(Zpy) 'http://weathers.co/api.php?city=New+York' | j req(z, (err,res,body) => sync(body)) | j JSON.parse(z).data | "Today is %s and current temperature %s" % (z['date'], z['temperature'])Today is 03-12-2017 and current temperature -14````python` -> `javascript`-> `javascript`-> `python`Get current temperature and date from weather.co.**Note** here we use `sync` function from javascript, this command will send data from **Async** function call (see description in javascript section).#### Salad of languages```(Zpy) j [1,2,3,4].map((e) => `js ${e}`) | ["python + %s" %x for x in z] | "\n".join(z) | sed -e 's/$/ + bash = Zpy/'python + js 1 + bash = Zpypython + js 2 + bash = Zpypython + js 3 + bash = Zpypython + js 4 + bash = Zpy```How about dah? `javascript` -> `python` -> `bash`### Requirements* Python 3* pip3* compgen* nodejs or any other js runtime.### InstallInstall via pip```pip3 install zpyshell```Install from github sources:```git clone [email protected]:albertaleksieiev/zpy.gitcd zpy;pip3 install -r requirements.txt```If you want use power of js, install [nodejs](https://nodejs.org/en/).### RunIf you install zpy via pip just run in terminal```$ zpy```But if you install from sources, navigate to repository root folder and run it like python script```python3 Zpy/main.py```### Test```python3 tests/main_test.py```-----## LanguagesCurrently zpy support 3 languages* [Python](#python)* [Javascript](#javascript)* Unix shell script* [Chain Pool](#chain-pool) (additional language)### More languagesNow Zpy supports python and js, but in the first release, we will add more languages!## PythonZpy written in python, so python it's the first language which was be added and supported.* [Imports](#python-imports)* [Default imports](#default-imports)* [Own modules](#adding-new-module)* [Create python module](#1create-python-module)* [Import module](#2add-module-to-zpy)* [Advanced usage pipe and module](#3processing-input-from-pipe)### Python ImportsIf you wan't import some modules into zpy, just add `~` in the begging and type your import command.```(Zpy) ~import random,os(Zpy) ~from PIL import Image(Zpy) find /Users/XXXX/Pictures -name "*.jpg" | z.split('\n') | z[random.randint(0,len(z))] | Image.open(z).show()```Show random Image from your Pictures folder.**Note: change /Users/XXXX/Pictures to your folder with images**```(Zpy) ~import os(Zpy) pwd | os.listdir(z)['__pycache__', 'a.txt', 'index.py', 'linux-command-to-list-all-available-commands-and-aliases', 'README.md', 'Zpy'](Zpy) ~from Zpy.Utils import get_linux_commands['adduser', 'arch', 'awk', 'bc', 'cal', 'cat', 'chdir', 'chgrp', 'chkconfig', 'chmod', 'chown', 'chroot', 'cksum', 'clear', 'cmp', 'comm', 'cp', 'cron', 'crontab', 'csplit', 'cut', 'date', 'dc', 'dd', 'df', 'diff', 'diff3', 'dir', 'dircolors', 'dirname', 'du', 'echo', 'ed', 'egrep', 'eject', 'env', 'expand', 'expr', 'factor', 'FALSE', 'fdformat', 'fdisk', 'fgrep', 'find', 'fmt', 'fold', 'format', 'free', 'fsck', 'gawk', 'grep', 'groups', 'gzip', 'head', 'hostname', 'id', 'info', 'install', 'join', 'kill', 'less', 'ln', 'locate', 'logname', 'lpc', 'lpr', 'lprm', 'ls', 'man', 'mkdir', 'mkfifo', 'mknod', 'more', 'mount', 'mv', 'nice', 'nl', 'nohup', 'passwd', 'paste', 'pathchk', 'pr', 'printcap', 'printenv', 'printf', 'ps', 'pwd', 'quota', 'quotacheck', 'quotactl', 'ram', 'rcp', 'rm', 'rmdir', 'rpm', 'rsync', 'screen', 'sdiff', 'sed', 'select', 'seq', 'shutdown', 'sleep', 'sort', 'split', 'su', 'sum', 'symlink', 'sync', 'tac', 'tail', 'tar', 'tee', 'test', 'time', 'touch', 'top', 'traceroute', 'tr', 'TRUE', 'tsort', 'tty', 'umount', 'uname', 'unexpand', 'uniq', 'units', 'unshar', 'useradd', 'usermod', 'users', 'uuencode', 'uudecode', 'vdir', 'watch', 'wc', 'whereis', 'which', 'who', 'whoami', 'xargs', 'yes']```Print all linux commands defined in zpy.#### Default importsIf you don't want import general modules like `os` every time when you launch zpy, you can use **default imports**You just need execute zpy method `add_def_imports`.```(Zpy) zpy.add_def_imports("numpy","import numpy as np")(Zpy) zpy.get_def_imports()numpy => import numpy as np```Done! When you launch Zpy, this modules will be imported automatically. Let's try evaluate something.```(Zpy) np.arange(20)[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19](Zpy) np.arange(20) | np.std5.76628129734```**Note** Here we use np.std without input arguments, Zpy will pass z-value as 1 argument to function and evaluate it.Function will be evaluated with z parameter as argument by default, if return type of evaluation is function.#### ModulesZpy have some cool things, like modules! Modules is your own script which will be imported by default. Zpy have own zpy module.```(Zpy) zpy<Zpy.languages.zpy.zpy object at 0x10268d2e8>```zpy is just python class, which can storage some information (like scripts).zpy Methods :- - return list of scripts- add_script(name) - Currying `add_new_script` method, returns `add_new_script(name=name)`- add_new_script(name, script) - create new script- remove_script(name) - remove script- eval(name, input='') - eval script and send input- eval_with_input(name) - Currying `eval` method, returns `eval(name=name)`- last_zcommand() - return last z-command. **Note** after evaluation `last_zcommand()` method and value returns,, last z-command will be `last_zcommand()`- add_module(module_name, path_to_module_file_py) - add module, it will be available from zpy like `module_name`- get_modules() - returns all modules- remove_module(name) - remove module by name, **file will not be deleted**- as_table(data) - trying to convert string to table data```(Zpy) zpy.get_scripts()(Zpy) zpy.add_new_script("ls", "ls -lah")(Zpy) zpy.get_scripts()ls => ls -lah(Zpy) zpy.eval('ls')total 408drwxr-xr-x 9 albert staff 306B Feb 27 22:29 .drwxr-xr-x 33 albert staff 1.1K Feb 24 22:47 ..drwxr-xr-x 8 albert staff 272B Feb 27 22:36 .idea-rw-r--r-- 1 albert staff 6.1K Feb 27 22:13 README.mddrwxr-xr-x 7 albert staff 238B Feb 27 22:35 Zpy-rw-r--r-- 1 albert staff 685B Feb 27 22:25 index.py-rw-r--r-- 1 albert staff 182K Feb 1 20:00 linux-command-to-list-all-available-commands-and-aliases-rw-r--r-- 1 albert staff 36B Feb 27 15:47 random.file-rw-r--r-- 1 albert staff 24B Feb 27 22:13 zpy.conf```Some advanced stuff```(Zpy) ~import requests, json(Zpy) requests.get('http://finance.google.com/finance/info?client=ig&q=NSE:HDFC') | z.text | z.replace('//','') | json.loads(z)[0] | z['pcls_fix']1375.7(Zpy) zpy.last_zcommand()requests.get('http://finance.google.com/finance/info?client=ig&q=NSE:HDFC') | z.text | z.replace('//','') | json.loads(z)[0] | z['pcls_fix'](Zpy) zpy.last_zcommand()zpy.last_zcommand()(Zpy) requests.get('http://finance.google.com/finance/info?client=ig&q=NSE:HDFC') | z.text | z.replace('//','') | json.loads(z)[0] | z['pcls_fix']1375.7(Zpy) zpy.last_zcommand() | zpy.add_script("Get stock NSE:HDFC")(Zpy) zpy.eval('Get stock NSE:HDFC')1375.7```#### Adding new moduleYou may want to add the module to Zpy functionality written in python, in Zpy you can do this in few steps##### 1)Create python module```(Zpy) pwd/path(Zpy) cd to(Zpy) pwd/path/to(Zpy) ['def square(a):','\treturn a * a'] | "\n".join(z) | cat > some_module.py(Zpy) cat some_module.pydef square(a):return a * a```##### 2)Add module to ZpyRun zpy method `add_module` from zpy python module.```(Zpy) zpy.add_module("some_model","/path/to/some_module.py"```Or edit **zpy.conf** file - add name and py file location to [MODULE] section :```....[MODULE]....some_model = /path/to/some_module.py```*zpy.conf*And try evaluate method from some_module```(Zpy) some_module.square(4)16```##### 3)Processing input from pipePassing pipe output to your module function - really easy. You just need declare `zpy_input` in your function argument list :```def square(a):return a * adef square_from_pipe(zpy_input):return square(zpy_input)```*some_module.py*```(Zpy) 12 | some_module.square_from_pipe144```Also, we can use currying if we want implement pow function, we should pass 2 variables - base value and exponent value. But pipe can send only 1 variable, we can pass them as string array and parse them inside our function **OR** we can use carrying,```import mathdef square(a):return a * adef square_from_pipe(zpy_input):return square(zpy_input)def power(base, exponent=None):if exponent is None:def currying_function(zpy_input):return math.pow(base, zpy_input)return currying_functionelse:return math.pow(base, exponent)```*zpy.conf*Universal function power is done! Let's test it```(Zpy) some_module.power(2)(2)4.0(Zpy) some_module.power(2)(4)16.0(Zpy) 5 | some_module.power(2)32.0```## JavascriptJavascript one of the most popular language ever, so zpy work with them. You can use nodejs with some features like File System I/O, or other JS runtime. Special thanks for [PyExecJS](https://github.com/doloopwhile/PyExecJS)! Zpy use this module inside, so you can see the full list of available runtimes in the link above.Everybody knows javascript use async functions, this is a problem cause pipes do not works async. This problem will be solved bu using [`sync`](#sync-function) or [`sync_err`](#sync_err) functions.* [Syntax](#js-syntax)* [Imports](#js-imports)* [Default imports](#js-default-imports)* [Async](#async-to-sync)* [`sync` function](#sync-function)* [`sync_err` function](#sync_err)### JS SyntaxCommand will be evaluated by **javascript** command if you add `j` at begining of token.```(Zpy) j 2 + 35```### JS ImportsIf you wan't import some modules into js chain, use `require`.```npm i request --global...(Zpy) j request = require('request')Added new requirements : { [['request', 'request']] }```**Note** your modules should be installed globaly##### JS Default importsIf you want import general modules like `request` every time when you launch Zpy, you can use **default imports**.You just need execute method `add_def_imports` from `zjs` object.```(Zpy) zjs.add_def_imports('request', 'require("request")')(Zpy) zjs.get_def_imports()request => require("request")```Done!### Async to SyncAs I wrote above, we should have ability going from async function to sync function, but why we cannot use async without any modification? If we want make a request and after request send data to next chain, request should be fineshed before we go to next chain.```(Zpy) j [1,2,3].join("-") | z.split("-")['1', '2', '3'] //It's work great! Cause js chain not async.(Zpy) j request('http://weathers.co/api.php?city=New+York', (err,res,body) => ""){'method': 'GET', 'uri': {'auth': None, 'path': '/api.php?city=New+York', 'host': 'weathers.co', 'hostname': 'weathers.co', 'hash': None, 'query': 'city=New+York', 'protocol': 'http:', 'port': 80, 'search': '?city=New+York', 'href': 'http://weathers.co/api.php?city=New+York', 'pathname': '/api.php', 'slashes': True}, 'headers': {'host': 'weathers.co'}}```As we can see result of evaluation request function is object with request properties like href, headers, host etc. Zpy trying convert it to JSON format. If result of evaluation is `function` and this function has attribute `skip_print='zkip_'` zpy skip result of evaluation (it will be helpfull in async function calls). **Zpy do not return evaluation result if this is a func and func has properties `skip_print='zkip_'` or we use `sync`, `sync_err` function call.**#### `sync` function`sync` command will send data from **Async** function call and finish current chain. It's realy easy to use.```(Zpy) j request('http://weathers.co/api.php?city=New+York', (err,res,body) => sync(body)) | "Python retreive requests results from js `%s`" %zPython retreive requests results from js `{"apiVersion":"1.0", "data":{ "location":"New York", "temperature":"-14", "skytext":"Light snow", "humidity":"64", "wind":"7.56 km/h", "date":"03-12-2017", "day":"Sunday" } }````#### `sync_err`Throw error from async function call.```(Zpy) j setTimeout(function(){ sync_err('SOME ERROR') },200)Traceback (most recent call last):File .......execjs._exceptions.ProgramError: SOME ERROR```## Chain PoolChain pool is programming language which have a lot of usefull functions inside Zpy. To start use functions like `[for]` just type this keyword after pipe character `|`, like `|[for]`. Square brackets` []` indicate *Chain pool* function `for`. Chain pool take **stdin** as input stdin, and do some work with stdin, what work you enter after `|[CHAIN_FUNCTION]` keyword, you can use your **favorite language** with Chain pool function.### `[for]` function`[for]` function iterate throught every item in *array* or *data splited by `\n`* character as stdin and evaluate every iterated item by any other language.#### Syntax**`[`** `for` **`]`** `any other language command`, where `[]` is *Chain pool* syntax, `for` - for function.![Chain pool [for] function](https://raw.githubusercontent.com/albertaleksieiev/zpy/content/img/Chain%20Pool%20%5Bfor%5D%20function.jpg)Here we generate data by python, simply by typing array initialization keyword, after that we use `[for]` keyword, split this array to 2 stdin arguments, evaluate shell function `ls` for every argument ('folder1' and 'folder2') and finally join result into array, and send into next chain. And in the last chain we just concatenate array by `,` character.```(Zpy) ['.', '..'] |[for] ls $z | ','.join(z)LICENSE.txtREADME.mdZpy ...., parent_folder content```Code for diagram above. Generate array, use *Chain pool* function `for` and join results by using ',' character.```(Zpy) ~import numpy as np(Zpy) np.arange(10).reshape(2,5).tolist() |[for] [for] z**2[[0, 1, 4, 9, 16], [25, 36, 49, 64, 81]]```Iterate every row and column and change every value, by `power` function.#### Examples```(Zpy) ~import os(Zpy) pwd | os.listdir(z) | "Files divided by commma %s" % ",".join(z)Files divided by commma .idea,__pycache__,a.txt,index.py,linux-command-to-list-all-available-commands-and-aliases,README.md,Zpy```Get current directory using shell command, pipe into python code as z-variable and print result of last chain```(Zpy) ~from terminaltables import AsciiTable, SingleTable(Zpy) ls -lah | z.split('\n') | [' '.join(x.split()).split(' ') for x in z] | SingleTable(z).table┌────────────┬────┬────────┬───────┬──────┬─────┬───┬───────┬────────────────┐│ total │ 8 │ │ │ │ │ │ │ │├────────────┼────┼────────┼───────┼──────┼─────┼───┼───────┼────────────────┤│ drwxr-xr-x │ 4 │ albert │ staff │ 136B │ Mar │ 4 │ 23:32 │ . ││ drwxr-xr-x │ 10 │ albert │ staff │ 340B │ Mar │ 4 │ 23:34 │ .. ││ -rw-r--r-- │ 1 │ albert │ staff │ 0B │ Mar │ 4 │ 23:32 │ empty_file.txt ││ -rw-r--r-- │ 1 │ albert │ staff │ 9B │ Mar │ 4 │ 23:32 │ not_empy.txt ││ │ │ │ │ │ │ │ │ │└────────────┴────┴────────┴───────┴──────┴─────┴───┴───────┴────────────────┘```Convert ugly result after evaluation `ls -lah` to great table!**Note** This functionality available inside zpy module `ls -lah | zpy.as_table````(Zpy) ['http://google.com','http://yandex.ru'] |[for] j request(z, (err,res,body) => sync(body))``````(Zpy) `wget -qO- http://example.com | z.split(" ") | filter(lambda x : "head" in x,z) | list(z)['html>\n<html>\n<head>\n', '\n</head>\n\n<body>\n<div>\n'](Zpy) `wget -qO- http://example.com | z.split(" ") | filter(lambda x : "head" in x,z) | list(z) | "Total size : %s" % len(z)Total size : 2```Download content from page and count current entrance word 'head'```(Zpy) find ./ -name "*.py" | z.split("\n")[:2]['.//index.py', './/Zpy/languages/LanguageAnalyzer.py'](Zpy) find ./ -name "*.py" | z.split("\n")[:2] | "\n".join(z) |grep "an".//Zppy/languages/LanguageAnalyzer.py```First evaluation will find file in current directory and get first 2 results. Second evaluation do the same plus filter results by shell command `grep````(Zpy) ~import re(Zpy) "https://www.reddit.com/r/books/" | `wget -qO- $z | re.findall(r"Book[^\.].*?",z,re.IGNORECASE) | "COUNT : %s" % len(z)COUNT : 645``````(Zpy) ~import uuid(Zpy) uuid.uuid4() | str(z) | cat > random.file(Zpy) cat random.file7ff48f51-b31d-44c2-9aaf-428a63099739```### **Danger tricks** (Do not evaluate)```(Zpy) ~from Zpy.Utils import get_linux_commands(Zpy) ~import random,os(Zpy) get_linux_commands() | z[random.randint(0,len(z))] | os.system(z)staff com.apple.sharepoint.group.1 everyone localaccounts _appserverusr admin _appserveradm _lpadmin _appstore _lpoperator _develope...```Get all shell commands declared in Zpy, and execute random one```(Zpy) ~import random,os(Zpy) ['you are lucky','displaysleepnow','lock'] | z[random.randint(0,len(z))] | os.system("pmset %s" %z)0```If you run on OSX, 33% nothing happens### LicenseThe module is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
zpystream
python stream
zpython-tools
ZPYTHON TOOLS PACKAGEThis package is mainly used to build utils with python, the utils will be as many as needed, e.g, we have a util for manging kafka broker meta.properties.HOW TO USESpip install zpython-tools==0.0.5broker-meta-management –zookeeper-url=localhost:3181 –log-dir=/Users/jliu/kafka/data –max-broker-id=1008
zpytrading
zpytradingPython - Zinnion SDKhttps://pypi.org/project/zpytrading/pip3 install --upgrade --force-reinstall --no-cache-dir zpytradingsudo -H pip3 install zpytradingRequirementsYou need to download and export the path tolibztrading.sohttps://github.com/Zinnion/zpytrading/wikiExampleimportzpytradingimportjsonimportosimportsysdefinit():zTrading=zpytrading.ZinnionAPI()streamingr_config='{"subscriptions": [ "BINANCE_SPOT_BTC_USDT"], "channels": ["trade","indicator"], "comment": "lets do it" }'zTrading.add_streaming(streamingr_config)indicators_config='{"indicators_config":[{"indicator_name":"decay","name":"","plot":true,"symbol_id":"BINANCE_SPOT_BTC_USDT","options":[9],"data_in_bar_type":["close"],"bar_type":"simple","timeframe":1,"max_bars":30}]}'zTrading.add_indicators(indicators_config)zTrading.start_streaming(handle_data)defhandle_data(self,data):print(data)if__name__=="__main__":init()Indicator Listing104 total indicators Overlay avgprice Average Price bbands Bollinger Bands dema Double Exponential Moving Average ema Exponential Moving Average hma Hull Moving Average kama Kaufman Adaptive Moving Average linreg Linear Regression medprice Median Price psar Parabolic SAR sma Simple Moving Average tema Triple Exponential Moving Average trima Triangular Moving Average tsf Time Series Forecast typprice Typical Price vidya Variable Index Dynamic Average vwma Volume Weighted Moving Average wcprice Weighted Close Price wilders Wilders Smoothing wma Weighted Moving Average zlema Zero-Lag Exponential Moving Average Indicator ad Accumulation/Distribution Line adosc Accumulation/Distribution Oscillator adx Average Directional Movement Index adxr Average Directional Movement Rating ao Awesome Oscillator apo Absolute Price Oscillator aroon Aroon aroonosc Aroon Oscillator atr Average True Range bop Balance of Power cci Commodity Channel Index cmo Chande Momentum Oscillator cvi Chaikins Volatility di Directional Indicator dm Directional Movement dpo Detrended Price Oscillator dx Directional Movement Index emv Ease of Movement fisher Fisher Transform fosc Forecast Oscillator kvo Klinger Volume Oscillator linregintercept Linear Regression Intercept linregslope Linear Regression Slope macd Moving Average Convergence/Divergence marketfi Market Facilitation Index mass Mass Index mfi Money Flow Index mom Momentum msw Mesa Sine Wave natr Normalized Average True Range nvi Negative Volume Index obv On Balance Volume ppo Percentage Price Oscillator pvi Positive Volume Index qstick Qstick roc Rate of Change rocr Rate of Change Ratio rsi Relative Strength Index stoch Stochastic Oscillator stochrsi Stochastic RSI tr True Range trix Trix ultosc Ultimate Oscillator vhf Vertical Horizontal Filter volatility Annualized Historical Volatility vosc Volume Oscillator wad Williams Accumulation/Distribution willr Williams %R Math crossany Crossany crossover Crossover decay Linear Decay edecay Exponential Decay lag Lag max Maximum In Period md Mean Deviation Over Period min Minimum In Period stddev Standard Deviation Over Period stderr Standard Error Over Period sum Sum Over Period var Variance Over Period Simple abs Vector Absolute Value acos Vector Arccosine add Vector Addition asin Vector Arcsine atan Vector Arctangent ceil Vector Ceiling cos Vector Cosine cosh Vector Hyperbolic Cosine div Vector Division exp Vector Exponential floor Vector Floor ln Vector Natural Log log10 Vector Base-10 Log mul Vector Multiplication round Vector Round sin Vector Sine sinh Vector Hyperbolic Sine sqrt Vector Square Root sub Vector Subtraction tan Vector Tangent tanh Vector Hyperbolic Tangent todeg Vector Degree Conversion torad Vector Radian Conversion trunc Vector Truncate
zpywallet
ZPyWalletZPyWallet is a Python-based hierarchical deterministic (HD) wallet generator and transaction manager. HD wallets allow you to generate a tree-like structure of cryptographic key pairs from a single seed phrase, providing a convenient way to manage multiple accounts or addresses securely.ZPyWallet can generate transactions quickly, because it defers transaction validity to the broadcasting stage. It can also coordinate the creation and broadcasting of transactions to different nodes, and can decode transactions as well.BIP32 (or HD for “hierarchical deterministic”) wallets allow you to create child wallets which can only generate public keys and don’t expose a private key to an insecure server.FeaturesSimple BIP32 (HD) wallet creation for BTC, BCH, ETH, LTC, DASH, DOGE, and many other networksGenerate a hierarchical deterministic wallet from a mnemonic seed phrase.Create and broadcast RBF-aware transactions to pre-defined or custom nodesDecode existing transactionsMonitor for incoming transactionsGet the latest fee rates for mainnet networksDerive multiple accounts or addresses from the generated wallet.Support for popular cryptocurrencies such as Bitcoin, Ethereum, and more.BIP32 and BIP39 compliant.Secure key generation using the industry-standard libsecp256k1 library, resistant to side-channel attacks.Supports generating P2WPKH (segwit) keys and bech32 addresses for supported networksSign and verify messages in Bitcoin-Qt and RFC2440 formatLimitationsAddress types that use complex scripts such as P2WSH, P2WPKH-P2SH, and Taproot currently can only be decoded but not created.Multisig addresses are not supported.Transactions cannot be created with timelocks yet.In the case of Ethereum, alternate chains (e.g. Testnet) are not supported yet.HistoryZPyWallet started out as a fork ofPyWallet <https://github.com/ranaroussi/pywallet>with elements ofBitmerchant <https://github.com/sbuss/bitmerchant>, just to simply make these modules run. At the time, it was just an HD wallet generator. However, as time went by, I discovered serious bugs in both programs, such as incorrect master private key genration, and the use of ECDSA code that is vulnerable to side-channel attacks, Thus I have embarked on a complete rewrite of the codebase so that it follows crypto security best practices. And thus we arrive to the present day: A robust wallet generator that supports altcoins, segwit, sign/verify, and can be used as a backend to implement custom wallet software.Enjoy!InstallationInstall via PiP:$pipinstallzpywalletOr build directly:$gitclonehttps://github.com/ZenulAbidin/zpywallet$cdzpywallet# Developers should also run "pip install -r requirements-dev.txt"$pythonsetup.pyinstallExample code:Note that this code is probably out-of-date.Create HD WalletThe following code creates a new Bitcoin HD wallet:# create_btc_wallet.pyfromzpywalletimportwallet# creates a wallet with a new, random mnemonic phrase.# By default, it creates Bitcoin Mainnet wallets.w=wallet.create_wallet_json(children=1)print(w)Output looks like this:$pythoncreate_btc_wallet.py{'address':'bc1qjvugs62gt5w97rv4sw3kkhnmv2s2kg58lucmux','children':[{'address':'bc1q5vyxj4a6c2v4p9dxrd59vztfussg9hdywr5yrn','bip32_path':"m/44'/0'/0'/0",'path':'m/0','xpublic_key':'xpub68yG1oCYQLpAKxj3DPo6cvqAzNEeUFMhMfEhXcEyem1vqK87QeaQH8o7uUw8fYkhtuVcMiJrxbLFDyESnK8YPQ97fSzPpPLTiauEWyqTX76'}],'coin':'BTC','private_key':'45471d4504a3631425371a590d168fa0df4f01c7fe5df2b355da6434145b6915','public_key':'0286e42376ab09ce71b2be8174f2ebbf2f79fef9ca0c255838c2016951b7b4411f','seed':'spring ahead flat scheme can opera genre tribe airport friend nurse ''exclude','wif':'5JLoBxMCZCAqnue56GZZLquzPwob6XHdJttKJn19qGShKQgE2xM','xprivate_key':'xprv9s21ZrQH143K28nnAjfgJ9eRCmQMYuBtbKWVZLqsEc7aBYh81uLFHQoKt2dZdSyKAu6KaFSiqjWyZejrtx3FmRjRaf1KsBFgkNM4CMm66Jh','xpublic_key':'xpub661MyMwAqRbcEcsFGmCgfHb9koEqxMujxYS6MjFUnweZ4M2GZSeVqD7ojJAE5QvmbXn16QPHcHLk5bkdkqXtcV1nj1aVyRqax9NeaTAnhH6','xpublic_key_prime':'xpub68yG1oCgk1M8XBxmkp6f6JgRdTyX6XJd7a6LmDG14DomrswTMkxGiByKiwpf5p6szSqDciybesxjDC7yKBrgbaczQe6q1puBHbvfKxg1uqr'}Similarly, you can do the same for an Ethereum wallet:# create_eth_wallet.pyfromzpywalletimportwalletw=wallet.create_wallet_json(network="ETH",children=1)print(w)Output looks like this (no WIF or xpub/prv for Ethereum as its not supported):$pythoncreate_eth_wallet.py{'address':'0x8dbe02c146eacbe410f63348f489a16160deb6f0','children':[{'address':'0xdd030270458ad17b125c200bb2f11d0fdbf7e05c','path':'m/0'}],'coin':'ETH','private_key':'85b41c45f425dd1f7f431326449afc0564b2d110f7f89563f1a1ee4055a4ce39','public_key':'026e93d77ee81bd28e2d2e0962928a00ee27a20f0da2b7437db8bce39e23c6d873','seed':'admit push digital opinion system snap announce help gas business ''trigger please','wif':'','xprivate_key':'','xpublic_key':''}Consult the documentation for more information about the API.Create Child WalletYou can create child-wallets (BIP32 wallets) from the HD wallet’sExtended Public Keyto generate new public addresses without revealing your private key.Example:# create_child_wallet.pyfromzpywalletimportwalletfromzpywallet.utils.bip32importWalletw=Wallet.from_mnemonic(wallet.generate_mnemonic())# generate address for specific user (id = 10)child_w=w.get_child_for_path("m/10")user_addr=child_w.address()print(f"User Address:{user_addr}")Output looks like this:$pythoncreate_child_wallet.pyUserAddress:bc1qdwfh4duva4hvzva9cdyguh9c9k2hez3r7taergCONTRIBUTINGBugfixes and enhancements are welcome. Please read CONTRIBUTING.md for contributing instructions.At the moment, I’m not accepting pull requests for new coins unless they are big and historic coins such as Tether (ERC20), BNB and XMR.SECURITYThis module has been hardened against various types of attacks:Runtime dependencies are kept to an absolute minimum. Only modules that have compile-time native code are installed using pip. The rest are hardcoded directly into ZPyWallet. This prevents many kinds of supply chain attacks.Coincurve is using libsecp256k1, which protects keys from various power and RF frequency analysis side-channels.NO WARRANTYZPyWallet is provided without any sort of warranty of any kind. Additionally, I am not responsible for damages caused by the use of this program, including but not limited to lost coins. Read the license file for full details.
zpy-zumo
zpy: Synthetic data in Blender.AbstractCollecting, labeling, and cleaning data for computer vision is a pain. Jump into the future and create your own data instead! Synthetic data is faster to develop with, effectively infinite, and gives you full control to prevent bias and privacy issues from creeping in. We createdzpyto make synthetic data easy, by simplifying the simulation (sim) creation process and providing an easy way to generate synthetic data at scale.Check out our fulldocumentation:bookmark_tabs:What's New? :rocket:(06/23/21) Check out our newscript writing guide(06/17/21) Read ourlatest articleon our blog!(06/08/21) Blender 2.93 Support is out! Latest features can be foundon blender.org.Install:thinking:You can installzpywith pip:pip install zpy-zumoMore installation instructions can be found in the docs:Install using pip(Windows/Mac/Linux)Install Blender Addon from .zip(Windows/Mac/Linux)Install from script(Mac/Linux)Developer mode(Linux)Developer mode(Windows)OSStatusLinux:heavy_check_mark:MacOS:heavy_check_mark:Windowszpy#126Contribute:busts_in_silhouette:We welcome community contributions! Search through thecurrent issuesor open your own.License:page_facing_up:This release of zpy is under the GPLv3 license, a free copyleft license used by Blender. TLDR: Its free, use it!Citation:writing_hand:If you usezpyin your research, we would appreciate the citation!@misc{zpy,title={zpy: Synthetic data for Blender.},author={Ponte, H. and Ponte, N. and Crowder, S.},journal={GitHub. Note: https://github.com/ZumoLabs/zpy},volume={1},year={2021}}
zpz
Python UtilitiesThis repo collects some small Python utilities that I have created (or collected) in practice, and organizes them as a package namedzpz.These utilities are not "one-off" experiments; they are really useful code. However, they do not form a coherent set of utilities for a particular application domain. There is no plan to maintain this code as a coherent library. This package is uploaded topypi. Consider it to be mainly for the author's personal convenience. Do not assume the releases will be maintained in a stable, regular, and backward-compatible way.One reasonable way to use it is to copy-paste whatever segments you find useful.To install, dopip install zpzThere are a few optional dependencies specified by 'avro' and 'lineprofiler'.
zq
ZQL - Zabbix Query Language and a Python Module================================================
zqadd
No description available on PyPI.
zq-auth-sdk
zq-auth-sdk-python自强统一认证 Python SDK简介依赖需求Python 3.9+安装安装 zq-auth-sdk 包使用pip安装:pipinstallzq-auth-sdk使用poetry安装:poetryaddzq-auth-sdk使用 zq-django-utilTODO
zq-config
zq-configIntroductionzq-config is wrapper library for config centers, such as nacos, etcd, apollo.Here is a program to usenacos:fromzq_configimportZQ_ConfigSERVER_ADDRESSES="localhost:8848"NAMESPACE="sho-test"USER_NAME="nacos"PASSWORD="nacos"zq=ZQ_Config("nacos",server_addresses=SERVER_ADDRESSES,namespace=NAMESPACE,username=USER_NAME,password=PASSWORD)config=zq.get("config-id","dev")print(config)TODOnacosetcdapollo
zq-django-template
zq-django-template自强 Studio Django 模板English Version简介zq-django-util 是自强 Studio 开发的 Django 模板,用于快速搭建 Django+DRF 项目。其中包括:使用zq-django-util工具搭建的基础框架JWT 认证OSS 存储、直传示例微信小程序登录示例(可选)Sentry 监控(可选)Celery 异步任务(可选)git 提交规范与代码检查Docker 配置与自动化部署使用说明详见使用说明文档开发使用 poetry 安装依赖,并进行项目修改
zq-django-util
zq-django-util自强 Studio Django 工具English Version简介zq-django-util 是用于辅助搭建 django-drf 应用的工具集合,其中包含:标准异常、响应处理jwt、微信认证oss 存储与直传默认分页类测试 ViewSet详细文档:zq-django-util.readthedocs.io依赖需求Python 3.8+Django 3.2+Django REST framework 3.12+强烈建议使用官方支持的最新版本,当前的测试环境为:Python 3.10, Django 4.1, DRF 3.14安装安装 zq-django-util 包使用pip安装:pipinstallzq-django-util使用poetry安装:poetryaddzq-django-util使用可以根据以下说明进行配置,以启用相关功能。使用文档开发本项目使用 Poetry 进行依赖管理,Pytest 进行单元测试。开发文档
zqifatools
No description available on PyPI.
zql
No description available on PyPI.
zqlib
This package is built for common python usage, and I will update for a long time.# How to upload to pypi? #https://juejin.im/post/5d370d94f265da1b8b2b9f71# 1. Build the package # pip install –user –upgrade setuptools wheel python3 setup.py sdist bdist_wheel# 2. Upload to website # pip3 install –user –upgrade twine # python -m twine upload –repository-urlhttps://test.pypi.org/legacy/dist/* python3 -m twine upload dist/*
zq-logger
No description available on PyPI.
zqmtool
python3 -m pip install --upgrade setuptools wheelpython3 setup.py sdist bdist_wheeltwine upload dist/*qiming_zou zqm@00123321
zqpy
使用老版本:pip install zqpy==0.1.48 使用新版本:pip install zqpy 新老版本区别在于:最前面位 0(老版本)1(新版本)
zqqonlymyrailgun
No description available on PyPI.
zq-tools
zq_loggergenerates a logger, preformatted with the file name, line number information, differrent levels of color, and can be output in the console and written to a file at the same time.If you use vscode to view the output log in the editor,ANSI Colorsextension is recommended to install.zq_tracinghelp generate json file used inchrome://tracingRelease Notes1.0.2: Fine grained control of different handlers0.9.9: add__repr__for zq_cycle0.9.8: supportfrom zq_tools import loggeras well asfrom zq_tools.zq_logger import default_logger as loggerfor shorter code0.9.7: fixsetLevelbug in zq_logger; use env value to initilize ZQ_Logger's controlling level0.9.6: increase version due to keep failing on uploading0.9.4: fix bug:zq_decorator.time_it(sync)0.9.3: updatezq_decorator:: do_nothing, pass_it, time_it(support sync and self-defined print)0.9.2: fix bug:.zq_loggertozq_tools.zq_logger0.9.1: usedefault_loggerinstead ofprint0.9.0: add decorator and manager:zq_decorator.timeit0.8.8: add decorator:zq_decorator.do_nothing0.8.7: add api:zq_tracing.enable_trace,zq_tracing.disable_trace0.8.6: add api:zq_tracing.record_init,zq_tracing.record_append0.8.5: add api:zq_tracing.set_start_timestamp0.8.4: fix bug, addcolorfulto dependency0.8.3: addzq_files0.8.2: supportfrom zq_tools.zq_logger import default_logger as logger0.8.0: useadd_log_fileto add a log file to the logger.0.7.0: re-think the color print logic0.6.0: rename function: logger.print* --> logger.prank*0.5.9: set level of print bewteen DEBUG and INFO, add*_rootfunctions0.5.8: implement__len__and__iter__for zq_cycle0.5.6: add colors for different rank. add filter for zq_logger0.5.5: disable color by default forprintandprint_all0.5.3: zq_logger supportsprint,print_all,set_rank0.5.1: move tag to ahead of msg0.5.0: zq_logger supports color API, add tag0.4.1: fix bug of zq_cycle0.4.0: add zq_cycle0.3.6: default unit of timestamp: us0.3.5: support manually specifiying tid/pid when callingzq_tracing.record_*0.3.4: fix bug0.3.3: add default logger, callzq_logger.get_logger(), return a pre-defined logger0.3.2: add async record, support nested and ordered tracing events0.3.1: add install dependencies0.3.0: outputpathnameinstead offilename, better support for IDE's jumping functionTODO:add setLogPath()
zquant
No description available on PyPI.
z-quantum-core
Failed to fetch description. HTTP Status Code: 404
zquantum-core
Failed to fetch description. HTTP Status Code: 404
zquery
Please go tohttps://github.com/WiseDoge/zquery
zqueue
相对别的队列模块提高了执行速度并且减少了资源开销Home-page: https://pypi.org/Author: zlyuanAuthor-email: [email protected]: GNU GENERAL PUBLIC LICENSEDescription: 本地队列模块为什么要做这个:1.目前的队列模块在进行数据put时会将对象进行序列化为bytes数据, 然后通过socket发送给调用get的进程, 然后再将bytes数据转化为原始对象, 中间会产生大量机器资源消耗, 并且费时间2.别的队列模块在使用的时候, 如果put的对象被装饰器装饰过, 调用get的进程在对bytes数据转化的时候会报错本地队列作用:1.使用方法类似于multiprocessing.Queue模块, 但是数据不会进行转换而是直接保存到一个列表中, 减少了资源消耗, 并且提高执行速度2.允许传入被装饰器装饰过的对象缺点:此队列的数据交换仅用于单个进程, 也就是说无法将数据共享到多进程或远程机器, 但是可以用于多线程Platform: allClassifier: Environment :: Web EnvironmentClassifier: Intended Audience :: DevelopersClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.5Classifier: Programming Language :: Python :: 3.6
zqw-pkgs
========================== zqw-pkgs 用来测试学习的包
zqy
No description available on PyPI.
zqybxqqwetest
UNKNOWN
zqybxqtest
No description available on PyPI.
zqygis
No description available on PyPI.
zqy_math
No description available on PyPI.
zqyMathTest
Failed to fetch description. HTTP Status Code: 404
zqytest
No description available on PyPI.
zqyTestFunction
郑钦元测试
zqy-utils
utilities lib used by zqy!
zr
zrAdWords reporting toolsTo install:pip install zr
zradio
zradioInstallationLinux:$pythonsetup.pyinstallUsage example$zradioDevelopment setup$virtualenvvenv $sourcevenv/bin/activate $pythonsetup.pydevelop $zradioRelease History- Work in progressMetaAndré P. Santos –@ztzandre–[email protected] under the XYZ license. SeeLICENSEfor more information.https://github.com/andreztz/zradioContributingFork it (https://github.com/andreztz/zradio/fork)Create your feature branch (git checkout -b feature/fooBar)Commit your changes (git commit -am 'Add some fooBar')Push to the branch (git push origin feature/fooBar)Create a new Pull Request
zram-advisor
Quick-start:If running python 5.11+, installpipx, and install withpipx install zram-advisorelse installpip, and install withpip install zram-advisor --userzram-advisor- reports on currently running zRAMzram-advisor --setup- configure/starts zRAM w defaults on system w/o rRAM already configured.zram-advisor: Check/Setup/Test zRAM Toolzram-advisorcan:Check on your running zRAM and report ill advised settings and zRAM effectiveness.Installfix-zramwhich can setup your zRAM and/or reload it with different parameters (e.g., for testing).Provide a browser bookmark file to be imported to help testing your settings.Checking Your Running zRAMChecking with zram-advisorHere is the sample output ofzram-advisorw/o arguments on a system with zRAM running:$ zram-advisor Distro : Linux Mint 21.3 180 : vm.swappiness.................. in [150, 200] 0 : vm.watermark_boost_factor...... in [0, 0] 125 : vm.watermark_scale_factor...... in [125, 125] 0 : vm.page-cluster................ in [0, 0] 1.6G : zRAM.disksize.................. >= 1.4G ================ 410s ================ 952.4M : Total Memory eTotal=2.2G/239% 830.2M/87% : Used eUsed=1.4G/155% 122.3M/13% : Available eAvail=800.7M/84% zram0: uncmpr: 814.5M limit=1.6G cmpr: 158.5M/17% factor=5.14 RAM: 165.5M/17% most=240M/25% limit=0The top section show key parameters for zRAM and suggested ranges (if it did not like those it would preface the range with "NOT in")The midsection shows traditional key memory stats on the left, and on the right, the "effective values":eUsed: is the amount of memory used if the compressed part in zRAM were expanded; than number is "true".eTotalandeAvailare projected numbers based on the current compression ratio; these number are more accurate as the zRAM memory footprint grows increases.The lower section are stats for each zram device .. typically, there is just one.uncmpr: is the amount of "original" memory stored by zRAM; its limit is officially called 'disksize' which is the name/value you see fromzramctl.RAM: is the amount of physical RAM consumed by zRAM including overhead;mostit the largest RAM used since boot.Checking with pmemstatAnother app (installable withpipxorpip) is `pmemstat``. The top of it sample output (on the same system as above) was:14:41:39 Tot=952.4M Used=741.5M Avail=210.9M Oth=0 Sh+Tmp=8.7M PIDs=122 0.6/ker zRAM=210.2M eTot:2.2G/240% eUsed:1.5G/166% eAvail:705.7M/74% cpu_pct pswap other data ptotal key/info (exe by mem) 9.8 945 100 195 1,239 T 122x --TOTALS in MB -- ─────────────────────────────────────────────────────────────────────────── 3.3 396 65 106 567 23x chromiumYou can see those same "effective" key memory stats, plus you can see kernel cpu% (i.e., the0.6/ker). Kernal CPU (most the swap process) can be significant, and that CPU cost is the primary "cost" of using zRAM).zram-advisor Optionsusage: zram-advisor [-h] [-s] [-d] [-t] [--DB] options: -s, --setup-fix-zram install "fix-zram" program and start zRAM -d, --dump-fix-zram print "fix-zram.sh" for manual install -t, --gen-test-sites print "bookmarks.html" to import to a web-browser for load test--setup-fix-zraminstalls a programsfix-ramand creates a service calledfix-zram-initto run it on boot.--dump-fix-zramprints the stockfix-zram.sh(e.g., so you can modify it) and install your modified script by running it (e.g.,bash my-fix-zram.sh).--gen-test-sitesprints a .html that can be imported into most browsers which creates folders of sites that can be opened to create typical memory demands (of browsers at least).Note:do not installfix-zramif w/o uninstalling any competing tool to configure zRAM.Controlling zRAM with fix-zramfix-zram.shis bash script bundled withzram-advisor. Its usage is:fix-zram [--(load|reload|unload|setup|unsetup)] [-n|--dry-run] [-cN] [N.Nx] [Nm|Ng] where: --{command} defaults to 'load' but can be one of: load - load/start zRAM with given params or their defaults reload - remove any existing zRAM and load zram unload - unloads any existing zRAM setup - copy fix-zram to '/usr/local/bin' and setup service [dflt=no] unsetup - remove '/usr/local/bin/fix-zram' and remove service [dflt=no] -n,--dry-run - only print commands that would be executed -c{integer} - set number of zram devices {float}x - set zram-size to {float} * ram at most [dflt=1.75] {integer}m - set gross zram-size to {integer} megabytes at most [dflt=12288m] {integer}g - set gross zram-size to {integer} gigabytes at mostfix-zram Run-Time Commandsload,reload, andunloadaffect the running system and any effect do not survive reboot. So, these can be used for testing (or initializing) zRAM.loadandreloadset thevm.*parameters shown byvram-advisor(but they do not unset them although a reboot will do that).unloadandreloadremove preexisting zRAM if running. Removal only works if all memory stored in zRAM can be placed in memory or another storage device.Typical use:fix-zram reload 3x 12g- will unload the current zRAM (if exists and possible), and then install zRAM with sized at the minimum of 3xRAM and 12GB.fix-zram Setup Methodsfix-zram --setup- installsfix-zramand creates azram-init-fixservice which will load zRAM per the defaults on each load with default values.fix-zram --unsetup- removes the installedfix-zramand removes thezram-init-fixservice.Typical use:fix-zram setup 3x 12g- installs a zRAM init service that start zRAM sized at the minimum of 3xRAM and 12GB on boot.
zran
ZRANRandom read access for ZLIB, GZIP and DEFLATE file formatsDescriptionzranis a Python extension that wraps thezranlibrary, which was created by Mark Adler (the creator ofzlib). This utility will create an index that will allow you to begin decompressing DEFLATE-compressed data (ZLIB, GZIP, or DEFLATE format) from compression block boundaries on subsequent reads. This effectively allows you to randomly access DEFLATE-compressed data once the index is created.Installationzrancan be installed in your preferred Python environment via pip:python-mpipinstallzranCurrently, only macOS/Linux x86_64 and ARM64 architectures are supported. Please open an issue or submit a PR if you would like to see support for other platforms!UsageTo usezran, you need to:Create an index for a compressed fileSave this indexUse this index to access the data on subsequent readsTo create and save the index:importzranwithopen('compressed.gz','rb')asf:compressed_file=f.read()index=zran.Index.create_index(compressed_file)ThisIndexcan be written to a file (index.to_file('index.dflidx')), or directly passed tozran.deompress:start=1000length=2000data=zran.decompress(compressed_file,index,start,length)That's it!ContributingWe use the standard GitHub flow to manage contributions to this project. Check out thisdocumentationif you are unfamiliar with this process.You can install a development version ofzranvia pip as well:gitclonehttps://github.com/forrestfwilliams/zran.gitcdzran python-mpipinstall.Then, runpytestto ensure that all tests are passing. We useblackwithline-length 120for formatting andrufffor linting. Please ensure that your code is correctly formatted and linted before submitting a PR. As far as I can tell, pip installing with the--editablecommand is not valid when the code needs to be compiled, so you will need to re-install the package if you make any changes.Similar ProjectsIf you prefer to work in the C programming language, you may want to work directly with thezransource C code in thezliblibrary. Paul McCarthy'sindexed_gziplibrary was a huge inspiration for this project, and in particular was a huge help while creating oursetup.pyfile. If you plan to work exclusively with gzip files, you may be better served by theindexed_gziplibrary. However, this project has some unique functionality that sets it apart:Use of the most up-to-date version of thezranC librarySupport for ZLIB, GZIP, and DEFLATE formatted dataGreater visibility into the contents of indexesCompression of the indexes when written to a file, leading to smaller index file sizesThe ability to modify the points contained within an index via theIndex.create_modified_index()method
zrandomlist
This is a simple list of random numbers generator.
zrb
🫰 Installation|📖 Documentation|🏁 Getting Started|💃 Common Mistakes|❓ FAQ🤖 Zrb: A Framework to Enhance Your WorkflowZrb is aCLI-basedautomationtoolandlow-codeplatform. Zrb can help you to:Automateday-to-day tasks.Generateprojects or applications.Prepare,run, anddeployyour applications with a single command.Etc.You can also write custom task definitions inPython, enhancing Zrb's base capabilities. Defining your tasks in Zrb gives you several advantages because:Every task has aretry mechanism.Zrb handles yourtask dependenciesautomatically.Zrb runs your task dependenciesconcurrently.🫰 Installing ZrbYou can install Zrb as a pip package by invoking the following command:pipinstallzrbAlternatively, you can also use our installation script to install Zrb along with some prerequisites:source<(curl-shttps://raw.githubusercontent.com/state-alchemists/zrb/main/install.sh)Check ourinstallation guidefor more information about the installation methods, including installation as a docker container.⚙️ Zrb as A Task-Automation ToolAt the very core, Zrb is a task automation tool. It helps you to automate some tedious jobs so that you can focus on what matters.Let's say you want to be able to describe the statistics property of any public CSV dataset. To do this, you need to perform three tasks like the following:Install pandas.Download the CSV dataset (at the same time).Show statistics properties of the CSV dataset.🐼 Install Pandas ─────┐ 📊 ├──► Show Statistics Download Datasets ──┘ ⬇️You can create a file namedzrb_init.pyand define the tasks as follows:# File name: zrb_init.pyfromzrbimportrunner,Parallel,CmdTask,python_task,StrInputDEFAULT_URL='https://raw.githubusercontent.com/state-alchemists/datasets/main/iris.csv'# 🐼 Define a task named `install-pandas` to install pandas.# If this task failed, we want Zrb to retry it again 4 times at most.install_pandas=CmdTask(name='install-pandas',cmd='pip install pandas',retry=4)# ⬇️ Define a task named `download-dataset` to download dataset.# This task has an input named `url`.# The input will be accessible by using Jinja template: `{{input.url}}`# If this task failed, we want Zrb to retry it again 4 times at mostdownload_dataset=CmdTask(name='download-dataset',inputs=[StrInput(name='url',default=DEFAULT_URL)],cmd='wget -O dataset.csv {{input.url}}',retry=4)# 📊 Define a task named `show-stat` to show the statistics properties of the dataset.# @python_task` decorator turns a function into a Zrb Task (i.e., `show_stat` is now a Zrb Task).# If this task failed, we don't want to retry@python_task(name='show-stats',retry=0)defshow_stats(*args,**kwargs):importpandasaspddf=pd.read_csv('dataset.csv')returndf.describe()# Define dependencies: `show_stat` depends on both, `download_dataset` and `install_pandas`Parallel(download_dataset,install_pandas)>>show_stats# Register the tasks so that they are accessbie from the CLIrunner.register(install_pandas,download_dataset,show_stats)📝 NOTE:It is possible (although less readable) to defineshow_statasCmdTask:Show codeshow_stats=CmdTask(name='show-stats',cmd='python -c "import pandas as pd; df=pd.read_csv(\'dataset.csv\'); print(df.describe())"',retry=0)Once you write the definitions, Zrb will automatically load yourzrb_init.pyso that you can invoke your registered task:zrbshow-statThe command will give you the statistics property of the dataset:sepal_length sepal_width petal_length petal_width count 150.000000 150.000000 150.000000 150.000000 mean 5.843333 3.054000 3.758667 1.198667 std 0.828066 0.433594 1.764420 0.763161 min 4.300000 2.000000 1.000000 0.100000 25% 5.100000 2.800000 1.600000 0.300000 50% 5.800000 3.000000 4.350000 1.300000 75% 6.400000 3.300000 5.100000 1.800000 max 7.900000 4.400000 6.900000 2.500000See the full outputUrl [https://raw.githubusercontent.com/state-alchemists/datasets/main/iris.csv]: 🤖 ○ ◷ ❁ 43598 → 1/3 🐮 zrb project install-pandas • Run script: pip install pandas 🤖 ○ ◷ ❁ 43598 → 1/3 🐮 zrb project install-pandas • Working directory: /home/gofrendi/playground/my-project 🤖 ○ ◷ ❁ 43598 → 1/3 🍓 zrb project download-dataset • Run script: wget -O dataset.csv https://raw.githubusercontent.com/state-alchemists/datasets/main/iris.csv 🤖 ○ ◷ ❁ 43598 → 1/3 🍓 zrb project download-dataset • Working directory: /home/gofrendi/playground/my-project 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • --2023-11-12 09:45:12-- https://raw.githubusercontent.com/state-alchemists/datasets/main/iris.csv 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.109.133, 185.199.110.133, ... 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected. 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • HTTP request sent, awaiting response... 200 OK 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • Length: 4606 (4.5K) [text/plain] 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • Saving to: ‘dataset.csv’ 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • 0K .... 100% 1.39M=0.003s 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • 2023-11-12 09:45:12 (1.39 MB/s) - ‘dataset.csv’ saved [4606/4606] 🤖 △ ◷ ❁ 43603 → 1/3 🍓 zrb project download-dataset • 🤖 ○ ◷ ❁ 43601 → 1/3 🐮 zrb project install-pandas • Requirement already satisfied: pandas in /home/gofrendi/zrb/.venv/lib/python3.10/site-packages (2.1.3) 🤖 ○ ◷ ❁ 43601 → 1/3 🐮 zrb project install-pandas • Requirement already satisfied: numpy<2,>=1.22.4 in /home/gofrendi/zrb/.venv/lib/python3.10/site-packages (from pandas) (1.26.1) 🤖 ○ ◷ ❁ 43601 → 1/3 🐮 zrb project install-pandas • Requirement already satisfied: python-dateutil>=2.8.2 in /home/gofrendi/zrb/.venv/lib/python3.10/site-packages (from pandas) (2.8.2) 🤖 ○ ◷ ❁ 43601 → 1/3 🐮 zrb project install-pandas • Requirement already satisfied: pytz>=2020.1 in /home/gofrendi/zrb/.venv/lib/python3.10/site-packages (from pandas) (2023.3.post1) 🤖 ○ ◷ ❁ 43601 → 1/3 🐮 zrb project install-pandas • Requirement already satisfied: tzdata>=2022.1 in /home/gofrendi/zrb/.venv/lib/python3.10/site-packages (from pandas) (2023.3) 🤖 ○ ◷ ❁ 43601 → 1/3 🐮 zrb project install-pandas • Requirement already satisfied: six>=1.5 in /home/gofrendi/zrb/.venv/lib/python3.10/site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0) Support zrb growth and development! ☕ Donate at: https://stalchmst.com/donation 🐙 Submit issues/PR at: https://github.com/state-alchemists/zrb 🐤 Follow us at: https://twitter.com/zarubastalchmst 🤖 ○ ◷ 2023-11-12 09:45:14.366 ❁ 43598 → 1/3 🍎 zrb project show-stats • Completed in 2.2365798950195312 seconds sepal_length sepal_width petal_length petal_width count 150.000000 150.000000 150.000000 150.000000 mean 5.843333 3.054000 3.758667 1.198667 std 0.828066 0.433594 1.764420 0.763161 min 4.300000 2.000000 1.000000 0.100000 25% 5.100000 2.800000 1.600000 0.300000 50% 5.800000 3.000000 4.350000 1.300000 75% 6.400000 3.300000 5.100000 1.800000 max 7.900000 4.400000 6.900000 2.500000 To run again: zrb project show-stats --url "https://raw.githubusercontent.com/state-alchemists/datasets/main/iris.csv"Since you have registeredinstall_pandasanddownload_dataset(i.e.,runner.register(install_pandas, download_dataset)), then you can also execute those tasks as well:zrbinstall-pandas zrbdownload-dataset📝 NOTE:When executing a task, you can also provide the parameter directly, for example you want to provide theurlzrbshow-stat--urlhttps://raw.githubusercontent.com/state-alchemists/datasets/main/iris.csvWhen you provide the parameter directly, Zrb will not prompt you to supply the URL. Another way to disable the prompt is by setZRB_SHOW_PROMPTto0orfalse.You can also run a Docker compose file, start a Web server, generate a CRUD application, or set up multiple servers simultaneously.Seeour getting started guideandtutorialsto learn more about the details.✂️ Zrb as A Low-Code FrameworkZrb has some built-in tasks that allow you to create and run aCRUDapplication.Let's see the following example.# Create a projectzrbprojectcreate--project-dirmy-project--project-name"My Project"cdmy-project# Create a Fastappzrbprojectaddfastapp--project-dir.--app-name"fastapp"--http-port3000# Add library module to fastappzrbprojectaddfastapp-module--project-dir.--app-name"fastapp"--module-name"library"# Add entity named "books"zrbprojectaddfastapp-crud--project-dir.--app-name"fastapp"--module-name"library"\--entity-name"book"--plural-entity-name"books"--column-name"code"# Add column to the entityzrbprojectaddfastapp-field--project-dir.--app-name"fastapp"--module-name"library"\--entity-name"book"--column-name"title"--column-type"str"# Run Fastapp as monolithzrbprojectstart-fastapp--fastapp-run-mode"monolith"Once you invoke the commands, you will be able to access the CRUD application by pointing your browser tohttp://localhost:3000Furthermore, you can also split your application intomicroservices, run them asdocker containers, and even deploy them to yourkubernetes cluster.# Run Fastapp as microserviceszrbprojectstart-fastapp--fastapp-run-mode"microservices"# Run Fastapp as containerzrbprojectstart-fastapp-container--fastapp-run-mode"microservices"zrbprojectstop-fastapp-container# Deploy fastapp and all it's dependencies to kubernetesdockerlogin zrbprojectdeploy-fastapp--fastapp-deploy-mode"microservices"Visitour tutorialsto see more cool tricks.📖 Documentation🫰 Installation🏁 Getting Started📖 Documentation💃 Common Mistakes❓ FAQ🐞 Bug Report + Feature RequestYou can submit bug report and feature request by creating a newissueon Zrb Github Repositories. When reporting a bug or requesting a feature, please be sure to:Include the version of Zrb you are using (i.e.,zrb version)Tell us what you have tryTell us what you expectTell us what you getWe will also welcome yourpull requests and contributions.☕ DonationHelp Red Skull to click the donation button:🎉 Fun FactMadou Ring Zaruba (魔導輪ザルバ, Madōrin Zaruba) is a Madougu which supports bearers of the Garo Armor.(Garo Wiki | Fandom)🙇 CreditsWe are thankful for the following libraries and services. They accelerate Zrb development processes and make things more fun.LibrariesBeartype: Catch invalid typing earlier during runtime.Click: Creating a beautiful CLI interface.Termcolor: Make the terminal interface more colorful.Jinja: A robust templating engine.Ruamel.yaml: Parse YAML effortlessly.Jsons: Parse JSON. This package should be part of the standard library.Libcst: Turn Python code into a Concrete Syntax Tree.Croniter: Parse cron pattern.Flit,Twine, and many more. See the complete list of Zrb's requirements.txtServicesasciiflow.com: Creates beautiful ASCII-based diagrams.emojipedia.org: Find emoji.emoji.aranja.com: Turns emoji into imagesfavicon.io: Turns pictures and texts (including emoji) into favicon.
zrb-extras
Zrb extraszrb-extras is apypipackage.You can install zrb-extras by invoking:pip install zrb-extrasFor maintainersPublish to pypiTo publish zrb-extras, you need to have aPypiaccount:Log in or register tohttps://pypi.org/Create an API tokenYou can also create aTestPypiaccount:Log in or register tohttps://test.pypi.org/Create an API tokenOnce you have your API token, you need to create a~/.pypircfile:[distutils] index-servers = pypi testpypi [pypi] repository = https://upload.pypi.org/legacy/ username = __token__ password = pypi-xxx-xxx [testpypi] repository = https://test.pypi.org/legacy/ username = __token__ password = pypi-xxx-xxxTo publish zrb-extras, you can do the following command:zrbprojectpublish-zrb-extrasUpdating versionYou can update zrb-extras version by modifying the following section inpyproject.toml:[project]version="0.0.2"Adding dependenciesTo add zrb-extras dependencies, you can edit the following section inpyproject.toml:[project]dependencies=["Jinja2==3.1.2","jsons==1.6.3"]Adding scriptTo make zrb-package-name executable, you can edit the following section inpyproject.toml:[project-scripts]zrb-extras="zrb-extras.__main__:hello"This will look forhellocallable inside of your__main__.pyfile
zrb-ollama
Zrb OllamaZrb Ollama is apypipackage that acts as Ollama and LangChain wrapper, allowing you to incorporate LLM into your workflow.InstallationYou can install Zrb Ollama by invoking any of the following commands:# From pypipipinstallzrb-ollama# From githubpipinstallgit+https://github.com/goFrendiAsgard/zrb-ollama.git@main# From directorypipinstall--use-feature=in-tree-buildpath/to/this/directoryBy default, Zrb Ollama uses Ollama-based LLM. You can install Ollama by visiting the official website:https://ollama.ai/.You can, however, change this behavior by settingOPENAI_API_KEY. WhenOPENAI_API_KEYis present, Zrb Ollama will use the Open AI API instead.ConfigurationYou can configure Zrb Ollama using a few environment variables:ZRB_DEFAULT_LLM_PROVIDER: LLM Provider (i.e.,ollama,openai,bedrock). If not specified, Zrb Ollama will useollamaZRB_DEFAULT_SYSTEM_PROMPTDefault system promptZRB_DEFAULT_CHAT_HISTORY_RETENTION: Default: 3ZRB_OLLAMA_BASE_URL: Default Ollama base URL. If not specified, Zrb Ollama will usehttp://localhost:11434.ZRB_OLLAMA_DEFAULT_MODEL: Default Ollama model. If not specified, Zrb Ollama will usemistral.OPENAI_API_KEYAWS_ACCESS_KEYAWS_SECRET_ACCESS_KEYTalk to Zrb OllamaZrb Ollama provides a simple CLI command to interact with the LLM. This CLI command also manages your chat history and saves everything under~/.zrb-ollama-context.json.Let's see the following example:zrb-ollama"Why is the sky blue?"👇See the outputThe sky appears blue due to a phenomenon called Rayleigh scattering. When sunlight enters Earth's atmosphere, it encounters molecules and tiny particles in the air. The shorter wavelengths of light, such as blue and violet, are scattered more strongly by these particles compared to the longer wavelengths of light, like red and orange. As a result, the blue light gets scattered in all directions, creating the blue appearance of the sky.Zrb Ollama will explain why the sky is blue.Next, you can ask it to give a more detailed explanation:zrb-ollama"Explain in more detailed"👇See the outputSure! When sunlight reaches Earth's atmosphere, it is composed of different colors of light, each with a different wavelength. The shorter wavelengths, such as blue and violet, have higher energy, while the longer wavelengths, such as red and orange, have lower energy. As sunlight enters the atmosphere, it interacts with the molecules and tiny particles present in the air. These particles include nitrogen and oxygen molecules, as well as dust, water droplets, and other small particles. The interaction between the sunlight and these particles causes a scattering of light. This scattering process is known as Rayleigh scattering. It is named after the British physicist Lord Rayleigh, who first explained it in the 19th century. Rayleigh scattering occurs when the size of the particles in the atmosphere is much smaller than the wavelength of light. In this case, the scattering is inversely proportional to the fourth power of the wavelength. This means that shorter wavelengths, such as blue and violet light, are scattered much more strongly than longer wavelengths, such as red and orange light. As a result, when sunlight enters the atmosphere, the blue and violet light is scattered in all directions by the particles in the air. This scattered blue light then reaches our eyes from all parts of the sky, making it appear blue to us. It's important to note that the scattering of light is not limited to just the blue color. However, since our eyes are more sensitive to blue light, we perceive the scattered blue light more prominently, hence the blue appearance of the sky. At sunrise or sunset, when the sun is lower in the sky, the sunlight has to pass through a larger portion of the atmosphere before reaching us. This longer path causes more scattering and absorption of shorter wavelengths, like blue and violet light, resulting in the red, orange, and pink hues commonly seen during these times. In summary, the sky appears blue due to Rayleigh scattering, where the shorter wavelengths of sunlight, particularly blue and violet light, are scattered more strongly by the particles in the atmosphere, making the scattered blue light dominant in our perception.It will understand that you asked for a more detailed explanation of why the sky is blue.Talk is Cheap, Show Me The CodeFurthermore, Zrb Ollama also allows you to use an AI Agent. This AI Agent can access the internet and interact with the Python interpreter.Zrb Ollama Agent will show you the reasoning process, the solution, and the respecting Python code.Note that for this to work, you need better LLM models likeMistralor Open AI.Let's see the following example:# You can use Ollama's mistral model:# export ZRB_OLLAMA_DEFAULT_MODEL=mistral# or you can use Open AI:exportOPENAI_API_KEY=your-api-keyexportDEFAULT_LLM_PROVIDER=openai zrb-ollama-agent"What is the area of a square with 20 cm perimeter?"👇See the outputThought: To find the area of a square, we need to know the side length. We can calculate the side length by dividing the perimeter by 4. Once we have the side length, we can use the formula for the area of a square, which is side length squared. Action: Python code ```python # Calculating the area of a square perimeter = 20 side_length = perimeter / 4 area = side_length ** 2 # Displaying the solution print(area) ``` I need to provide the input for the action, which is the value of the perimeter. Action: python_repl Action Input: 20 The code executed successfully and provided the expected output. Final Answer: - Solution: The area of a square with a perimeter of 20 cm is 25 square centimeters. - Code: ```python # Calculating the area of a square perimeter = 20 side_length = perimeter / 4 area = side_length ** 2 # Displaying the solution print(area) ```Getting CreativeThe Zrb Ollama CLI program is helpful on its own. You can, for example, ask the LLM model to explain a code for you and refactor it.zrb-ollama"What this code do?$(catfibo.py)"zrb-ollama"Can you make it better?"There are a lot of things you can do with Zrb Ollama.Creating Custom PromptTasksFinally, you can incorporate Zrb Ollama into yourZrbproject workflow. Zrb Ollama introduces aPromptTaskclass that you can use to create more customized LLM tasks.Let's see an example:fromzrbimportrunnerfromzrb_ollamaimportPromptTaskchat=PromptTask(name="chat",input_prompt='echo {{ " ".join(input._args) if input._args | length > 0 else "tell me some fun fact" }}',# noqa)runner.register(chat)PromptTask PropertiesEach PrompTask has the following properties:name (str): The name of the task.history_file (str | None): Optional file path for storing conversation history.callback_handler_factories (Iterable[CallbackHandlerFactory]): Factory for creating CallbackHandler.tool_factories (Iterable[ToolFactory]): Factory for creating tools.llm_factory (LLMFactory | None): Factory for creating LLM.prompt_factory (PromptFactory | None): Factory for creating prompt.group (Group | None): The group to which this task belongs.description (str): Description of the task.inputs (List[AnyInput]): List of inputs for the task.envs (Iterable[Env]): Iterable of environment variables for the task.env_files (Iterable[EnvFile]): Iterable of environment files for the task.icon (str | None): Icon for the task.color (str | None): Color associated with the task.retry (int): Number of retries for the task.retry_interval (float | int): Interval between retries.upstreams (Iterable[AnyTask]): Iterable of upstream tasks.checkers (Iterable[AnyTask]): Iterable of checker tasks.checking_interval (float | int): Interval for checking task status.on_triggered (OnTriggered | None): Callback for when the task is triggered.on_waiting (OnWaiting | None): Callback for when the task is waiting.on_skipped (OnSkipped | None): Callback for when the task is skipped.on_started (OnStarted | None): Callback for when the task starts.on_ready (OnReady | None): Callback for when the task is ready.on_retry (OnRetry | None): Callback for when the task retries.on_failed (OnFailed | None): Callback for when the task fails.should_execute (bool | str | Callable[..., bool]): Condition for executing the task.return_upstream_result (bool): Flag to return the result of upstream tasks.FactoriesTo understand what factories are for, first, we need to see what a LangChain program looks like:importosimportsysfromtypingimportAnyfromlangchainimporthubfromlangchain.agentsimportAgentExecutor,Tool,create_react_agentfromlangchain_community.chat_modelsimportChatOllamafromlangchain_community.utilities.duckduckgo_searchimportDuckDuckGoSearchAPIWrapperfromlangchain.promptsimportPromptTemplatetools=[Tool(name="Search",func=DuckDuckGoSearchAPIWrapper().run,description="Search engine to answer questions about current events",)]prompt=hub.pull("hwchase17/react-chat")llm=ChatOllama(model="mistral",temperature=0.9,)agent=create_react_agent(llm=llm,tools=tools,prompt=prompt)agent_executor=AgentExecutor(agent=agent,tools=tools,handle_parsing_errors=True,)result=agent_executor.invoke({# "input": "Who am I?","input":"How many people live in Canada right now?","chat_history":"Human: Hi! My name is Bob\nAI: Hello Bob! Nice to meet you",})You can see a lot of things going on. But let's focus on theagent. You can see that you need a few other components to create anagent:llmtoolspromptLangChain allows you to swap the component with anything if the interface matches. For example, you can use botOpenAIChatandOllamaChatasllm.PromptTask handles this by allowing you to define how to create elements based on other existing components. Let's see the following pseudo-code:classPromptTask(AnyPromptTask,BaseTask):def__init__(self,user_prompt,llm_factory,prompt_factory,tool_factories):self.user_prompt=user_promptself.llm_factory=llm_factoryself.prompt_factory=prompt_factoryself.tool_factories=tool_factoriesdefrun():agent=self.get_agent()agent_executor=AgentExecutor(agent=agent,tools=self.get_tools(),handle_parsing_errors=True,)result=agent_executor.invoke({# "input": "Who am I?","input":"How many people live in Canada right now?","chat_history":"Human: Hi! My name is Bob\nAI: Hello Bob! Nice to meet you",})returnresult["output"]defget_agent(self):returnAgent(llm=self.get_llm(),prompt=self.get_prompt(),tools=self.get_tools(),)@lru_cache(maxsize=1)defget_llm(self):returnself.llm_factory(self)@lru_cache(maxsize=1)defget_prompt(self):returnself.prompt_factory(self)@lru_cache(maxsize=1)defget_tools(self):return[tool_factory(self)fortool_factoryinself.llm_chain_factories]Now, you can control howget_llm,get_prompt, andget_toolsbehave by setting up the factory properties.Thelru_cachealso ensures that the getter method will only be called once or less, so you won't lose reference to the components (i.e., when you callget_llmtwice, the result will refer to the same object).How Factories WorkLet's continue with factories:defollama_llm_factory(model,temperature):defcreate_ollama_llm(task)returnChatOllama(model=model,callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),temperature=temperature,)returncreate_ollama_llmdefopenai_llm_factory(api_key,temperature):defcreate_openai_llm(task)returnChatOpenAI(api_key,callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),streaming=Truetemperature=temperature,)returncreate_openai_llmprompt_task=PromptTask(user_prompt='Why is the sky blue?',llm_factory=ollama_llm_factory(),# ...)We will see how things work in detail by focusing onPromptTask'srun,get_agent, andget_llmmethods.classPromptTask(AnyPromptTask,BaseTask):# ...defrun(self):agent=self.get_agent()agent_executor=AgentExecutor(agent=agent,tools=self.get_tools(),handle_parsing_errors=True,)result=agent_executor.invoke({# "input": "Who am I?","input":"How many people live in Canada right now?","chat_history":"Human: Hi! My name is Bob\nAI: Hello Bob! Nice to meet you",})returnresult["output"]defget_agent(self):returnAgent(llm=self.get_llm(),prompt=self.get_prompt(),tools=self.get_tools(),)@lru_cache(maxsize=1)defget_llm(self):returnself.llm_factory(self)# ...When Zrb callsprompt_task.run(), PromptTask will invokeget_llm_chainto get thellm_chain.The AdvantageBy using factories, we create a dependency inversion mechanism. The mechanism allows you to:Only create components whenever necessarySwap components painlesslyImplement your custom factory without affecting the other componentsFor maintainersPublish to pypiTo publish zrb-ollama, you need to have aPypiaccount:Log in or register tohttps://pypi.org/Create an API tokenYou can also create aTestPypiaccount:Log in or register tohttps://test.pypi.org/Create an API tokenOnce you have your API token, you need to create a~/.pypircfile:[distutils] index-servers = pypi testpypi [pypi] repository = https://upload.pypi.org/legacy/ username = __token__ password = pypi-xxx-xxx [testpypi] repository = https://test.pypi.org/legacy/ username = __token__ password = pypi-xxx-xxxTo publish zrb-ollama, you can do the following command:zrbpluginpublishUpdating versionYou can update zrb-ollama version by modifying the following section inpyproject.toml:[project]version="0.0.2"Adding dependenciesTo add zrb-ollama dependencies, you can edit the following section inpyproject.toml:[project]dependencies=["Jinja2==3.1.2","jsons==1.6.3"]Adding scriptTo make zrb-package-name executable, you can edit the following section inpyproject.toml:[project-scripts]zrb-ollama="zrb-ollama.__main__:hello"This will look forhellocallable inside of your__main__.pyfile
zrcalc
zrcalc is a simple calculator.Let’s say you want to add the numbers.Then do it like this: zrcalc.add(1, 1) i used 1, 1 but you can use every number if you want.Change Log0.0.1 (7/27/2022)First Release
zrchnpypidemo
MyFirstPypiDemoOK, Let me just say something.
zrcl3
py-zrcl3zack's common reusable libraryInstallationpipinstallzrcl3install from githubpipinstallgit+https://github.com/ZackaryW/py-zrcl3.gitWhy the nameZrCl3 is a catalyst, and unstable by itself (need other pieces for a working product)NoteGiven that this module is intended to only hold utility methods, it will not include any required dependencies
zredis
一个封装的redis连接器参数说明参数名数据类型默认值描述更新日志发布时间发布版本发布说明19-01-100.1.0发布第一版本项目仅供所有人学习交流使用, 禁止用于商业用途
zreion
zreionzreionis a way of quickly computing a "redshift of reionization" field using a semi-numeric method developed inBattaglia et al. (2013). The method assumes the redshift of reionization for a particular point in a cosmological volume is a biased tracer of the matter field, and can be written as a parameterized bias function. For a full derivation and comparison with simulations, see the linked paper.InstallationInstalling the package can be performed by checking the repo out, and then running:pip install .Dependencies should be handled automatically bypipif not already installed.Dependenciessetuptools >= 38.3cythonnumpypyfftwTestsThe repo includes a test suite, which can be invoked by runningpytestin the top-level of the repo. In addition to the package dependencies, it requirespackaging,pytest-covandpytest-cases. These can be installed using:pip install .[test]
zrelay
No description available on PyPI.
zreprt
zreprtZAP and ZAP-like reporting facilityStructures here resemble OWASP® ZAP Traditional JSON Report, with or without Requests and Responses. Alerts are considered grouped by their info.Changes to the Traditional JSON Report format:some fields renamed, keeping original names as aliases;some (re)typing: timestamps are ISO-formatted, some int and bool instead of strings;html tags are stripped from some fields containing descriptions.See also:https://www.zaproxy.org/docs/desktop/addons/report-generation/report-traditional-json/https://www.zaproxy.org/docs/constants/
zretry
一个轻量的重试包实例代码fromzretryimportretry@retrydeffun():a=1/0fun()# 此时会不停的尝试调用直到成功, 每次尝试间隔一秒限制尝试次数fromzretryimportretry@retry(max_attempt_count=5)# 最多尝试调用5次, 超出5次后报错deffun():a=1/0fun()参数说明参数名数据类型默认值描述intervalfloat1每次尝试间隔时间max_attempt_countintNone最大尝试次数result_retry_flaganyNone如果调用的函数不报错, 它的返回值和result_retry_flag的id是同一个id, 则重试error_callbackfunctionNone每次尝试错误都会回调这个函数, 它接收一个参数, 该参数表示尝试的是哪个函数更新日志发布时间发布版本发布说明19-01-130.1.1修复对类函数使用装饰器会导致调用时报错的bug19-01-080.1.0发布第一版本项目仅供所有人学习交流使用, 禁止用于商业用途
zrf-test-box-py
长描述
zrHAPPY
HAPPy (Hydride Analysis Package in Python)This is a Python package developed to aid in the charactacterisation and quantification of hydrides from micrographs. The main functions of this package are to:Determine the Radial Hydride Fraction (RHF)Characterise the extent of branchingDetermine the most probable crack path within a micrographHow to installInstal from PyPi link aboveHow to useEnterjupyter labinto the anaconda terminal and Jupyter lab will open in your browser.Open the example notebook, provided with the folder downloaded earlier.Examples of how to use the software are included, as well as an example micrograph.Documentationhappy-hydride-analysis-package-in-python.readthedocs.ioCreditsThe software uses the following open source packages:jupyter-notebooknumpymatplotlibscikit-imagescipyskannetworkxtoolzmatplotlib-scalebarContactsMiss Mia Maric ([email protected])Dr Pratheek Shanthraj ([email protected])Dr Rhys Thomas ([email protected])Dr Michael Atkinson ([email protected])Dr Juan Nunez-Iglesias ([email protected])
zrip
No description available on PyPI.
zrlog
Zirconium Logging (ZrLog)Logging configuration is often complex and Python is missing a few "nice" features that exist in other languages logging systems. This package hopes to simplify the experience of configuring logging while adding a few nice features:Loading logging configuration from TOML or YAML (viazirconium) instead of the olderconfigparserformatTRACElevel for very fine-grained output (more so thatDEBUG)NOTICElevel for normal conditions that should always be outputOUTlevel for logging user messagesAUDITlevel for interacting with Python's audit hooksA threaded audit hook that logs most audit messagesThe ability to disable stack trace outputThe ability to set context-specific "extra" variables on all loggers and to provide defaults for these so that they can be added to all logging messages within that context (e.g. for usernames)Basic Usage# Do this at the start of any run of your codeimportzrlog# Imports logging configuration from TOML and sets up the logging system for you.zrlog.init_logging()# Set a default usernamezrlog.set_default_extra('username','**anonymous**')# logging.getLogger() works as well, this version is a wrapper that (a) makes sure that `zrlog.init_logging()` was# called and (b) provides a better type hint for the logger class.logger=zrlog.get_logger(__name__)Configuration FileBy default, logging configuration comes from a TOML file in up to three places:[HOME_DIRECTORY]/.logging.toml[CURRENT_WORKING_DIRECTORY]/.logging.tomlValue of theZRLOG_CONFIG_FILEenvironment variable. This file may also be a YAML or other formats supported byzirconiumIf you usezirconiumfor your project configuration, it can also be in any configuration file specified by your project.The logging configuration file is similar to that defined bylogging.config.dictConfig(), with a few extensions. See the.logging.example.tomlfile for configuration.Performance impactTesting suggests that the impact of replacing the typicalloggingapproach with this module is about 14% slower to get a logger and 10% slower to make a logging call with extras. However, the time to make a log tostdoutis still only 0.013 ms (compared to 0.012 ms for the standard logging package), therefore this performance impact is probably insignificant in most use cases.Log Level RecommendationsLevelUse CasecriticalAn error so severe has occurred that the application may now crash.errorAn error has occurred and may have created unexpected behaviour.warningSomething unexpected happen but it is recoverable, or a problem may occur in the future.noticeSomething expected has happened that needs to be tracked in a production environment (e.g. user login).outSomething expected has happened in a command line environment that the user needs to be notified of.infoSomething expected has happened that does not need tracking but can be useful to confirm normal operation.debugAdditional detail for debugging an issuetraceEven more detail for debugging an issueauditPython auditing output onlyLogging Audit EventsThis package provides a system for turningsys.audit()events into log records using a thread-based queue. This is necessary because audit events don't play nicely with the logging subsystem, leading to inconsistent errors if the loggerlog()method is called directly from the audit hook. Audit logging must be enabled specifically by setting thewith_auditflag:# .logging.toml[logging]with_audit=trueWhile the default level is "AUDIT", you can change this to any of the logging level prefixes by specifying the audit_level:# .logging.toml[logging]with_audit=trueaudit_level="INFO"One specific event can cause further problems:sys._getframe()is called repeatedly from the logging subsystem in Python (in 3.8 at least). These audit events are NOT logged by default, but logging of them can be enabled by turning off theomit_logging_framesflag.# .logging.toml[logging]with_audit=trueomit_logging_frames=falseAudit events are logged (by default) at the AUDIT level which is below TRACE; your logger and handler must be set to that level to see these events:[logging.root]level="AUDIT"handlers=["console"][logging.handlers.console]class="logging.StreamHandler"formatter="brief"level="AUDIT"stream="ext://sys.stdout"Change Logversion 0.3.0Added logger extra handling viaset_logger_extraandset_default_logger_extraAdded theNOTICElevel to correspond with more typical usage.OUTshould be used for user output where it needs to be logged andNOTICEfor normal conditions that need to be logged even in production.version 0.2.0Updated the audit handling thread to use athreading.Eventto end itself rather than a boolean flag.Added theno_configflag, mostly to be used in test suites to ensure everything still works properly.Several documentation cleanup items
zrna
zrna - software-defined analogAPI client for the Zrna software-defined analog platform.See thequickstart guidefor more information about how to use it.See thedemo applicationsfor example usage.Seezrna.org/docsfor the full documentation.Orderhardware.Browse thesource code.
zrok
Geo-scale, next-generation peer-to-peer sharing platform built on top of OpenZiti.