code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def task_done(self):
'''Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
For each :meth:`get <Queue.get>` used to fetch a task, a subsequent call to :meth:`task_done` tells the queue
that the processing on the task is complete.
If a :meth:`join` is currently blocking, it will resume when all items have been processed
(meaning that a :meth:`task_done` call was received for every item that had been
:meth:`put <Queue.put>` into the queue).
Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
'''
if self.unfinished_tasks <= 0:
raise ValueError('task_done() called too many times')
self.unfinished_tasks -= 1
if self.unfinished_tasks == 0:
self._cond.set()
|
Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
For each :meth:`get <Queue.get>` used to fetch a task, a subsequent call to :meth:`task_done` tells the queue
that the processing on the task is complete.
If a :meth:`join` is currently blocking, it will resume when all items have been processed
(meaning that a :meth:`task_done` call was received for every item that had been
:meth:`put <Queue.put>` into the queue).
Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
|
task_done
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/queue.py
|
MIT
|
def select(rlist, wlist, xlist, timeout=None):
"""An implementation of :meth:`select.select` that blocks only the current greenlet.
Note: *xlist* is ignored.
"""
watchers = []
loop = get_hub().loop
io = loop.io
MAXPRI = loop.MAXPRI
result = SelectResult()
try:
try:
for readfd in rlist:
watcher = io(get_fileno(readfd), 1)
watcher.priority = MAXPRI
watcher.start(result.add_read, readfd)
watchers.append(watcher)
for writefd in wlist:
watcher = io(get_fileno(writefd), 2)
watcher.priority = MAXPRI
watcher.start(result.add_write, writefd)
watchers.append(watcher)
except IOError as ex:
raise error(*ex.args)
result.event.wait(timeout=timeout)
return result.read, result.write, []
finally:
for watcher in watchers:
watcher.stop()
|
An implementation of :meth:`select.select` that blocks only the current greenlet.
Note: *xlist* is ignored.
|
select
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/select.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/select.py
|
MIT
|
def _tcp_listener(address, backlog=50, reuse_addr=None, family=_socket.AF_INET):
"""A shortcut to create a TCP socket, bind it and put it into listening state."""
sock = socket(family=family)
if reuse_addr is not None:
sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr)
try:
sock.bind(address)
except _socket.error as ex:
strerror = getattr(ex, 'strerror', None)
if strerror is not None:
ex.strerror = strerror + ': ' + repr(address)
raise
sock.listen(backlog)
sock.setblocking(0)
return sock
|
A shortcut to create a TCP socket, bind it and put it into listening state.
|
_tcp_listener
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/server.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/server.py
|
MIT
|
def getsignal(signalnum):
"""
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
"""
if signalnum != _signal.SIGCHLD:
return _signal_getsignal(signalnum)
global _child_handler
if _child_handler is _INITIAL:
_child_handler = _signal_getsignal(_signal.SIGCHLD)
return _child_handler
|
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
|
getsignal
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/signal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/signal.py
|
MIT
|
def signal(signalnum, handler):
"""
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
.. note::
A :const:`signal.SIGCHLD` handler installed with this function
will only be triggered for children that are forked using
:func:`gevent.os.fork` (:func:`gevent.os.fork_and_watch`);
children forked before monkey patching, or otherwise by the raw
:func:`os.fork`, will not trigger the handler installed by this
function. (It's unlikely that a SIGCHLD handler installed with
the builtin :func:`signal.signal` would be triggered either;
libev typically overwrites such a handler at the C level. At
the very least, it's full of race conditions.)
.. note::
Use of ``SIG_IGN`` and ``SIG_DFL`` may also have race conditions
with libev child watchers and the :mod:`gevent.subprocess` module.
.. versionchanged:: 1.1rc2
Allow using ``SIG_IGN`` and ``SIG_DFL`` to reset and ignore ``SIGCHLD``.
However, this allows the possibility of a race condition.
"""
if signalnum != _signal.SIGCHLD:
return _signal_signal(signalnum, handler)
# TODO: raise value error if not called from the main
# greenlet, just like threads
if handler != _signal.SIG_IGN and handler != _signal.SIG_DFL and not callable(handler):
# exact same error message raised by the stdlib
raise TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object")
old_handler = getsignal(signalnum)
global _child_handler
_child_handler = handler
if handler == _signal.SIG_IGN or handler == _signal.SIG_DFL:
# Allow resetting/ignoring this signal at the process level.
# Note that this conflicts with gevent.subprocess and other users
# of child watchers.
_signal_signal(signalnum, handler)
return old_handler
|
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
.. note::
A :const:`signal.SIGCHLD` handler installed with this function
will only be triggered for children that are forked using
:func:`gevent.os.fork` (:func:`gevent.os.fork_and_watch`);
children forked before monkey patching, or otherwise by the raw
:func:`os.fork`, will not trigger the handler installed by this
function. (It's unlikely that a SIGCHLD handler installed with
the builtin :func:`signal.signal` would be triggered either;
libev typically overwrites such a handler at the C level. At
the very least, it's full of race conditions.)
.. note::
Use of ``SIG_IGN`` and ``SIG_DFL`` may also have race conditions
with libev child watchers and the :mod:`gevent.subprocess` module.
.. versionchanged:: 1.1rc2
Allow using ``SIG_IGN`` and ``SIG_DFL`` to reset and ignore ``SIGCHLD``.
However, this allows the possibility of a race condition.
|
signal
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/signal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/signal.py
|
MIT
|
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
A host of '' or port 0 tells the OS to use the default.
"""
host, port = address
err = None
for res in getaddrinfo(host, port, 0 if has_ipv6 else AF_INET, SOCK_STREAM):
af, socktype, proto, _canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except error as ex:
# without exc_clear(), if connect() fails once, the socket is referenced by the frame in exc_info
# and the next bind() fails (see test__socket.TestCreateConnection)
# that does not happen with regular sockets though, because _socket.socket.connect() is a built-in.
# this is similar to "getnameinfo loses a reference" failure in test_socket.py
if not PY3:
sys.exc_clear()
if sock is not None:
sock.close()
err = ex
if err is not None:
raise err
else:
raise error("getaddrinfo returns an empty list")
|
Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
A host of '' or port 0 tells the OS to use the default.
|
create_connection
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/socket.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/socket.py
|
MIT
|
def call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = call(["ls", "-l"])
"""
timeout = kwargs.pop('timeout', None)
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
|
Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = call(["ls", "-l"])
|
call
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def check_call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
:exc:`CalledProcessError`. The ``CalledProcessError`` object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = check_call(["ls", "-l"])
"""
retcode = call(*popenargs, **kwargs)
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd)
return 0
|
Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
:exc:`CalledProcessError`. The ``CalledProcessError`` object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = check_call(["ls", "-l"])
|
check_call
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output.
If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
``CalledProcessError`` object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-1", "/dev/null"])
b'/dev/null\n'
The ``stdout`` argument is not allowed as it is used internally.
To capture standard error in the result, use ``stderr=STDOUT``::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
b'ls: non_existent_file: No such file or directory\n'
There is an additional optional argument, "input", allowing you to
pass a string to the subprocess's stdin. If you use this argument
you may not also use the Popen constructor's "stdin" argument, as
it too will be used internally. Example::
>>> check_output(["sed", "-e", "s/foo/bar/"],
... input=b"when in the course of fooman events\n")
b'when in the course of barman events\n'
If ``universal_newlines=True`` is passed, the return value will be a
string rather than bytes.
"""
timeout = kwargs.pop('timeout', None)
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
if 'input' in kwargs:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
inputdata = kwargs['input']
del kwargs['input']
kwargs['stdin'] = PIPE
else:
inputdata = None
with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
try:
output, unused_err = process.communicate(inputdata, timeout=timeout)
except TimeoutExpired:
process.kill()
output, unused_err = process.communicate()
raise TimeoutExpired(process.args, timeout, output=output)
except:
process.kill()
process.wait()
raise
retcode = process.poll()
if retcode:
raise CalledProcessError(retcode, process.args, output=output)
return output
|
Run command with arguments and return its output.
If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
``CalledProcessError`` object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-1", "/dev/null"])
b'/dev/null\n'
The ``stdout`` argument is not allowed as it is used internally.
To capture standard error in the result, use ``stderr=STDOUT``::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
b'ls: non_existent_file: No such file or directory\n'
There is an additional optional argument, "input", allowing you to
pass a string to the subprocess's stdin. If you use this argument
you may not also use the Popen constructor's "stdin" argument, as
it too will be used internally. Example::
>>> check_output(["sed", "-e", "s/foo/bar/"],
... input=b"when in the course of fooman events\n")
b'when in the course of barman events\n'
If ``universal_newlines=True`` is passed, the return value will be a
string rather than bytes.
|
check_output
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> print(check_output(["ls", "-1", "/dev/null"]).decode('ascii'))
/dev/null
<BLANKLINE>
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> print(check_output(["/bin/sh", "-c", "echo hello world"], stderr=STDOUT).decode('ascii'))
hello world
<BLANKLINE>
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output = process.communicate()[0]
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
ex = CalledProcessError(retcode, cmd)
# on Python 2.6 and older CalledProcessError does not accept 'output' argument
ex.output = output
raise ex
return output
|
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> print(check_output(["ls", "-1", "/dev/null"]).decode('ascii'))
/dev/null
<BLANKLINE>
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> print(check_output(["/bin/sh", "-c", "echo hello world"], stderr=STDOUT).decode('ascii'))
hello world
<BLANKLINE>
|
check_output
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def __init__(self, args, bufsize=None, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0, threadpool=None,
**kwargs):
"""Create new Popen instance.
:param kwargs: *Only* allowed under Python 3; under Python 2, any
unrecognized keyword arguments will result in a :exc:`TypeError`.
Under Python 3, keyword arguments can include ``pass_fds``, ``start_new_session``,
and ``restore_signals``.
"""
if not PY3 and kwargs:
raise TypeError("Got unexpected keyword arguments", kwargs)
pass_fds = kwargs.pop('pass_fds', ())
start_new_session = kwargs.pop('start_new_session', False)
restore_signals = kwargs.pop('restore_signals', True)
hub = get_hub()
if bufsize is None:
# bufsize has different defaults on Py3 and Py2
if PY3:
bufsize = -1
else:
bufsize = 0
if not isinstance(bufsize, integer_types):
raise TypeError("bufsize must be an integer")
if mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
any_stdio_set = (stdin is not None or stdout is not None or
stderr is not None)
if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
if any_stdio_set:
close_fds = False
else:
close_fds = True
elif close_fds and any_stdio_set:
raise ValueError("close_fds is not supported on Windows "
"platforms if you redirect stdin/stdout/stderr")
if threadpool is None:
threadpool = hub.threadpool
self.threadpool = threadpool
self._waiting = False
else:
# POSIX
if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
# close_fds has different defaults on Py3/Py2
if PY3:
close_fds = True
else:
close_fds = False
if pass_fds and not close_fds:
import warnings
warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
close_fds = True
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
assert threadpool is None
self._loop = hub.loop
if PY3:
self.args = args
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.universal_newlines = universal_newlines
self.result = AsyncResult()
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are None when not using PIPEs. The child objects are None
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
# We wrap OS handles *before* launching the child, otherwise a
# quickly terminating child could make our fds unwrappable
# (see #8458).
if mswindows:
if p2cwrite is not None:
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
if c2pread is not None:
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
if errread is not None:
errread = msvcrt.open_osfhandle(errread.Detach(), 0)
if p2cwrite is not None:
if PY3 and universal_newlines:
# Under Python 3, if we left on the 'b' we'd get different results
# depending on whether we used FileObjectPosix or FileObjectThread
self.stdin = FileObject(p2cwrite, 'wb', bufsize)
self.stdin._translate = True
self.stdin.io = io.TextIOWrapper(self.stdin.io, write_through=True,
line_buffering=(bufsize == 1))
else:
self.stdin = FileObject(p2cwrite, 'wb', bufsize)
if c2pread is not None:
if universal_newlines:
if PY3:
# FileObjectThread doesn't support the 'U' qualifier
# with a bufsize of 0
self.stdout = FileObject(c2pread, 'rb', bufsize)
# NOTE: Universal Newlines are broken on Windows/Py3, at least
# in some cases. This is true in the stdlib subprocess module
# as well; the following line would fix the test cases in
# test__subprocess.py that depend on python_universal_newlines,
# but would be inconsistent with the stdlib:
#msvcrt.setmode(self.stdout.fileno(), os.O_TEXT)
self.stdout.io = io.TextIOWrapper(self.stdout.io)
self.stdout.io.mode = 'r'
self.stdout._translate = True
else:
self.stdout = FileObject(c2pread, 'rU', bufsize)
else:
self.stdout = FileObject(c2pread, 'rb', bufsize)
if errread is not None:
if universal_newlines:
if PY3:
self.stderr = FileObject(errread, 'rb', bufsize)
self.stderr.io = io.TextIOWrapper(self.stderr.io)
self.stderr._translate = True
else:
self.stderr = FileObject(errread, 'rU', bufsize)
else:
self.stderr = FileObject(errread, 'rb', bufsize)
self._closed_child_pipe_fds = False
try:
self._execute_child(args, executable, preexec_fn, close_fds,
pass_fds, cwd, env, universal_newlines,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
restore_signals, start_new_session)
except:
# Cleanup if the child failed starting.
# (gevent: New in python3, but reported as gevent bug in #347.
# Note that under Py2, any error raised below will replace the
# original error so we have to use reraise)
if not PY3:
exc_info = sys.exc_info()
for f in filter(None, (self.stdin, self.stdout, self.stderr)):
try:
f.close()
except (OSError, IOError):
pass # Ignore EBADF or other errors.
if not self._closed_child_pipe_fds:
to_close = []
if stdin == PIPE:
to_close.append(p2cread)
if stdout == PIPE:
to_close.append(c2pwrite)
if stderr == PIPE:
to_close.append(errwrite)
if hasattr(self, '_devnull'):
to_close.append(self._devnull)
for fd in to_close:
try:
os.close(fd)
except (OSError, IOError):
pass
if not PY3:
try:
reraise(*exc_info)
finally:
del exc_info
raise
|
Create new Popen instance.
:param kwargs: *Only* allowed under Python 3; under Python 2, any
unrecognized keyword arguments will result in a :exc:`TypeError`.
Under Python 3, keyword arguments can include ``pass_fds``, ``start_new_session``,
and ``restore_signals``.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def communicate(self, input=None, timeout=None):
"""Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.
communicate() returns a tuple (stdout, stderr).
:keyword timeout: Under Python 2, this is a gevent extension; if
given and it expires, we will raise :class:`gevent.timeout.Timeout`.
Under Python 3, this raises the standard :exc:`TimeoutExpired` exception.
.. versionchanged:: 1.1a2
Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout`
exception. Previously, we silently returned.
.. versionchanged:: 1.1b5
Honor a *timeout* even if there's no way to communicate with the child
(stdin, stdout, and stderr are not pipes).
"""
greenlets = []
if self.stdin:
greenlets.append(spawn(write_and_close, self.stdin, input))
# If the timeout parameter is used, and the caller calls back after
# getting a TimeoutExpired exception, we can wind up with multiple
# greenlets trying to run and read from and close stdout/stderr.
# That's bad because it can lead to 'RuntimeError: reentrant call in io.BufferedReader'.
# We can't just kill the previous greenlets when a timeout happens,
# though, because we risk losing the output collected by that greenlet
# (and Python 3, where timeout is an official parameter, explicitly says
# that no output should be lost in the event of a timeout.) Instead, we're
# watching for the exception and ignoring it. It's not elegant,
# but it works
if self.stdout:
def _read_out():
try:
data = self.stdout.read()
except RuntimeError:
return
if self._stdout_buffer is not None:
self._stdout_buffer += data
else:
self._stdout_buffer = data
stdout = spawn(_read_out)
greenlets.append(stdout)
else:
stdout = None
if self.stderr:
def _read_err():
try:
data = self.stderr.read()
except RuntimeError:
return
if self._stderr_buffer is not None:
self._stderr_buffer += data
else:
self._stderr_buffer = data
stderr = spawn(_read_err)
greenlets.append(stderr)
else:
stderr = None
# If we were given stdin=stdout=stderr=None, we have no way to
# communicate with the child, and thus no greenlets to wait
# on. This is a nonsense case, but it comes up in the test
# case for Python 3.5 (test_subprocess.py
# RunFuncTestCase.test_timeout). Instead, we go directly to
# self.wait
if not greenlets and timeout is not None:
result = self.wait(timeout=timeout)
# Python 3 would have already raised, but Python 2 would not
# so we need to do that manually
if result is None:
from gevent.timeout import Timeout
raise Timeout(timeout)
done = joinall(greenlets, timeout=timeout)
if timeout is not None and len(done) != len(greenlets):
if PY3:
raise TimeoutExpired(self.args, timeout)
from gevent.timeout import Timeout
raise Timeout(timeout)
if self.stdout:
try:
self.stdout.close()
except RuntimeError:
pass
if self.stderr:
try:
self.stderr.close()
except RuntimeError:
pass
self.wait()
stdout_value = self._stdout_buffer
self._stdout_buffer = None
stderr_value = self._stderr_buffer
self._stderr_buffer = None
# XXX: Under python 3 in universal newlines mode we should be
# returning str, not bytes
return (None if stdout is None else stdout_value or b'',
None if stderr is None else stderr_value or b'')
|
Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.
communicate() returns a tuple (stdout, stderr).
:keyword timeout: Under Python 2, this is a gevent extension; if
given and it expires, we will raise :class:`gevent.timeout.Timeout`.
Under Python 3, this raises the standard :exc:`TimeoutExpired` exception.
.. versionchanged:: 1.1a2
Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout`
exception. Previously, we silently returned.
.. versionchanged:: 1.1b5
Honor a *timeout* even if there's no way to communicate with the child
(stdin, stdout, and stderr are not pipes).
|
communicate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
if stdin is None and stdout is None and stderr is None:
return (None, None, None, None, None, None)
p2cread, p2cwrite = None, None
c2pread, c2pwrite = None, None
errread, errwrite = None, None
try:
DEVNULL
except NameError:
_devnull = object()
else:
_devnull = DEVNULL
if stdin is None:
p2cread = GetStdHandle(STD_INPUT_HANDLE)
if p2cread is None:
p2cread, _ = CreatePipe(None, 0)
if PY3:
p2cread = Handle(p2cread)
_winapi.CloseHandle(_)
elif stdin == PIPE:
p2cread, p2cwrite = CreatePipe(None, 0)
if PY3:
p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
elif stdin == _devnull:
p2cread = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdin, int):
p2cread = msvcrt.get_osfhandle(stdin)
else:
# Assuming file-like object
p2cread = msvcrt.get_osfhandle(stdin.fileno())
p2cread = self._make_inheritable(p2cread)
if stdout is None:
c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
if c2pwrite is None:
_, c2pwrite = CreatePipe(None, 0)
if PY3:
c2pwrite = Handle(c2pwrite)
_winapi.CloseHandle(_)
elif stdout == PIPE:
c2pread, c2pwrite = CreatePipe(None, 0)
if PY3:
c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
elif stdout == _devnull:
c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdout, int):
c2pwrite = msvcrt.get_osfhandle(stdout)
else:
# Assuming file-like object
c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
c2pwrite = self._make_inheritable(c2pwrite)
if stderr is None:
errwrite = GetStdHandle(STD_ERROR_HANDLE)
if errwrite is None:
_, errwrite = CreatePipe(None, 0)
if PY3:
errwrite = Handle(errwrite)
_winapi.CloseHandle(_)
elif stderr == PIPE:
errread, errwrite = CreatePipe(None, 0)
if PY3:
errread, errwrite = Handle(errread), Handle(errwrite)
elif stderr == STDOUT:
errwrite = c2pwrite
elif stderr == _devnull:
errwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stderr, int):
errwrite = msvcrt.get_osfhandle(stderr)
else:
# Assuming file-like object
errwrite = msvcrt.get_osfhandle(stderr.fileno())
errwrite = self._make_inheritable(errwrite)
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
|
Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
|
_get_handles
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _make_inheritable(self, handle):
"""Return a duplicate of handle, which is inheritable"""
return DuplicateHandle(GetCurrentProcess(),
handle, GetCurrentProcess(), 0, 1,
DUPLICATE_SAME_ACCESS)
|
Return a duplicate of handle, which is inheritable
|
_make_inheritable
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _find_w9xpopen(self):
"""Find and return absolute path to w9xpopen.exe"""
w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
"w9xpopen.exe")
if not os.path.exists(w9xpopen):
# Eeek - file-not-found - possibly an embedding
# situation - see if we can locate it in sys.exec_prefix
w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
"w9xpopen.exe")
if not os.path.exists(w9xpopen):
raise RuntimeError("Cannot locate w9xpopen.exe, which is "
"needed for Popen to work with your "
"shell or platform.")
return w9xpopen
|
Find and return absolute path to w9xpopen.exe
|
_find_w9xpopen
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _internal_poll(self):
"""Check if child process has terminated. Returns returncode
attribute.
"""
if self.returncode is None:
if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
self.returncode = GetExitCodeProcess(self._handle)
self.result.set(self.returncode)
return self.returncode
|
Check if child process has terminated. Returns returncode
attribute.
|
_internal_poll
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def wait(self, timeout=None):
"""Wait for child process to terminate. Returns returncode
attribute."""
if self.returncode is None:
if not self._waiting:
self._waiting = True
self._wait()
result = self.result.wait(timeout=timeout)
if PY3 and timeout is not None and not self.result.ready():
raise TimeoutExpired(self.args, timeout)
return result
|
Wait for child process to terminate. Returns returncode
attribute.
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
p2cread, p2cwrite = None, None
c2pread, c2pwrite = None, None
errread, errwrite = None, None
try:
DEVNULL
except NameError:
_devnull = object()
else:
_devnull = DEVNULL
if stdin is None:
pass
elif stdin == PIPE:
p2cread, p2cwrite = self.pipe_cloexec()
elif stdin == _devnull:
p2cread = self._get_devnull()
elif isinstance(stdin, int):
p2cread = stdin
else:
# Assuming file-like object
p2cread = stdin.fileno()
if stdout is None:
pass
elif stdout == PIPE:
c2pread, c2pwrite = self.pipe_cloexec()
elif stdout == _devnull:
c2pwrite = self._get_devnull()
elif isinstance(stdout, int):
c2pwrite = stdout
else:
# Assuming file-like object
c2pwrite = stdout.fileno()
if stderr is None:
pass
elif stderr == PIPE:
errread, errwrite = self.pipe_cloexec()
elif stderr == STDOUT:
errwrite = c2pwrite
elif stderr == _devnull:
errwrite = self._get_devnull()
elif isinstance(stderr, int):
errwrite = stderr
else:
# Assuming file-like object
errwrite = stderr.fileno()
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
|
Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
|
_get_handles
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def pipe_cloexec(self):
"""Create a pipe with FDs set CLOEXEC."""
# Pipes' FDs are set CLOEXEC by default because we don't want them
# to be inherited by other subprocesses: the CLOEXEC flag is removed
# from the child's FDs by _dup2(), between fork() and exec().
# This is not atomic: we would need the pipe2() syscall for that.
r, w = os.pipe()
self._set_cloexec_flag(r)
self._set_cloexec_flag(w)
return r, w
|
Create a pipe with FDs set CLOEXEC.
|
pipe_cloexec
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _internal_poll(self):
"""Check if child process has terminated. Returns returncode
attribute.
"""
if self.returncode is None:
if get_hub() is not getcurrent():
sig_pending = getattr(self._loop, 'sig_pending', True)
if sig_pending:
sleep(0.00001)
return self.returncode
|
Check if child process has terminated. Returns returncode
attribute.
|
_internal_poll
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def wait(self, timeout=None):
"""Wait for child process to terminate. Returns :attr:`returncode`
attribute.
:keyword timeout: The floating point number of seconds to wait.
Under Python 2, this is a gevent extension, and we simply return if it
expires. Under Python 3,
if this time elapses without finishing the process, :exc:`TimeoutExpired`
is raised."""
result = self.result.wait(timeout=timeout)
if PY3 and timeout is not None and not self.result.ready():
raise TimeoutExpired(self.args, timeout)
return result
|
Wait for child process to terminate. Returns :attr:`returncode`
attribute.
:keyword timeout: The floating point number of seconds to wait.
Under Python 2, this is a gevent extension, and we simply return if it
expires. Under Python 3,
if this time elapses without finishing the process, :exc:`TimeoutExpired`
is raised.
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def join(self):
"""Waits until all outstanding tasks have been completed."""
delay = 0.0005
while self.task_queue.unfinished_tasks > 0:
sleep(delay)
delay = min(delay * 2, .05)
|
Waits until all outstanding tasks have been completed.
|
join
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/threadpool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/threadpool.py
|
MIT
|
def spawn(self, func, *args, **kwargs):
"""
Add a new task to the threadpool that will run ``func(*args, **kwargs)``.
Waits until a slot is available. Creates a new thread if necessary.
:return: A :class:`gevent.event.AsyncResult`.
"""
while True:
semaphore = self._semaphore
semaphore.acquire()
if semaphore is self._semaphore:
break
thread_result = None
try:
task_queue = self.task_queue
result = AsyncResult()
# XXX We're calling the semaphore release function in the hub, otherwise
# we get LoopExit (why?). Previously it was done with a rawlink on the
# AsyncResult and the comment that it is "competing for order with get(); this is not
# good, just make ThreadResult release the semaphore before doing anything else"
thread_result = ThreadResult(result, hub=self.hub, call_when_ready=semaphore.release)
task_queue.put((func, args, kwargs, thread_result))
self.adjust()
except:
if thread_result is not None:
thread_result.destroy()
semaphore.release()
raise
return result
|
Add a new task to the threadpool that will run ``func(*args, **kwargs)``.
Waits until a slot is available. Creates a new thread if necessary.
:return: A :class:`gevent.event.AsyncResult`.
|
spawn
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/threadpool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/threadpool.py
|
MIT
|
def apply_e(self, expected_errors, function, args=None, kwargs=None):
"""
.. deprecated:: 1.1a2
Identical to :meth:`apply`; the ``expected_errors`` argument is ignored.
"""
# Deprecated but never documented. In the past, before
# self.apply() allowed all errors to be raised to the caller,
# expected_errors allowed a caller to specify a set of errors
# they wanted to be raised, through the wrap_errors function.
# In practice, it always took the value Exception or
# BaseException.
return self.apply(function, args, kwargs)
|
.. deprecated:: 1.1a2
Identical to :meth:`apply`; the ``expected_errors`` argument is ignored.
|
apply_e
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/threadpool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/threadpool.py
|
MIT
|
def start_new(cls, timeout=None, exception=None, ref=True):
"""Create a started :class:`Timeout`.
This is a shortcut, the exact action depends on *timeout*'s type:
* If *timeout* is a :class:`Timeout`, then call its :meth:`start` method
if it's not already begun.
* Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as
arguments, then call its :meth:`start` method.
Returns the :class:`Timeout` instance.
"""
if isinstance(timeout, Timeout):
if not timeout.pending:
timeout.start()
return timeout
timeout = cls(timeout, exception, ref=ref)
timeout.start()
return timeout
|
Create a started :class:`Timeout`.
This is a shortcut, the exact action depends on *timeout*'s type:
* If *timeout* is a :class:`Timeout`, then call its :meth:`start` method
if it's not already begun.
* Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as
arguments, then call its :meth:`start` method.
Returns the :class:`Timeout` instance.
|
start_new
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/timeout.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/timeout.py
|
MIT
|
def __str__(self):
"""
>>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Timeout
"""
if self.seconds is None:
return ''
suffix = '' if self.seconds == 1 else 's'
if self.exception is None:
return '%s second%s' % (self.seconds, suffix)
if self.exception is False:
return '%s second%s (silent)' % (self.seconds, suffix)
return '%s second%s: %s' % (self.seconds, suffix, self.exception)
|
>>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Timeout
|
__str__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/timeout.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/timeout.py
|
MIT
|
def with_timeout(seconds, function, *args, **kwds):
"""Wrap a call to *function* with a timeout; if the called
function fails to return before the timeout, cancel it and return a
flag value, provided by *timeout_value* keyword argument.
If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`.
Keyword argument *timeout_value* is not passed to *function*.
"""
timeout_value = kwds.pop("timeout_value", _NONE)
timeout = Timeout.start_new(seconds)
try:
try:
return function(*args, **kwds)
except Timeout as ex:
if ex is timeout and timeout_value is not _NONE:
return timeout_value
raise
finally:
timeout.cancel()
|
Wrap a call to *function* with a timeout; if the called
function fails to return before the timeout, cancel it and return a
flag value, provided by *timeout_value* keyword argument.
If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`.
Keyword argument *timeout_value* is not passed to *function*.
|
with_timeout
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/timeout.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/timeout.py
|
MIT
|
def __init__(self, errors, func):
"""
Calling this makes a new function from *func*, such that it catches *errors* (an
:exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and
return it as a value.
"""
self.__errors = errors
self.__func = func
# Set __doc__, __wrapped__, etc, especially useful on Python 3.
functools.update_wrapper(self, func)
|
Calling this makes a new function from *func*, such that it catches *errors* (an
:exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and
return it as a value.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/util.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/util.py
|
MIT
|
def fromEnvironment(cls):
"""
Get as many of the platform-specific error translation objects as
possible and return an instance of C{cls} created with them.
"""
try:
from ctypes import WinError
except ImportError:
WinError = None
try:
from win32api import FormatMessage
except ImportError:
FormatMessage = None
try:
from socket import errorTab
except ImportError:
errorTab = None
return cls(WinError, FormatMessage, errorTab)
|
Get as many of the platform-specific error translation objects as
possible and return an instance of C{cls} created with them.
|
fromEnvironment
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/win32util.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/win32util.py
|
MIT
|
def formatError(self, errorcode):
"""
Returns the string associated with a Windows error message, such as the
ones found in socket.error.
Attempts direct lookup against the win32 API via ctypes and then
pywin32 if available), then in the error table in the socket module,
then finally defaulting to C{os.strerror}.
@param errorcode: the Windows error code
@type errorcode: C{int}
@return: The error message string
@rtype: C{str}
"""
if self.winError is not None:
return str(self.winError(errorcode))
if self.formatMessage is not None:
return self.formatMessage(errorcode)
if self.errorTab is not None:
result = self.errorTab.get(errorcode)
if result is not None:
return result
return os.strerror(errorcode)
|
Returns the string associated with a Windows error message, such as the
ones found in socket.error.
Attempts direct lookup against the win32 API via ctypes and then
pywin32 if available), then in the error table in the socket module,
then finally defaulting to C{os.strerror}.
@param errorcode: the Windows error code
@type errorcode: C{int}
@return: The error message string
@rtype: C{str}
|
formatError
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/win32util.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/win32util.py
|
MIT
|
def release(self):
"""
Release the semaphore, notifying any waiters if needed.
"""
self.counter += 1
self._start_notify()
return self.counter
|
Release the semaphore, notifying any waiters if needed.
|
release
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def rawlink(self, callback):
"""
rawlink(callback) -> None
Register a callback to call when a counter is more than zero.
*callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
*callback* will be passed one argument: this instance.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code
will not need to use it.
"""
if not callable(callback):
raise TypeError('Expected callable:', callback)
if self._links is None:
self._links = [callback]
else:
self._links.append(callback)
self._dirty = True
|
rawlink(callback) -> None
Register a callback to call when a counter is more than zero.
*callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
*callback* will be passed one argument: this instance.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code
will not need to use it.
|
rawlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def unlink(self, callback):
"""
unlink(callback) -> None
Remove the callback set by :meth:`rawlink`.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most
code will not need to use it.
"""
try:
self._links.remove(callback)
self._dirty = True
except (ValueError, AttributeError):
pass
if not self._links:
self._links = None
# TODO: Cancel a notifier if there are no links?
|
unlink(callback) -> None
Remove the callback set by :meth:`rawlink`.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most
code will not need to use it.
|
unlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def _do_wait(self, timeout):
"""
Wait for up to *timeout* seconds to expire. If timeout
elapses, return the exception. Otherwise, return None.
Raises timeout if a different timer expires.
"""
switch = getcurrent().switch
self.rawlink(switch)
try:
timer = Timeout._start_new_or_dummy(timeout)
try:
try:
result = get_hub().switch()
assert result is self, 'Invalid switch into Semaphore.wait/acquire(): %r' % (result, )
except Timeout as ex:
if ex is not timer:
raise
return ex
finally:
timer.cancel()
finally:
self.unlink(switch)
|
Wait for up to *timeout* seconds to expire. If timeout
elapses, return the exception. Otherwise, return None.
Raises timeout if a different timer expires.
|
_do_wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def wait(self, timeout=None):
"""
wait(timeout=None) -> int
Wait until it is possible to acquire this semaphore, or until the optional
*timeout* elapses.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever if no timeout is given.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A number indicating how many times the semaphore can be acquired
before blocking.
"""
if self.counter > 0:
return self.counter
self._do_wait(timeout) # return value irrelevant, whether we got it or got a timeout
return self.counter
|
wait(timeout=None) -> int
Wait until it is possible to acquire this semaphore, or until the optional
*timeout* elapses.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever if no timeout is given.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A number indicating how many times the semaphore can be acquired
before blocking.
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def acquire(self, blocking=True, timeout=None):
"""
acquire(blocking=True, timeout=None) -> bool
Acquire the semaphore.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever (unless a timeout is given or blocking is
set to false).
:keyword bool blocking: If True (the default), this function will block
until the semaphore is acquired.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A boolean indicating whether the semaphore was acquired.
If ``blocking`` is True and ``timeout`` is None (the default), then
(so long as this semaphore was initialized with a size greater than 0)
this will always return True. If a timeout was given, and it expired before
the semaphore was acquired, False will be returned. (Note that this can still
raise a ``Timeout`` exception, if some other caller had already started a timer.)
"""
if self.counter > 0:
self.counter -= 1
return True
if not blocking:
return False
timeout = self._do_wait(timeout)
if timeout is not None:
# Our timer expired.
return False
# Neither our timer no another one expired, so we blocked until
# awoke. Therefore, the counter is ours
self.counter -= 1
assert self.counter >= 0
return True
|
acquire(blocking=True, timeout=None) -> bool
Acquire the semaphore.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever (unless a timeout is given or blocking is
set to false).
:keyword bool blocking: If True (the default), this function will block
until the semaphore is acquired.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A boolean indicating whether the semaphore was acquired.
If ``blocking`` is True and ``timeout`` is None (the default), then
(so long as this semaphore was initialized with a size greater than 0)
this will always return True. If a timeout was given, and it expired before
the semaphore was acquired, False will be returned. (Note that this can still
raise a ``Timeout`` exception, if some other caller had already started a timer.)
|
acquire
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def _wait(self, watcher, timeout_exc=timeout('timed out')):
"""Block the current greenlet until *watcher* has pending events.
If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
By default *timeout_exc* is ``socket.timeout('timed out')``.
If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
"""
if watcher.callback is not None:
raise _socketcommon.ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (watcher.callback, ))
if self.timeout is not None:
timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False)
else:
timeout = None
try:
self.hub.wait(watcher)
finally:
if timeout is not None:
timeout.cancel()
|
Block the current greenlet until *watcher* has pending events.
If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
By default *timeout_exc* is ``socket.timeout('timed out')``.
If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
|
_wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket2.py
|
MIT
|
def __send_chunk(self, data_memory, flags, timeleft, end):
"""
Send the complete contents of ``data_memory`` before returning.
This is the core loop around :meth:`send`.
:param timeleft: Either ``None`` if there is no timeout involved,
or a float indicating the timeout to use.
:param end: Either ``None`` if there is no timeout involved, or
a float giving the absolute end time.
:return: An updated value for ``timeleft`` (or None)
:raises timeout: If ``timeleft`` was given and elapsed while
sending this chunk.
"""
data_sent = 0
len_data_memory = len(data_memory)
started_timer = 0
while data_sent < len_data_memory:
chunk = data_memory[data_sent:]
if timeleft is None:
data_sent += self.send(chunk, flags)
elif started_timer and timeleft <= 0:
# Check before sending to guarantee a check
# happens even if each chunk successfully sends its data
# (especially important for SSL sockets since they have large
# buffers)
raise timeout('timed out')
else:
started_timer = 1
data_sent += self.send(chunk, flags, timeout=timeleft)
timeleft = end - time.time()
return timeleft
|
Send the complete contents of ``data_memory`` before returning.
This is the core loop around :meth:`send`.
:param timeleft: Either ``None`` if there is no timeout involved,
or a float indicating the timeout to use.
:param end: Either ``None`` if there is no timeout involved, or
a float giving the absolute end time.
:return: An updated value for ``timeleft`` (or None)
:raises timeout: If ``timeleft`` was given and elapsed while
sending this chunk.
|
__send_chunk
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket2.py
|
MIT
|
def __repr__(self):
"""Wrap __repr__() to reveal the real class name."""
try:
s = _socket.socket.__repr__(self._sock)
except Exception as ex:
# Observed on Windows Py3.3, printing the repr of a socket
# that just sufferred a ConnectionResetError [WinError 10054]:
# "OverflowError: no printf formatter to display the socket descriptor in decimal"
# Not sure what the actual cause is or if there's a better way to handle this
s = '<socket [%r]>' % ex
if s.startswith("<socket object"):
s = "<%s.%s%s%s" % (self.__class__.__module__,
self.__class__.__name__,
getattr(self, '_closed', False) and " [closed] " or "",
s[7:])
return s
|
Wrap __repr__() to reveal the real class name.
|
__repr__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def _wait(self, watcher, timeout_exc=timeout('timed out')):
"""Block the current greenlet until *watcher* has pending events.
If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
By default *timeout_exc* is ``socket.timeout('timed out')``.
If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
"""
if watcher.callback is not None:
raise _socketcommon.ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (watcher.callback, ))
if self.timeout is not None:
timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False)
else:
timeout = None
try:
self.hub.wait(watcher)
finally:
if timeout is not None:
timeout.cancel()
|
Block the current greenlet until *watcher* has pending events.
If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
By default *timeout_exc* is ``socket.timeout('timed out')``.
If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
|
_wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def dup(self):
"""dup() -> socket object
Return a new socket object connected to the same system resource.
"""
fd = dup(self.fileno())
sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
sock.settimeout(self.gettimeout())
return sock
|
dup() -> socket object
Return a new socket object connected to the same system resource.
|
dup
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def accept(self):
"""accept() -> (socket object, address info)
Wait for an incoming connection. Return a new socket
representing the connection, and the address of the client.
For IP sockets, the address info is a pair (hostaddr, port).
"""
while True:
try:
fd, addr = self._accept()
break
except BlockingIOError:
if self.timeout == 0.0:
raise
self._wait(self._read_event)
sock = socket(self.family, self.type, self.proto, fileno=fd)
# Python Issue #7995: if no default timeout is set and the listening
# socket had a (non-zero) timeout, force the new socket in blocking
# mode to override platform-specific socket flags inheritance.
# XXX do we need to do this?
if getdefaulttimeout() is None and self.gettimeout():
sock.setblocking(True)
return sock, addr
|
accept() -> (socket object, address info)
Wait for an incoming connection. Return a new socket
representing the connection, and the address of the client.
For IP sockets, the address info is a pair (hostaddr, port).
|
accept
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def makefile(self, mode="r", buffering=None, *,
encoding=None, errors=None, newline=None):
"""Return an I/O stream connected to the socket
The arguments are as for io.open() after the filename,
except the only mode characters supported are 'r', 'w' and 'b'.
The semantics are similar too.
"""
# (XXX refactor to share code?)
for c in mode:
if c not in {"r", "w", "b"}:
raise ValueError("invalid mode %r (only r, w, b allowed)")
writing = "w" in mode
reading = "r" in mode or not writing
assert reading or writing
binary = "b" in mode
rawmode = ""
if reading:
rawmode += "r"
if writing:
rawmode += "w"
raw = SocketIO(self, rawmode)
self._io_refs += 1
if buffering is None:
buffering = -1
if buffering < 0:
buffering = io.DEFAULT_BUFFER_SIZE
if buffering == 0:
if not binary:
raise ValueError("unbuffered streams must be binary")
return raw
if reading and writing:
buffer = io.BufferedRWPair(raw, raw, buffering)
elif reading:
buffer = io.BufferedReader(raw, buffering)
else:
assert writing
buffer = io.BufferedWriter(raw, buffering)
if binary:
return buffer
text = io.TextIOWrapper(buffer, encoding, errors, newline)
text.mode = mode
return text
|
Return an I/O stream connected to the socket
The arguments are as for io.open() after the filename,
except the only mode characters supported are 'r', 'w' and 'b'.
The semantics are similar too.
|
makefile
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def fromfd(fd, family, type, proto=0):
""" fromfd(fd, family, type[, proto]) -> socket object
Create a socket object from a duplicate of the given file
descriptor. The remaining arguments are the same as for socket().
"""
nfd = dup(fd)
return socket(family, type, proto, nfd)
|
fromfd(fd, family, type[, proto]) -> socket object
Create a socket object from a duplicate of the given file
descriptor. The remaining arguments are the same as for socket().
|
fromfd
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def socketpair(family=None, type=SOCK_STREAM, proto=0):
"""socketpair([family[, type[, proto]]]) -> (socket object, socket object)
Create a pair of socket objects from the sockets returned by the platform
socketpair() function.
The arguments are the same as for socket() except the default family is
AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
"""
if family is None:
try:
family = AF_UNIX
except NameError:
family = AF_INET
a, b = _socket.socketpair(family, type, proto)
a = socket(family, type, proto, a.detach())
b = socket(family, type, proto, b.detach())
return a, b
|
socketpair([family[, type[, proto]]]) -> (socket object, socket object)
Create a pair of socket objects from the sockets returned by the platform
socketpair() function.
The arguments are the same as for socket() except the default family is
AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
|
socketpair
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def wait(io, timeout=None, timeout_exc=_NONE):
"""
Block the current greenlet until *io* is ready.
If *timeout* is non-negative, then *timeout_exc* is raised after
*timeout* second has passed. By default *timeout_exc* is
``socket.timeout('timed out')``.
If :func:`cancel_wait` is called on *io* by another greenlet,
raise an exception in this blocking greenlet
(``socket.error(EBADF, 'File descriptor was closed in another
greenlet')`` by default).
:param io: A libev watcher, most commonly an IO watcher obtained from
:meth:`gevent.core.loop.io`
:keyword timeout_exc: The exception to raise if the timeout expires.
By default, a :class:`socket.timeout` exception is raised.
If you pass a value for this keyword, it is interpreted as for
:class:`gevent.timeout.Timeout`.
"""
if io.callback is not None:
raise ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (io.callback, ))
if timeout is not None:
timeout_exc = timeout_exc if timeout_exc is not _NONE else _timeout_error('timed out')
timeout = Timeout.start_new(timeout, timeout_exc)
try:
return get_hub().wait(io)
finally:
if timeout is not None:
timeout.cancel()
# rename "io" to "watcher" because wait() works with any watcher
|
Block the current greenlet until *io* is ready.
If *timeout* is non-negative, then *timeout_exc* is raised after
*timeout* second has passed. By default *timeout_exc* is
``socket.timeout('timed out')``.
If :func:`cancel_wait` is called on *io* by another greenlet,
raise an exception in this blocking greenlet
(``socket.error(EBADF, 'File descriptor was closed in another
greenlet')`` by default).
:param io: A libev watcher, most commonly an IO watcher obtained from
:meth:`gevent.core.loop.io`
:keyword timeout_exc: The exception to raise if the timeout expires.
By default, a :class:`socket.timeout` exception is raised.
If you pass a value for this keyword, it is interpreted as for
:class:`gevent.timeout.Timeout`.
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def wait_read(fileno, timeout=None, timeout_exc=_NONE):
"""
Block the current greenlet until *fileno* is ready to read.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
.. seealso:: :func:`cancel_wait`
"""
io = get_hub().loop.io(fileno, 1)
return wait(io, timeout, timeout_exc)
|
Block the current greenlet until *fileno* is ready to read.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
.. seealso:: :func:`cancel_wait`
|
wait_read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def wait_write(fileno, timeout=None, timeout_exc=_NONE, event=_NONE):
"""
Block the current greenlet until *fileno* is ready to write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
"""
io = get_hub().loop.io(fileno, 2)
return wait(io, timeout, timeout_exc)
|
Block the current greenlet until *fileno* is ready to write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
|
wait_write
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def wait_readwrite(fileno, timeout=None, timeout_exc=_NONE, event=_NONE):
"""
Block the current greenlet until *fileno* is ready to read or
write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
"""
io = get_hub().loop.io(fileno, 3)
return wait(io, timeout, timeout_exc)
|
Block the current greenlet until *fileno* is ready to read or
write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
|
wait_readwrite
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def getfqdn(name=''):
"""Get fully qualified domain name from name.
An empty argument is interpreted as meaning the local host.
First the hostname returned by gethostbyaddr() is checked, then
possibly existing aliases. In case no FQDN is available, hostname
from gethostname() is returned.
"""
name = name.strip()
if not name or name == '0.0.0.0':
name = gethostname()
try:
hostname, aliases, ipaddrs = gethostbyaddr(name)
except error:
pass
else:
aliases.insert(0, hostname)
for name in aliases:
if isinstance(name, bytes):
if b'.' in name:
break
elif '.' in name:
break
else:
name = hostname
return name
|
Get fully qualified domain name from name.
An empty argument is interpreted as meaning the local host.
First the hostname returned by gethostbyaddr() is checked, then
possibly existing aliases. In case no FQDN is available, hostname
from gethostname() is returned.
|
getfqdn
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def read(self, len=1024):
"""Read up to LEN bytes and return them.
Return zero-length string on EOF."""
while True:
try:
return self._sslobj.read(len)
except SSLError as ex:
if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
return ''
elif ex.args[0] == SSL_ERROR_WANT_READ:
if self.timeout == 0.0:
raise
sys.exc_clear()
self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
elif ex.args[0] == SSL_ERROR_WANT_WRITE:
if self.timeout == 0.0:
raise
sys.exc_clear()
# note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional
self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout)
else:
raise
|
Read up to LEN bytes and return them.
Return zero-length string on EOF.
|
read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl2.py
|
MIT
|
def connect(self, addr):
"""Connects to remote ADDR, and then wraps the connection in
an SSL channel."""
# Here we assume that the socket is client-side, and not
# connected at the time of the call. We connect it, then wrap it.
if self._sslobj:
raise ValueError("attempt to connect already-connected SSLSocket!")
socket.connect(self, addr)
if self.ciphers is None:
self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
self.cert_reqs, self.ssl_version,
self.ca_certs)
else:
self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
self.cert_reqs, self.ssl_version,
self.ca_certs, self.ciphers)
if self.do_handshake_on_connect:
self.do_handshake()
|
Connects to remote ADDR, and then wraps the connection in
an SSL channel.
|
connect
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl2.py
|
MIT
|
def accept(self):
"""Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client."""
sock = self._sock
while True:
try:
client_socket, address = sock.accept()
break
except socket_error as ex:
if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0:
raise
sys.exc_clear()
self._wait(self._read_event)
sslobj = SSLSocket(client_socket,
keyfile=self.keyfile,
certfile=self.certfile,
server_side=True,
cert_reqs=self.cert_reqs,
ssl_version=self.ssl_version,
ca_certs=self.ca_certs,
do_handshake_on_connect=self.do_handshake_on_connect,
suppress_ragged_eofs=self.suppress_ragged_eofs,
ciphers=self.ciphers)
return sslobj, address
|
Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client.
|
accept
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl2.py
|
MIT
|
def makefile(self, mode='r', bufsize=-1):
"""Make and return a file-like object that
works with the SSL connection. Just use the code
from the socket module."""
if not PYPY:
self._makefile_refs += 1
# close=True so as to decrement the reference count when done with
# the file-like object.
return _fileobject(self, mode, bufsize, close=True)
|
Make and return a file-like object that
works with the SSL connection. Just use the code
from the socket module.
|
makefile
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl2.py
|
MIT
|
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
"""Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt."""
host, port = addr
if (ca_certs is not None):
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
s = wrap_socket(socket(), ssl_version=ssl_version,
cert_reqs=cert_reqs, ca_certs=ca_certs)
s.connect(addr)
dercert = s.getpeercert(True)
s.close()
return DER_cert_to_PEM_cert(dercert)
|
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt.
|
get_server_certificate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl2.py
|
MIT
|
def read(self, len=1024, buffer=None):
"""Read up to LEN bytes and return them.
Return zero-length string on EOF."""
self._checkClosed()
if not self._sslobj:
raise ValueError("Read on closed or unwrapped SSL socket.")
while True:
try:
if buffer is not None:
return self._sslobj.read(len, buffer)
else:
return self._sslobj.read(len or 1024)
except SSLWantReadError:
if self.timeout == 0.0:
raise
self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
except SSLWantWriteError:
if self.timeout == 0.0:
raise
# note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional
self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout)
except SSLError as ex:
if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
if buffer is None:
return b''
else:
return 0
else:
raise
|
Read up to LEN bytes and return them.
Return zero-length string on EOF.
|
read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl3.py
|
MIT
|
def getpeercert(self, binary_form=False):
"""Returns a formatted version of the data in the
certificate provided by the other end of the SSL channel.
Return None if no certificate was provided, {} if a
certificate was provided, but not validated."""
self._checkClosed()
self._check_connected()
return self._sslobj.peer_certificate(binary_form)
|
Returns a formatted version of the data in the
certificate provided by the other end of the SSL channel.
Return None if no certificate was provided, {} if a
certificate was provided, but not validated.
|
getpeercert
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl3.py
|
MIT
|
def version(self):
"""Return a string identifying the protocol version used by the
current SSL channel. """
if not self._sslobj:
return None
return self._sslobj.version()
|
Return a string identifying the protocol version used by the
current SSL channel.
|
version
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl3.py
|
MIT
|
def accept(self):
"""Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client."""
newsock, addr = socket.accept(self)
newsock = self.context.wrap_socket(newsock,
do_handshake_on_connect=self.do_handshake_on_connect,
suppress_ragged_eofs=self.suppress_ragged_eofs,
server_side=True)
return newsock, addr
|
Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client.
|
accept
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl3.py
|
MIT
|
def get_channel_binding(self, cb_type="tls-unique"):
"""Get channel binding data for current connection. Raise ValueError
if the requested `cb_type` is not supported. Return bytes of the data
or None if the data is not available (e.g. before the handshake).
"""
if cb_type not in CHANNEL_BINDING_TYPES:
raise ValueError("Unsupported channel binding type")
if cb_type != "tls-unique":
raise NotImplementedError("{0} channel binding type not implemented".format(cb_type))
if self._sslobj is None:
return None
return self._sslobj.tls_unique_cb()
|
Get channel binding data for current connection. Raise ValueError
if the requested `cb_type` is not supported. Return bytes of the data
or None if the data is not available (e.g. before the handshake).
|
get_channel_binding
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl3.py
|
MIT
|
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
"""Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt."""
host, port = addr
if (ca_certs is not None):
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
s = create_connection(addr)
s = wrap_socket(s, ssl_version=ssl_version,
cert_reqs=cert_reqs, ca_certs=ca_certs)
dercert = s.getpeercert(True)
s.close()
return DER_cert_to_PEM_cert(dercert)
|
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt.
|
get_server_certificate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl3.py
|
MIT
|
def create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None,
capath=None, cadata=None):
"""Create a SSLContext object with default settings.
NOTE: The protocol and settings may change anytime without prior
deprecation. The values represent a fair balance between maximum
compatibility and security.
"""
if not isinstance(purpose, _ASN1Object):
raise TypeError(purpose)
context = SSLContext(PROTOCOL_SSLv23)
# SSLv2 considered harmful.
context.options |= OP_NO_SSLv2
# SSLv3 has problematic security and is only required for really old
# clients such as IE6 on Windows XP
context.options |= OP_NO_SSLv3
# disable compression to prevent CRIME attacks (OpenSSL 1.0+)
context.options |= getattr(_ssl, "OP_NO_COMPRESSION", 0)
if purpose == Purpose.SERVER_AUTH:
# verify certs and host name in client mode
context.verify_mode = CERT_REQUIRED
context.check_hostname = True
elif purpose == Purpose.CLIENT_AUTH:
# Prefer the server's ciphers by default so that we get stronger
# encryption
context.options |= getattr(_ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
# Use single use keys in order to improve forward secrecy
context.options |= getattr(_ssl, "OP_SINGLE_DH_USE", 0)
context.options |= getattr(_ssl, "OP_SINGLE_ECDH_USE", 0)
# disallow ciphers with known vulnerabilities
context.set_ciphers(_RESTRICTED_SERVER_CIPHERS)
if cafile or capath or cadata:
context.load_verify_locations(cafile, capath, cadata)
elif context.verify_mode != CERT_NONE:
# no explicit cafile, capath or cadata but the verify mode is
# CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
# root CA certificates for the given purpose. This may fail silently.
context.load_default_certs(purpose)
return context
|
Create a SSLContext object with default settings.
NOTE: The protocol and settings may change anytime without prior
deprecation. The values represent a fair balance between maximum
compatibility and security.
|
create_default_context
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def _create_unverified_context(protocol=PROTOCOL_SSLv23, cert_reqs=None,
check_hostname=False, purpose=Purpose.SERVER_AUTH,
certfile=None, keyfile=None,
cafile=None, capath=None, cadata=None):
"""Create a SSLContext object for Python stdlib modules
All Python stdlib modules shall use this function to create SSLContext
objects in order to keep common settings in one place. The configuration
is less restrict than create_default_context()'s to increase backward
compatibility.
"""
if not isinstance(purpose, _ASN1Object):
raise TypeError(purpose)
context = SSLContext(protocol)
# SSLv2 considered harmful.
context.options |= OP_NO_SSLv2
# SSLv3 has problematic security and is only required for really old
# clients such as IE6 on Windows XP
context.options |= OP_NO_SSLv3
if cert_reqs is not None:
context.verify_mode = cert_reqs
context.check_hostname = check_hostname
if keyfile and not certfile:
raise ValueError("certfile must be specified")
if certfile or keyfile:
context.load_cert_chain(certfile, keyfile)
# load CA root certs
if cafile or capath or cadata:
context.load_verify_locations(cafile, capath, cadata)
elif context.verify_mode != CERT_NONE:
# no explicit cafile, capath or cadata but the verify mode is
# CERT_OPTIONAL or CERT_REQUIRED. Let's try to load default system
# root CA certificates for the given purpose. This may fail silently.
context.load_default_certs(purpose)
return context
|
Create a SSLContext object for Python stdlib modules
All Python stdlib modules shall use this function to create SSLContext
objects in order to keep common settings in one place. The configuration
is less restrict than create_default_context()'s to increase backward
compatibility.
|
_create_unverified_context
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def read(self, len=0, buffer=None):
"""Read up to LEN bytes and return them.
Return zero-length string on EOF."""
self._checkClosed()
if not self._sslobj:
raise ValueError("Read on closed or unwrapped SSL socket.")
while True:
try:
if buffer is not None:
return self._sslobj.read(len, buffer)
else:
return self._sslobj.read(len or 1024)
except SSLWantReadError:
if self.timeout == 0.0:
raise
self._wait(self._read_event, timeout_exc=_SSLErrorReadTimeout)
except SSLWantWriteError:
if self.timeout == 0.0:
raise
# note: using _SSLErrorReadTimeout rather than _SSLErrorWriteTimeout below is intentional
self._wait(self._write_event, timeout_exc=_SSLErrorReadTimeout)
except SSLError as ex:
if ex.args[0] == SSL_ERROR_EOF and self.suppress_ragged_eofs:
if buffer is not None:
return 0
else:
return b''
else:
raise
|
Read up to LEN bytes and return them.
Return zero-length string on EOF.
|
read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def getpeercert(self, binary_form=False):
"""Returns a formatted version of the data in the
certificate provided by the other end of the SSL channel.
Return None if no certificate was provided, {} if a
certificate was provided, but not validated."""
self._checkClosed()
self._check_connected()
return self._sslobj.peer_certificate(binary_form)
|
Returns a formatted version of the data in the
certificate provided by the other end of the SSL channel.
Return None if no certificate was provided, {} if a
certificate was provided, but not validated.
|
getpeercert
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def accept(self):
"""Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client."""
newsock, addr = socket.accept(self)
newsock = self.context.wrap_socket(newsock,
do_handshake_on_connect=self.do_handshake_on_connect,
suppress_ragged_eofs=self.suppress_ragged_eofs,
server_side=True)
return newsock, addr
|
Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client.
|
accept
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def makefile(self, mode='r', bufsize=-1):
"""Make and return a file-like object that
works with the SSL connection. Just use the code
from the socket module."""
if not PYPY:
self._makefile_refs += 1
# close=True so as to decrement the reference count when done with
# the file-like object.
return _fileobject(self, mode, bufsize, close=True)
|
Make and return a file-like object that
works with the SSL connection. Just use the code
from the socket module.
|
makefile
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def get_channel_binding(self, cb_type="tls-unique"):
"""Get channel binding data for current connection. Raise ValueError
if the requested `cb_type` is not supported. Return bytes of the data
or None if the data is not available (e.g. before the handshake).
"""
if cb_type not in CHANNEL_BINDING_TYPES:
raise ValueError("Unsupported channel binding type")
if cb_type != "tls-unique":
raise NotImplementedError(
"{0} channel binding type not implemented"
.format(cb_type))
if self._sslobj is None:
return None
return self._sslobj.tls_unique_cb()
|
Get channel binding data for current connection. Raise ValueError
if the requested `cb_type` is not supported. Return bytes of the data
or None if the data is not available (e.g. before the handshake).
|
get_channel_binding
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def version(self):
"""
Return a string identifying the protocol version used by the
current SSL channel, or None if there is no established channel.
"""
if self._sslobj is None:
return None
return self._sslobj.version()
|
Return a string identifying the protocol version used by the
current SSL channel, or None if there is no established channel.
|
version
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
"""Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt."""
host, port = addr
if ca_certs is not None:
cert_reqs = CERT_REQUIRED
else:
cert_reqs = CERT_NONE
context = _create_stdlib_context(ssl_version,
cert_reqs=cert_reqs,
cafile=ca_certs)
with closing(create_connection(addr)) as sock:
with closing(context.wrap_socket(sock)) as sslsock:
dercert = sslsock.getpeercert(True)
return DER_cert_to_PEM_cert(dercert)
|
Retrieve the certificate from the server at the specified address,
and return it as a PEM-encoded string.
If 'ca_certs' is specified, validate the server cert against it.
If 'ssl_version' is specified, use it in the connection attempt.
|
get_server_certificate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_sslgte279.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_sslgte279.py
|
MIT
|
def _init_ugly_crap():
"""This function implements a few ugly things so that we can patch the
traceback objects. The function returned allows resetting `tb_next` on
any python traceback object. Do not attempt to use this on non cpython
interpreters
"""
import ctypes
from types import TracebackType
# figure out side of _Py_ssize_t
if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
_Py_ssize_t = ctypes.c_int64
else:
_Py_ssize_t = ctypes.c_int
# regular python
class _PyObject(ctypes.Structure):
pass
_PyObject._fields_ = [
('ob_refcnt', _Py_ssize_t),
('ob_type', ctypes.POINTER(_PyObject))
]
# python with trace
if hasattr(sys, 'getobjects'):
class _PyObject(ctypes.Structure):
pass
_PyObject._fields_ = [
('_ob_next', ctypes.POINTER(_PyObject)),
('_ob_prev', ctypes.POINTER(_PyObject)),
('ob_refcnt', _Py_ssize_t),
('ob_type', ctypes.POINTER(_PyObject))
]
class _Traceback(_PyObject):
pass
_Traceback._fields_ = [
('tb_next', ctypes.POINTER(_Traceback)),
('tb_frame', ctypes.POINTER(_PyObject)),
('tb_lasti', ctypes.c_int),
('tb_lineno', ctypes.c_int)
]
def tb_set_next(tb, next):
"""Set the tb_next attribute of a traceback object."""
if not (isinstance(tb, TracebackType) and
(next is None or isinstance(next, TracebackType))):
raise TypeError('tb_set_next arguments must be traceback objects')
obj = _Traceback.from_address(id(tb))
if tb.tb_next is not None:
old = _Traceback.from_address(id(tb.tb_next))
old.ob_refcnt -= 1
if next is None:
obj.tb_next = ctypes.POINTER(_Traceback)()
else:
next = _Traceback.from_address(id(next))
next.ob_refcnt += 1
obj.tb_next = ctypes.pointer(next)
return tb_set_next
|
This function implements a few ugly things so that we can patch the
traceback objects. The function returned allows resetting `tb_next` on
any python traceback object. Do not attempt to use this on non cpython
interpreters
|
_init_ugly_crap
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_tblib.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_tblib.py
|
MIT
|
def tb_set_next(tb, next):
"""Set the tb_next attribute of a traceback object."""
if not (isinstance(tb, TracebackType) and
(next is None or isinstance(next, TracebackType))):
raise TypeError('tb_set_next arguments must be traceback objects')
obj = _Traceback.from_address(id(tb))
if tb.tb_next is not None:
old = _Traceback.from_address(id(tb.tb_next))
old.ob_refcnt -= 1
if next is None:
obj.tb_next = ctypes.POINTER(_Traceback)()
else:
next = _Traceback.from_address(id(next))
next.ob_refcnt += 1
obj.tb_next = ctypes.pointer(next)
|
Set the tb_next attribute of a traceback object.
|
tb_set_next
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_tblib.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_tblib.py
|
MIT
|
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
"""
self.all_tasks_done.acquire()
try:
unfinished = self.unfinished_tasks - 1
if unfinished <= 0:
if unfinished < 0:
raise ValueError('task_done() called too many times')
self.all_tasks_done.notify_all()
self.unfinished_tasks = unfinished
finally:
self.all_tasks_done.release()
|
Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items
have been processed (meaning that a task_done() call was received
for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items
placed in the queue.
|
task_done
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_threading.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_threading.py
|
MIT
|
def join(self):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
"""
self.all_tasks_done.acquire()
try:
while self.unfinished_tasks:
self.all_tasks_done.wait()
finally:
self.all_tasks_done.release()
|
Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
|
join
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_threading.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_threading.py
|
MIT
|
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
try:
return self._qsize()
finally:
self.mutex.release()
|
Return the approximate size of the queue (not reliable!).
|
qsize
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_threading.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_threading.py
|
MIT
|
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
try:
return not self._qsize()
finally:
self.mutex.release()
|
Return True if the queue is empty, False otherwise (not reliable!).
|
empty
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_threading.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_threading.py
|
MIT
|
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
try:
if self.maxsize <= 0:
return False
if self.maxsize >= self._qsize():
return True
finally:
self.mutex.release()
|
Return True if the queue is full, False otherwise (not reliable!).
|
full
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_threading.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_threading.py
|
MIT
|
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
"""
self.not_full.acquire()
try:
if self.maxsize > 0:
if not block:
if self._qsize() >= self.maxsize:
raise Full
elif timeout is None:
while self._qsize() >= self.maxsize:
self.not_full.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while self._qsize() >= self.maxsize:
remaining = endtime - _time()
if remaining <= 0.0:
raise Full
self.not_full.wait(remaining)
self._put(item)
self.unfinished_tasks += 1
self.not_empty.notify()
finally:
self.not_full.release()
|
Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Full exception if no free slot was available within that time.
Otherwise ('block' is false), put an item on the queue if a free slot
is immediately available, else raise the Full exception ('timeout'
is ignored in that case).
|
put
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_threading.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_threading.py
|
MIT
|
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
"""
self.not_empty.acquire()
try:
if not block:
if not self._qsize():
raise Empty
elif timeout is None:
while not self._qsize():
self.not_empty.wait()
elif timeout < 0:
raise ValueError("'timeout' must be a positive number")
else:
endtime = _time() + timeout
while not self._qsize():
remaining = endtime - _time()
if remaining <= 0.0:
raise Empty
self.not_empty.wait(remaining)
item = self._get()
self.not_full.notify()
return item
finally:
self.not_empty.release()
|
Remove and return an item from the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until an item is available. If 'timeout' is
a positive number, it blocks at most 'timeout' seconds and raises
the Empty exception if no item was available within that time.
Otherwise ('block' is false), return an item if one is immediately
available, else raise the Empty exception ('timeout' is ignored
in that case).
|
get
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_threading.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_threading.py
|
MIT
|
def __new__(self, projparams=None, preserve_units=False, **kwargs):
"""
initialize a Proj class instance.
Proj4 projection control parameters must either be given in a
dictionary 'projparams' or as keyword arguments. See the proj
documentation (http://trac.osgeo.org/proj/) for more information
about specifying projection parameters.
Example usage:
>>> from pyproj import Proj
>>> p = Proj(proj='utm',zone=10,ellps='WGS84') # use kwargs
>>> x,y = p(-120.108, 34.36116666)
>>> 'x=%9.3f y=%11.3f' % (x,y)
'x=765975.641 y=3805993.134'
>>> 'lon=%8.3f lat=%5.3f' % p(x,y,inverse=True)
'lon=-120.108 lat=34.361'
>>> # do 3 cities at a time in a tuple (Fresno, LA, SF)
>>> lons = (-119.72,-118.40,-122.38)
>>> lats = (36.77, 33.93, 37.62 )
>>> x,y = p(lons, lats)
>>> 'x: %9.3f %9.3f %9.3f' % x
'x: 792763.863 925321.537 554714.301'
>>> 'y: %9.3f %9.3f %9.3f' % y
'y: 4074377.617 3763936.941 4163835.303'
>>> lons, lats = p(x, y, inverse=True) # inverse transform
>>> 'lons: %8.3f %8.3f %8.3f' % lons
'lons: -119.720 -118.400 -122.380'
>>> 'lats: %8.3f %8.3f %8.3f' % lats
'lats: 36.770 33.930 37.620'
>>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84') # use proj4 string
>>> x,y = p2(-120.108, 34.36116666)
>>> 'x=%9.3f y=%11.3f' % (x,y)
'x=765975.641 y=3805993.134'
>>> p = Proj(init="epsg:32667")
>>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045)
'x=-1783486.760 y= 6193833.196 (meters)'
>>> p = Proj("+init=epsg:32667",preserve_units=True)
>>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045)
'x=-5851322.810 y=20320934.409 (feet)'
>>> p = Proj(proj='hammer') # hammer proj and inverse
>>> x,y = p(-30,40)
>>> 'x=%12.3f y=%12.3f' % (x,y)
'x=-2711575.083 y= 4395506.619'
>>> lon,lat = p(x,y,inverse=True)
>>> 'lon=%9.3f lat=%9.3f (degrees)' % (lon,lat)
'lon= -30.000 lat= 40.000 (degrees)'
"""
# if projparams is None, use kwargs.
if projparams is None:
if len(kwargs) == 0:
raise RuntimeError('no projection control parameters specified')
else:
projstring = _dict2string(kwargs)
elif isinstance(projparams, string_types):
# if projparams is a string or a unicode string, interpret as a proj4 init string.
projstring = projparams
else: # projparams a dict
projstring = _dict2string(projparams)
# make sure units are meters if preserve_units is False.
if not projstring.count('+units=') and not preserve_units:
projstring = '+units=m '+projstring
else:
kvpairs = []
for kvpair in projstring.split():
if kvpair.startswith('+units') and not preserve_units:
k,v = kvpair.split('=')
kvpairs.append(k+'=m ')
else:
kvpairs.append(kvpair+' ')
projstring = ''.join(kvpairs)
# look for EPSG, replace with epsg (EPSG only works
# on case-insensitive filesystems).
projstring = projstring.replace('EPSG','epsg')
return _proj.Proj.__new__(self, projstring)
|
initialize a Proj class instance.
Proj4 projection control parameters must either be given in a
dictionary 'projparams' or as keyword arguments. See the proj
documentation (http://trac.osgeo.org/proj/) for more information
about specifying projection parameters.
Example usage:
>>> from pyproj import Proj
>>> p = Proj(proj='utm',zone=10,ellps='WGS84') # use kwargs
>>> x,y = p(-120.108, 34.36116666)
>>> 'x=%9.3f y=%11.3f' % (x,y)
'x=765975.641 y=3805993.134'
>>> 'lon=%8.3f lat=%5.3f' % p(x,y,inverse=True)
'lon=-120.108 lat=34.361'
>>> # do 3 cities at a time in a tuple (Fresno, LA, SF)
>>> lons = (-119.72,-118.40,-122.38)
>>> lats = (36.77, 33.93, 37.62 )
>>> x,y = p(lons, lats)
>>> 'x: %9.3f %9.3f %9.3f' % x
'x: 792763.863 925321.537 554714.301'
>>> 'y: %9.3f %9.3f %9.3f' % y
'y: 4074377.617 3763936.941 4163835.303'
>>> lons, lats = p(x, y, inverse=True) # inverse transform
>>> 'lons: %8.3f %8.3f %8.3f' % lons
'lons: -119.720 -118.400 -122.380'
>>> 'lats: %8.3f %8.3f %8.3f' % lats
'lats: 36.770 33.930 37.620'
>>> p2 = Proj('+proj=utm +zone=10 +ellps=WGS84') # use proj4 string
>>> x,y = p2(-120.108, 34.36116666)
>>> 'x=%9.3f y=%11.3f' % (x,y)
'x=765975.641 y=3805993.134'
>>> p = Proj(init="epsg:32667")
>>> 'x=%12.3f y=%12.3f (meters)' % p(-114.057222, 51.045)
'x=-1783486.760 y= 6193833.196 (meters)'
>>> p = Proj("+init=epsg:32667",preserve_units=True)
>>> 'x=%12.3f y=%12.3f (feet)' % p(-114.057222, 51.045)
'x=-5851322.810 y=20320934.409 (feet)'
>>> p = Proj(proj='hammer') # hammer proj and inverse
>>> x,y = p(-30,40)
>>> 'x=%12.3f y=%12.3f' % (x,y)
'x=-2711575.083 y= 4395506.619'
>>> lon,lat = p(x,y,inverse=True)
>>> 'lon=%9.3f lat=%9.3f (degrees)' % (lon,lat)
'lon= -30.000 lat= 40.000 (degrees)'
|
__new__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def __call__(self, *args, **kw):
#,lon,lat,inverse=False,radians=False,errcheck=False):
"""
Calling a Proj class instance with the arguments lon, lat will
convert lon/lat (in degrees) to x/y native map projection
coordinates (in meters). If optional keyword 'inverse' is True
(default is False), the inverse transformation from x/y to
lon/lat is performed. If optional keyword 'radians' is True
(default is False) the units of lon/lat are radians instead of
degrees. If optional keyword 'errcheck' is True (default is
False) an exception is raised if the transformation is invalid.
If errcheck=False and the transformation is invalid, no
exception is raised and 1.e30 is returned.
Inputs should be doubles (they will be cast to doubles if they
are not, causing a slight performance hit).
Works with numpy and regular python array objects, python
sequences and scalars, but is fastest for array objects.
"""
inverse = kw.get('inverse', False)
radians = kw.get('radians', False)
errcheck = kw.get('errcheck', False)
#if len(args) == 1:
# latlon = np.array(args[0], copy=True,
# order='C', dtype=float, ndmin=2)
# if inverse:
# _proj.Proj._invn(self, latlon, radians=radians, errcheck=errcheck)
# else:
# _proj.Proj._fwdn(self, latlon, radians=radians, errcheck=errcheck)
# return latlon
lon, lat = args
# process inputs, making copies that support buffer API.
inx, xisfloat, xislist, xistuple = _copytobuffer(lon)
iny, yisfloat, yislist, yistuple = _copytobuffer(lat)
# call proj4 functions. inx and iny modified in place.
if inverse:
_proj.Proj._inv(self, inx, iny, radians=radians, errcheck=errcheck)
else:
_proj.Proj._fwd(self, inx, iny, radians=radians, errcheck=errcheck)
# if inputs were lists, tuples or floats, convert back.
outx = _convertback(xisfloat,xislist,xistuple,inx)
outy = _convertback(yisfloat,yislist,xistuple,iny)
return outx, outy
|
Calling a Proj class instance with the arguments lon, lat will
convert lon/lat (in degrees) to x/y native map projection
coordinates (in meters). If optional keyword 'inverse' is True
(default is False), the inverse transformation from x/y to
lon/lat is performed. If optional keyword 'radians' is True
(default is False) the units of lon/lat are radians instead of
degrees. If optional keyword 'errcheck' is True (default is
False) an exception is raised if the transformation is invalid.
If errcheck=False and the transformation is invalid, no
exception is raised and 1.e30 is returned.
Inputs should be doubles (they will be cast to doubles if they
are not, causing a slight performance hit).
Works with numpy and regular python array objects, python
sequences and scalars, but is fastest for array objects.
|
__call__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def transform(p1, p2, x, y, z=None, radians=False):
"""
x2, y2, z2 = transform(p1, p2, x1, y1, z1, radians=False)
Transform points between two coordinate systems defined by the
Proj instances p1 and p2.
The points x1,y1,z1 in the coordinate system defined by p1 are
transformed to x2,y2,z2 in the coordinate system defined by p2.
z1 is optional, if it is not set it is assumed to be zero (and
only x2 and y2 are returned).
In addition to converting between cartographic and geographic
projection coordinates, this function can take care of datum
shifts (which cannot be done using the __call__ method of the
Proj instances). It also allows for one of the coordinate
systems to be geographic (proj = 'latlong').
If optional keyword 'radians' is True (default is False) and p1
is defined in geographic coordinate (pj.is_latlong() is True),
x1,y1 is interpreted as radians instead of the default degrees.
Similarly, if p2 is defined in geographic coordinates and
radians=True, x2, y2 are returned in radians instead of degrees.
if p1.is_latlong() and p2.is_latlong() both are False, the
radians keyword has no effect.
x,y and z can be numpy or regular python arrays, python
lists/tuples or scalars. Arrays are fastest. For projections in
geocentric coordinates, values of x and y are given in meters.
z is always meters.
Example usage:
>>> # projection 1: UTM zone 15, grs80 ellipse, NAD83 datum
>>> # (defined by epsg code 26915)
>>> p1 = Proj(init='epsg:26915')
>>> # projection 2: UTM zone 15, clrk66 ellipse, NAD27 datum
>>> p2 = Proj(init='epsg:26715')
>>> # find x,y of Jefferson City, MO.
>>> x1, y1 = p1(-92.199881,38.56694)
>>> # transform this point to projection 2 coordinates.
>>> x2, y2 = transform(p1,p2,x1,y1)
>>> '%9.3f %11.3f' % (x1,y1)
'569704.566 4269024.671'
>>> '%9.3f %11.3f' % (x2,y2)
'569722.342 4268814.027'
>>> '%8.3f %5.3f' % p2(x2,y2,inverse=True)
' -92.200 38.567'
>>> # process 3 points at a time in a tuple
>>> lats = (38.83,39.32,38.75) # Columbia, KC and StL Missouri
>>> lons = (-92.22,-94.72,-90.37)
>>> x1, y1 = p1(lons,lats)
>>> x2, y2 = transform(p1,p2,x1,y1)
>>> xy = x1+y1
>>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy
'567703.344 351730.944 728553.093 4298200.739 4353698.725 4292319.005'
>>> xy = x2+y2
>>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy
'567721.149 351747.558 728569.133 4297989.112 4353489.644 4292106.305'
>>> lons, lats = p2(x2,y2,inverse=True)
>>> xy = lons+lats
>>> '%8.3f %8.3f %8.3f %5.3f %5.3f %5.3f' % xy
' -92.220 -94.720 -90.370 38.830 39.320 38.750'
>>> # test datum shifting, installation of extra datum grid files.
>>> p1 = Proj(proj='latlong',datum='WGS84')
>>> x1 = -111.5; y1 = 45.25919444444
>>> p2 = Proj(proj="utm",zone=10,datum='NAD27')
>>> x2, y2 = transform(p1, p2, x1, y1)
>>> "%s %s" % (str(x2)[:9],str(y2)[:9])
'1402285.9 5076292.4'
"""
# check that p1 and p2 are from the Proj class
if not isinstance(p1, Proj):
raise TypeError("p1 must be a Proj class")
if not isinstance(p2, Proj):
raise TypeError("p2 must be a Proj class")
# process inputs, making copies that support buffer API.
inx, xisfloat, xislist, xistuple = _copytobuffer(x)
iny, yisfloat, yislist, yistuple = _copytobuffer(y)
if z is not None:
inz, zisfloat, zislist, zistuple = _copytobuffer(z)
else:
inz = None
# call pj_transform. inx,iny,inz buffers modified in place.
_proj._transform(p1,p2,inx,iny,inz,radians)
# if inputs were lists, tuples or floats, convert back.
outx = _convertback(xisfloat,xislist,xistuple,inx)
outy = _convertback(yisfloat,yislist,xistuple,iny)
if inz is not None:
outz = _convertback(zisfloat,zislist,zistuple,inz)
return outx, outy, outz
else:
return outx, outy
|
x2, y2, z2 = transform(p1, p2, x1, y1, z1, radians=False)
Transform points between two coordinate systems defined by the
Proj instances p1 and p2.
The points x1,y1,z1 in the coordinate system defined by p1 are
transformed to x2,y2,z2 in the coordinate system defined by p2.
z1 is optional, if it is not set it is assumed to be zero (and
only x2 and y2 are returned).
In addition to converting between cartographic and geographic
projection coordinates, this function can take care of datum
shifts (which cannot be done using the __call__ method of the
Proj instances). It also allows for one of the coordinate
systems to be geographic (proj = 'latlong').
If optional keyword 'radians' is True (default is False) and p1
is defined in geographic coordinate (pj.is_latlong() is True),
x1,y1 is interpreted as radians instead of the default degrees.
Similarly, if p2 is defined in geographic coordinates and
radians=True, x2, y2 are returned in radians instead of degrees.
if p1.is_latlong() and p2.is_latlong() both are False, the
radians keyword has no effect.
x,y and z can be numpy or regular python arrays, python
lists/tuples or scalars. Arrays are fastest. For projections in
geocentric coordinates, values of x and y are given in meters.
z is always meters.
Example usage:
>>> # projection 1: UTM zone 15, grs80 ellipse, NAD83 datum
>>> # (defined by epsg code 26915)
>>> p1 = Proj(init='epsg:26915')
>>> # projection 2: UTM zone 15, clrk66 ellipse, NAD27 datum
>>> p2 = Proj(init='epsg:26715')
>>> # find x,y of Jefferson City, MO.
>>> x1, y1 = p1(-92.199881,38.56694)
>>> # transform this point to projection 2 coordinates.
>>> x2, y2 = transform(p1,p2,x1,y1)
>>> '%9.3f %11.3f' % (x1,y1)
'569704.566 4269024.671'
>>> '%9.3f %11.3f' % (x2,y2)
'569722.342 4268814.027'
>>> '%8.3f %5.3f' % p2(x2,y2,inverse=True)
' -92.200 38.567'
>>> # process 3 points at a time in a tuple
>>> lats = (38.83,39.32,38.75) # Columbia, KC and StL Missouri
>>> lons = (-92.22,-94.72,-90.37)
>>> x1, y1 = p1(lons,lats)
>>> x2, y2 = transform(p1,p2,x1,y1)
>>> xy = x1+y1
>>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy
'567703.344 351730.944 728553.093 4298200.739 4353698.725 4292319.005'
>>> xy = x2+y2
>>> '%9.3f %9.3f %9.3f %11.3f %11.3f %11.3f' % xy
'567721.149 351747.558 728569.133 4297989.112 4353489.644 4292106.305'
>>> lons, lats = p2(x2,y2,inverse=True)
>>> xy = lons+lats
>>> '%8.3f %8.3f %8.3f %5.3f %5.3f %5.3f' % xy
' -92.220 -94.720 -90.370 38.830 39.320 38.750'
>>> # test datum shifting, installation of extra datum grid files.
>>> p1 = Proj(proj='latlong',datum='WGS84')
>>> x1 = -111.5; y1 = 45.25919444444
>>> p2 = Proj(proj="utm",zone=10,datum='NAD27')
>>> x2, y2 = transform(p1, p2, x1, y1)
>>> "%s %s" % (str(x2)[:9],str(y2)[:9])
'1402285.9 5076292.4'
|
transform
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def _copytobuffer(x):
"""
return a copy of x as an object that supports the python Buffer
API (python array if input is float, list or tuple, numpy array
if input is a numpy array). returns copyofx, isfloat, islist,
istuple (islist is True if input is a list, istuple is true if
input is a tuple, isfloat is true if input is a float).
"""
# make sure x supports Buffer API and contains doubles.
isfloat = False; islist = False; istuple = False
# first, if it's a numpy array scalar convert to float
# (array scalars don't support buffer API)
if hasattr(x,'shape'):
if x.shape == ():
return _copytobuffer_return_scalar(x)
else:
try:
# typecast numpy arrays to double.
# (this makes a copy - which is crucial
# since buffer is modified in place)
x.dtype.char
# Basemap issue
# https://github.com/matplotlib/basemap/pull/223/files
# (deal with input array in fortran order)
inx = x.copy(order="C").astype('d')
# inx,isfloat,islist,istuple
return inx,False,False,False
except:
try: # perhaps they are Numeric/numarrays?
# sorry, not tested yet.
# i don't know Numeric/numarrays has `shape'.
x.typecode()
inx = x.astype('d')
# inx,isfloat,islist,istuple
return inx,False,False,False
except:
raise TypeError('input must be an array, list, tuple or scalar')
else:
# perhaps they are regular python arrays?
if hasattr(x, 'typecode'):
#x.typecode
inx = array('d',x)
# try to convert to python array
# a list.
elif type(x) == list:
inx = array('d',x)
islist = True
# a tuple.
elif type(x) == tuple:
inx = array('d',x)
istuple = True
# a scalar?
else:
return _copytobuffer_return_scalar(x)
return inx,isfloat,islist,istuple
|
return a copy of x as an object that supports the python Buffer
API (python array if input is float, list or tuple, numpy array
if input is a numpy array). returns copyofx, isfloat, islist,
istuple (islist is True if input is a list, istuple is true if
input is a tuple, isfloat is true if input is a float).
|
_copytobuffer
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def __new__(self, initstring=None, **kwargs):
"""
initialize a Geod class instance.
Geodetic parameters for specifying the ellipsoid
can be given in a dictionary 'initparams', as keyword arguments,
or as as proj4 geod initialization string.
Following is a list of the ellipsoids that may be defined using the
'ellps' keyword (these are stored in the model variable pj_ellps)::
MERIT a=6378137.0 rf=298.257 MERIT 1983
SGS85 a=6378136.0 rf=298.257 Soviet Geodetic System 85
GRS80 a=6378137.0 rf=298.257222101 GRS 1980(IUGG, 1980)
IAU76 a=6378140.0 rf=298.257 IAU 1976
airy a=6377563.396 b=6356256.910 Airy 1830
APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965
airy a=6377563.396 b=6356256.910 Airy 1830
APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965
NWL9D a=6378145.0. rf=298.25 Naval Weapons Lab., 1965
mod_airy a=6377340.189 b=6356034.446 Modified Airy
andrae a=6377104.43 rf=300.0 Andrae 1876 (Den., Iclnd.)
aust_SA a=6378160.0 rf=298.25 Australian Natl & S. Amer. 1969
GRS67 a=6378160.0 rf=298.247167427 GRS 67(IUGG 1967)
bessel a=6377397.155 rf=299.1528128 Bessel 1841
bess_nam a=6377483.865 rf=299.1528128 Bessel 1841 (Namibia)
clrk66 a=6378206.4 b=6356583.8 Clarke 1866
clrk80 a=6378249.145 rf=293.4663 Clarke 1880 mod.
CPM a=6375738.7 rf=334.29 Comm. des Poids et Mesures 1799
delmbr a=6376428. rf=311.5 Delambre 1810 (Belgium)
engelis a=6378136.05 rf=298.2566 Engelis 1985
evrst30 a=6377276.345 rf=300.8017 Everest 1830
evrst48 a=6377304.063 rf=300.8017 Everest 1948
evrst56 a=6377301.243 rf=300.8017 Everest 1956
evrst69 a=6377295.664 rf=300.8017 Everest 1969
evrstSS a=6377298.556 rf=300.8017 Everest (Sabah & Sarawak)
fschr60 a=6378166. rf=298.3 Fischer (Mercury Datum) 1960
fschr60m a=6378155. rf=298.3 Modified Fischer 1960
fschr68 a=6378150. rf=298.3 Fischer 1968
helmert a=6378200. rf=298.3 Helmert 1906
hough a=6378270.0 rf=297. Hough
helmert a=6378200. rf=298.3 Helmert 1906
hough a=6378270.0 rf=297. Hough
intl a=6378388.0 rf=297. International 1909 (Hayford)
krass a=6378245.0 rf=298.3 Krassovsky, 1942
kaula a=6378163. rf=298.24 Kaula 1961
lerch a=6378139. rf=298.257 Lerch 1979
mprts a=6397300. rf=191. Maupertius 1738
new_intl a=6378157.5 b=6356772.2 New International 1967
plessis a=6376523. b=6355863. Plessis 1817 (France)
SEasia a=6378155.0 b=6356773.3205 Southeast Asia
walbeck a=6376896.0 b=6355834.8467 Walbeck
WGS60 a=6378165.0 rf=298.3 WGS 60
WGS66 a=6378145.0 rf=298.25 WGS 66
WGS72 a=6378135.0 rf=298.26 WGS 72
WGS84 a=6378137.0 rf=298.257223563 WGS 84
sphere a=6370997.0 b=6370997.0 Normal Sphere (r=6370997)
The parameters of the ellipsoid may also be set directly using
the 'a' (semi-major or equatorial axis radius) keyword, and
any one of the following keywords: 'b' (semi-minor,
or polar axis radius), 'e' (eccentricity), 'es' (eccentricity
squared), 'f' (flattening), or 'rf' (reciprocal flattening).
See the proj documentation (http://trac.osgeo.org/proj/) for more
See the proj documentation (http://trac.osgeo.org/proj/) for more
information about specifying ellipsoid parameters (specifically,
the chapter 'Specifying the Earth's figure' in the main Proj
users manual).
Example usage:
>>> from pyproj import Geod
>>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid.
>>> # specify the lat/lons of some cities.
>>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.)
>>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.)
>>> newyork_lat = 40.+(47./60.); newyork_lon = -73.-(58./60.)
>>> london_lat = 51.+(32./60.); london_lon = -(5./60.)
>>> # compute forward and back azimuths, plus distance
>>> # between Boston and Portland.
>>> az12,az21,dist = g.inv(boston_lon,boston_lat,portland_lon,portland_lat)
>>> "%7.3f %6.3f %12.3f" % (az12,az21,dist)
'-66.531 75.654 4164192.708'
>>> # compute latitude, longitude and back azimuth of Portland,
>>> # given Boston lat/lon, forward azimuth and distance to Portland.
>>> endlon, endlat, backaz = g.fwd(boston_lon, boston_lat, az12, dist)
>>> "%6.3f %6.3f %13.3f" % (endlat,endlon,backaz)
'45.517 -123.683 75.654'
>>> # compute the azimuths, distances from New York to several
>>> # cities (pass a list)
>>> lons1 = 3*[newyork_lon]; lats1 = 3*[newyork_lat]
>>> lons2 = [boston_lon, portland_lon, london_lon]
>>> lats2 = [boston_lat, portland_lat, london_lat]
>>> az12,az21,dist = g.inv(lons1,lats1,lons2,lats2)
>>> for faz,baz,d in list(zip(az12,az21,dist)): "%7.3f %7.3f %9.3f" % (faz,baz,d)
' 54.663 -123.448 288303.720'
'-65.463 79.342 4013037.318'
' 51.254 -71.576 5579916.651'
>>> g2 = Geod('+ellps=clrk66') # use proj4 style initialization string
>>> az12,az21,dist = g2.inv(boston_lon,boston_lat,portland_lon,portland_lat)
>>> "%7.3f %6.3f %12.3f" % (az12,az21,dist)
'-66.531 75.654 4164192.708'
"""
# if initparams is a proj-type init string,
# convert to dict.
ellpsd = {}
if initstring is not None:
for kvpair in initstring.split():
# Actually only +a and +b are needed
# We can ignore safely any parameter that doesn't have a value
if kvpair.find('=') == -1:
continue
k,v = kvpair.split('=')
k = k.lstrip('+')
if k in ['a','b','rf','f','es','e']:
v = float(v)
ellpsd[k] = v
# merge this dict with kwargs dict.
kwargs = dict(list(kwargs.items()) + list(ellpsd.items()))
self.sphere = False
if 'ellps' in kwargs:
# ellipse name given, look up in pj_ellps dict
ellps_dict = pj_ellps[kwargs['ellps']]
a = ellps_dict['a']
if ellps_dict['description']=='Normal Sphere':
self.sphere = True
if 'b' in ellps_dict:
b = ellps_dict['b']
es = 1. - (b * b) / (a * a)
f = (a - b)/a
elif 'rf' in ellps_dict:
f = 1./ellps_dict['rf']
b = a*(1. - f)
es = 1. - (b * b) / (a * a)
else:
# a (semi-major axis) and one of
# b the semi-minor axis
# rf the reciprocal flattening
# f flattening
# es eccentricity squared
# must be given.
a = kwargs['a']
if 'b' in kwargs:
b = kwargs['b']
es = 1. - (b * b) / (a * a)
f = (a - b)/a
elif 'rf' in kwargs:
f = 1./kwargs['rf']
b = a*(1. - f)
es = 1. - (b * b) / (a * a)
elif 'f' in kwargs:
f = kwargs['f']
b = a*(1. - f)
es = 1. - (b/a)**2
elif 'es' in kwargs:
es = kwargs['es']
b = math.sqrt(a**2 - es*a**2)
f = (a - b)/a
elif 'e' in kwargs:
es = kwargs['e']**2
b = math.sqrt(a**2 - es*a**2)
f = (a - b)/a
else:
b = a
f = 0.
es = 0.
#msg='ellipse name or a, plus one of f,es,b must be given'
#raise ValueError(msg)
if math.fabs(f) < 1.e-8: self.sphere = True
self.a = a
self.b = b
self.f = f
self.es = es
return _proj.Geod.__new__(self, a, f)
|
initialize a Geod class instance.
Geodetic parameters for specifying the ellipsoid
can be given in a dictionary 'initparams', as keyword arguments,
or as as proj4 geod initialization string.
Following is a list of the ellipsoids that may be defined using the
'ellps' keyword (these are stored in the model variable pj_ellps)::
MERIT a=6378137.0 rf=298.257 MERIT 1983
SGS85 a=6378136.0 rf=298.257 Soviet Geodetic System 85
GRS80 a=6378137.0 rf=298.257222101 GRS 1980(IUGG, 1980)
IAU76 a=6378140.0 rf=298.257 IAU 1976
airy a=6377563.396 b=6356256.910 Airy 1830
APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965
airy a=6377563.396 b=6356256.910 Airy 1830
APL4.9 a=6378137.0. rf=298.25 Appl. Physics. 1965
NWL9D a=6378145.0. rf=298.25 Naval Weapons Lab., 1965
mod_airy a=6377340.189 b=6356034.446 Modified Airy
andrae a=6377104.43 rf=300.0 Andrae 1876 (Den., Iclnd.)
aust_SA a=6378160.0 rf=298.25 Australian Natl & S. Amer. 1969
GRS67 a=6378160.0 rf=298.247167427 GRS 67(IUGG 1967)
bessel a=6377397.155 rf=299.1528128 Bessel 1841
bess_nam a=6377483.865 rf=299.1528128 Bessel 1841 (Namibia)
clrk66 a=6378206.4 b=6356583.8 Clarke 1866
clrk80 a=6378249.145 rf=293.4663 Clarke 1880 mod.
CPM a=6375738.7 rf=334.29 Comm. des Poids et Mesures 1799
delmbr a=6376428. rf=311.5 Delambre 1810 (Belgium)
engelis a=6378136.05 rf=298.2566 Engelis 1985
evrst30 a=6377276.345 rf=300.8017 Everest 1830
evrst48 a=6377304.063 rf=300.8017 Everest 1948
evrst56 a=6377301.243 rf=300.8017 Everest 1956
evrst69 a=6377295.664 rf=300.8017 Everest 1969
evrstSS a=6377298.556 rf=300.8017 Everest (Sabah & Sarawak)
fschr60 a=6378166. rf=298.3 Fischer (Mercury Datum) 1960
fschr60m a=6378155. rf=298.3 Modified Fischer 1960
fschr68 a=6378150. rf=298.3 Fischer 1968
helmert a=6378200. rf=298.3 Helmert 1906
hough a=6378270.0 rf=297. Hough
helmert a=6378200. rf=298.3 Helmert 1906
hough a=6378270.0 rf=297. Hough
intl a=6378388.0 rf=297. International 1909 (Hayford)
krass a=6378245.0 rf=298.3 Krassovsky, 1942
kaula a=6378163. rf=298.24 Kaula 1961
lerch a=6378139. rf=298.257 Lerch 1979
mprts a=6397300. rf=191. Maupertius 1738
new_intl a=6378157.5 b=6356772.2 New International 1967
plessis a=6376523. b=6355863. Plessis 1817 (France)
SEasia a=6378155.0 b=6356773.3205 Southeast Asia
walbeck a=6376896.0 b=6355834.8467 Walbeck
WGS60 a=6378165.0 rf=298.3 WGS 60
WGS66 a=6378145.0 rf=298.25 WGS 66
WGS72 a=6378135.0 rf=298.26 WGS 72
WGS84 a=6378137.0 rf=298.257223563 WGS 84
sphere a=6370997.0 b=6370997.0 Normal Sphere (r=6370997)
The parameters of the ellipsoid may also be set directly using
the 'a' (semi-major or equatorial axis radius) keyword, and
any one of the following keywords: 'b' (semi-minor,
or polar axis radius), 'e' (eccentricity), 'es' (eccentricity
squared), 'f' (flattening), or 'rf' (reciprocal flattening).
See the proj documentation (http://trac.osgeo.org/proj/) for more
See the proj documentation (http://trac.osgeo.org/proj/) for more
information about specifying ellipsoid parameters (specifically,
the chapter 'Specifying the Earth's figure' in the main Proj
users manual).
Example usage:
>>> from pyproj import Geod
>>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid.
>>> # specify the lat/lons of some cities.
>>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.)
>>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.)
>>> newyork_lat = 40.+(47./60.); newyork_lon = -73.-(58./60.)
>>> london_lat = 51.+(32./60.); london_lon = -(5./60.)
>>> # compute forward and back azimuths, plus distance
>>> # between Boston and Portland.
>>> az12,az21,dist = g.inv(boston_lon,boston_lat,portland_lon,portland_lat)
>>> "%7.3f %6.3f %12.3f" % (az12,az21,dist)
'-66.531 75.654 4164192.708'
>>> # compute latitude, longitude and back azimuth of Portland,
>>> # given Boston lat/lon, forward azimuth and distance to Portland.
>>> endlon, endlat, backaz = g.fwd(boston_lon, boston_lat, az12, dist)
>>> "%6.3f %6.3f %13.3f" % (endlat,endlon,backaz)
'45.517 -123.683 75.654'
>>> # compute the azimuths, distances from New York to several
>>> # cities (pass a list)
>>> lons1 = 3*[newyork_lon]; lats1 = 3*[newyork_lat]
>>> lons2 = [boston_lon, portland_lon, london_lon]
>>> lats2 = [boston_lat, portland_lat, london_lat]
>>> az12,az21,dist = g.inv(lons1,lats1,lons2,lats2)
>>> for faz,baz,d in list(zip(az12,az21,dist)): "%7.3f %7.3f %9.3f" % (faz,baz,d)
' 54.663 -123.448 288303.720'
'-65.463 79.342 4013037.318'
' 51.254 -71.576 5579916.651'
>>> g2 = Geod('+ellps=clrk66') # use proj4 style initialization string
>>> az12,az21,dist = g2.inv(boston_lon,boston_lat,portland_lon,portland_lat)
>>> "%7.3f %6.3f %12.3f" % (az12,az21,dist)
'-66.531 75.654 4164192.708'
|
__new__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def fwd(self, lons, lats, az, dist, radians=False):
"""
forward transformation - Returns longitudes, latitudes and back
azimuths of terminus points given longitudes (lons) and
latitudes (lats) of initial points, plus forward azimuths (az)
and distances (dist).
latitudes (lats) of initial points, plus forward azimuths (az)
and distances (dist).
Works with numpy and regular python array objects, python
sequences and scalars.
if radians=True, lons/lats and azimuths are radians instead of
degrees. Distances are in meters.
"""
# process inputs, making copies that support buffer API.
inx, xisfloat, xislist, xistuple = _copytobuffer(lons)
iny, yisfloat, yislist, yistuple = _copytobuffer(lats)
inz, zisfloat, zislist, zistuple = _copytobuffer(az)
ind, disfloat, dislist, distuple = _copytobuffer(dist)
_proj.Geod._fwd(self, inx, iny, inz, ind, radians=radians)
# if inputs were lists, tuples or floats, convert back.
outx = _convertback(xisfloat,xislist,xistuple,inx)
outy = _convertback(yisfloat,yislist,xistuple,iny)
outz = _convertback(zisfloat,zislist,zistuple,inz)
return outx, outy, outz
|
forward transformation - Returns longitudes, latitudes and back
azimuths of terminus points given longitudes (lons) and
latitudes (lats) of initial points, plus forward azimuths (az)
and distances (dist).
latitudes (lats) of initial points, plus forward azimuths (az)
and distances (dist).
Works with numpy and regular python array objects, python
sequences and scalars.
if radians=True, lons/lats and azimuths are radians instead of
degrees. Distances are in meters.
|
fwd
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def inv(self,lons1,lats1,lons2,lats2,radians=False):
"""
inverse transformation - Returns forward and back azimuths, plus
distances between initial points (specified by lons1, lats1) and
terminus points (specified by lons2, lats2).
Works with numpy and regular python array objects, python
sequences and scalars.
if radians=True, lons/lats and azimuths are radians instead of
degrees. Distances are in meters.
"""
# process inputs, making copies that support buffer API.
inx, xisfloat, xislist, xistuple = _copytobuffer(lons1)
iny, yisfloat, yislist, yistuple = _copytobuffer(lats1)
inz, zisfloat, zislist, zistuple = _copytobuffer(lons2)
ind, disfloat, dislist, distuple = _copytobuffer(lats2)
_proj.Geod._inv(self,inx,iny,inz,ind,radians=radians)
# if inputs were lists, tuples or floats, convert back.
outx = _convertback(xisfloat,xislist,xistuple,inx)
outy = _convertback(yisfloat,yislist,xistuple,iny)
outz = _convertback(zisfloat,zislist,zistuple,inz)
return outx, outy, outz
|
inverse transformation - Returns forward and back azimuths, plus
distances between initial points (specified by lons1, lats1) and
terminus points (specified by lons2, lats2).
Works with numpy and regular python array objects, python
sequences and scalars.
if radians=True, lons/lats and azimuths are radians instead of
degrees. Distances are in meters.
|
inv
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def npts(self, lon1, lat1, lon2, lat2, npts, radians=False):
"""
Given a single initial point and terminus point (specified by
python floats lon1,lat1 and lon2,lat2), returns a list of
longitude/latitude pairs describing npts equally spaced
intermediate points along the geodesic between the initial and
terminus points.
if radians=True, lons/lats are radians instead of degrees.
Example usage:
>>> from pyproj import Geod
>>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid.
>>> # specify the lat/lons of Boston and Portland.
>>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid.
>>> # specify the lat/lons of Boston and Portland.
>>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.)
>>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.)
>>> # find ten equally spaced points between Boston and Portland.
>>> lonlats = g.npts(boston_lon,boston_lat,portland_lon,portland_lat,10)
>>> for lon,lat in lonlats: '%6.3f %7.3f' % (lat, lon)
'43.528 -75.414'
'44.637 -79.883'
'45.565 -84.512'
'46.299 -89.279'
'46.830 -94.156'
'47.149 -99.112'
'47.251 -104.106'
'47.136 -109.100'
'46.805 -114.051'
'46.262 -118.924'
>>> # test with radians=True (inputs/outputs in radians, not degrees)
>>> import math
>>> dg2rad = math.radians(1.)
>>> rad2dg = math.degrees(1.)
>>> lonlats = g.npts(dg2rad*boston_lon,dg2rad*boston_lat,dg2rad*portland_lon,dg2rad*portland_lat,10,radians=True)
>>> for lon,lat in lonlats: '%6.3f %7.3f' % (rad2dg*lat, rad2dg*lon)
'43.528 -75.414'
'44.637 -79.883'
'45.565 -84.512'
'46.299 -89.279'
'46.830 -94.156'
'47.149 -99.112'
'47.251 -104.106'
'47.136 -109.100'
'46.805 -114.051'
'46.262 -118.924'
"""
lons, lats = _proj.Geod._npts(self, lon1, lat1, lon2, lat2, npts, radians=radians)
return list(zip(lons, lats))
|
Given a single initial point and terminus point (specified by
python floats lon1,lat1 and lon2,lat2), returns a list of
longitude/latitude pairs describing npts equally spaced
intermediate points along the geodesic between the initial and
terminus points.
if radians=True, lons/lats are radians instead of degrees.
Example usage:
>>> from pyproj import Geod
>>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid.
>>> # specify the lat/lons of Boston and Portland.
>>> g = Geod(ellps='clrk66') # Use Clarke 1966 ellipsoid.
>>> # specify the lat/lons of Boston and Portland.
>>> boston_lat = 42.+(15./60.); boston_lon = -71.-(7./60.)
>>> portland_lat = 45.+(31./60.); portland_lon = -123.-(41./60.)
>>> # find ten equally spaced points between Boston and Portland.
>>> lonlats = g.npts(boston_lon,boston_lat,portland_lon,portland_lat,10)
>>> for lon,lat in lonlats: '%6.3f %7.3f' % (lat, lon)
'43.528 -75.414'
'44.637 -79.883'
'45.565 -84.512'
'46.299 -89.279'
'46.830 -94.156'
'47.149 -99.112'
'47.251 -104.106'
'47.136 -109.100'
'46.805 -114.051'
'46.262 -118.924'
>>> # test with radians=True (inputs/outputs in radians, not degrees)
>>> import math
>>> dg2rad = math.radians(1.)
>>> rad2dg = math.degrees(1.)
>>> lonlats = g.npts(dg2rad*boston_lon,dg2rad*boston_lat,dg2rad*portland_lon,dg2rad*portland_lat,10,radians=True)
>>> for lon,lat in lonlats: '%6.3f %7.3f' % (rad2dg*lat, rad2dg*lon)
'43.528 -75.414'
'44.637 -79.883'
'45.565 -84.512'
'46.299 -89.279'
'46.830 -94.156'
'47.149 -99.112'
'47.251 -104.106'
'47.136 -109.100'
'46.805 -114.051'
'46.262 -118.924'
|
npts
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/pyproj/__init__.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/pyproj/__init__.py
|
MIT
|
def check_access_token(self):
"""
Add few seconds to now so the token get refreshed
before it invalidates in the middle of the request
"""
now_s = get_time() + 120
if self._access_token is not None:
if self._access_token_expiry == 0:
self.log.debug('No Access Token Expiry found - assuming it is still valid!')
return True
elif self._access_token_expiry > now_s:
h, m, s = get_format_time_diff(now_s, self._access_token_expiry, False)
self.log.debug('Access Token still valid for further %02d:%02d:%02d hours (%s < %s)', h, m, s, now_s, self._access_token_expiry)
return True
else:
self.log.info('Access Token expired!')
return False
else:
self.log.debug('No Access Token available!')
return False
|
Add few seconds to now so the token get refreshed
before it invalidates in the middle of the request
|
check_access_token
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/shared/pgoapi/auth.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/shared/pgoapi/auth.py
|
MIT
|
def dict_to_protobuf(pb_klass_or_instance, values, type_callable_map=REVERSE_TYPE_CALLABLE_MAP, strict=True):
"""Populates a protobuf model from a dictionary.
:param pb_klass_or_instance: a protobuf message class, or an protobuf instance
:type pb_klass_or_instance: a type or instance of a subclass of google.protobuf.message.Message
:param dict values: a dictionary of values. Repeated and nested values are
fully supported.
:param dict type_callable_map: a mapping of protobuf types to callables for setting
values on the target instance.
:param bool strict: complain if keys in the map are not fields on the message.
"""
if isinstance(pb_klass_or_instance, Message):
instance = pb_klass_or_instance
else:
instance = pb_klass_or_instance()
return _dict_to_protobuf(instance, values, type_callable_map, strict)
|
Populates a protobuf model from a dictionary.
:param pb_klass_or_instance: a protobuf message class, or an protobuf instance
:type pb_klass_or_instance: a type or instance of a subclass of google.protobuf.message.Message
:param dict values: a dictionary of values. Repeated and nested values are
fully supported.
:param dict type_callable_map: a mapping of protobuf types to callables for setting
values on the target instance.
:param bool strict: complain if keys in the map are not fields on the message.
|
dict_to_protobuf
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/shared/pgoapi/protobuf_to_dict.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/shared/pgoapi/protobuf_to_dict.py
|
MIT
|
def long_to_bytes(val, endianness='big'):
"""
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param long val: The value to pack
:param str endianness: The endianness of the result. ``'big'`` for
big-endian, ``'little'`` for little-endian.
If you want byte- and word-ordering to differ, you're on your own.
Using :ref:`string formatting` lets us use Python's C innards.
"""
# one (1) hex digit per four (4) bits
width = val.bit_length()
# unhexlify wants an even multiple of eight (8) bits, but we don't
# want more digits than we need (hence the ternary-ish 'or')
width += 8 - ((width % 8) or 8)
# format width specifier: four (4) bits per hex digit
fmt = '%%0%dx' % (width // 4)
# prepend zero (0) to the width, to zero-pad the output
s = unhexlify(fmt % val)
if endianness == 'little':
# see http://stackoverflow.com/a/931095/309233
s = s[::-1]
return s
|
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param long val: The value to pack
:param str endianness: The endianness of the result. ``'big'`` for
big-endian, ``'little'`` for little-endian.
If you want byte- and word-ordering to differ, you're on your own.
Using :ref:`string formatting` lets us use Python's C innards.
|
long_to_bytes
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/shared/pgoapi/utilities.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/shared/pgoapi/utilities.py
|
MIT
|
def _create_base_cipher(dict_parameters):
"""This method instantiates and returns a handle to a low-level
base cipher. It will absorb named parameters in the process."""
use_aesni = dict_parameters.pop("use_aesni", True)
try:
key = dict_parameters.pop("key")
except KeyError:
raise TypeError("Missing 'key' parameter")
expect_byte_string(key)
if len(key) not in key_size:
raise ValueError("Incorrect AES key length (%d bytes)" % len(key))
if use_aesni and _raw_aesni_lib:
start_operation = _raw_aesni_lib.AESNI_start_operation
stop_operation = _raw_aesni_lib.AESNI_stop_operation
else:
start_operation = _raw_aes_lib.AES_start_operation
stop_operation = _raw_aes_lib.AES_stop_operation
cipher = VoidPointer()
result = start_operation(key,
c_size_t(len(key)),
cipher.address_of())
if result:
raise ValueError("Error %X while instantiating the AES cipher"
% result)
return SmartPointer(cipher.get(), stop_operation)
|
This method instantiates and returns a handle to a low-level
base cipher. It will absorb named parameters in the process.
|
_create_base_cipher
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/AES.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/AES.py
|
MIT
|
def new(key, mode, *args, **kwargs):
"""Create a new AES cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*)
bytes long.
Only in `MODE_SIV`, it needs to be 32, 48, or 64 bytes long.
mode : a *MODE_** constant
The chaining mode to use for encryption or decryption.
If in doubt, use `MODE_EAX`.
:Keywords:
iv : byte string
(*Only* `MODE_CBC`, `MODE_CFB`, `MODE_OFB`, `MODE_OPENPGP`).
The initialization vector to use for encryption or decryption.
For `MODE_OPENPGP`, it must be 16 bytes long for encryption
and 18 bytes for decryption (in the latter case, it is
actually the *encrypted* IV which was prefixed to the ciphertext).
For all other modes, it must be 16 bytes long.
In not provided, a random byte string is used (you must then
read its value with the ``iv`` attribute).
nonce : byte string
(*Only* `MODE_CCM`, `MODE_EAX`, `MODE_GCM`, `MODE_SIV`, `MODE_OCB`,
`MODE_CTR`).
A value that must never be reused for any other encryption done
with this key.
For `MODE_CCM`, its length must be in the range ``[7..13]``.
Bear in mind that with CCM there is a trade-off between nonce
length and maximum message size.
For `MODE_OCB`, its length must be in the range ``[1..15]``.
For `MODE_CTR`, its length must be in the range ``[0..15]``.
For the other modes, there are no restrictions on its length.
The recommended length depends on the mode: 8 bytes for `MODE_CTR`,
11 bytes for `MODE_CCM`, 15 bytes for `MODE_OCB` and 16 bytes
for the remaining modes.
In not provided, a random byte string of the recommended
length is used (you must then read its value with the ``nonce`` attribute).
segment_size : integer
(*Only* `MODE_CFB`).The number of **bits** the plaintext and ciphertext
are segmented in. It must be a multiple of 8.
If not specified, it will be assumed to be 8.
mac_len : integer
(*Only* `MODE_EAX`, `MODE_GCM`, `MODE_OCB`, `MODE_CCM`)
Length of the authentication tag, in bytes.
It must be even and in the range ``[4..16]``.
The recommended value (and the default, if not specified) is 16.
msg_len : integer
(*Only* `MODE_CCM`). Length of the message to (de)cipher.
If not specified, ``encrypt`` must be called with the entire message.
Similarly, ``decrypt`` can only be called once.
assoc_len : integer
(*Only* `MODE_CCM`). Length of the associated data.
If not specified, all associated data is buffered internally,
which may represent a problem for very large messages.
initial_value : integer
(*Only* `MODE_CTR`). The initial value for the counter within
the counter block. By default it is 0.
use_aesni : boolean
Use Intel AES-NI hardware extensions if available.
:Return: an AES object, of the applicable mode:
- CBC_ mode
- CCM_ mode
- CFB_ mode
- CTR_ mode
- EAX_ mode
- ECB_ mode
- GCM_ mode
- OCB_ mode
- OFB_ mode
- OpenPgp_ mode
- SIV_ mode
.. _CBC: Cryptodome.Cipher._mode_cbc.CbcMode-class.html
.. _CCM: Cryptodome.Cipher._mode_ccm.CcmMode-class.html
.. _CFB: Cryptodome.Cipher._mode_cfb.CfbMode-class.html
.. _CTR: Cryptodome.Cipher._mode_ctr.CtrMode-class.html
.. _EAX: Cryptodome.Cipher._mode_eax.EaxMode-class.html
.. _ECB: Cryptodome.Cipher._mode_ecb.EcbMode-class.html
.. _GCM: Cryptodome.Cipher._mode_gcm.GcmMode-class.html
.. _OCB: Cryptodome.Cipher._mode_ocb.OcbMode-class.html
.. _OFB: Cryptodome.Cipher._mode_ofb.OfbMode-class.html
.. _OpenPgp: Cryptodome.Cipher._mode_openpgp.OpenPgpMode-class.html
.. _SIV: Cryptodome.Cipher._mode_siv.SivMode-class.html
"""
kwargs["add_aes_modes"] = True
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
|
Create a new AES cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
It must be 16 (*AES-128*), 24 (*AES-192*), or 32 (*AES-256*)
bytes long.
Only in `MODE_SIV`, it needs to be 32, 48, or 64 bytes long.
mode : a *MODE_** constant
The chaining mode to use for encryption or decryption.
If in doubt, use `MODE_EAX`.
:Keywords:
iv : byte string
(*Only* `MODE_CBC`, `MODE_CFB`, `MODE_OFB`, `MODE_OPENPGP`).
The initialization vector to use for encryption or decryption.
For `MODE_OPENPGP`, it must be 16 bytes long for encryption
and 18 bytes for decryption (in the latter case, it is
actually the *encrypted* IV which was prefixed to the ciphertext).
For all other modes, it must be 16 bytes long.
In not provided, a random byte string is used (you must then
read its value with the ``iv`` attribute).
nonce : byte string
(*Only* `MODE_CCM`, `MODE_EAX`, `MODE_GCM`, `MODE_SIV`, `MODE_OCB`,
`MODE_CTR`).
A value that must never be reused for any other encryption done
with this key.
For `MODE_CCM`, its length must be in the range ``[7..13]``.
Bear in mind that with CCM there is a trade-off between nonce
length and maximum message size.
For `MODE_OCB`, its length must be in the range ``[1..15]``.
For `MODE_CTR`, its length must be in the range ``[0..15]``.
For the other modes, there are no restrictions on its length.
The recommended length depends on the mode: 8 bytes for `MODE_CTR`,
11 bytes for `MODE_CCM`, 15 bytes for `MODE_OCB` and 16 bytes
for the remaining modes.
In not provided, a random byte string of the recommended
length is used (you must then read its value with the ``nonce`` attribute).
segment_size : integer
(*Only* `MODE_CFB`).The number of **bits** the plaintext and ciphertext
are segmented in. It must be a multiple of 8.
If not specified, it will be assumed to be 8.
mac_len : integer
(*Only* `MODE_EAX`, `MODE_GCM`, `MODE_OCB`, `MODE_CCM`)
Length of the authentication tag, in bytes.
It must be even and in the range ``[4..16]``.
The recommended value (and the default, if not specified) is 16.
msg_len : integer
(*Only* `MODE_CCM`). Length of the message to (de)cipher.
If not specified, ``encrypt`` must be called with the entire message.
Similarly, ``decrypt`` can only be called once.
assoc_len : integer
(*Only* `MODE_CCM`). Length of the associated data.
If not specified, all associated data is buffered internally,
which may represent a problem for very large messages.
initial_value : integer
(*Only* `MODE_CTR`). The initial value for the counter within
the counter block. By default it is 0.
use_aesni : boolean
Use Intel AES-NI hardware extensions if available.
:Return: an AES object, of the applicable mode:
- CBC_ mode
- CCM_ mode
- CFB_ mode
- CTR_ mode
- EAX_ mode
- ECB_ mode
- GCM_ mode
- OCB_ mode
- OFB_ mode
- OpenPgp_ mode
- SIV_ mode
.. _CBC: Cryptodome.Cipher._mode_cbc.CbcMode-class.html
.. _CCM: Cryptodome.Cipher._mode_ccm.CcmMode-class.html
.. _CFB: Cryptodome.Cipher._mode_cfb.CfbMode-class.html
.. _CTR: Cryptodome.Cipher._mode_ctr.CtrMode-class.html
.. _EAX: Cryptodome.Cipher._mode_eax.EaxMode-class.html
.. _ECB: Cryptodome.Cipher._mode_ecb.EcbMode-class.html
.. _GCM: Cryptodome.Cipher._mode_gcm.GcmMode-class.html
.. _OCB: Cryptodome.Cipher._mode_ocb.OcbMode-class.html
.. _OFB: Cryptodome.Cipher._mode_ofb.OfbMode-class.html
.. _OpenPgp: Cryptodome.Cipher._mode_openpgp.OpenPgpMode-class.html
.. _SIV: Cryptodome.Cipher._mode_siv.SivMode-class.html
|
new
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/AES.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/AES.py
|
MIT
|
def _create_base_cipher(dict_parameters):
"""This method instantiates and returns a handle to a low-level
base cipher. It will absorb named parameters in the process."""
try:
key = dict_parameters.pop("key")
except KeyError:
raise TypeError("Missing 'key' parameter")
effective_keylen = dict_parameters.pop("effective_keylen", 1024)
expect_byte_string(key)
if len(key) not in key_size:
raise ValueError("Incorrect ARC2 key length (%d bytes)" % len(key))
if not (40 < effective_keylen <= 1024):
raise ValueError("'effective_key_len' must be no larger than 1024 "
"(not %d)" % effective_keylen)
start_operation = _raw_arc2_lib.ARC2_start_operation
stop_operation = _raw_arc2_lib.ARC2_stop_operation
cipher = VoidPointer()
result = start_operation(key,
c_size_t(len(key)),
c_size_t(effective_keylen),
cipher.address_of())
if result:
raise ValueError("Error %X while instantiating the ARC2 cipher"
% result)
return SmartPointer(cipher.get(), stop_operation)
|
This method instantiates and returns a handle to a low-level
base cipher. It will absorb named parameters in the process.
|
_create_base_cipher
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/ARC2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/ARC2.py
|
MIT
|
def __init__(self, key, *args, **kwargs):
"""Initialize an ARC4 cipher object
See also `new()` at the module level."""
if len(args) > 0:
ndrop = args[0]
args = args[1:]
else:
ndrop = kwargs.pop('drop', 0)
if len(key) not in key_size:
raise ValueError("Incorrect ARC4 key length (%d bytes)" %
len(key))
expect_byte_string(key)
self._state = VoidPointer()
result = _raw_arc4_lib.ARC4_stream_init(key,
c_size_t(len(key)),
self._state.address_of())
if result != 0:
raise ValueError("Error %d while creating the ARC4 cipher"
% result)
self._state = SmartPointer(self._state.get(),
_raw_arc4_lib.ARC4_stream_destroy)
if ndrop > 0:
# This is OK even if the cipher is used for decryption,
# since encrypt and decrypt are actually the same thing
# with ARC4.
self.encrypt(b('\x00') * ndrop)
self.block_size = 1
self.key_size = len(key)
|
Initialize an ARC4 cipher object
See also `new()` at the module level.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/ARC4.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/ARC4.py
|
MIT
|
def encrypt(self, plaintext):
"""Encrypt a piece of data.
:Parameters:
plaintext : byte string
The piece of data to encrypt. It can be of any size.
:Return: the encrypted data (byte string, as long as the
plaintext).
"""
expect_byte_string(plaintext)
ciphertext = create_string_buffer(len(plaintext))
result = _raw_arc4_lib.ARC4_stream_encrypt(self._state.get(),
plaintext,
ciphertext,
c_size_t(len(plaintext)))
if result:
raise ValueError("Error %d while encrypting with RC4" % result)
return get_raw_buffer(ciphertext)
|
Encrypt a piece of data.
:Parameters:
plaintext : byte string
The piece of data to encrypt. It can be of any size.
:Return: the encrypted data (byte string, as long as the
plaintext).
|
encrypt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/ARC4.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/ARC4.py
|
MIT
|
def decrypt(self, ciphertext):
"""Decrypt a piece of data.
:Parameters:
ciphertext : byte string
The piece of data to decrypt. It can be of any size.
:Return: the decrypted data (byte string, as long as the
ciphertext).
"""
try:
return self.encrypt(ciphertext)
except ValueError, e:
raise ValueError(str(e).replace("enc", "dec"))
|
Decrypt a piece of data.
:Parameters:
ciphertext : byte string
The piece of data to decrypt. It can be of any size.
:Return: the decrypted data (byte string, as long as the
ciphertext).
|
decrypt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/ARC4.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/ARC4.py
|
MIT
|
def _create_base_cipher(dict_parameters):
"""This method instantiates and returns a smart pointer to
a low-level base cipher. It will absorb named parameters in
the process."""
try:
key = dict_parameters.pop("key")
except KeyError:
raise TypeError("Missing 'key' parameter")
expect_byte_string(key)
if len(key) not in key_size:
raise ValueError("Incorrect Blowfish key length (%d bytes)" % len(key))
start_operation = _raw_blowfish_lib.Blowfish_start_operation
stop_operation = _raw_blowfish_lib.Blowfish_stop_operation
void_p = VoidPointer()
result = start_operation(key, c_size_t(len(key)), void_p.address_of())
if result:
raise ValueError("Error %X while instantiating the Blowfish cipher"
% result)
return SmartPointer(void_p.get(), stop_operation)
|
This method instantiates and returns a smart pointer to
a low-level base cipher. It will absorb named parameters in
the process.
|
_create_base_cipher
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/Blowfish.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/Blowfish.py
|
MIT
|
def _create_base_cipher(dict_parameters):
"""This method instantiates and returns a handle to a low-level
base cipher. It will absorb named parameters in the process."""
try:
key = dict_parameters.pop("key")
except KeyError:
raise TypeError("Missing 'key' parameter")
expect_byte_string(key)
if len(key) not in key_size:
raise ValueError("Incorrect CAST key length (%d bytes)" % len(key))
start_operation = _raw_cast_lib.CAST_start_operation
stop_operation = _raw_cast_lib.CAST_stop_operation
cipher = VoidPointer()
result = start_operation(key,
c_size_t(len(key)),
cipher.address_of())
if result:
raise ValueError("Error %X while instantiating the CAST cipher"
% result)
return SmartPointer(cipher.get(), stop_operation)
|
This method instantiates and returns a handle to a low-level
base cipher. It will absorb named parameters in the process.
|
_create_base_cipher
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/CAST.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/CAST.py
|
MIT
|
def __init__(self, key, nonce):
"""Initialize a ChaCha20 cipher object
See also `new()` at the module level."""
expect_byte_string(key)
expect_byte_string(nonce)
self.nonce = nonce
self._next = ( self.encrypt, self.decrypt )
self._state = VoidPointer()
result = _raw_chacha20_lib.chacha20_init(
self._state.address_of(),
key,
c_size_t(len(key)),
nonce,
c_size_t(len(nonce)))
if result:
raise ValueError("Error %d instantiating a ChaCha20 cipher")
self._state = SmartPointer(self._state.get(),
_raw_chacha20_lib.chacha20_destroy)
|
Initialize a ChaCha20 cipher object
See also `new()` at the module level.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/ChaCha20.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/ChaCha20.py
|
MIT
|
def encrypt(self, plaintext):
"""Encrypt a piece of data.
:Parameters:
plaintext : byte string
The piece of data to encrypt. It can be of any size.
:Return: the encrypted data (byte string, as long as the
plaintext).
"""
if self.encrypt not in self._next:
raise TypeError("Cipher object can only be used for decryption")
self._next = ( self.encrypt, )
return self._encrypt(plaintext)
|
Encrypt a piece of data.
:Parameters:
plaintext : byte string
The piece of data to encrypt. It can be of any size.
:Return: the encrypted data (byte string, as long as the
plaintext).
|
encrypt
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Cipher/ChaCha20.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Cipher/ChaCha20.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.