Saravanan666/pypi-org huggingface dataset:
Package: pymple
WhyIf you search for Inversion of Control containers for Python you often encounter the argument “Python is dynamic and does not need those things that static languages need”. This is partly true.Dependency Injection and Inversion of Control is a pattern and not a language feature. It not only makes your code easier to test, but also way more readable. The dependencies are clearly noted in the constructor and your IDEs will give you autocompletion support. If you need to test a class, it is clear where and how to pass in the mocks.Therefore Inversion and Control and Dependency Injection (which go hand in hand) should also be practiced in dynamic languages. If you think this is not viable, check outAngularJSwhich also makes use of the above mentioned patterns in a dynamic programming language, namely JavaScript.For further information watchGoogle’s Clean Code TalksLimitationsPymple does currently not support:ThreadsafetyLifetimesInstallationThis library is a Python 3.4+ library. On Python 3.4 however thetypingspackage is required.Install it via pip for Python 3:sudo pip3 install pympleUsagePymple knows two types of parameters:Singletons: A singleton is acallablethat is executed once and the result is saved so future calls to the build method will return the same instanceFactories: A factory iscallablethat is executed again every time it is accessedBy default Pymple tries to resolved a singleton based on the annotated type, e.g.:frompympleimportContainerclassA:def__init__(self):passclassB:def__init__(self,param:A):self.a=Acontainer=Container()b=container.resolve(B)isinstance(b.a,A)==TrueOverriding The Default BehaviorHowever you can also override it by defining it explicitly:container=Container()ccontainer.register(B,lambdac:B('hi'))b=container.resolve(B)b.a=='hi'The first passed in variable to the lambda is the container instance itself, so you can also resolve other classes on it:container=Container()ccontainer.register(B,lambdac:B(c.resolve(A)))b=container.resolve(B)isinstance(b.a,A)==TrueRegistering FactoriesIf you want to register a factory instead of a singleton, simple pass False as the second parameter:container=Container()ccontainer.register(B,lambdac:B('hi'),False)b=container.resolve(B)c=container.resolve(B)b!=cAliasingSometimes a type interface uses an abstract class as type annotation. In that case you can simply define an alias:container=Container()ccontainer.alias(ConcreteClass,AbstractClass)clazz=container.resolve(AbstractClass)isinstance(clazz,ConcreteClass)==True
Package: pymplschapters
pymplschaptersExtract chapters from a blu-ray mpls to a matroska recognized xml fileInstallationpip install pymplschaptersUsagepymplschapters -p "C:/A Path/To/The/Playlist.mpls"It will place any found chapters next to the input playlist file or to a specified directory with-d.CreditThanksPyGuymerfor the MPLS parsing code, it
has been modified a bit to suit my needs.
Package: pyMPM
A Python implementation of the millimeter wave propagation model MPM as described in H.J. Liebe, G.A. Hufford, M.G. Cotton, “Propagation modeling of moist air and suspended water/ice particles at frequencies below 1000 GHz” Proc. NATO/AGARD Wave Propagation Panel, 52nd meeting, No. 3/1-10, Mallorca, Spain, 17 - 20 May, 1993.Currently only dry air and water vapor are considered. The other MPM modules will be added later (hopefully…).This implementation is based on the MATLAB version of MPM93 developed at theuniversity of Bern.InstallationpyMPM uses Python 2 (tested with 2.7) and depends onnumpy. It can be installed viapip:$ pip install pyMPMUsageHere is an example provided asIPython notebook.
Package: pympris
pympris is a Python library usedto control media players using MPRIS2 interfaces.Usage=====::import gobjectimport dbusfrom dbus.mainloop.glib import DBusGMainLoopimport pymprisdbus_loop = DBusGMainLoop()bus = dbus.SessionBus(mainloop=dbus_loop)# get unique ids for all available playersplayers_ids = list(pympris.available_players())mp = pympris.MediaPlayer(players_ids[1], bus)# mp.root implements org.mpris.MediaPlayer2 interface# mp.player implements org.mpris.MediaPlayer2.Player# mp.track_list implements org.mpris.MediaPlayer2.TrackList# mp.playlists implements org.mpris.MediaPlayer2.Playlists# print player Identityprint mp.root.Identityif mp.root.CanRaise:mp.root.Raise()if mp.player.CanPlay and mp.player.CanPause:mp.player.PlayPause()mp.player.Volume = mp.player.Volume*2if mp.player.CanGoNext:mp.player.Next()tracks = mp.track_list.Tracksfor track_id in tracks:print track_idif len(tracks) > 1:mp.track_list.RemoveTrack(tracks[-1])mp.track_list.GoTo(tracks[0])n = mp.playlists.PlaylistCountordering = pympris.PlaylistOrdering.LastPlayDateplaylists = mp.playlists.GetPlaylists(0, n, ordering, reversed=False)pl_id, pl_name, pl_icon = playlists[-2]mp.playlists.ActivatePlaylist(pl_id)# setup signal handlersdef seeked(x):print(x)def PlaylistChanged(arg):print "PlaylistChanged", argdef TrackMetadataChanged(track_id, metadata):print "TrackMetadataChanged", track_id, metadatadef TrackListReplaced(tracks, current_track):print "TrackListReplaced", tracks, current_trackdef TrackAdded(metadata, after_track):print "TrackAdded", metadata, after_trackdef TrackRemoved(track_id):print "TrackRemoved", track_idmp.player.register_signal_handler('Seeked', seeked)mp.playlists.register_signal_handler('PlaylistChanged', PlaylistChanged)mp.track_list.register_signal_handler('TrackMetadataChanged',TrackMetadataChanged)mp.track_list.register_signal_handler('TrackListReplaced', TrackListReplaced)mp.track_list.register_signal_handler('TrackAdded', TrackAdded)mp.track_list.register_signal_handler('TrackRemoved', TrackRemoved)loop = gobject.MainLoop()loop.run()
Package: pymprog
An easy and flexible mathematical programming environment for Python.DescriptionPyMathProg is a pythonic reincarnation of AMPL and GNU MathProg
modeling language, implemented in pure Python, connecting to GLPK via
swiglpk. Create, optimize, report, change and re-optimize your model
with Python, easily integrate database, plotting, etc.PyMathProg provides an easy and flexible modelling syntax
usingPythonto create and optimize mathematical programming models.
Optimization is done by open source optimization packages such as
theGNU Linear Programming Kit (GLPK)that is made available
to PyMathProg by swiglpk.Great features offered by PyMathProg include:Ergonomic syntax for modellingFriendly interactive sessionSensitivity reportAdvanced solver optionsAutomatic model update on parameter changesParameters sharable between modelsDeleting variables/constraintsSupporting both Python 2 and 3Supporting all major platformsInstallationAssuming you already have Python 2 or Python 3 installed, now open a
terminal window (also known as a command window), and type in this
line of command and hit return:pip install pymprogThat’s it. Since it is a pure Python project that only depends on swiglpk,
it can be installed this way wherever swiglpk can be installed.
Currently, swiglpk comes with binary wheels for Windows, Mac, and Linux.
If you’d like to have PyMathProg installed on other platforms,
the only hurdle to overcome is to get swiglpk installed there first.ExampleBelow is a small example taken from the dive-in turorial
in thePyMathProg Documentation:from pymprog import *
begin('bike production')
x, y = var('x, y') # variables
maximize(15 * x + 10 * y, 'profit')
x <= 3 # mountain bike limit
y <= 4 # racer production limit
x + y <= 5 # metal finishing limit
solve()Help in the following ways are more than welcome:tutorials and samples.bug reportsfeature requestscode contributionI hope you will find it useful.
Package: pymprpc
﻿
pymprpc
===============================version: 0.0.3status: devauthor: hszemail:hsz1273327@gmail.comDesca rpc framework for message-pack rpc.keywords:rpc,server,tcpFeatureapi seems to stdlib xmlrpceasy to use, easy to debugsupport stream responseExampleserverimportplatformfrompymprpc.serverimportSimpleMprpcServerifplatform.system()=="Windows":try:importaio_windows_patchasasyncioexcept:importwarningswarnings.warn("you should install aio_windows_patch to support windows",RuntimeWarning,stacklevel=3)importasyncioelse:importasynciotry:importuvloopasyncio.set_event_loop_policy(uvloop.EventLoopPolicy())exceptImportError:passclassMyMPRPCServer(SimpleMprpcServer):passwithMyMPRPCServer(("127.0.0.1",5000),debug=True)asserver:server.register_introspection_functions()@server.register_function()deftestfunc(a,b):'''有help'''returna+b@server.register_function()asyncdeftestcoro(a,b):awaitasyncio.sleep(0.1)returna+b@server.register_function()asyncdeftestcorogen(a,b):foriinrange(10):awaitasyncio.sleep(0.1)yieldi+a+bclassTestClass:deftestclassmethod(self,a,b):returna+basyncdeftestclasscoro(self,a,b):awaitasyncio.sleep(0.1)returna+basyncdeftestclasscorogen(self,a,b):foriinrange(10):awaitasyncio.sleep(0.1)yieldi+a+bt=TestClass()server.register_instance(t)server.run_forever()sync clientimporttimefrompymprpc.clientimportRPCwithRPC(addr="tcp://admin:admin@127.0.0.1:5000",debug=True)asrpc:print(rpc.system.listMethods())print(rpc.system.methodSignature("testclassmethod"))print(rpc.system.methodHelp("testfunc"))print(rpc.system.lenConnections())print(rpc.system.lenUndoneTasks())print(rpc.testclassmethod(1,2))print(rpc.testclasscoro(2,3))print(rpc.testcoro(5,6))print(rpc.testfunc(5,4))agen=rpc.testcorogen(1,2)foriinagen:print(i)time.sleep(200)print("wait done")# rpc.close()print(rpc.testfunc())async clientimportasynciofrompymprpc.clientimportAsyncRPCasyncdefmain(loop):asyncwithAsyncRPC(addr="tcp://admin:admin@127.0.0.1:5000",loop=loop,debug=True)asrpc:print(awaitrpc.system.listMethods())print(awaitrpc.system.methodSignature("testclassmethod"))print(awaitrpc.system.methodHelp("testfunc"))print(awaitrpc.system.lenConnections())print(awaitrpc.system.lenUndoneTasks())print(awaitrpc.testclassmethod(1,2))print(awaitrpc.testclasscoro(2,3))print(awaitrpc.testcoro(5,6))print(awaitrpc.testfunc(5,4))# await asyncio.sleep(200)print("wait done")print(awaitrpc.testfunc())print("end")loop=asyncio.get_event_loop()try:loop.run_until_complete(main(loop))exceptExceptionase:raiseeInstallpython-mpip install pymprpcDocumentationDocumentation on Readthedocs.TODOLoad balancing brokerLimitationssync client do not support heartbeat and timeout
Package: pympv
pympvA python wrapper for libmpv.Basic usageimportsysimportmpvdefmain(args):iflen(args)!=1:print('pass a single media file as argument')return1try:m=mpv.Context()exceptmpv.MPVError:print('failed creating context')return1m.set_option('input-default-bindings')m.set_option('osc')m.set_option('input-vo-keyboard')m.initialize()m.command('loadfile',args[0])whileTrue:event=m.wait_event(.01)ifevent.id==mpv.Events.none:continueprint(event.name)ifevent.idin[mpv.Events.end_file,mpv.Events.shutdown]:breakif__name__=='__main__':try:exit(main(sys.argv[1:])or0)exceptmpv.MPVErrorase:print(str(e))exit(1)More examples can be found in thesamplesdirectory.libmpv is a client library for the media player mpvFor more info see:https://github.com/mpv-player/mpv/blob/master/libmpv/client.hpympv was originally written by Andre D, and the PyPI package is maintained
by Hector Martin.
Package: pymqi
PyMQI is a production-ready, open-source Python extension for IBM MQ (formerly known as WebSphere MQ and MQSeries).For 20+ years, the library has been used by thousands of companies around the world with their queue managers running on
Linux, Windows, UNIX and z/OS.Sample codeTo put a message on a queue:importpymqiqueue_manager=pymqi.connect('QM.1','SVRCONN.CHANNEL.1','192.168.1.121(1434)')q=pymqi.Queue(queue_manager,'TESTQ.1')q.put('Hello from Python!')To read the message back from the queue:importpymqiqueue_manager=pymqi.connect('QM.1','SVRCONN.CHANNEL.1','192.168.1.121(1434)')q=pymqi.Queue(queue_manager,'TESTQ.1')msg=q.get()print('Here is the message:',msg)The backbone of IBM MQ Python messagingPyMQI is a low-level library that requires one to know IBM MQ APIs well.It serves, however, as the basis for
IBM MQ
support
inZato,
which is an enterprise
API platform and backend application server in Python that lets one connect to many technologies
with little or no programming.This includes IBM MQ queue managers as well as the ability to seamlessly integrate with Java JMS systems.Learn moreVisit thedocumentationfor more information and usage examples.
Package: pymqtt
pymqttpymqtt is a mqtt python client library extension meant to facilitate the integration of a MQTT client into your web application. Basically it is a thin wrapper around the paho-mqtt package to simplify MQTT integration in a python application. MQTT is a machine-to-machine (M2M)/”Internet of Things” (IoT) protocol which is designed as a lightweight publish/subscribe messaging transport. It comes very handy when trying to connect multiple IoT devices with each other or monitor and control these devices from one or multiple clients.InstallingInstall and update usingpip:$ pip install -U pymqttA Simple ExampleimportloggingfromflaskimportFlaskfrompymqttimportMqttlogging.basicConfig(format='%(asctime)s%(process)d,%(threadName)s%(filename)s:%(lineno)d[%(levelname)s]%(message)s',datefmt='%Y-%m-%d%H:%M:%S',level=logging.INFO)logger=logging.getLogger(__name__)app=Flask(__name__)app.config.setdefault('MQTT_IP','127.0.0.1')app.config.setdefault('MQTT_PORT',1883)app.config.setdefault('MQTT_USER','user')app.config.setdefault('MQTT_PASSWORD','password')fmqtt=Mqtt()fmqtt.config_from_obj(app.config)@app.route('/')defhello_world():content='hello world'success=fmqtt.publish('hell world','topic',qos=2)return'send%ssuccess%s'%(content,success)@fmqtt.subscribe(topic='topic',qos=2)defflask_rabmq_test(body):logger.info(body)returnTrueif__name__=='__main__':fmqtt.run()app.run()
Package: pymqttbench
This is a tool to benchmark the performance of an mqtt broker. It works by
launching an arbitrary number of publishers and subscribers in parallel. These
workers both publish and subscribe to the same topic and either send or recieve
a fixed number of messages.InstallationThe easiest way to install pymqttbench is use pip:pip install pymqttbenchAlternatively you can clone the repo with:git clone https://github.com/mtreinish/pymqttbench.gitthen install it using pip:pip install ./pymqttbenchAlternatively you can run:cd pymqttbench && python setup.py installhowever using pip is recommended.UsageAfter installing pymqttbench you simply run it with the:pymqttbench --hostname $BROKER_HOSTcommand. The hostname parameter is required to tell pymqttbench the hostname
of the broker. This is the only required field, but there are several other
options exposed for how to connect to the broker.--portis used to specify
the port if you’re not connecting on the standard port,1883.--usernameand--passwordare used to specify user authentication if needed. Similiarly--cacertcan be used to specify a trusted CA certificate to verify the TLS
connection on the broker. There is also the--topicparameter which
is used to specify a topic to use for the benchmark, by defaultpybenchis
used. Note that all of these settings are used for both the publishers and
subscribers.Outside of mqtt connection options there is also the--briefflag which is
used to print a colon separated list of benchmark results instead of the default
human readable formatted output. The format for this output is:Subscriber Count:Publisher Count:Subscriber Mean Duration:Subscriber Duration Std. Deviation:Subscriber Avg. Throughput:Subscriber Total Throughput:Publisher Mean Duration:Publisher Duration Std. Deviation:Publisher Avg. Throughput:Publisher Total ThroughputTuning the benchmarkAfter pymqttbench knows how to connect to the broker you can tune the benchmark
to your specific needs. There are several axes you can adjust the bechmark on,
the first being the number of publishers and subscribers. This is configurable
with the--pub-clientsand--sub-clientsflags. By default each is set
to10. The next option you can tune is the number of messages that the
publishers will send, with--pub-count, and the number of messages the
subscribers will listen for, with--sub-count. It’s worth pointing out that
the subscribers do not pair with an individual worker like in some other
benchmarking tools, but instead listen to the same topic that all the publishers
publish to. In addition with adjusting these options you’ll likely want to
change the publisher timeout,--pub-timeout, and the subscriber timeout,sub-timeout, which describe how long the benchmark will wait for the worker
to either publish or recieve the specified message count.You can also set how large the message payload is with--msg-sizewhich
takes the number of bytes to use. By default it uses a 1024 byte payload. The
last tuning option is--qoswhich is used to specify the qos level to use
for benchmarking. By default qos 0 is used.
Package: pymqttmicroservicebase-tspspi
Python MQTT based microservice base daemonSince this is a recurring task this project contains a base implementation for
a simple MQTT based service that offers just some basic features required for
simple MQTT based microservices:DaemonizingPID file handlingLog file handlingHandling signals like SIGHUP and SIGTERMConnecting to an MQTT service using the Paho MQTT client, keeping the
connection activeProcessing JSON configuration files to gather MQTT configuration and reloading
of that configurationAllowing to specify topics relative to a base topicServices are able to simply subclass and implement their own message processing
functions. This makes life a little bit easier. This repository also implements
some client utilities that wrap the Paho MQTT library that implement a similar
pattern.Note that this library does not work when subscribing to a huge number of topics
with different handlers since it uses an own callback registration mechanism that
all messages go through. It also does not work well when one wants to dynamically
register or unregister from topics. Also in it's current implementation it linearly
iterates over all registered handlers for each message and does not use any kind
of trie.UsageThe most simple usage possible just registers topic handlers and reacts to the
received messages.from mqttservice import mqttbaseservice

