desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Send a complete multipart zmq message.
Returns a Future that resolves when sending is complete.'
| def send_multipart(self, msg, flags=0, copy=True, track=False):
| return self._add_send_event('send_multipart', msg=msg, kwargs=dict(flags=flags, copy=copy, track=track))
|
'Send a single zmq frame.
Returns a Future that resolves when sending is complete.
Recommend using send_multipart instead.'
| def send(self, msg, flags=0, copy=True, track=False):
| return self._add_send_event('send', msg=msg, kwargs=dict(flags=flags, copy=copy, track=track))
|
'Deserialize with Futures'
| def _deserialize(self, recvd, load):
| f = self._Future()
def _chain(_):
'Chain result through serialization to recvd'
if f.done():
return
if recvd.exception():
f.set_exception(recvd.exception())
else:
buf = recvd.result()
try:
loaded = loa... |
'poll the socket for events
returns a Future for the poll results.'
| def poll(self, timeout=None, flags=_zmq.POLLIN):
| if self.closed:
raise _zmq.ZMQError(_zmq.ENOTSUP)
p = self._poller_class()
p.register(self, flags)
f = p.poll(timeout)
future = self._Future()
def unwrap_result(f):
if future.done():
return
if f.exception():
future.set_exception(f.exception())
... |
'Add a timeout for a send or recv Future'
| def _add_timeout(self, future, timeout):
| def future_timeout():
if future.done():
return
future.set_exception(_zmq.Again())
self._call_later(timeout, future_timeout)
|
'Schedule a function to be called later
Override for different IOLoop implementations
Tornado and asyncio happen to both have ioloop.call_later
with the same signature.'
| def _call_later(self, delay, callback):
| self.io_loop.call_later(delay, callback)
|
'Make sure that futures are removed from the event list when they resolve
Avoids delaying cleanup until the next send/recv event,
which may never come.'
| @staticmethod
def _remove_finished_future(future, event_list):
| if getattr(future, '_pyzmq_popped', False):
return
for (f_idx, (f, kind, kwargs, _)) in enumerate(event_list):
if (f is future):
break
else:
return
future._pyzmq_popped = True
event_list.remove(event_list[f_idx])
|
'Add a recv event, returning the corresponding Future'
| def _add_recv_event(self, kind, kwargs=None, future=None):
| f = (future or self._Future())
if (kind.startswith('recv') and (kwargs.get('flags', 0) & _zmq.DONTWAIT)):
recv = getattr(self._shadow_sock, kind)
try:
r = recv(**kwargs)
except Exception as e:
f.set_exception(e)
else:
f.set_result(r)
re... |
'Add a send event, returning the corresponding Future'
| def _add_send_event(self, kind, msg=None, kwargs=None, future=None):
| f = (future or self._Future())
if (kind.startswith('send') and (kwargs.get('flags', 0) & _zmq.DONTWAIT)):
send = getattr(self._shadow_sock, kind)
try:
r = send(msg, **kwargs)
except Exception as e:
f.set_exception(e)
else:
f.set_result(r)
... |
'Handle recv events'
| def _handle_recv(self):
| if (not (self._shadow_sock.EVENTS & POLLIN)):
return
f = None
while self._recv_futures:
(f, kind, kwargs, _) = self._recv_futures.popleft()
f._pyzmq_popped = True
if f.done():
f = None
else:
break
if (not self._recv_futures):
self._... |
'Dispatch IO events to _handle_recv, etc.'
| def _handle_events(self, fd=0, events=0):
| zmq_events = self._shadow_sock.EVENTS
if (zmq_events & _zmq.POLLIN):
self._handle_recv()
if (zmq_events & _zmq.POLLOUT):
self._handle_send()
self._schedule_remaining_events()
|
'Schedule a call to handle_events next loop iteration
If there are still events to handle.'
| def _schedule_remaining_events(self, events=None):
| if (events is None):
events = self._shadow_sock.EVENTS
if (events & self._state):
self._call_later(0, self._handle_events)
|
'Add io_state to poller.'
| def _add_io_state(self, state):
| if (not (self._state & state)):
self._state = (self._state | state)
self._update_handler(self._state)
|
'Stop poller from watching an io_state.'
| def _drop_io_state(self, state):
| if (self._state & state):
self._state = (self._state & (~ state))
self._update_handler(self._state)
|
'Update IOLoop handler with state.
zmq FD is always read-only.'
| def _update_handler(self, state):
| self._schedule_remaining_events()
|
'initialize the ioloop event handler'
| def _init_io_state(self):
| self.io_loop.add_handler(self._shadow_sock, self._handle_events, self._READ)
|
'unregister the ioloop event handler
called once during close'
| def _clear_io_state(self):
| self.io_loop.remove_handler(self._shadow_sock)
|
'The address of the underlying libzmq socket'
| @property
def underlying(self):
| return int(ffi.cast('size_t', self._zmq_socket))
|
'thorough check of whether the socket has been closed,
even if by another entity (e.g. ctx.destroy).
Only used by the `closed` property.
returns True if closed, False otherwise'
| def _check_closed_deep(self):
| if self._closed:
return True
try:
self.get(zmq.TYPE)
except ZMQError as e:
if (e.errno == zmq.ENOTSOCK):
self._closed = True
return True
else:
raise
return False
|
's.monitor(addr, flags)
Start publishing socket events on inproc.
See libzmq docs for zmq_monitor for details.
Note: requires libzmq >= 3.2
Parameters
addr : str
The inproc url used for monitoring. Passing None as
the addr will cause an existing socket monitor to be
deregistered.
events : int [default: zmq.EVENT_ALL]
T... | def monitor(self, addr, events=(-1)):
| _check_version((3, 2), 'monitor')
if (events < 0):
events = zmq.EVENT_ALL
if (addr is None):
addr = ffi.NULL
if isinstance(addr, unicode):
addr = addr.encode('utf8')
rc = C.zmq_socket_monitor(self._zmq_socket, addr, events)
|
'The address of the underlying libzmq context'
| @property
def underlying(self):
| return int(ffi.cast('size_t', self._zmq_ctx))
|
'set a context option
see zmq_ctx_set'
| def set(self, option, value):
| rc = C.zmq_ctx_set(self._zmq_ctx, option, value)
_check_rc(rc)
|
'get context option
see zmq_ctx_get'
| def get(self, option):
| rc = C.zmq_ctx_get(self._zmq_ctx, option)
_check_rc(rc)
return rc
|
'The main logic of decorator
Here is how those arguments works::
@out_decorator(*dec_args, *dec_kwargs)
def func(*wrap_args, **wrap_kwargs):
And in the ``wrapper``, we simply create ``self.target`` instance via
``with``::
target = self.get_target(*args, **kwargs)
with target(*dec_args, **dec_kwargs) as obj:'
| def __call__(self, *dec_args, **dec_kwargs):
| (kw_name, dec_args, dec_kwargs) = self.process_decorator_args(*dec_args, **dec_kwargs)
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
target = self.get_target(*args, **kwargs)
with target(*dec_args, **dec_kwargs) as obj:
if (kw_name and (k... |
'Return the target function
Allows modifying args/kwargs to be passed.'
| def get_target(self, *args, **kwargs):
| return self._target
|
'Process args passed to the decorator.
args not consumed by the decorator will be passed to the target factory
(Context/Socket constructor).'
| def process_decorator_args(self, *args, **kwargs):
| kw_name = None
if isinstance(kwargs.get('name'), basestring):
kw_name = kwargs.pop('name')
elif ((len(args) >= 1) and isinstance(args[0], basestring)):
kw_name = args[0]
args = args[1:]
return (kw_name, args, kwargs)
|
'Also grab context_name out of kwargs'
| def process_decorator_args(self, *args, **kwargs):
| (kw_name, args, kwargs) = super(_SocketDecorator, self).process_decorator_args(*args, **kwargs)
self.context_name = kwargs.pop('context_name', 'context')
return (kw_name, args, kwargs)
|
'Get context, based on call-time args'
| def get_target(self, *args, **kwargs):
| context = self._get_context(*args, **kwargs)
return context.socket
|
'Find the ``zmq.Context`` from ``args`` and ``kwargs`` at call time.
First, if there is an keyword argument named ``context`` and it is a
``zmq.Context`` instance , we will take it.
Second, we check all the ``args``, take the first ``zmq.Context``
instance.
Finally, we will provide default Context -- ``zmq.Context.inst... | def _get_context(self, *args, **kwargs):
| if (self.context_name in kwargs):
ctx = kwargs[self.context_name]
if isinstance(ctx, zmq.Context):
return ctx
for arg in args:
if isinstance(arg, zmq.Context):
return arg
return zmq.Context.instance()
|
'Format a record.'
| def format(self, record):
| return self.formatters[record.levelno].format(record)
|
'Emit a log message on my socket.'
| def emit(self, record):
| try:
(topic, record.msg) = record.msg.split(TOPIC_DELIM, 1)
except Exception:
topic = ''
try:
bmsg = cast_bytes(self.format(record))
except Exception:
self.handleError(record)
return
topic_list = []
if self.root_topic:
topic_list.append(self.root_t... |
'Log \'msg % args\' with level and topic.
To pass exception information, use the keyword argument exc_info
with a True value::
logger.log(level, "zmq.fun", "We have a %s",
"mysterious problem", exc_info=1)'
| def log(self, level, topic, msg, *args, **kwargs):
| logging.Logger.log(self, level, ('%s::%s' % (topic, msg)), *args, **kwargs)
|
'Starts the timer.'
| def start(self):
| self._running = True
self._firstrun = True
self._next_timeout = (time.time() + (self.callback_time / 1000.0))
self.io_loop.add_timeout(self._next_timeout, self._run)
|
'Returns a global `IOLoop` instance.
Most applications have a single, global `IOLoop` running on the
main thread. Use this method to get this instance from
another thread. To get the current thread\'s `IOLoop`, use `current()`.'
| @classmethod
def instance(cls, *args, **kwargs):
| PollIOLoop.configure(cls)
_deprecated()
loop = PollIOLoop.instance(*args, **kwargs)
return loop
|
'Returns the current threadâs IOLoop.'
| @classmethod
def current(cls, *args, **kwargs):
| PollIOLoop.configure(cls)
_deprecated()
loop = PollIOLoop.current(*args, **kwargs)
return loop
|
'Schedule callback for a raw socket'
| def _watch_raw_socket(self, loop, socket, evt, f):
| loop.add_handler(socket, (lambda *args: f()), evt)
|
'Unschedule callback for a raw socket'
| def _unwatch_raw_sockets(self, loop, *sockets):
| for socket in sockets:
loop.remove_handler(socket)
|
'Disable callback and automatic receiving.'
| def stop_on_recv(self):
| return self.on_recv(None)
|
'Disable callback on sending.'
| def stop_on_send(self):
| return self.on_send(None)
|
'DEPRECATED, does nothing'
| def stop_on_err(self):
| gen_log.warn('on_err does nothing, and will be removed')
|
'DEPRECATED, does nothing'
| def on_err(self, callback):
| gen_log.warn('on_err does nothing, and will be removed')
|
'Register a callback for when a message is ready to recv.
There can be only one callback registered at a time, so each
call to `on_recv` replaces previously registered callbacks.
on_recv(None) disables recv event polling.
Use on_recv_stream(callback) instead, to register a callback that will receive
both this ZMQStream... | def on_recv(self, callback, copy=True):
| self._check_closed()
assert ((callback is None) or callable(callback))
self._recv_callback = stack_context.wrap(callback)
self._recv_copy = copy
if (callback is None):
self._drop_io_state(zmq.POLLIN)
else:
self._add_io_state(zmq.POLLIN)
|
'Same as on_recv, but callback will get this stream as first argument
callback must take exactly two arguments, as it will be called as::
callback(stream, msg)
Useful when a single callback should be used with multiple streams.'
| def on_recv_stream(self, callback, copy=True):
| if (callback is None):
self.stop_on_recv()
else:
self.on_recv((lambda msg: callback(self, msg)), copy=copy)
|
'Register a callback to be called on each send
There will be two arguments::
callback(msg, status)
* `msg` will be the list of sendable objects that was just sent
* `status` will be the return result of socket.send_multipart(msg) -
MessageTracker or None.
Non-copying sends return a MessageTracker object whose
`done` at... | def on_send(self, callback):
| self._check_closed()
assert ((callback is None) or callable(callback))
self._send_callback = stack_context.wrap(callback)
|
'Same as on_send, but callback will get this stream as first argument
Callback will be passed three arguments::
callback(stream, msg, status)
Useful when a single callback should be used with multiple streams.'
| def on_send_stream(self, callback):
| if (callback is None):
self.stop_on_send()
else:
self.on_send((lambda msg, status: callback(self, msg, status)))
|
'Send a message, optionally also register a new callback for sends.
See zmq.socket.send for details.'
| def send(self, msg, flags=0, copy=True, track=False, callback=None):
| return self.send_multipart([msg], flags=flags, copy=copy, track=track, callback=callback)
|
'Send a multipart message, optionally also register a new callback for sends.
See zmq.socket.send_multipart for details.'
| def send_multipart(self, msg, flags=0, copy=True, track=False, callback=None):
| kwargs = dict(flags=flags, copy=copy, track=track)
self._send_queue.put((msg, kwargs))
callback = (callback or self._send_callback)
if (callback is not None):
self.on_send(callback)
else:
self.on_send((lambda *args: None))
self._add_io_state(zmq.POLLOUT)
|
'Send a unicode message with an encoding.
See zmq.socket.send_unicode for details.'
| def send_string(self, u, flags=0, encoding='utf-8', callback=None):
| if (not isinstance(u, basestring)):
raise TypeError('unicode/str objects only')
return self.send(u.encode(encoding), flags=flags, callback=callback)
|
'Send json-serialized version of an object.
See zmq.socket.send_json for details.'
| def send_json(self, obj, flags=0, callback=None):
| if (jsonapi is None):
raise ImportError('jsonlib{1,2}, json or simplejson library is required.')
else:
msg = jsonapi.dumps(obj)
return self.send(msg, flags=flags, callback=callback)
|
'Send a Python object as a message using pickle to serialize.
See zmq.socket.send_json for details.'
| def send_pyobj(self, obj, flags=0, protocol=(-1), callback=None):
| msg = pickle.dumps(obj, protocol)
return self.send(msg, flags, callback=callback)
|
'callback for unsetting _flushed flag.'
| def _finish_flush(self):
| self._flushed = False
|
'Flush pending messages.
This method safely handles all pending incoming and/or outgoing messages,
bypassing the inner loop, passing them to the registered callbacks.
A limit can be specified, to prevent blocking under high load.
flush will return the first time ANY of these conditions are met:
* No more events matchin... | def flush(self, flag=(zmq.POLLIN | zmq.POLLOUT), limit=None):
| self._check_closed()
already_flushed = self._flushed
self._flushed = False
count = 0
def update_flag():
"Update the poll flag, to prevent registering POLLOUT events\n if we don't have pending sends."
... |
'Call the given callback when the stream is closed.'
| def set_close_callback(self, callback):
| self._close_callback = stack_context.wrap(callback)
|
'Close this stream.'
| def close(self, linger=None):
| if (self.socket is not None):
self.io_loop.remove_handler(self.socket)
self.socket.close(linger)
self.socket = None
if self._close_callback:
self._run_callback(self._close_callback)
|
'Returns True if we are currently receiving from the stream.'
| def receiving(self):
| return (self._recv_callback is not None)
|
'Returns True if we are currently sending to the stream.'
| def sending(self):
| return (not self._send_queue.empty())
|
'Wrap running callbacks in try/except to allow us to
close our socket.'
| def _run_callback(self, callback, *args, **kwargs):
| try:
with stack_context.NullContext():
callback(*args, **kwargs)
except:
gen_log.error('Uncaught exception in ZMQStream callback', exc_info=True)
raise
|
'This method is the actual handler for IOLoop, that gets called whenever
an event on my socket is posted. It dispatches to _handle_recv, etc.'
| def _handle_events(self, fd, events):
| if (not self.socket):
gen_log.warning('Got events for closed stream %s', fd)
return
zmq_events = self.socket.EVENTS
try:
if ((zmq_events & zmq.POLLIN) and self.receiving()):
self._handle_recv()
if (not self.socket):
return
... |
'Handle a recv event.'
| def _handle_recv(self):
| if self._flushed:
return
try:
msg = self.socket.recv_multipart(zmq.NOBLOCK, copy=self._recv_copy)
except zmq.ZMQError as e:
if (e.errno == zmq.EAGAIN):
pass
else:
raise
else:
if self._recv_callback:
callback = self._recv_callbac... |
'Handle a send event.'
| def _handle_send(self):
| if self._flushed:
return
if (not self.sending()):
gen_log.error("Shouldn't have handled a send event")
return
(msg, kwargs) = self._send_queue.get()
try:
status = self.socket.send_multipart(msg, **kwargs)
except zmq.ZMQError as e:
gen_log.error(... |
'rebuild io state based on self.sending() and receiving()'
| def _rebuild_io_state(self):
| if (self.socket is None):
return
state = 0
if self.receiving():
state |= zmq.POLLIN
if self.sending():
state |= zmq.POLLOUT
self._state = state
self._update_handler(state)
|
'Add io_state to poller.'
| def _add_io_state(self, state):
| if (not (self._state & state)):
self._state = (self._state | state)
self._update_handler(self._state)
|
'Stop poller from watching an io_state.'
| def _drop_io_state(self, state):
| if (self._state & state):
self._state = (self._state & (~ state))
self._update_handler(self._state)
|
'Update IOLoop handler with state.'
| def _update_handler(self, state):
| if (self.socket is None):
return
if (state & self.socket.events):
self.io_loop.add_callback((lambda : self._handle_events(self.socket, 0)))
|
'initialize the ioloop event handler'
| def _init_io_state(self):
| with stack_context.NullContext():
self.io_loop.add_handler(self.socket, self._handle_events, self.io_loop.READ)
|
'Start the Authentication Agent thread task'
| def run(self):
| self.authenticator.start()
self.started.set()
zap = self.authenticator.zap_socket
poller = zmq.Poller()
poller.register(self.pipe, zmq.POLLIN)
poller.register(zap, zmq.POLLIN)
while True:
try:
socks = dict(poller.poll())
except zmq.ZMQError:
break
... |
'Handle a message from the ZAP socket.'
| def _handle_zap(self):
| msg = self.authenticator.zap_socket.recv_multipart()
if (not msg):
return
self.authenticator.handle_zap_message(msg)
|
'Handle a message from front-end API.'
| def _handle_pipe(self):
| terminate = False
msg = self.pipe.recv_multipart()
if (msg is None):
terminate = True
return terminate
command = msg[0]
self.log.debug('auth received API command %r', command)
if (command == 'ALLOW'):
addresses = [u(m, self.encoding) for m in msg[1:]]
... |
'Start the authentication thread'
| def start(self):
| self.pipe = self.context.socket(zmq.PAIR)
self.pipe.linger = 1
self.pipe.bind(self.pipe_endpoint)
self.thread = AuthenticationThread(self.context, self.pipe_endpoint, encoding=self.encoding, log=self.log)
self.thread.start()
if (sys.version_info < (2, 7)):
self.thread.started.wait(timeou... |
'Stop the authentication thread'
| def stop(self):
| if self.pipe:
self.pipe.send('TERMINATE')
if self.is_alive():
self.thread.join()
self.thread = None
self.pipe.close()
self.pipe = None
|
'Is the ZAP thread currently running?'
| def is_alive(self):
| if (self.thread and self.thread.is_alive()):
return True
return False
|
'Create and bind the ZAP socket'
| def start(self):
| self.zap_socket = self.context.socket(zmq.REP)
self.zap_socket.linger = 1
self.zap_socket.bind('inproc://zeromq.zap.01')
self.log.debug('Starting')
|
'Close the ZAP socket'
| def stop(self):
| if self.zap_socket:
self.zap_socket.close()
self.zap_socket = None
|
'Allow (whitelist) IP address(es).
Connections from addresses not in the whitelist will be rejected.
- For NULL, all clients from this address will be accepted.
- For real auth setups, they will be allowed to continue with authentication.
whitelist is mutually exclusive with blacklist.'
| def allow(self, *addresses):
| if self.blacklist:
raise ValueError('Only use a whitelist or a blacklist, not both')
self.log.debug('Allowing %s', ','.join(addresses))
self.whitelist.update(addresses)
|
'Deny (blacklist) IP address(es).
Addresses not in the blacklist will be allowed to continue with authentication.
Blacklist is mutually exclusive with whitelist.'
| def deny(self, *addresses):
| if self.whitelist:
raise ValueError('Only use a whitelist or a blacklist, not both')
self.log.debug('Denying %s', ','.join(addresses))
self.blacklist.update(addresses)
|
'Configure PLAIN authentication for a given domain.
PLAIN authentication uses a plain-text password file.
To cover all domains, use "*".
You can modify the password file at any time; it is reloaded automatically.'
| def configure_plain(self, domain='*', passwords=None):
| if passwords:
self.passwords[domain] = passwords
self.log.debug('Configure plain: %s', domain)
|
'Configure CURVE authentication for a given domain.
CURVE authentication uses a directory that holds all public client certificates,
i.e. their public keys.
To cover all domains, use "*".
You can add and remove certificates in that directory at any time.
To allow all client keys without checking, specify CURVE_ALLOW_AN... | def configure_curve(self, domain='*', location=None):
| self.log.debug('Configure curve: %s[%s]', domain, location)
if (location == CURVE_ALLOW_ANY):
self.allow_any = True
else:
self.allow_any = False
try:
self.certs[domain] = load_certificates(location)
except Exception as e:
self.log.error('Failed ... |
'Return the User-Id corresponding to a CURVE client\'s public key
Default implementation uses the z85-encoding of the public key.
Override to define a custom mapping of public key : user-id
This is only called on successful authentication.
Parameters
client_public_key: bytes
The client public key used for the given mes... | def curve_user_id(self, client_public_key):
| return z85.encode(client_public_key).decode('ascii')
|
'Configure GSSAPI authentication
Currently this is a no-op because there is nothing to configure with GSSAPI.'
| def configure_gssapi(self, domain='*', location=None):
| pass
|
'Perform ZAP authentication'
| def handle_zap_message(self, msg):
| if (len(msg) < 6):
self.log.error('Invalid ZAP message, not enough frames: %r', msg)
if (len(msg) < 2):
self.log.error('Not enough information to reply')
else:
self._send_zap_reply(msg[1], '400', 'Not enough frames')
return
... |
'PLAIN ZAP authentication'
| def _authenticate_plain(self, domain, username, password):
| allowed = False
reason = ''
if self.passwords:
if (not domain):
domain = '*'
if (domain in self.passwords):
if (username in self.passwords[domain]):
if (password == self.passwords[domain][username]):
allowed = True
e... |
'CURVE ZAP authentication'
| def _authenticate_curve(self, domain, client_key):
| allowed = False
reason = ''
if self.allow_any:
allowed = True
reason = 'OK'
self.log.debug('ALLOWED (CURVE allow any client)')
else:
if (not domain):
domain = '*'
if (domain in self.certs):
z85_client_key = z85.encode(client_key... |
'Nothing to do for GSSAPI, which has already been handled by an external service.'
| def _authenticate_gssapi(self, domain, principal):
| self.log.debug('ALLOWED (GSSAPI) domain=%s principal=%s', domain, principal)
return (True, 'OK')
|
'Send a ZAP reply to finish the authentication.'
| def _send_zap_reply(self, request_id, status_code, status_text, user_id='anonymous'):
| user_id = (user_id if (status_code == '200') else '')
if isinstance(user_id, unicode):
user_id = user_id.encode(self.encoding, 'replace')
metadata = ''
self.log.debug('ZAP reply code=%s text=%s', status_code, status_text)
reply = [VERSION, request_id, status_code, status_text, user_... |
'Start ZAP authentication'
| def start(self):
| super(IOLoopAuthenticator, self).start()
self.zap_stream = zmqstream.ZMQStream(self.zap_socket, self.io_loop)
self.zap_stream.on_recv(self.handle_zap_message)
|
'Stop ZAP authentication'
| def stop(self):
| if self.zap_stream:
self.zap_stream.close()
self.zap_stream = None
super(IOLoopAuthenticator, self).stop()
|
'atexit callback
sets _stay_down flag so that gc doesn\'t try to start up again in other atexit handlers'
| def _atexit(self):
| self._stay_down = True
self.stop()
|
'stop the garbage-collection thread'
| def stop(self):
| if (not self.is_alive()):
return
self._stop()
|
'The PUSH socket for use in the zmq message destructor callback.'
| @property
def _push_socket(self):
| if ((not self.is_alive()) or (self._push is None)):
self._push = self.context.socket(zmq.PUSH)
self._push.connect(self.url)
return self._push
|
'Start a new garbage collection thread.
Creates a new zmq Context used for garbage collection.
Under most circumstances, this will only be called once per process.'
| def start(self):
| if ((self.thread is not None) and (self.pid != getpid())):
self._stop()
self.pid = getpid()
self.refs = {}
self.thread = GarbageCollectorThread(self)
self.thread.start()
self.thread.ready.wait()
|
'Is the garbage collection thread currently running?
Includes checks for process shutdown or fork.'
| def is_alive(self):
| if ((getpid is None) or (getpid() != self.pid) or (self.thread is None) or (not self.thread.is_alive())):
return False
return True
|
'store an object and (optionally) event for zero-copy'
| def store(self, obj, event=None):
| if (not self.is_alive()):
if self._stay_down:
return 0
with self._lock:
if (not self.is_alive()):
self.start()
tup = gcref(obj, event)
theid = id(tup)
self.refs[theid] = tup
return theid
|
'Translate ``action`` into a CTRL-C handler.
``action`` is a callable that takes no arguments and returns no
value (returned value is ignored). It must *NEVER* raise an
exception.
If unspecified, a no-op will be used.'
| def __init__(self, action=None):
| self._init_action(action)
|
'Parameters
data : str
String with lines separated by \''
| def __init__(self, data):
| if isinstance(data, list):
self._str = data
else:
self._str = data.split('\n')
self.reset()
|
'func_name : Descriptive text
continued text
another_func_name : Descriptive text
func_name1, func_name2, :meth:`func_name`, func_name3'
| def _parse_see_also(self, content):
| items = []
def parse_item_name(text):
"Match ':role:`name`' or 'name'"
m = self._name_rgx.match(text)
if m:
g = m.groups()
if (g[1] is None):
return (g[3], None)
else:
return (g[2], g[1])
raise ValueErro... |
'.. index: default
:refguide: something, else, and more'
| def _parse_index(self, section, content):
| def strip_each_in(lst):
return [s.strip() for s in lst]
out = {}
section = section.split('::')
if (len(section) > 1):
out['default'] = strip_each_in(section[1].split(','))[0]
for line in content:
line = line.split(':')
if (len(line) > 2):
out[line[1]] = st... |
'Grab signature (if given) and summary'
| def _parse_summary(self):
| if self._is_at_section():
return
summary = self._doc.read_to_next_empty_line()
summary_str = ' '.join([s.strip() for s in summary]).strip()
if re.compile('^([\\w., ]+=)?\\s*[\\w\\.]+\\(.*\\)$').match(summary_str):
self['Signature'] = summary_str
if (not self._is_at_section(... |
'*class_names* is a list of child classes to show bases from.
If *show_builtins* is True, then Python builtins will be shown
in the graph.'
| def __init__(self, class_names, show_builtins=False):
| self.class_names = class_names
self.classes = self._import_classes(class_names)
self.all_classes = self._all_classes(self.classes)
if (len(self.all_classes) == 0):
raise ValueError('No classes found for inheritance diagram')
self.show_builtins = show_builtins
|
'Import a class using its fully-qualified *name*.'
| def _import_class_or_module(self, name):
| try:
(path, base) = self.py_sig_re.match(name).groups()
except:
raise ValueError(("Invalid class or module '%s' specified for inheritance diagram" % name))
fullname = ((path or '') + base)
path = (path and path.rstrip('.'))
if (not path):
path = base
... |
'Import a list of classes.'
| def _import_classes(self, class_names):
| classes = []
for name in class_names:
classes.extend(self._import_class_or_module(name))
return classes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.