Saravanan666/pypi-org huggingface dataset:
Package: gev
Gev (General Events Manager)$pipinstallgevUsagefromgevimportEvent,EventManagermanager=EventManager()defhandler_1(e):print("handler_1 called with",e)defhandler_2(e):print("handler_2 called with",e)# Register event handlersmanager.on('sys_1::event_a').do(handler_1)manager.on('sys_1::event_b').do(handler_2)manager.take(Event(source='sys_1',type='event_a',payload={'a':1}))# handler_1 will be calledmanager.take(Event(source='sys_1',type='event_b',payload={'b':1}))# handler_1 will be calledIf you don't want to initialize anEventManagerinstance,
you can use the globaldefault_managerand itsonandtakemethods exposed at module level.fromgevimporton,take,Eventdefhandler_1(e):print("handler_1 called with",e)on('sys_1::event_a').do(handler_1)take(Event(source='sys_1',type='event_a',payload={'a':1}))# handler_1 will be called
Package: gevent-breaker
gevent-breaker==============[![Build Status](https://travis-ci.org/daroot/gevent-breaker.svg?branch=1.0.0)](https://travis-ci.org/daroot/gevent-breaker)Circuit Breaker pattern for gevent apps.Install-------$ pip install gevent-breakerUsage-----```pythonfrom gevent_breaker import circuit_breaker, CircuitBrokenwhile True:try:# After enough errors (5 by default), raise a CircuitBrokenwith circuit_breaker("breaker1"):1/0except ZeroDivisionError:print("Got an exception!")except CircuitBroken:print("Too many errors!")breaktry:# Don't raise a CircuitBroken, instead just wait for a period# of time (default 60s) before trying again.with circuit_breaker("breaker2", block=True):1/0except ZeroDivisionError:print("Got an exception")```
Package: geventcron
# GeventCron### 原理:gevent有个spawn_later()函数，专为定时任务打造...他的`缺点`就是，别让gevent调度堵塞了....尽量让你业务逻辑，采用gevent patch模块正在尝试下，借助spawn_later周期功能，解决堵塞的问题, [查看更多GeventCron相关信息](http://xiaorui.cc)### 安装方法:```pip install geventcronorpython setup.py install```### 使用方法:```import timeimport requestsimport threadingimport functoolsfrom datetime import datetimeimport geventcrondef async(func):@functools.wraps(func)def wrapper(*args, **kwargs):my_thread = threading.Thread(target=func, args=args, kwargs=kwargs)my_thread.start()return wrapper@asyncdef func_1():print 'Call func_1'def func_2():print 'Call func_2'def func_3():print 'Call func_3'#尽量别用堵塞的模块,可以用grequestsdef block():requests.get("http://www.google.com/")if __name__ == "__main__":scheduler = geventcron.Scheduler(logger_name='task_scheduler')scheduler.schedule('task_1', geventcron.Interval("*/1 * * * *"), func_1)scheduler.schedule('task_2', geventcron.Interval(2), func_2)scheduler.schedule('task_3', geventcron.Interval(3), func_3)# scheduler.run_forever()scheduler.daemon(flag=True)print "daemon"time.sleep(100)```
Package: gevent_dht
This is a basic implementation of a dht using gevent.There are two things you have to concern yourself with.1.) Bootstrapping the network.The following example creates a network of one node-------------------------------------------------------------------import gevent_dhttable = gevent_dht.distributedHashTable(None) #This tell the network it# is the first node by default it listens on port 8339#table['key_1'] = [1,2,3] #This sets a value in our hash tablefor i in table['key_1']:print i #Prints 123table.append('key_1', 4) #Adds an item to a list in a hash table#Note if the key is not in the hash table#It will put a list in place and then append#to it.#Now we are adding another nodeother_clients_table = gevent_dht.distributedHashTable('127.0.0.1:8339', local_port = 8449)#Another client has connected. It supplied the address of# a node in the network to connect with the preexisting networkfor i in other_clients_table['key_1']:print i #Prints 1234-------------------------------------------------------------------So in order to connect to an existing network you must have a way to get anaddress of another member. It doesn't have to be the first node but needsto be a node in the network.2.) Latency/ This may fail.Keys are not guarenteed to persist forever, nodes may crash, the networkmay eat messages etc... While we are working in tcp/ip mode there may stillbe bizarre glitches. Always check for a return value of None.Additionally due to the time it takes for messages to travel the networksometimes a key will not be immedietly available after you set it orwhen you get the result back it may not be completely current.
Package: gevent_etcd
## 项目名gevent-etcd## 介绍gevent-etcd 是一个使用gevent requests封装的python client模块. 至于gevent_etcd用途是用来解决在多任务请求下io阻塞的情况 (主要是针对应用环境用gevent调度的情况下) . etcd原版是用urllib2开发的, 我个人曾经被gevent urllib2坑过, 所以轻易不会用urllib2.另外，gevent-etcd的功能还很简单，期待有人提交pull request我个人的看法，在网络io堵塞的问题上，能用协程坚决不用多线程.## 用法pypi安装` pip install gevent_etcd `源码安装` git clonehttps://github.com/rfyiamcool/gevent-etcd.gitcdgevent-etcdpython setup.py install `### ToDOListcomplement write functionfix stream watch bugAdd leader api , manage etcd cluster
Package: gevent-eventemitter
This module implements EventEmitter with gevent.InstallationTo install the latest release frompypi:pip install gevent-eventemitterUsageEventEmittercan be used as mixin, or on it’s own. Here is an example as mixin:fromeventemitterimportEventEmitterclassMyClass(EventEmitter):passinstance=MyClass()Registering a callbackdefdo_stuff():print"Hello world!"instance.on('my event',do_stuff)instance.emit('my event')Or as decorator@instance.on('my event')defdo_stuff():print"Hello world!"Withoncethe callback will be called, you guessed it, only once.@instance.once('my event')defdo_stuff(var):print"Hello%s!"%varinstance.emit('my event','Earth')# arguments can be passed along eventsinstance.emit('my event')# do_stuff won't be calledIt’s possible to block wait for an event.If there are event arguments they will be returned as atuplemy_args=instance.wait_event('my event')my_args=instance.wait_event('my event',timeout=5)# wait at most 5secondsOn timeoutwait_eventwill returnNone, or raisegevent.Timeoutifraises=Truemy_args=instance.wait_event('my event',timeout=5)ifmy_argsisNone:print"Timeout!"try:my_args=instance.wait_event('my event',timeout=5,raises=True)exceptgevent.Timeout:print"Timeout!"To remove a callback, or all callbacks.instance.remove_listener('my event',do_stuff)instance.remove_all_listeners()# absolutely all listenersinstance.remove_all_listeners('my event')# all listners for the eventListening forNoneevent will result in catching all events.
Package: gevent-fsm
Gevent FSMFinite State Machines with GeventFree software: Apache Software License 2.0Documentation:https://gevent-fsm.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2018-11-08)First release on PyPI.0.2.0 (2018-11-09)Adds the tools get_fsm and fsm_generate_diffs0.2.1 (2018-11-09)Fixes python 3 import statement0.2.2 (2019-01-17)Fixes packaging of gevent.tools
Package: gevent-helpers
gevent-helperscontains a collection of utilities which are helpful while
developing withgevent.Compatible withgevent==1.0rc3.fork()A workaround forgevent issue 154, until that issue is fixed.BlockingDetector(timeout=1, raise_exc=AlarmInterrupt, aggressive=True)Use operating system signals to detect blocking threads.timeout=1is the number of seconds to wait before considering the
thread blocked (note: ifsignal.setitimeror theitimerpackage is
available, this can be a real number; otherwise it will be rounded up to
the nearest integer).raise_exc=AlarmInterruptcontrols which exception will be raised
in the blocking thread. Ifraise_excis False-ish, no exception will be
raised (alog.warningmessage, including stack trace, will always be
issued).NOTE: the default value,AlarmInterrupt, is a subclass ofBaseException, so itwill notbe caught byexcept Exception:(it
will be caught bydirt.runloop). For example:# Don't raise an exception, only log a warning message and stack trace:
BlockingDetector(raise_exc=False)

# Raise ``MyException()`` and lot a warning message:
BlockingDetector(raise_exc=MyException())

# Raise ``MyException("blocking detected after timeout=...")`` and log
# a warning message:
BlockingDetector(raise_exc=MyException)aggressive=Truedetermines whether the blocking detector will reset
as soon as it is triggered, or whether it will wait until the blocking
thread yields before it resets. For example, ifaggressive=True,raise_exc=False, andtimeout=1, a log message will be written for
every second that a thread blocks. However, ifaggressive=False, only
one log message will be written until the blocking thread yields, at which
point the alarm will be reset.Note:BlockingDetectoroverwrites thesignal.SIGALRMhandler and
does not attempt to save the previous value.For example:>>> def spinblock():
...     while True:
...         pass
>>> gevent.spawn(BlockingDetector())
>>> gevent.sleep()
>>> spinblock()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in spinblock
  File ".../dirt/misc/gevent_.py", line 167, in alarm_handler
    raise exc
gevent_helpers.AlarmInterrupt: blocking detected after timeout=1
Package: geventhttpclient
A high performance, concurrent HTTP client library for python using gevent.gevent.httplib support was removed in gevent 1.0, geventhttpclient now
provides that missing functionality.geventhttpclient uses a fast http parser, written in C, originating from
nginx, extracted and modified by Joyent.geventhttpclient has been specifically designed for high concurrency,
streaming and support HTTP 1.1 persistent connections. More generally it is
designed for efficiently pulling from REST APIs and streaming APIs
like Twitter’s.Safe SSL support is provided by default. geventhttpclient depends on
the certifi CA Bundle. This is the same CA Bundle which ships with the
Requests codebase, and is derived from Mozilla Firefox’s canonical set.As of 1.5, only Python 3.6+ is fully supported (with prebuilt wheels),
but Python 2.7 and 3.5shouldwork too.Use of SSL/TLS with python 2.7.9 is not recommended and may be broken.
Package: geventhttpclient-facebook
This fork is still in development:TODO:put_photo isn’t working yet.
shortcuts out of GraphAPI class aren’t testedFacebook Python SDKThis client library is designed to support theFacebook Graph APIand the
officialFacebook JavaScript SDK, which is the canonical way to implement
Facebook authentication. You can read more about the Graph API by accessing itsofficial documentation.Basic usage:graph = facebook.GraphAPI(oauth_access_token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
graph.put_object("me", "feed", message="I am writing on my wall!")Photo uploads:graph = facebook.GraphAPI(oauth_access_token)
tags = json.dumps([{'x':50, 'y':50, tag_uid:12345}, {'x':10, 'y':60, tag_text:'a turtle'}])
graph.put_photo(open('img.jpg'), 'Look at this cool photo!', album_id_or_None, tags=tags)If you are using the module within a web application with the JavaScript SDK,
you can also use the module to use Facebook for login, parsing the cookie set
by the JavaScript SDK for logged in users. For example, in Google AppEngine,
you could get the profile of the logged in user with:user = facebook.get_user_from_cookie(self.request.cookies, key, secret)
if user:
    graph = facebook.GraphAPI(user["access_token"])
    profile = graph.get_object("me")
    friends = graph.get_connections("me", "friends")You can see a full AppEngine example application in examples/appengine.Reporting IssuesIf you have bugs or other issues specifically pertaining to this library, file
themhere. Bugs with the Graph API should be filed onFacebook’s
bugtracker.
Package: geventhttpclient-wheels
A high performance, concurrent HTTP client library for python using gevent.gevent.httplib support was removed in gevent 1.0, geventhttpclient now
provides that missing functionality.geventhttpclient uses a fast http parser, written in C, originating from
nginx, extracted and modified by Joyent.geventhttpclient has been specifically designed for high concurrency,
streaming and support HTTP 1.1 persistent connections. More generally it is
designed for efficiently pulling from REST APIs and streaming APIs
like Twitter’s.Safe SSL support is provided by default. geventhttpclient depends on
the certifi CA Bundle. This is the same CA Bundle which ships with the
Requests codebase, and is derived from Mozilla Firefox’s canonical set.Python 2.7 and 3.4+ are supported.
Python 2.6 is no longer supported.Use of SSL/TLS with python 2.7.9 is not recommended and may be broken.
Package: gevent_inotifyx
Gevent-compatible low-level inotify bindings based oninotifyx.Python 2 and 3 compatibleExposes a low-levelinotify(7)APIAllows to wait for events in a non-blocking way when usinggevent.Installation$ pip install gevent_inotifyxFrom source:$ python setup.py installTo run the tests:$ python setup.py testExamplesWatch a directory while creating new files. This printsevent: test.txt IN_CLOSE|IN_CLOSE_WRITE|IN_ALL_EVENTSevery second:#!/usr/bin/env pythonfrom__future__importprint_functionimportosimportgeventimportgevent_inotifyxasinotifydefcreate_file_events():"""Open and close a file to generate inotify events."""whileTrue:withopen('/tmp/test.txt','a'):passgevent.sleep(1)defwatch_for_events():"""Wait for events and print them to stdout."""fd=inotify.init()try:wd=inotify.add_watch(fd,'/tmp',inotify.IN_CLOSE_WRITE)whileTrue:foreventininotify.get_events(fd):print("event:",event.name,event.get_mask_description())finally:os.close(fd)if__name__=='__main__':tasks=[gevent.spawn(watch_for_events),gevent.spawn(create_file_events),]gevent.joinall(tasks)Licensegevent_inotifyx is licensed under the MIT License. See the included
fileLICENSEfor details.
Package: geventmp
WarningHIC SUNT DRACONES!!!This code is experimental (beta). There is some testing, but a lots of things are in flux, and
some platforms don’t work at all.You MAY try to use this in production with the understanding that this is a beta-quality software.That said, this code may crash your server, bankrupt your company, burn your house down and be mean
to your puppy.You’ve been warned.ProblemDue to internal implementation,multiprocessing(MP) is unsafe to use withGeventeven whenmonkey-patched.
Namely, the use of OS semaphore primitives and inter-process IO inMPwill cause the main
loop to stall/deadlock/block (specific issue depends on the version of CPython).SolutionGeventMP(Gee-vent Em-Pee) is ageventmultiprocessing extension plugin for themonkey-patchingsubsystem.
As with the rest of the monkey patch subsystem the process is fairly clear:Identify all places where blocking occurs and where it may stall the loop.If blocking occurs on a file descriptor (FD), try to convert the file descriptor from blocking to non-blocking
(sockets/pipes/fifos, sometimes even files where, rarely, appropriate) and replace blocking IO functions with theirgeventnon-blocking equivalents.If blocking occurs in a Python/OS primitive that does not support non-blocking access and thus cannot be geventized,
wrap all blocking access to that primitive with native thread-pool-based wrappers and call it a day (while fully
understanding that primitive access latency will increase and raw performance may suffer as a result).If you are really brave and have lots of free time on your hands, completely replace a standard blocking Python
non-FD-based primitive with implementation based on anFD-based OS primitive (e.g. POSIX semaphore =>
Linuxeventfd-based semaphore for kernels > 2.6.30).Due to launching of separate processes inMP, figure out how, when, and whether tomonkey-patchspawned/forked
children and grandchildren.InstallationThe package is hosted onPyPi.For stable version:pipinstallgeventmpFor unstable version:pipinstall--pregeventmpOnce installed,GeventMPwill activate by default in the below stanza.fromgevent.monkeyimportpatch_allpatch_all()If you would likeGeventMPto not activate by default, either do not install it or explicitly disable it:fromgevent.monkeyimportpatch_allpatch_all(geventmp=False)That’s it - there are no other flags, settings, properties or config values so far.Supported PlatformsNoteAll claims of support may not be real at all. You’re welcome to experiment. See warnings on top.Linux and Darwin.CPython 3.7, 3.8, 3.9, 3.10, 3.11, 3.12PyPy 3.8, 3.9Known IssuesMultiprocessingforkserverworks inGeventMP, but the spawned child isn’t green.TODOMonkey patch Windows to the extent possible.Lots of applications useBilliardfor multiprocessing instead of stock Python
package. Consider monkey patching Billiard if detected.Contact UsPost feedback and issues on theBug Tracker,Gitter,
andTwitter (@karelleninc).
Package: gevent_openssl
This library wraps pyOpenSSL to make it compatible with gevent. OpenSSL connection
operations that would normally block the current thread will only block the
current greenlet instead.RequirementsPyOpenSSL >= 0.11gevent (compatible with 1.0 pre-releases as well)UsageInstead of importing OpenSSL directly, do so in the following manner:import gevent_openssl as OpenSSLorimport gevent_openssl; gevent_openssl.monkey_patch()Any calls that would have blocked the current thread will now only block the
current green thread.AboutThis compatibility is accomplished by yielding to the gevent scheduler
when pyOpenSSL is waiting to be able to read or write data.LicenseNew BSDHistoryThis project was originally created by Phus Lu (phus.lu@gmail.com) and
is now maintained by Menno Finlay-Smits (menno@freshfoo.com).
Package: gevent-pika
Pika is a RabbitMQ (AMQP-0-9-1) client library for Python.IntroductionPika is a pure-Python implementation of the AMQP 0-9-1 protocol including RabbitMQ’s
extensions.Python 2.6+ and 3.3+ are supported.Since threads aren’t appropriate to every situation, it doesn’t
require threads. It takes care not to forbid them, either. The same
goes for greenlets, callbacks, continuations and generators. It is
not necessarily thread-safe however, and your mileage will vary.People may be using direct sockets, plain oldselect(),
or any of the wide variety of ways of getting network events to and from a
python application. Pika tries to stay compatible with all of these, and to
make adapting it to a new environment as simple as possible.DocumentationPika’s documentation can be found athttps://pika.readthedocs.ioExampleHere is the most simple example of use, sending a message with the BlockingConnection adapter:importpikaconnection=pika.BlockingConnection()channel=connection.channel()channel.basic_publish(exchange='example',routing_key='test',body='Test Message')connection.close()And an example of writing a blocking consumer:importpikaconnection=pika.BlockingConnection()channel=connection.channel()formethod_frame,properties,bodyinchannel.consume('test'):# Display the message parts and ack the messageprint(method_frame,properties,body)channel.basic_ack(method_frame.delivery_tag)# Escape out of the loop after 10 messagesifmethod_frame.delivery_tag==10:break# Cancel the consumer and return any pending messagesrequeued_messages=channel.cancel()print('Requeued%imessages'%requeued_messages)connection.close()Pika provides the following adaptersAsyncioConnection  - adapter for the Python3 AsyncIO event loopBlockingConnection - enables blocking, synchronous operation on top of library for simple usesLibevConnection    - adapter for use with the libev event loophttp://libev.schmorp.deSelectConnection   - fast asynchronous adapterTornadoConnection  - adapter for use with the Tornado IO Loophttp://tornadoweb.orgTwistedConnection  - adapter for use with the Twisted asynchronous packagehttp://twistedmatrix.com/ContributingTo contribute to pika, please make sure that any new features or changes
to existing functionalityinclude test coverage.Pull requests that add or change code without coverage will most likely be rejected.Additionally, please format your code usingyapfwithgooglestyle prior to issuing your pull request.
Package: gevent-pipeline
Multi-worker pipelines with gevent.Installationpipinstallgevent-pipelineExampleimportgeventimportrandomfromitertoolsimportrepeatfromgevent_pipelineimportPipelinedefsample(b):r=random.uniform(0,b)gevent.sleep(r)returnr(Pipeline().from_iter(repeat(1,times=200)).map(sample,n_workers=100).filter(lambdax:x<0.5).fold(max,x0=0,n_workers=50))PipelineChain together operations with multiple workers for each layer.Example:>>>importoperator>>>defonly_odd(x):...returnx&1...>>>defdouble(x):...return2*x...>>>(Pipeline()....from_iter(range(100))....filter(only_odd,n_workers=10)....map(double,n_workers=8)....fold(operator.add,x0=0,n_workers=5))5000The above is functionally equivalent to:>>>@worker(discard_none=True)...defonly_odd(x):...'''Forward only odd numbers to the next layer'''...ifx&1:...returnx...>>>@worker()...defdouble(x):...return2*x...>>>defload_numbers(q_in,q_out,q_done):...foriinrange(100):...q_out.put(i)...q_done.put(None)...>>>q_out=ClosableQueue()>>>p=(Pipeline()....chain_workers(load_numbers)....chain_workers(only_odd,n_workers=10)....chain_workers(double,n_workers=8,q_out=q_out))>>>sum(iforiinq_out)5000There is no guarantee of order:>>>deff(x):...gevent.sleep(random.uniform(0,0.001))...returnx>>>p=Pipeline().from_iter(range(10)).map(f,n_workers=5)>>>list(p)[2,1,4,0,3,5,8,6,7,9]Exceptions in workersThere is a predefinedforward_inputexception handler, in the event
the function raises an exception the handler takes the input to the
function and passes it along as if it was the output.fromgevent_pipelineimportPipeline,worker,forward_input@worker(exception_handler=forward_input)deff(x):ifx&1:raiseValueError("oh no!")# Will be treated as if it were:# return xelse:return2*xp=(Pipeline().from_iter(range(100)).chain_workers(f,n_workers=10))s_odd=sum(range(1,100,2))s_even=sum(2*iforiinrange(0,100,2))assertsum(p)==s_odd+s_evenClosableQueueActs likegevent.queue.Queuebut in addition has a.close()method which invokes following behavior:Calling.put(item)becomes an errorSuccessive calls to.get()will return whatever remains in the
queue and after that StopIteration is returned for every subsequent
call>>>fromgevent_pipelineimportClosableQueue>>>q=ClosableQueue()>>>q.put('hello')>>>q.close()>>>q.get()'hello'>>>q.get()isStopIterationTrue
Package: gevent-requests
Gevent-Requests allows you to use Requests with Gevent to make asynchronous HTTP
Requests easily.
And this project also allow your own custom useage with gevent in your production environment,
for example your can use it with flask like:>>> from gevent import monkey
>>> monkey.patch_all(thread=False, select=False)UsageUsage is simple:>>> # First patch the socket
>>> import gevent_requests

>>> urls = [
>>>     'http://www.heroku.com',
>>>     'http://tablib.org',
>>>     'http://httpbin.org',
>>>     'http://python-requests.org',
>>>     'http://kennethreitz.com'
>>> ]Create a set of unsent Requests:>>> rs = (gevent_requests.get(u) for u in urls)Send them all at the same time:>>> gevent_requests.gmap(rs)
[<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]
Package: gevent-serial
gevent-serialA python 3geventfriendly access to the serial port.Deeply inspired bypyserial. It tries to mimic
its interface but it doesn't aim to garantee full API compatibility.For now only Linux (and possibly any BSD or posix complient system) is supported.Support for local serial port, RFC2217, and RS485 (untested).Includes an optional serial to TCP bridge (experimental).InstallationFrom within your favourite python environment:$pipinstallgevent-serialSerial to TCP bridgeTo be available, it requires you to install the optional server package
with:$pipinstallgevent-serial[ser2tcp]The ser2tcp server needs a configuration file written in YAML. It consists of a
list of serial entries. Each entry describes the serial port address (url),
the TCP port (listener) and optionally a TCP mode and other serial line options
(baudrate, parity, byte size, etc.)Here is an example:-url:/dev/ttyS0baudrate:9600listener::2217# listen on all network interfaces, TCP port 2217mode:rfc2217-url:/dev/ttyS1baudrate:115200mode:rawlistener::2218-url:loop://listener::2219baudrate:115200mode:raw-url:loop://listener::2220baudrate:9600mode:rfc2217