class EchoService(mqttbaseservice.MQTTBaseService):
	def __init__(self):
		super().__init__(
			applicationName = "MQTTEchoService",

			topicHandlers = [
				{ 'topic' : 'echoservice/echo', 'handler' : [ self._handleEchoRequestMessage ] }
			]
		)

	def _handleEchoRequestMessage(self, topic, msg):
        self._logger.debug("Received echo request")
		self.mqttPublish('echoservice/reply', { 'some' : "payload", 'will' : "be serialized", 'to' : "JSON from dict" })

	def __enter__(self):
		return self

	def __exit__(self, type, value, tb):
		pass

if __name__ == "__main__":
	with EchoService() as service:
		service.main()
Package: pymqttusb
#pymqttusbPermet la connexion d'un microprocesseur branché sur un port usb vers un serveur MQTT.Un fichier json de configuration "arduino_mqtt_data.json" doit être présent dans le répertoire.Contenu du fichier "arduino_mqtt_data.json" :{"broker_url":"url_de_votre_broker_mqtt","broker_protocol_mqtt_mqtts_ws_wss":"wss","broker_port":443,"salle":"maSalle","KEY":"bureau/lumiere1"}-----------Le topic de réception sera : salle/KEY/outLe topic d'envoi sera : salle/KEY/inLes protocoles possibles sont "wss" websockets sécurisés avec login et mot de passe ( pas de certificat)
ou "tcp" pour ssl avec login et mot de passe ( pas de certificats client)Lancement du programme :En indiquant le nom du port usb (vitesse par défaut 9600 bauds)
py -m pymqttusb.main com8 <br />

En modifiant la vitesse de communication par défaut du port série :
py -m pymqttusb.main com8 57600<br />
Package: py-mrandom
mrandomThis package provides a random number generator.
It is based on theMersenne Twisteralgorithm.
It includes both 32 and 64 bit versions of the algorithm.
The generator has large period of 2^19937-1FeaturesCan generate random numbersCan return a choice from a listCan shuffle a listCan flip a coinCan roll a dieCan shuffle a deckInstalling the packagepipinstallmrandomImporting the module>>>importmrandom# 1 = 32 bit, 2 = 64 bit algorithm>>>random=mrandom.RandomGenerator(s)ExamplesReturn a random number between 0 and 1>>>print(random.rand())0.9888888888888889Return a random number between a and b (inclusive)>>>print(random.randint(a,b))1Return a random number between a and b (exclusive)>>>print(random.randrange(a,b))12Return k random numbers between a and b (inclusive)>>>print(random.sample(a,b,k))[1,2,3,4,5]Return a random number from a list l>>>print(random.choice(l))21Return shuffled list l>>>print(random.shuffle(l))[1,3,5,4,2]Return sample of flipping k coins n times>>>print(random.flip_coin(n,k))[1,0,0,1,0]Return sample of rolling k dices n times>>>print(random.roll_dice(n,k))[[1,4],[1,1]]Return sample of picking a card from a deck of 52 cards n times>>>print(random.shuffle_deck(n))["Ace of Spades","Ace of Hearts","Ace of Clubs","Ace of Diamonds","Ace of Clubs"]Classesmrandom.RandomGenerator- Random number generatorMethods:MethodsDescriptionrand()Return a random number between 0 and 1randint(a, b)Return a random number between a and b (inclusive)randrange(a, b)Return a random number between a and b (exclusive)sample(a, b, k)Return k random numbers between a and b (inclusive)choice(l)Return a random number from a list lshuffle(l)Return shuffled list lflip_coin(n, k)Return sample of flipping k coins n timesroll_dice(n, k)Return sample of rolling k dices n timesshuffle_deck(n)Return sample of picking a card from a deck of 52 cards n times
Package: pyMRAW
We developed this module while working on this publication:
J. Javh, J. Slavič and M. Boltežar: The Subpixel Resolution of Optical-Flow-Based Modal Analysis,
Mechanical Systems and Signal Processing, Vol. 88, p. 89–99, 2017Our recent research effort can be found here:http://lab.fs.uni-lj.si/ladisk/?what=incfl&flnm=research_filtered.php&keyword=optical%20methodsIf you find our research useful, consider to cite us.
Package: pymrequests
RequestsRequestsis a simple, yet elegant, HTTP library.>>>importrequests>>>r=requests.get('https://httpbin.org/basic-auth/user/pass',auth=('user','pass'))>>>r.status_code200>>>r.headers['content-type']'application/json; charset=utf8'>>>r.encoding'utf-8'>>>r.text'{"authenticated": true, ...'>>>r.json(){'authenticated':True,...}Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode yourPUT&POSTdata — but nowadays, just use thejsonmethod!Requests is one of the most downloaded Python packages today, pulling in around30M downloads / week— according to GitHub, Requests is currentlydepended uponby1,000,000+repositories. You may certainly put your trust in this code.Installing Requests and Supported VersionsRequests is available on PyPI:$python-mpipinstallrequestsRequests officially supports Python 3.7+.Supported Features & Best–PracticesRequests is ready for the demands of building robust and reliable HTTP–speaking applications, for the needs of today.Keep-Alive & Connection PoolingInternational Domains and URLsSessions with Cookie PersistenceBrowser-style TLS/SSL VerificationBasic & Digest AuthenticationFamiliardict–like CookiesAutomatic Content Decompression and DecodingMulti-part File UploadsSOCKS Proxy SupportConnection TimeoutsStreaming DownloadsAutomatic honoring of.netrcChunked HTTP RequestsAPI Reference and User Guide available onRead the DocsCloning the repositoryWhen cloning the Requests repository, you may need to add the-c fetch.fsck.badTimezone=ignoreflag to avoid an error about a bad commit (seethis issuefor more background):gitclone-cfetch.fsck.badTimezone=ignorehttps://github.com/psf/requests.gitYou can also apply this setting to your global Git config:gitconfig--globalfetch.fsck.badTimezoneignore