repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
efortuna/AndroidSDKClone | refs/heads/master | ndk_experimental/prebuilt/linux-x86_64/lib/python2.7/test/test_locale.py | 72 | from test.test_support import run_unittest, verbose
import unittest
import locale
import sys
import codecs
enUS_locale = None
def get_enUS_locale():
global enUS_locale
if sys.platform == 'darwin':
import os
tlocs = ("en_US.UTF-8", "en_US.ISO8859-1", "en_US")
if int(os.uname()[2].split('.')[0]) < 10:
# The locale test work fine on OSX 10.6, I (ronaldoussoren)
# haven't had time yet to verify if tests work on OSX 10.5
# (10.4 is known to be bad)
raise unittest.SkipTest("Locale support on MacOSX is minimal")
if sys.platform.startswith("win"):
tlocs = ("En", "English")
else:
tlocs = ("en_US.UTF-8", "en_US.US-ASCII", "en_US")
oldlocale = locale.setlocale(locale.LC_NUMERIC)
for tloc in tlocs:
try:
locale.setlocale(locale.LC_NUMERIC, tloc)
except locale.Error:
continue
break
else:
raise unittest.SkipTest(
"Test locale not supported (tried %s)" % (', '.join(tlocs)))
enUS_locale = tloc
locale.setlocale(locale.LC_NUMERIC, oldlocale)
class BaseLocalizedTest(unittest.TestCase):
#
# Base class for tests using a real locale
#
def setUp(self):
self.oldlocale = locale.setlocale(self.locale_type)
locale.setlocale(self.locale_type, enUS_locale)
if verbose:
print "testing with \"%s\"..." % enUS_locale,
def tearDown(self):
locale.setlocale(self.locale_type, self.oldlocale)
class BaseCookedTest(unittest.TestCase):
#
# Base class for tests using cooked localeconv() values
#
def setUp(self):
locale._override_localeconv = self.cooked_values
def tearDown(self):
locale._override_localeconv = {}
class CCookedTest(BaseCookedTest):
# A cooked "C" locale
cooked_values = {
'currency_symbol': '',
'decimal_point': '.',
'frac_digits': 127,
'grouping': [],
'int_curr_symbol': '',
'int_frac_digits': 127,
'mon_decimal_point': '',
'mon_grouping': [],
'mon_thousands_sep': '',
'n_cs_precedes': 127,
'n_sep_by_space': 127,
'n_sign_posn': 127,
'negative_sign': '',
'p_cs_precedes': 127,
'p_sep_by_space': 127,
'p_sign_posn': 127,
'positive_sign': '',
'thousands_sep': ''
}
class EnUSCookedTest(BaseCookedTest):
# A cooked "en_US" locale
cooked_values = {
'currency_symbol': '$',
'decimal_point': '.',
'frac_digits': 2,
'grouping': [3, 3, 0],
'int_curr_symbol': 'USD ',
'int_frac_digits': 2,
'mon_decimal_point': '.',
'mon_grouping': [3, 3, 0],
'mon_thousands_sep': ',',
'n_cs_precedes': 1,
'n_sep_by_space': 0,
'n_sign_posn': 1,
'negative_sign': '-',
'p_cs_precedes': 1,
'p_sep_by_space': 0,
'p_sign_posn': 1,
'positive_sign': '',
'thousands_sep': ','
}
class FrFRCookedTest(BaseCookedTest):
# A cooked "fr_FR" locale with a space character as decimal separator
# and a non-ASCII currency symbol.
cooked_values = {
'currency_symbol': '\xe2\x82\xac',
'decimal_point': ',',
'frac_digits': 2,
'grouping': [3, 3, 0],
'int_curr_symbol': 'EUR ',
'int_frac_digits': 2,
'mon_decimal_point': ',',
'mon_grouping': [3, 3, 0],
'mon_thousands_sep': ' ',
'n_cs_precedes': 0,
'n_sep_by_space': 1,
'n_sign_posn': 1,
'negative_sign': '-',
'p_cs_precedes': 0,
'p_sep_by_space': 1,
'p_sign_posn': 1,
'positive_sign': '',
'thousands_sep': ' '
}
class BaseFormattingTest(object):
#
# Utility functions for formatting tests
#
def _test_formatfunc(self, format, value, out, func, **format_opts):
self.assertEqual(
func(format, value, **format_opts), out)
def _test_format(self, format, value, out, **format_opts):
self._test_formatfunc(format, value, out,
func=locale.format, **format_opts)
def _test_format_string(self, format, value, out, **format_opts):
self._test_formatfunc(format, value, out,
func=locale.format_string, **format_opts)
def _test_currency(self, value, out, **format_opts):
self.assertEqual(locale.currency(value, **format_opts), out)
class EnUSNumberFormatting(BaseFormattingTest):
# XXX there is a grouping + padding bug when the thousands separator
# is empty but the grouping array contains values (e.g. Solaris 10)
def setUp(self):
self.sep = locale.localeconv()['thousands_sep']
def test_grouping(self):
self._test_format("%f", 1024, grouping=1, out='1%s024.000000' % self.sep)
self._test_format("%f", 102, grouping=1, out='102.000000')
self._test_format("%f", -42, grouping=1, out='-42.000000')
self._test_format("%+f", -42, grouping=1, out='-42.000000')
def test_grouping_and_padding(self):
self._test_format("%20.f", -42, grouping=1, out='-42'.rjust(20))
if self.sep:
self._test_format("%+10.f", -4200, grouping=1,
out=('-4%s200' % self.sep).rjust(10))
self._test_format("%-10.f", -4200, grouping=1,
out=('-4%s200' % self.sep).ljust(10))
def test_integer_grouping(self):
self._test_format("%d", 4200, grouping=True, out='4%s200' % self.sep)
self._test_format("%+d", 4200, grouping=True, out='+4%s200' % self.sep)
self._test_format("%+d", -4200, grouping=True, out='-4%s200' % self.sep)
def test_integer_grouping_and_padding(self):
self._test_format("%10d", 4200, grouping=True,
out=('4%s200' % self.sep).rjust(10))
self._test_format("%-10d", -4200, grouping=True,
out=('-4%s200' % self.sep).ljust(10))
def test_simple(self):
self._test_format("%f", 1024, grouping=0, out='1024.000000')
self._test_format("%f", 102, grouping=0, out='102.000000')
self._test_format("%f", -42, grouping=0, out='-42.000000')
self._test_format("%+f", -42, grouping=0, out='-42.000000')
def test_padding(self):
self._test_format("%20.f", -42, grouping=0, out='-42'.rjust(20))
self._test_format("%+10.f", -4200, grouping=0, out='-4200'.rjust(10))
self._test_format("%-10.f", 4200, grouping=0, out='4200'.ljust(10))
def test_complex_formatting(self):
# Spaces in formatting string
self._test_format_string("One million is %i", 1000000, grouping=1,
out='One million is 1%s000%s000' % (self.sep, self.sep))
self._test_format_string("One million is %i", 1000000, grouping=1,
out='One million is 1%s000%s000' % (self.sep, self.sep))
# Dots in formatting string
self._test_format_string(".%f.", 1000.0, out='.1000.000000.')
# Padding
if self.sep:
self._test_format_string("--> %10.2f", 4200, grouping=1,
out='--> ' + ('4%s200.00' % self.sep).rjust(10))
# Asterisk formats
self._test_format_string("%10.*f", (2, 1000), grouping=0,
out='1000.00'.rjust(10))
if self.sep:
self._test_format_string("%*.*f", (10, 2, 1000), grouping=1,
out=('1%s000.00' % self.sep).rjust(10))
# Test more-in-one
if self.sep:
self._test_format_string("int %i float %.2f str %s",
(1000, 1000.0, 'str'), grouping=1,
out='int 1%s000 float 1%s000.00 str str' %
(self.sep, self.sep))
class TestFormatPatternArg(unittest.TestCase):
# Test handling of pattern argument of format
def test_onlyOnePattern(self):
# Issue 2522: accept exactly one % pattern, and no extra chars.
self.assertRaises(ValueError, locale.format, "%f\n", 'foo')
self.assertRaises(ValueError, locale.format, "%f\r", 'foo')
self.assertRaises(ValueError, locale.format, "%f\r\n", 'foo')
self.assertRaises(ValueError, locale.format, " %f", 'foo')
self.assertRaises(ValueError, locale.format, "%fg", 'foo')
self.assertRaises(ValueError, locale.format, "%^g", 'foo')
self.assertRaises(ValueError, locale.format, "%f%%", 'foo')
class TestLocaleFormatString(unittest.TestCase):
"""General tests on locale.format_string"""
def test_percent_escape(self):
self.assertEqual(locale.format_string('%f%%', 1.0), '%f%%' % 1.0)
self.assertEqual(locale.format_string('%d %f%%d', (1, 1.0)),
'%d %f%%d' % (1, 1.0))
self.assertEqual(locale.format_string('%(foo)s %%d', {'foo': 'bar'}),
('%(foo)s %%d' % {'foo': 'bar'}))
def test_mapping(self):
self.assertEqual(locale.format_string('%(foo)s bing.', {'foo': 'bar'}),
('%(foo)s bing.' % {'foo': 'bar'}))
self.assertEqual(locale.format_string('%(foo)s', {'foo': 'bar'}),
('%(foo)s' % {'foo': 'bar'}))
class TestNumberFormatting(BaseLocalizedTest, EnUSNumberFormatting):
# Test number formatting with a real English locale.
locale_type = locale.LC_NUMERIC
def setUp(self):
BaseLocalizedTest.setUp(self)
EnUSNumberFormatting.setUp(self)
class TestEnUSNumberFormatting(EnUSCookedTest, EnUSNumberFormatting):
# Test number formatting with a cooked "en_US" locale.
def setUp(self):
EnUSCookedTest.setUp(self)
EnUSNumberFormatting.setUp(self)
def test_currency(self):
self._test_currency(50000, "$50000.00")
self._test_currency(50000, "$50,000.00", grouping=True)
self._test_currency(50000, "USD 50,000.00",
grouping=True, international=True)
class TestCNumberFormatting(CCookedTest, BaseFormattingTest):
# Test number formatting with a cooked "C" locale.
def test_grouping(self):
self._test_format("%.2f", 12345.67, grouping=True, out='12345.67')
def test_grouping_and_padding(self):
self._test_format("%9.2f", 12345.67, grouping=True, out=' 12345.67')
class TestFrFRNumberFormatting(FrFRCookedTest, BaseFormattingTest):
# Test number formatting with a cooked "fr_FR" locale.
def test_decimal_point(self):
self._test_format("%.2f", 12345.67, out='12345,67')
def test_grouping(self):
self._test_format("%.2f", 345.67, grouping=True, out='345,67')
self._test_format("%.2f", 12345.67, grouping=True, out='12 345,67')
def test_grouping_and_padding(self):
self._test_format("%6.2f", 345.67, grouping=True, out='345,67')
self._test_format("%7.2f", 345.67, grouping=True, out=' 345,67')
self._test_format("%8.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%9.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%10.2f", 12345.67, grouping=True, out=' 12 345,67')
self._test_format("%-6.2f", 345.67, grouping=True, out='345,67')
self._test_format("%-7.2f", 345.67, grouping=True, out='345,67 ')
self._test_format("%-8.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%-9.2f", 12345.67, grouping=True, out='12 345,67')
self._test_format("%-10.2f", 12345.67, grouping=True, out='12 345,67 ')
def test_integer_grouping(self):
self._test_format("%d", 200, grouping=True, out='200')
self._test_format("%d", 4200, grouping=True, out='4 200')
def test_integer_grouping_and_padding(self):
self._test_format("%4d", 4200, grouping=True, out='4 200')
self._test_format("%5d", 4200, grouping=True, out='4 200')
self._test_format("%10d", 4200, grouping=True, out='4 200'.rjust(10))
self._test_format("%-4d", 4200, grouping=True, out='4 200')
self._test_format("%-5d", 4200, grouping=True, out='4 200')
self._test_format("%-10d", 4200, grouping=True, out='4 200'.ljust(10))
def test_currency(self):
euro = u'\u20ac'.encode('utf-8')
self._test_currency(50000, "50000,00 " + euro)
self._test_currency(50000, "50 000,00 " + euro, grouping=True)
# XXX is the trailing space a bug?
self._test_currency(50000, "50 000,00 EUR ",
grouping=True, international=True)
class TestStringMethods(BaseLocalizedTest):
locale_type = locale.LC_CTYPE
if sys.platform != 'sunos5' and not sys.platform.startswith("win"):
# Test BSD Rune locale's bug for isctype functions.
def test_isspace(self):
self.assertEqual('\x20'.isspace(), True)
self.assertEqual('\xa0'.isspace(), False)
self.assertEqual('\xa1'.isspace(), False)
def test_isalpha(self):
self.assertEqual('\xc0'.isalpha(), False)
def test_isalnum(self):
self.assertEqual('\xc0'.isalnum(), False)
def test_isupper(self):
self.assertEqual('\xc0'.isupper(), False)
def test_islower(self):
self.assertEqual('\xc0'.islower(), False)
def test_lower(self):
self.assertEqual('\xcc\x85'.lower(), '\xcc\x85')
def test_upper(self):
self.assertEqual('\xed\x95\xa0'.upper(), '\xed\x95\xa0')
def test_strip(self):
self.assertEqual('\xed\x95\xa0'.strip(), '\xed\x95\xa0')
def test_split(self):
self.assertEqual('\xec\xa0\xbc'.split(), ['\xec\xa0\xbc'])
class TestMiscellaneous(unittest.TestCase):
def test_getpreferredencoding(self):
# Invoke getpreferredencoding to make sure it does not cause exceptions.
enc = locale.getpreferredencoding()
if enc:
# If encoding non-empty, make sure it is valid
codecs.lookup(enc)
if hasattr(locale, "strcoll"):
def test_strcoll_3303(self):
# test crasher from bug #3303
self.assertRaises(TypeError, locale.strcoll, u"a", None)
def test_setlocale_category(self):
locale.setlocale(locale.LC_ALL)
locale.setlocale(locale.LC_TIME)
locale.setlocale(locale.LC_CTYPE)
locale.setlocale(locale.LC_COLLATE)
locale.setlocale(locale.LC_MONETARY)
locale.setlocale(locale.LC_NUMERIC)
# crasher from bug #7419
self.assertRaises(locale.Error, locale.setlocale, 12345)
def test_getsetlocale_issue1813(self):
# Issue #1813: setting and getting the locale under a Turkish locale
oldlocale = locale.getlocale()
self.addCleanup(locale.setlocale, locale.LC_CTYPE, oldlocale)
try:
locale.setlocale(locale.LC_CTYPE, 'tr_TR')
except locale.Error:
# Unsupported locale on this system
self.skipTest('test needs Turkish locale')
loc = locale.getlocale()
locale.setlocale(locale.LC_CTYPE, loc)
self.assertEqual(loc, locale.getlocale())
def test_normalize_issue12752(self):
# Issue #1813 caused a regression where locale.normalize() would no
# longer accept unicode strings.
self.assertEqual(locale.normalize(u'en_US'), 'en_US.ISO8859-1')
def test_main():
tests = [
TestMiscellaneous,
TestFormatPatternArg,
TestLocaleFormatString,
TestEnUSNumberFormatting,
TestCNumberFormatting,
TestFrFRNumberFormatting,
]
# SkipTest can't be raised inside unittests, handle it manually instead
try:
get_enUS_locale()
except unittest.SkipTest as e:
if verbose:
print "Some tests will be disabled: %s" % e
else:
tests += [TestNumberFormatting, TestStringMethods]
run_unittest(*tests)
if __name__ == '__main__':
test_main()
|
sudkannan/xen-hv | refs/heads/master | dist/install/usr/lib64/python2.6/site-packages/xen/web/connection.py | 44 | #============================================================================
# This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2005 Mike Wray <mike.wray@hp.com>
# Copyright (C) 2005 XenSource Ltd.
#============================================================================
import sys
import os
import threading
import socket
import fcntl
from errno import EAGAIN, EINTR, EWOULDBLOCK
try:
from OpenSSL import SSL
except ImportError:
pass
from xen.xend.XendLogging import log
"""General classes to support server and client sockets, without
specifying what kind of socket they are. There are subclasses
for TCP and unix-domain sockets (see tcp.py and unix.py).
"""
BUFFER_SIZE = 16384
BACKLOG = 5
class SocketServerConnection:
"""An accepted connection to a server.
"""
def __init__(self, sock, protocol_class):
self.sock = sock
self.protocol = protocol_class()
self.protocol.setTransport(self)
threading.Thread(target=self.main).start()
def main(self):
try:
while True:
try:
data = self.sock.recv(BUFFER_SIZE)
if data == '':
break
if self.protocol.dataReceived(data):
break
except socket.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
break
finally:
try:
self.sock.close()
except:
pass
def close(self):
self.sock.close()
def write(self, data):
self.sock.send(data)
class SocketListener:
"""A server socket, running listen in a thread.
Accepts connections and runs a thread for each one.
"""
def __init__(self, protocol_class):
self.protocol_class = protocol_class
self.sock = self.createSocket()
threading.Thread(target=self.main).start()
def close(self):
try:
self.sock.close()
except:
pass
def createSocket(self):
raise NotImplementedError()
def acceptConnection(self, sock, protocol, addr):
raise NotImplementedError()
def main(self):
try:
fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)
self.sock.listen(BACKLOG)
while True:
try:
(sock, addr) = self.sock.accept()
self.acceptConnection(sock, addr)
except socket.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
break
finally:
self.close()
class SSLSocketServerConnection(SocketServerConnection):
"""An SSL aware accepted connection to a server.
As pyOpenSSL SSL.Connection fileno() method just retrieve the file
descriptor number for the underlying socket, direct read/write to the file
descriptor will result no data encrypted.
recv2fd() and fd2send() are simple wrappers for functions who need direct
read/write to a file descriptor rather than a socket like object.
To use recv2fd(), you can create a pipe and start a thread to transfer all
received data to one end of the pipe, then read from the other end:
p2cread, p2cwrite = os.pipe()
threading.Thread(target=connection.SSLSocketServerConnection.recv2fd,
args=(sock, p2cwrite)).start()
os.read(p2cread, 1024)
To use fd2send():
p2cread, p2cwrite = os.pipe()
threading.Thread(target=connection.SSLSocketServerConnection.fd2send,
args=(sock, p2cread)).start()
os.write(p2cwrite, "data")
"""
def __init__(self, sock, protocol_class):
SocketServerConnection.__init__(self, sock, protocol_class)
def main(self):
try:
while True:
try:
data = self.sock.recv(BUFFER_SIZE)
if data == "":
break
if self.protocol.dataReceived(data):
break
except socket.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
break
except (SSL.WantReadError, SSL.WantWriteError, \
SSL.WantX509LookupError):
# The operation did not complete; the same I/O method
# should be called again.
continue
except SSL.ZeroReturnError:
# The SSL Connection has been closed.
break
except SSL.SysCallError, (retval, desc):
if ((retval == -1 and desc == "Unexpected EOF")
or retval > 0):
# The SSL Connection is lost.
break
log.debug("SSL SysCallError:%d:%s" % (retval, desc))
break
except SSL.Error, e:
# other SSL errors
log.debug("SSL Error:%s" % e)
break
finally:
try:
self.sock.close()
except:
pass
def recv2fd(sock, fd):
try:
while True:
try:
data = sock.recv(BUFFER_SIZE)
if data == "":
break
count = 0
while count < len(data):
try:
nbytes = os.write(fd, data[count:])
count += nbytes
except os.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
raise
except socket.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
break
except (SSL.WantReadError, SSL.WantWriteError, \
SSL.WantX509LookupError):
# The operation did not complete; the same I/O method
# should be called again.
continue
except SSL.ZeroReturnError:
# The SSL Connection has been closed.
break
except SSL.SysCallError, (retval, desc):
if ((retval == -1 and desc == "Unexpected EOF")
or retval > 0):
# The SSL Connection is lost.
break
log.debug("SSL SysCallError:%d:%s" % (retval, desc))
break
except SSL.Error, e:
# other SSL errors
log.debug("SSL Error:%s" % e)
break
finally:
try:
sock.close()
os.close(fd)
except:
pass
recv2fd = staticmethod(recv2fd)
def fd2send(sock, fd):
try:
while True:
try:
data = os.read(fd, BUFFER_SIZE)
if data == "":
break
count = 0
while count < len(data):
try:
nbytes = sock.send(data[count:])
count += nbytes
except socket.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
raise
except (SSL.WantReadError, SSL.WantWriteError, \
SSL.WantX509LookupError):
# The operation did not complete; the same I/O method
# should be called again.
continue
except SSL.ZeroReturnError:
# The SSL Connection has been closed.
raise
except SSL.SysCallError, (retval, desc):
if not (retval == -1 and data == ""):
# errors when writing empty strings are expected
# and can be ignored
log.debug("SSL SysCallError:%d:%s" % (retval, desc))
raise
except SSL.Error, e:
# other SSL errors
log.debug("SSL Error:%s" % e)
raise
except os.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
break
finally:
try:
sock.close()
os.close(fd)
except:
pass
fd2send = staticmethod(fd2send)
def hostAllowed(addrport, hosts_allowed):
if hosts_allowed is None:
return True
else:
fqdn = socket.getfqdn(addrport[0])
for h in hosts_allowed:
if h.match(fqdn) or h.match(addrport[0]):
return True
log.warn("Rejected connection from %s (%s).", addrport[0], fqdn)
return False
class SocketDgramListener:
"""A connectionless server socket, running listen in a thread.
"""
def __init__(self, protocol_class):
self.protocol = protocol_class()
self.sock = self.createSocket()
threading.Thread(target=self.main).start()
def close(self):
try:
self.sock.close()
except:
pass
def createSocket(self):
raise NotImplementedError()
def main(self):
try:
fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, fcntl.FD_CLOEXEC)
while True:
try:
data = self.sock.recv(BUFFER_SIZE)
self.protocol.dataReceived(data)
except socket.error, ex:
if ex.args[0] not in (EWOULDBLOCK, EAGAIN, EINTR):
break
finally:
try:
self.close()
except:
pass
|
sebastic/QGIS | refs/heads/master | tests/src/python/test_qgsgeometry.py | 2 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsGeometry.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Tim Sutton'
__date__ = '20/08/2012'
__copyright__ = 'Copyright 2012, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
import csv
from qgis.core import (
QgsGeometry,
QgsVectorLayer,
QgsFeature,
QgsPoint,
QgsPointV2,
QgsCoordinateTransform,
QgsRectangle,
QgsWKBTypes,
QGis
)
from qgis.testing import (
start_app,
unittest,
)
from utilities import(
compareWkt,
doubleNear,
unitTestDataPath,
writeShape
)
# Convenience instances in case you may need them not used in this test
start_app()
TEST_DATA_DIR = unitTestDataPath()
class TestQgsGeometry(unittest.TestCase):
def testWktPointLoading(self):
myWKT = 'Point (10 10)'
myGeometry = QgsGeometry.fromWkt(myWKT)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.WKBPoint, myGeometry.type()))
assert myGeometry.wkbType() == QGis.WKBPoint, myMessage
def testWktMultiPointLoading(self):
# Standard format
wkt = 'MultiPoint ((10 15),(20 30))'
geom = QgsGeometry.fromWkt(wkt)
assert geom.wkbType() == QGis.WKBMultiPoint, ('Expected:\n%s\nGot:\n%s\n' % (QGis.WKBPoint, geom.type()))
assert geom.geometry().numGeometries() == 2
assert geom.geometry().geometryN(0).x() == 10
assert geom.geometry().geometryN(0).y() == 15
assert geom.geometry().geometryN(1).x() == 20
assert geom.geometry().geometryN(1).y() == 30
# Check MS SQL format
wkt = 'MultiPoint (11 16, 21 31)'
geom = QgsGeometry.fromWkt(wkt)
assert geom.wkbType() == QGis.WKBMultiPoint, ('Expected:\n%s\nGot:\n%s\n' % (QGis.WKBPoint, geom.type()))
assert geom.geometry().numGeometries() == 2
assert geom.geometry().geometryN(0).x() == 11
assert geom.geometry().geometryN(0).y() == 16
assert geom.geometry().geometryN(1).x() == 21
assert geom.geometry().geometryN(1).y() == 31
def testFromPoint(self):
myPoint = QgsGeometry.fromPoint(QgsPoint(10, 10))
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.WKBPoint, myPoint.type()))
assert myPoint.wkbType() == QGis.WKBPoint, myMessage
def testFromMultiPoint(self):
myMultiPoint = QgsGeometry.fromMultiPoint([
(QgsPoint(0, 0)), (QgsPoint(1, 1))])
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.WKBMultiPoint, myMultiPoint.type()))
assert myMultiPoint.wkbType() == QGis.WKBMultiPoint, myMessage
def testFromLine(self):
myLine = QgsGeometry.fromPolyline([QgsPoint(1, 1), QgsPoint(2, 2)])
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.WKBLineString, myLine.type()))
assert myLine.wkbType() == QGis.WKBLineString, myMessage
def testFromMultiLine(self):
myMultiPolyline = QgsGeometry.fromMultiPolyline(
[[QgsPoint(0, 0), QgsPoint(1, 1)], [QgsPoint(0, 1), QgsPoint(2, 1)]])
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.WKBMultiLineString, myMultiPolyline.type()))
assert myMultiPolyline.wkbType() == QGis.WKBMultiLineString, myMessage
def testFromPolygon(self):
myPolygon = QgsGeometry.fromPolygon(
[[QgsPoint(1, 1), QgsPoint(2, 2), QgsPoint(1, 2), QgsPoint(1, 1)]])
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.WKBPolygon, myPolygon.type()))
assert myPolygon.wkbType() == QGis.WKBPolygon, myMessage
def testFromMultiPolygon(self):
myMultiPolygon = QgsGeometry.fromMultiPolygon([
[[QgsPoint(1, 1),
QgsPoint(2, 2),
QgsPoint(1, 2),
QgsPoint(1, 1)]],
[[QgsPoint(2, 2),
QgsPoint(3, 3),
QgsPoint(3, 1),
QgsPoint(2, 2)]]
])
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.WKBMultiPolygon, myMultiPolygon.type()))
assert myMultiPolygon.wkbType() == QGis.WKBMultiPolygon, myMessage
def testReferenceGeometry(self):
""" Test parsing a whole range of valid reference wkt formats and variants, and checking
expected values such as length, area, centroids, bounding boxes, etc of the resultant geometry.
Note the bulk of this test data was taken from the PostGIS WKT test data """
with open(os.path.join(TEST_DATA_DIR, 'geom_data.csv'), 'rb') as f:
reader = csv.DictReader(f)
for i, row in enumerate(reader):
# test that geometry can be created from WKT
geom = QgsGeometry.fromWkt(row['wkt'])
if row['valid_wkt']:
assert geom, "WKT conversion {} failed: could not create geom:\n{}\n".format(i + 1, row['wkt'])
else:
assert not geom, "Corrupt WKT {} was incorrectly converted to geometry:\n{}\n".format(i + 1, row['wkt'])
continue
# test exporting to WKT results in expected string
result = geom.exportToWkt()
exp = row['valid_wkt']
assert compareWkt(result, exp, 0.000001), "WKT conversion {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
# test num points in geometry
exp_nodes = int(row['num_points'])
assert geom.geometry().nCoordinates() == exp_nodes, "Node count {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp_nodes, geom.geometry().nCoordinates())
# test num geometries in collections
exp_geometries = int(row['num_geometries'])
try:
assert geom.geometry().numGeometries() == exp_geometries, "Geometry count {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp_geometries, geom.geometry().numGeometries())
except:
# some geometry types don't have numGeometries()
assert exp_geometries <= 1, "Geometry count {}: Expected:\n{} geometries but could not call numGeometries()\n".format(i + 1, exp_geometries)
# test count of rings
exp_rings = int(row['num_rings'])
try:
assert geom.geometry().numInteriorRings() == exp_rings, "Ring count {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp_rings, geom.geometry().numInteriorRings())
except:
# some geometry types don't have numInteriorRings()
assert exp_rings <= 1, "Ring count {}: Expected:\n{} rings but could not call numInteriorRings()\n{}".format(i + 1, exp_rings, geom.geometry())
# test isClosed
exp = (row['is_closed'] == '1')
try:
assert geom.geometry().isClosed() == exp, "isClosed {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, True, geom.geometry().isClosed())
except:
# some geometry types don't have isClosed()
assert not exp, "isClosed {}: Expected:\n isClosed() but could not call isClosed()\n".format(i + 1)
# test geometry centroid
exp = row['centroid']
result = geom.centroid().exportToWkt()
assert compareWkt(result, exp), "Centroid {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
# test bounding box limits
bbox = geom.geometry().boundingBox()
exp = float(row['x_min'])
result = bbox.xMinimum()
assert doubleNear(result, exp), "Min X {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
exp = float(row['y_min'])
result = bbox.yMinimum()
assert doubleNear(result, exp), "Min Y {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
exp = float(row['x_max'])
result = bbox.xMaximum()
assert doubleNear(result, exp), "Max X {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
exp = float(row['y_max'])
result = bbox.yMaximum()
assert doubleNear(result, exp), "Max Y {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
# test area calculation
exp = float(row['area'])
result = geom.geometry().area()
assert doubleNear(result, exp), "Area {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
# test length calculation
exp = float(row['length'])
result = geom.geometry().length()
assert doubleNear(result, exp, 0.00001), "Length {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
# test perimeter calculation
exp = float(row['perimeter'])
result = geom.geometry().perimeter()
assert doubleNear(result, exp, 0.00001), "Perimeter {}: mismatch Expected:\n{}\nGot:\n{}\n".format(i + 1, exp, result)
def testIntersection(self):
myLine = QgsGeometry.fromPolyline([
QgsPoint(0, 0),
QgsPoint(1, 1),
QgsPoint(2, 2)])
myPoint = QgsGeometry.fromPoint(QgsPoint(1, 1))
intersectionGeom = QgsGeometry.intersection(myLine, myPoint)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.Point, intersectionGeom.type()))
assert intersectionGeom.wkbType() == QGis.WKBPoint, myMessage
layer = QgsVectorLayer("Point", "intersection", "memory")
assert layer.isValid(), "Failed to create valid point memory layer"
provider = layer.dataProvider()
ft = QgsFeature()
ft.setGeometry(intersectionGeom)
provider.addFeatures([ft])
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(1, layer.featureCount()))
assert layer.featureCount() == 1, myMessage
def testBuffer(self):
myPoint = QgsGeometry.fromPoint(QgsPoint(1, 1))
bufferGeom = myPoint.buffer(10, 5)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
(QGis.Polygon, bufferGeom.type()))
assert bufferGeom.wkbType() == QGis.WKBPolygon, myMessage
myTestPoint = QgsGeometry.fromPoint(QgsPoint(3, 3))
assert bufferGeom.intersects(myTestPoint)
def testContains(self):
myPoly = QgsGeometry.fromPolygon(
[[QgsPoint(0, 0),
QgsPoint(2, 0),
QgsPoint(2, 2),
QgsPoint(0, 2),
QgsPoint(0, 0)]])
myPoint = QgsGeometry.fromPoint(QgsPoint(1, 1))
containsGeom = QgsGeometry.contains(myPoly, myPoint)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", containsGeom))
assert containsGeom, myMessage
def testTouches(self):
myLine = QgsGeometry.fromPolyline([
QgsPoint(0, 0),
QgsPoint(1, 1),
QgsPoint(2, 2)])
myPoly = QgsGeometry.fromPolygon([[
QgsPoint(0, 0),
QgsPoint(1, 1),
QgsPoint(2, 0),
QgsPoint(0, 0)]])
touchesGeom = QgsGeometry.touches(myLine, myPoly)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", touchesGeom))
assert touchesGeom, myMessage
def testOverlaps(self):
myPolyA = QgsGeometry.fromPolygon([[
QgsPoint(0, 0),
QgsPoint(1, 3),
QgsPoint(2, 0),
QgsPoint(0, 0)]])
myPolyB = QgsGeometry.fromPolygon([[
QgsPoint(0, 0),
QgsPoint(2, 0),
QgsPoint(2, 2),
QgsPoint(0, 2),
QgsPoint(0, 0)]])
overlapsGeom = QgsGeometry.overlaps(myPolyA, myPolyB)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", overlapsGeom))
assert overlapsGeom, myMessage
def testWithin(self):
myLine = QgsGeometry.fromPolyline([
QgsPoint(0.5, 0.5),
QgsPoint(1, 1),
QgsPoint(1.5, 1.5)
])
myPoly = QgsGeometry.fromPolygon([[
QgsPoint(0, 0),
QgsPoint(2, 0),
QgsPoint(2, 2),
QgsPoint(0, 2),
QgsPoint(0, 0)]])
withinGeom = QgsGeometry.within(myLine, myPoly)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", withinGeom))
assert withinGeom, myMessage
def testEquals(self):
myPointA = QgsGeometry.fromPoint(QgsPoint(1, 1))
myPointB = QgsGeometry.fromPoint(QgsPoint(1, 1))
equalsGeom = QgsGeometry.equals(myPointA, myPointB)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", equalsGeom))
assert equalsGeom, myMessage
def testCrosses(self):
myLine = QgsGeometry.fromPolyline([
QgsPoint(0, 0),
QgsPoint(1, 1),
QgsPoint(3, 3)])
myPoly = QgsGeometry.fromPolygon([[
QgsPoint(1, 0),
QgsPoint(2, 0),
QgsPoint(2, 2),
QgsPoint(1, 2),
QgsPoint(1, 0)]])
crossesGeom = QgsGeometry.crosses(myLine, myPoly)
myMessage = ('Expected:\n%s\nGot:\n%s\n' %
("True", crossesGeom))
assert crossesGeom, myMessage
def testSimplifyIssue4189(self):
"""Test we can simplify a complex geometry.
Note: there is a ticket related to this issue here:
http://hub.qgis.org/issues/4189
Backstory: Ole Nielson pointed out an issue to me
(Tim Sutton) where simplify ftools was dropping
features. This test replicates that issues.
Interestingly we could replicate the issue in PostGIS too:
- doing straight simplify returned no feature
- transforming to UTM49, then simplify with e.g. 200 threshold is ok
- as above with 500 threshold drops the feature
pgsql2shp -f /tmp/dissolve500.shp gis 'select *,
transform(simplify(transform(geom,32649),500), 4326) as
simplegeom from dissolve;'
"""
myWKTFile = file(os.path.join(unitTestDataPath('wkt'),
'simplify_error.wkt'), 'rt')
myWKT = myWKTFile.readline()
myWKTFile.close()
# print myWKT
myGeometry = QgsGeometry().fromWkt(myWKT)
assert myGeometry is not None
myStartLength = len(myWKT)
myTolerance = 0.00001
mySimpleGeometry = myGeometry.simplify(myTolerance)
myEndLength = len(mySimpleGeometry.exportToWkt())
myMessage = 'Before simplify: %i\nAfter simplify: %i\n : Tolerance %e' % (
myStartLength, myEndLength, myTolerance)
myMinimumLength = len('Polygon(())')
assert myEndLength > myMinimumLength, myMessage
def testClipping(self):
"""Test that we can clip geometries using other geometries."""
myMemoryLayer = QgsVectorLayer(
('LineString?crs=epsg:4326&field=name:string(20)&index=yes'),
'clip-in',
'memory')
assert myMemoryLayer is not None, 'Provider not initialised'
myProvider = myMemoryLayer.dataProvider()
assert myProvider is not None
myFeature1 = QgsFeature()
myFeature1.setGeometry(QgsGeometry.fromPolyline([
QgsPoint(10, 10),
QgsPoint(20, 10),
QgsPoint(30, 10),
QgsPoint(40, 10),
]))
myFeature1.setAttributes(['Johny'])
myFeature2 = QgsFeature()
myFeature2.setGeometry(QgsGeometry.fromPolyline([
QgsPoint(10, 10),
QgsPoint(20, 20),
QgsPoint(30, 30),
QgsPoint(40, 40),
]))
myFeature2.setAttributes(['Be'])
myFeature3 = QgsFeature()
myFeature3.setGeometry(QgsGeometry.fromPolyline([
QgsPoint(10, 10),
QgsPoint(10, 20),
QgsPoint(10, 30),
QgsPoint(10, 40),
]))
myFeature3.setAttributes(['Good'])
myResult, myFeatures = myProvider.addFeatures(
[myFeature1, myFeature2, myFeature3])
assert myResult
assert len(myFeatures) == 3
myClipPolygon = QgsGeometry.fromPolygon([[
QgsPoint(20, 20),
QgsPoint(20, 30),
QgsPoint(30, 30),
QgsPoint(30, 20),
QgsPoint(20, 20),
]])
print 'Clip: %s' % myClipPolygon.exportToWkt()
writeShape(myMemoryLayer, 'clipGeometryBefore.shp')
fit = myProvider.getFeatures()
myFeatures = []
myFeature = QgsFeature()
while fit.nextFeature(myFeature):
myGeometry = myFeature.geometry()
if myGeometry.intersects(myClipPolygon):
# Adds nodes where the clip and the line intersec
myCombinedGeometry = myGeometry.combine(myClipPolygon)
# Gives you the areas inside the clip
mySymmetricalGeometry = myGeometry.symDifference(
myCombinedGeometry)
# Gives you areas outside the clip area
# myDifferenceGeometry = myCombinedGeometry.difference(
# myClipPolygon)
# print 'Original: %s' % myGeometry.exportToWkt()
# print 'Combined: %s' % myCombinedGeometry.exportToWkt()
# print 'Difference: %s' % myDifferenceGeometry.exportToWkt()
print 'Symmetrical: %s' % mySymmetricalGeometry.exportToWkt()
myExpectedWkt = 'Polygon ((20 20, 20 30, 30 30, 30 20, 20 20))'
# There should only be one feature that intersects this clip
# poly so this assertion should work.
assert compareWkt(myExpectedWkt,
mySymmetricalGeometry.exportToWkt())
myNewFeature = QgsFeature()
myNewFeature.setAttributes(myFeature.attributes())
myNewFeature.setGeometry(mySymmetricalGeometry)
myFeatures.append(myNewFeature)
myNewMemoryLayer = QgsVectorLayer(
('LineString?crs=epsg:4326&field=name:string(20)&index=yes'),
'clip-out',
'memory')
myNewProvider = myNewMemoryLayer.dataProvider()
myResult, myFeatures = myNewProvider.addFeatures(myFeatures)
self.assertTrue(myResult)
self.assertEqual(len(myFeatures), 1)
writeShape(myNewMemoryLayer, 'clipGeometryAfter.shp')
def testClosestVertex(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
polyline = QgsGeometry.fromPolyline(
[QgsPoint(5, 0), QgsPoint(0, 0), QgsPoint(0, 4), QgsPoint(5, 4), QgsPoint(5, 1), QgsPoint(1, 1), QgsPoint(1, 3), QgsPoint(4, 3), QgsPoint(4, 2), QgsPoint(2, 2)]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPoint(6, 1))
self.assertEqual(point, QgsPoint(5, 1))
self.assertEqual(beforeVertex, 3)
self.assertEqual(atVertex, 4)
self.assertEqual(afterVertex, 5)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex) = polyline.closestSegmentWithContext(QgsPoint(6, 2))
self.assertEqual(dist, 1)
self.assertEqual(minDistPoint, QgsPoint(5, 2))
self.assertEqual(afterVertex, 4)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPoint(6, 0))
self.assertEqual(point, QgsPoint(5, 0))
self.assertEqual(beforeVertex, -1)
self.assertEqual(atVertex, 0)
self.assertEqual(afterVertex, 1)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex) = polyline.closestSegmentWithContext(QgsPoint(6, 0))
self.assertEqual(dist, 1)
self.assertEqual(minDistPoint, QgsPoint(5, 0))
self.assertEqual(afterVertex, 1)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPoint(0, -1))
self.assertEqual(point, QgsPoint(0, 0))
self.assertEqual(beforeVertex, 0)
self.assertEqual(atVertex, 1)
self.assertEqual(afterVertex, 2)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex) = polyline.closestSegmentWithContext(QgsPoint(0, 1))
self.assertEqual(dist, 0)
self.assertEqual(minDistPoint, QgsPoint(0, 1))
self.assertEqual(afterVertex, 2)
# 2-3 6-+-7 !
# | | | |
# 0-1 4 5 8-9
polyline = QgsGeometry.fromMultiPolyline(
[
[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 0), ],
[QgsPoint(3, 0), QgsPoint(3, 1), QgsPoint(5, 1), QgsPoint(5, 0), QgsPoint(6, 0), ]
]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polyline.closestVertex(QgsPoint(5, 2))
self.assertEqual(point, QgsPoint(5, 1))
self.assertEqual(beforeVertex, 6)
self.assertEqual(atVertex, 7)
self.assertEqual(afterVertex, 8)
self.assertEqual(dist, 1)
(dist, minDistPoint, afterVertex) = polyline.closestSegmentWithContext(QgsPoint(7, 0))
self.assertEqual(dist, 1)
self.assertEqual(minDistPoint, QgsPoint(6, 0))
self.assertEqual(afterVertex, 9)
# 5---4
# |! |
# | 2-3
# | |
# 0-1
polygon = QgsGeometry.fromPolygon(
[[
QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0),
]]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polygon.closestVertex(QgsPoint(0.7, 1.1))
self.assertEqual(point, QgsPoint(1, 1))
self.assertEqual(beforeVertex, 1)
self.assertEqual(atVertex, 2)
self.assertEqual(afterVertex, 3)
assert abs(dist - 0.1) < 0.00001, "Expected: %f; Got:%f" % (dist, 0.1)
(dist, minDistPoint, afterVertex) = polygon.closestSegmentWithContext(QgsPoint(0.7, 1.1))
self.assertEqual(afterVertex, 2)
self.assertEqual(minDistPoint, QgsPoint(1, 1))
exp = 0.3 ** 2 + 0.1 ** 2
assert abs(dist - exp) < 0.00001, "Expected: %f; Got:%f" % (exp, dist)
# 3-+-+-2
# | |
# + 8-7 +
# | |!| |
# + 5-6 +
# | |
# 0-+-+-1
polygon = QgsGeometry.fromPolygon(
[
[QgsPoint(0, 0), QgsPoint(3, 0), QgsPoint(3, 3), QgsPoint(0, 3), QgsPoint(0, 0)],
[QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(1, 2), QgsPoint(1, 1)],
]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polygon.closestVertex(QgsPoint(1.1, 1.9))
self.assertEqual(point, QgsPoint(1, 2))
self.assertEqual(beforeVertex, 7)
self.assertEqual(atVertex, 8)
self.assertEqual(afterVertex, 9)
assert abs(dist - 0.02) < 0.00001, "Expected: %f; Got:%f" % (dist, 0.02)
(dist, minDistPoint, afterVertex) = polygon.closestSegmentWithContext(QgsPoint(1.2, 1.9))
self.assertEqual(afterVertex, 8)
self.assertEqual(minDistPoint, QgsPoint(1.2, 2))
exp = 0.01
assert abs(dist - exp) < 0.00001, "Expected: %f; Got:%f" % (exp, dist)
# 5-+-4 0-+-9
# | | | |
# 6 2-3 1-2!+
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromMultiPolygon(
[
[[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0), ]],
[[QgsPoint(4, 0), QgsPoint(5, 0), QgsPoint(5, 2), QgsPoint(3, 2), QgsPoint(3, 1), QgsPoint(4, 1), QgsPoint(4, 0), ]]
]
)
(point, atVertex, beforeVertex, afterVertex, dist) = polygon.closestVertex(QgsPoint(4.1, 1.1))
self.assertEqual(point, QgsPoint(4, 1))
self.assertEqual(beforeVertex, 11)
self.assertEqual(atVertex, 12)
self.assertEqual(afterVertex, 13)
assert abs(dist - 0.02) < 0.00001, "Expected: %f; Got:%f" % (dist, 0.02)
(dist, minDistPoint, afterVertex) = polygon.closestSegmentWithContext(QgsPoint(4.1, 1.1))
self.assertEqual(afterVertex, 12)
self.assertEqual(minDistPoint, QgsPoint(4, 1))
exp = 0.02
assert abs(dist - exp) < 0.00001, "Expected: %f; Got:%f" % (exp, dist)
def testAdjacentVertex(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
polyline = QgsGeometry.fromPolyline(
[QgsPoint(5, 0), QgsPoint(0, 0), QgsPoint(0, 4), QgsPoint(5, 4), QgsPoint(5, 1), QgsPoint(1, 1), QgsPoint(1, 3), QgsPoint(4, 3), QgsPoint(4, 2), QgsPoint(2, 2)]
)
# don't crash
(before, after) = polyline.adjacentVertices(-100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
for i in range(0, 10):
(before, after) = polyline.adjacentVertices(i)
if i == 0:
assert before == -1 and after == 1, "Expected (0,1), Got:(%d,%d)" % (before, after)
elif i == 9:
assert before == i - 1 and after == -1, "Expected (0,1), Got:(%d,%d)" % (before, after)
else:
assert before == i - 1 and after == i + 1, "Expected (0,1), Got:(%d,%d)" % (before, after)
(before, after) = polyline.adjacentVertices(100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
polyline = QgsGeometry.fromMultiPolyline(
[
[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 0), ],
[QgsPoint(3, 0), QgsPoint(3, 1), QgsPoint(5, 1), QgsPoint(5, 0), QgsPoint(6, 0), ]
]
)
(before, after) = polyline.adjacentVertices(-100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
for i in range(0, 10):
(before, after) = polyline.adjacentVertices(i)
if i == 0 or i == 5:
assert before == -1 and after == i + 1, "Expected (-1,%d), Got:(%d,%d)" % (i + 1, before, after)
elif i == 4 or i == 9:
assert before == i - 1 and after == -1, "Expected (%d,-1), Got:(%d,%d)" % (i - 1, before, after)
else:
assert before == i - 1 and after == i + 1, "Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after)
(before, after) = polyline.adjacentVertices(100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
# 5---4
# | |
# | 2-3
# | |
# 0-1
polygon = QgsGeometry.fromPolygon(
[[
QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0),
]]
)
(before, after) = polygon.adjacentVertices(-100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
for i in range(0, 7):
(before, after) = polygon.adjacentVertices(i)
if i == 0 or i == 6:
assert before == 5 and after == 1, "Expected (5,1), Got:(%d,%d)" % (before, after)
else:
assert before == i - 1 and after == i + 1, "Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after)
(before, after) = polygon.adjacentVertices(100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
# 3-+-+-2
# | |
# + 8-7 +
# | | | |
# + 5-6 +
# | |
# 0-+-+-1
polygon = QgsGeometry.fromPolygon(
[
[QgsPoint(0, 0), QgsPoint(3, 0), QgsPoint(3, 3), QgsPoint(0, 3), QgsPoint(0, 0)],
[QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(1, 2), QgsPoint(1, 1)],
]
)
(before, after) = polygon.adjacentVertices(-100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
for i in range(0, 8):
(before, after) = polygon.adjacentVertices(i)
if i == 0 or i == 4:
assert before == 3 and after == 1, "Expected (3,1), Got:(%d,%d)" % (before, after)
elif i == 5:
assert before == 8 and after == 6, "Expected (2,0), Got:(%d,%d)" % (before, after)
else:
assert before == i - 1 and after == i + 1, "Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after)
(before, after) = polygon.adjacentVertices(100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromMultiPolygon(
[
[[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0), ]],
[[QgsPoint(4, 0), QgsPoint(5, 0), QgsPoint(5, 2), QgsPoint(3, 2), QgsPoint(3, 1), QgsPoint(4, 1), QgsPoint(4, 0), ]]
]
)
(before, after) = polygon.adjacentVertices(-100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
for i in range(0, 14):
(before, after) = polygon.adjacentVertices(i)
if i == 0 or i == 6:
assert before == 5 and after == 1, "Expected (5,1), Got:(%d,%d)" % (before, after)
elif i == 7 or i == 13:
assert before == 12 and after == 8, "Expected (12,8), Got:(%d,%d)" % (before, after)
else:
assert before == i - 1 and after == i + 1, "Expected (%d,%d), Got:(%d,%d)" % (i - 1, i + 1, before, after)
(before, after) = polygon.adjacentVertices(100)
assert before == -1 and after == -1, "Expected (-1,-1), Got:(%d,%d)" % (before, after)
def testVertexAt(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
points = [QgsPoint(5, 0), QgsPoint(0, 0), QgsPoint(0, 4), QgsPoint(5, 4), QgsPoint(5, 1), QgsPoint(1, 1), QgsPoint(1, 3), QgsPoint(4, 3), QgsPoint(4, 2), QgsPoint(2, 2)]
polyline = QgsGeometry.fromPolyline(points)
for i in range(0, len(points)):
assert points[i] == polyline.vertexAt(i), "Mismatch at %d" % i
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
points = [
[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 0), ],
[QgsPoint(3, 0), QgsPoint(3, 1), QgsPoint(5, 1), QgsPoint(5, 0), QgsPoint(6, 0), ]
]
polyline = QgsGeometry.fromMultiPolyline(points)
p = polyline.vertexAt(-100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
p = polyline.vertexAt(100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
assert points[j][k] == polyline.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k)
i += 1
# 5---4
# | |
# | 2-3
# | |
# 0-1
points = [[
QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0),
]]
polygon = QgsGeometry.fromPolygon(points)
p = polygon.vertexAt(-100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
p = polygon.vertexAt(100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
assert points[j][k] == polygon.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k)
i += 1
# 3-+-+-2
# | |
# + 8-7 +
# | | | |
# + 5-6 +
# | |
# 0-+-+-1
points = [
[QgsPoint(0, 0), QgsPoint(3, 0), QgsPoint(3, 3), QgsPoint(0, 3), QgsPoint(0, 0)],
[QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(1, 2), QgsPoint(1, 1)],
]
polygon = QgsGeometry.fromPolygon(points)
p = polygon.vertexAt(-100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
p = polygon.vertexAt(100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
assert points[j][k] == polygon.vertexAt(i), "Mismatch at %d / %d,%d" % (i, j, k)
i += 1
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
points = [
[[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0), ]],
[[QgsPoint(4, 0), QgsPoint(5, 0), QgsPoint(5, 2), QgsPoint(3, 2), QgsPoint(3, 1), QgsPoint(4, 1), QgsPoint(4, 0), ]]
]
polygon = QgsGeometry.fromMultiPolygon(points)
p = polygon.vertexAt(-100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
p = polygon.vertexAt(100)
assert p == QgsPoint(0, 0), "Expected 0,0, Got %s" % p.toString()
i = 0
for j in range(0, len(points)):
for k in range(0, len(points[j])):
for l in range(0, len(points[j][k])):
p = polygon.vertexAt(i)
assert points[j][k][l] == p, "Got %s, Expected %s at %d / %d,%d,%d" % (p.toString(), points[j][k][l].toString(), i, j, k, l)
i += 1
def testMultipoint(self):
# #9423
points = [QgsPoint(10, 30), QgsPoint(40, 20), QgsPoint(30, 10), QgsPoint(20, 10)]
wkt = "MultiPoint ((10 30),(40 20),(30 10),(20 10))"
multipoint = QgsGeometry.fromWkt(wkt)
assert multipoint.isMultipart(), "Expected MultiPoint to be multipart"
assert multipoint.wkbType() == QGis.WKBMultiPoint, "Expected wkbType to be WKBMultipoint"
i = 0
for p in multipoint.asMultiPoint():
assert p == points[i], "Expected %s at %d, got %s" % (points[i].toString(), i, p.toString())
i += 1
multipoint = QgsGeometry.fromWkt("MultiPoint ((5 5))")
assert multipoint.vertexAt(0) == QgsPoint(5, 5), "MULTIPOINT fromWkt failed"
assert multipoint.insertVertex(4, 4, 0), "MULTIPOINT insert 4,4 at 0 failed"
expwkt = "MultiPoint ((4 4),(5 5))"
wkt = multipoint.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.insertVertex(7, 7, 2), "MULTIPOINT append 7,7 at 2 failed"
expwkt = "MultiPoint ((4 4),(5 5),(7 7))"
wkt = multipoint.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.insertVertex(6, 6, 2), "MULTIPOINT append 6,6 at 2 failed"
expwkt = "MultiPoint ((4 4),(5 5),(6 6),(7 7))"
wkt = multipoint.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not multipoint.deleteVertex(4), "MULTIPOINT delete at 4 unexpectedly succeeded"
assert not multipoint.deleteVertex(-1), "MULTIPOINT delete at -1 unexpectedly succeeded"
assert multipoint.deleteVertex(1), "MULTIPOINT delete at 1 failed"
expwkt = "MultiPoint ((4 4),(6 6),(7 7))"
wkt = multipoint.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.deleteVertex(2), "MULTIPOINT delete at 2 failed"
expwkt = "MultiPoint ((4 4),(6 6))"
wkt = multipoint.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert multipoint.deleteVertex(0), "MULTIPOINT delete at 2 failed"
expwkt = "MultiPoint ((6 6))"
wkt = multipoint.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
multipoint = QgsGeometry.fromWkt("MultiPoint ((5 5))")
assert multipoint.vertexAt(0) == QgsPoint(5, 5), "MultiPoint fromWkt failed"
def testMoveVertex(self):
multipoint = QgsGeometry.fromWkt("MultiPoint ((5 0),(0 0),(0 4),(5 4),(5 1),(1 1),(1 3),(4 3),(4 2),(2 2))")
# try moving invalid vertices
assert not multipoint.moveVertex(9, 9, -1), "move vertex succeeded when it should have failed"
assert not multipoint.moveVertex(9, 9, 10), "move vertex succeeded when it should have failed"
assert not multipoint.moveVertex(9, 9, 11), "move vertex succeeded when it should have failed"
for i in range(0, 10):
assert multipoint.moveVertex(i + 1, -1 - i, i), "move vertex %d failed" % i
expwkt = "MultiPoint ((1 -1),(2 -2),(3 -3),(4 -4),(5 -5),(6 -6),(7 -7),(8 -8),(9 -9),(10 -10))"
wkt = multipoint.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
polyline = QgsGeometry.fromWkt("LineString (5 0, 0 0, 0 4, 5 4, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)")
# try moving invalid vertices
assert not polyline.moveVertex(9, 9, -1), "move vertex succeeded when it should have failed"
assert not polyline.moveVertex(9, 9, 10), "move vertex succeeded when it should have failed"
assert not polyline.moveVertex(9, 9, 11), "move vertex succeeded when it should have failed"
assert polyline.moveVertex(5.5, 4.5, 3), "move vertex failed"
expwkt = "LineString (5 0, 0 0, 0 4, 5.5 4.5, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5-+-4
# | |
# 6 2-3
# | |
# 0-1
polygon = QgsGeometry.fromWkt("Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))")
assert not polygon.moveVertex(3, 4, -10), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 7), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 8), "move vertex unexpectedly succeeded"
assert polygon.moveVertex(1, 2, 0), "move vertex failed"
expwkt = "Polygon ((1 2, 1 0, 1 1, 2 1, 2 2, 0 2, 1 2))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(3, 4, 3), "move vertex failed"
expwkt = "Polygon ((1 2, 1 0, 1 1, 3 4, 2 2, 0 2, 1 2))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(2, 3, 6), "move vertex failed"
expwkt = "Polygon ((2 3, 1 0, 1 1, 3 4, 2 2, 0 2, 2 3))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5-+-4 0-+-9
# | | | |
# 6 2-3 1-2!+
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromWkt("MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert not polygon.moveVertex(3, 4, -10), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 14), "move vertex unexpectedly succeeded"
assert not polygon.moveVertex(3, 4, 15), "move vertex unexpectedly succeeded"
assert polygon.moveVertex(6, 2, 9), "move vertex failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 6 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(1, 2, 0), "move vertex failed"
expwkt = "MultiPolygon (((1 2, 1 0, 1 1, 2 1, 2 2, 0 2, 1 2)),((4 0, 5 0, 6 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.moveVertex(2, 1, 7), "move vertex failed"
expwkt = "MultiPolygon (((1 2, 1 0, 1 1, 2 1, 2 2, 0 2, 1 2)),((2 1, 5 0, 6 2, 3 2, 3 1, 4 1, 2 1)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testDeleteVertex(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4
# |
# 1-+-+-+-+-0
polyline = QgsGeometry.fromWkt("LineString (5 0, 0 0, 0 4, 5 4, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)")
assert polyline.deleteVertex(3), "Delete vertex 5 4 failed"
expwkt = "LineString (5 0, 0 0, 0 4, 5 1, 1 1, 1 3, 4 3, 4 2, 2 2)"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not polyline.deleteVertex(-5), "Delete vertex -5 unexpectedly succeeded"
assert not polyline.deleteVertex(100), "Delete vertex 100 unexpectedly succeeded"
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
polyline = QgsGeometry.fromWkt("MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0),(3 0, 3 1, 5 1, 5 0, 6 0))")
assert polyline.deleteVertex(5), "Delete vertex 5 failed"
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0), (3 1, 5 1, 5 0, 6 0))"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not polyline.deleteVertex(-100), "Delete vertex -100 unexpectedly succeeded"
assert not polyline.deleteVertex(100), "Delete vertex 100 unexpectedly succeeded"
assert polyline.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "MultiLineString ((1 0, 1 1, 2 1, 2 0), (3 1, 5 1, 5 0, 6 0))"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polyline = QgsGeometry.fromWkt("MultiLineString ((0 0, 1 0, 1 1, 2 1,2 0),(3 0, 3 1, 5 1, 5 0, 6 0))")
for i in range(4):
assert polyline.deleteVertex(5), "Delete vertex 5 failed"
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0))"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5---4
# | |
# | 2-3
# | |
# 0-1
polygon = QgsGeometry.fromWkt("Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))")
assert polygon.deleteVertex(2), "Delete vertex 2 failed"
expwkt = "Polygon ((0 0, 1 0, 2 1, 2 2, 0 2, 0 0))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "Polygon ((1 0, 2 1, 2 2, 0 2, 1 0))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(4), "Delete vertex 4 failed"
#"Polygon ((2 1, 2 2, 0 2, 2 1))" #several possibilities are correct here
expwkt = "Polygon ((0 2, 2 1, 2 2, 0 2))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not polygon.deleteVertex(-100), "Delete vertex -100 unexpectedly succeeded"
assert not polygon.deleteVertex(100), "Delete vertex 100 unexpectedly succeeded"
# 5-+-4 0-+-9
# | | | |
# 6 2-3 1-2 +
# | | | |
# 0-1 7-8
polygon = QgsGeometry.fromWkt("MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert polygon.deleteVertex(9), "Delete vertex 5 2 failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "MultiPolygon (((1 0, 1 1, 2 1, 2 2, 0 2, 1 0)),((4 0, 5 0, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert polygon.deleteVertex(6), "Delete vertex 6 failed"
expwkt = "MultiPolygon (((1 0, 1 1, 2 1, 2 2, 0 2, 1 0)),((5 0, 3 2, 3 1, 4 1, 5 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt("MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
for i in range(4):
assert polygon.deleteVertex(0), "Delete vertex 0 failed"
expwkt = "MultiPolygon (((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 3-+-+-+-+-+-+-+-+-2
# | |
# + 8-7 3-2 8-7 3-2 +
# | | | | | | | | | |
# + 5-6 0-1 5-6 0-1 +
# | |
# 0-+-+-+-+---+-+-+-1
polygon = QgsGeometry.fromWkt("Polygon ((0 0, 9 0, 9 3, 0 3, 0 0),(1 1, 2 1, 2 2, 1 2, 1 1),(3 1, 4 1, 4 2, 3 2, 3 1),(5 1, 6 1, 6 2, 5 2, 5 1),(7 1, 8 1, 8 2, 7 2, 7 1))")
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
for i in range(2):
assert polygon.deleteVertex(16), "Delete vertex 16 failed" % i
expwkt = "Polygon ((0 0, 9 0, 9 3, 0 3, 0 0),(1 1, 2 1, 2 2, 1 2, 1 1),(3 1, 4 1, 4 2, 3 2, 3 1),(7 1, 8 1, 8 2, 7 2, 7 1))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
for i in range(3):
for j in range(2):
assert polygon.deleteVertex(5), "Delete vertex 5 failed" % i
expwkt = "Polygon ((0 0, 9 0, 9 3, 0 3, 0 0))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# Remove whole outer ring, inner ring should become outer
polygon = QgsGeometry.fromWkt("Polygon ((0 0, 9 0, 9 3, 0 3, 0 0),(1 1, 2 1, 2 2, 1 2, 1 1))")
for i in range(2):
assert polygon.deleteVertex(0), "Delete vertex 16 failed" % i
expwkt = "Polygon ((1 1, 2 1, 2 2, 1 2, 1 1))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testInsertVertex(self):
linestring = QgsGeometry.fromWkt("LineString(1 0, 2 0)")
assert linestring.insertVertex(0, 0, 0), "Insert vertex 0 0 at 0 failed"
expwkt = "LineString (0 0, 1 0, 2 0)"
wkt = linestring.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert linestring.insertVertex(1.5, 0, 2), "Insert vertex 1.5 0 at 2 failed"
expwkt = "LineString (0 0, 1 0, 1.5 0, 2 0)"
wkt = linestring.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
assert not linestring.insertVertex(3, 0, 5), "Insert vertex 3 0 at 5 should have failed"
polygon = QgsGeometry.fromWkt("MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert polygon.insertVertex(0, 0, 8), "Insert vertex 0 0 at 8 failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 0 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt("MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert polygon.insertVertex(0, 0, 7), "Insert vertex 0 0 at 7 failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((0 0, 4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 0 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testTranslate(self):
point = QgsGeometry.fromWkt("Point (1 1)")
assert point.translate(1, 2) == 0, "Translate failed"
expwkt = "Point (2 3)"
wkt = point.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
point = QgsGeometry.fromWkt("MultiPoint ((1 1),(2 2),(3 3))")
assert point.translate(1, 2) == 0, "Translate failed"
expwkt = "MultiPoint ((2 3),(3 4),(4 5))"
wkt = point.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
linestring = QgsGeometry.fromWkt("LineString (1 0, 2 0)")
assert linestring.translate(1, 2) == 0, "Translate failed"
expwkt = "LineString (2 2, 3 2)"
wkt = linestring.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt("MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))")
assert polygon.translate(1, 2) == 0, "Translate failed"
expwkt = "MultiPolygon (((1 2, 2 2, 2 3, 3 3, 3 4, 1 4, 1 2)),((5 2, 6 2, 6 2, 4 4, 4 3, 5 3, 5 2)))"
wkt = polygon.exportToWkt()
ct = QgsCoordinateTransform()
point = QgsGeometry.fromWkt("Point (1 1)")
assert point.transform(ct) == 0, "Translate failed"
expwkt = "Point (1 1)"
wkt = point.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
point = QgsGeometry.fromWkt("MultiPoint ((1 1),(2 2),(3 3))")
assert point.transform(ct) == 0, "Translate failed"
expwkt = "MultiPoint ((1 1),(2 2),(3 3))"
wkt = point.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
linestring = QgsGeometry.fromWkt("LineString (1 0, 2 0)")
assert linestring.transform(ct) == 0, "Translate failed"
expwkt = "LineString (1 0, 2 0)"
wkt = linestring.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polygon = QgsGeometry.fromWkt("MultiPolygon(((0 0,1 0,1 1,2 1,2 2,0 2,0 0)),((4 0,5 0,5 2,3 2,3 1,4 1,4 0)))")
assert polygon.transform(ct) == 0, "Translate failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
def testExtrude(self):
# test with empty geometry
g = QgsGeometry()
self.assertTrue(g.extrude(1, 2).isEmpty())
points = [QgsPoint(1, 2), QgsPoint(3, 2), QgsPoint(4, 3)]
line = QgsGeometry.fromPolyline(points)
expected = QgsGeometry.fromWkt('Polygon ((1 2, 3 2, 4 3, 5 5, 4 4, 2 4, 1 2))')
self.assertEqual(line.extrude(1, 2).exportToWkt(), expected.exportToWkt())
points2 = [[QgsPoint(1, 2), QgsPoint(3, 2)], [QgsPoint(4, 3), QgsPoint(8, 3)]]
multiline = QgsGeometry.fromMultiPolyline(points2)
expected = QgsGeometry.fromWkt('MultiPolygon (((1 2, 3 2, 4 4, 2 4, 1 2)),((4 3, 8 3, 9 5, 5 5, 4 3)))')
self.assertEqual(multiline.extrude(1, 2).exportToWkt(), expected.exportToWkt())
def testNearestPoint(self):
# test with empty geometries
g1 = QgsGeometry()
g2 = QgsGeometry()
self.assertTrue(g1.nearestPoint(g2).isEmpty())
g1 = QgsGeometry.fromWkt('LineString( 1 1, 5 1, 5 5 )')
self.assertTrue(g1.nearestPoint(g2).isEmpty())
self.assertTrue(g2.nearestPoint(g1).isEmpty())
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'Point( 5 3 )'
wkt = g1.nearestPoint(g2).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'Point( 6 3 )'
wkt = g2.nearestPoint(g1).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g1 = QgsGeometry.fromWkt('Polygon ((1 1, 5 1, 5 5, 1 5, 1 1))')
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'Point( 5 3 )'
wkt = g1.nearestPoint(g2).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'Point( 6 3 )'
wkt = g2.nearestPoint(g1).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g2 = QgsGeometry.fromWkt('Point( 2 3 )')
expWkt = 'Point( 2 3 )'
wkt = g1.nearestPoint(g2).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
def testShortestLine(self):
# test with empty geometries
g1 = QgsGeometry()
g2 = QgsGeometry()
self.assertTrue(g1.shortestLine(g2).isEmpty())
g1 = QgsGeometry.fromWkt('LineString( 1 1, 5 1, 5 5 )')
self.assertTrue(g1.shortestLine(g2).isEmpty())
self.assertTrue(g2.shortestLine(g1).isEmpty())
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'LineString( 5 3, 6 3 )'
wkt = g1.shortestLine(g2).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'LineString( 6 3, 5 3 )'
wkt = g2.shortestLine(g1).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g1 = QgsGeometry.fromWkt('Polygon ((1 1, 5 1, 5 5, 1 5, 1 1))')
g2 = QgsGeometry.fromWkt('Point( 6 3 )')
expWkt = 'LineString( 5 3, 6 3 )'
wkt = g1.shortestLine(g2).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
expWkt = 'LineString( 6 3, 5 3 )'
wkt = g2.shortestLine(g1).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
g2 = QgsGeometry.fromWkt('Point( 2 3 )')
expWkt = 'LineString( 2 3, 2 3 )'
wkt = g1.shortestLine(g2).exportToWkt()
self.assertTrue(compareWkt(expWkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt))
def testBoundingBox(self):
# 2-+-+-+-+-3
# | |
# + 6-+-+-7 +
# | | | |
# + + 9-+-8 +
# | | |
# ! 5-+-+-+-4 !
# |
# 1-+-+-+-+-0 !
points = [QgsPoint(5, 0), QgsPoint(0, 0), QgsPoint(0, 4), QgsPoint(5, 4), QgsPoint(5, 1), QgsPoint(1, 1), QgsPoint(1, 3), QgsPoint(4, 3), QgsPoint(4, 2), QgsPoint(2, 2)]
polyline = QgsGeometry.fromPolyline(points)
expbb = QgsRectangle(0, 0, 5, 4)
bb = polyline.boundingBox()
assert expbb == bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString())
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
points = [
[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 0), ],
[QgsPoint(3, 0), QgsPoint(3, 1), QgsPoint(5, 1), QgsPoint(5, 0), QgsPoint(6, 0), ]
]
polyline = QgsGeometry.fromMultiPolyline(points)
expbb = QgsRectangle(0, 0, 6, 1)
bb = polyline.boundingBox()
assert expbb == bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString())
# 5---4
# | |
# | 2-3
# | |
# 0-1
points = [[
QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0),
]]
polygon = QgsGeometry.fromPolygon(points)
expbb = QgsRectangle(0, 0, 2, 2)
bb = polygon.boundingBox()
assert expbb == bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString())
# 3-+-+-2
# | |
# + 8-7 +
# | | | |
# + 5-6 +
# | |
# 0-+-+-1
points = [
[QgsPoint(0, 0), QgsPoint(3, 0), QgsPoint(3, 3), QgsPoint(0, 3), QgsPoint(0, 0)],
[QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(1, 2), QgsPoint(1, 1)],
]
polygon = QgsGeometry.fromPolygon(points)
expbb = QgsRectangle(0, 0, 3, 3)
bb = polygon.boundingBox()
assert expbb == bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString())
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
points = [
[[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0), ]],
[[QgsPoint(4, 0), QgsPoint(5, 0), QgsPoint(5, 2), QgsPoint(3, 2), QgsPoint(3, 1), QgsPoint(4, 1), QgsPoint(4, 0), ]]
]
polygon = QgsGeometry.fromMultiPolygon(points)
expbb = QgsRectangle(0, 0, 5, 2)
bb = polygon.boundingBox()
assert expbb == bb, "Expected:\n%s\nGot:\n%s\n" % (expbb.toString(), bb.toString())
# NULL
points = []
line = QgsGeometry.fromPolyline(points)
assert line.boundingBox().isNull()
def testAddPart(self):
# add a part to a multipoint
points = [QgsPoint(0, 0), QgsPoint(1, 0)]
point = QgsGeometry.fromPoint(points[0])
assert point.addPart([points[1]]) == 0
expwkt = "MultiPoint ((0 0), (1 0))"
wkt = point.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a part with Z values
point = QgsGeometry.fromPoint(points[0])
point.geometry().addZValue(4.0)
assert point.addPart([QgsPointV2(QgsWKBTypes.PointZ, points[1][0], points[1][1], 3.0)]) == 0
expwkt = "MultiPointZ ((0 0 4), (1 0 3))"
wkt = point.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 2-3 6-+-7
# | | | |
# 0-1 4 5 8-9
points = [
[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 0), ],
[QgsPoint(3, 0), QgsPoint(3, 1), QgsPoint(5, 1), QgsPoint(5, 0), QgsPoint(6, 0), ]
]
polyline = QgsGeometry.fromPolyline(points[0])
assert polyline.addPart(points[1][0:1]) == 2, "addPart with one point line unexpectedly succeeded."
assert polyline.addPart(points[1][0:2]) == 0, "addPart with two point line failed."
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0), (3 0, 3 1))"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
polyline = QgsGeometry.fromPolyline(points[0])
assert polyline.addPart(points[1]) == 0, "addPart with %d point line failed." % len(points[1])
expwkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 0), (3 0, 3 1, 5 1, 5 0, 6 0))"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a part with Z values
polyline = QgsGeometry.fromPolyline(points[0])
polyline.geometry().addZValue(4.0)
points2 = [QgsPointV2(QgsWKBTypes.PointZ, p[0], p[1], 3.0) for p in points[1]]
assert polyline.addPart(points2) == 0
expwkt = "MultiLineStringZ ((0 0 4, 1 0 4, 1 1 4, 2 1 4, 2 0 4),(3 0 3, 3 1 3, 5 1 3, 5 0 3, 6 0 3))"
wkt = polyline.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# 5-+-4 0-+-9
# | | | |
# | 2-3 1-2 |
# | | | |
# 0-1 7-8
points = [
[[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0), ]],
[[QgsPoint(4, 0), QgsPoint(5, 0), QgsPoint(5, 2), QgsPoint(3, 2), QgsPoint(3, 1), QgsPoint(4, 1), QgsPoint(4, 0), ]]
]
polygon = QgsGeometry.fromPolygon(points[0])
assert polygon.addPart(points[1][0][0:1]) == 2, "addPart with one point ring unexpectedly succeeded."
assert polygon.addPart(points[1][0][0:2]) == 2, "addPart with two point ring unexpectedly succeeded."
assert polygon.addPart(points[1][0][0:3]) == 2, "addPart with unclosed three point ring unexpectedly succeeded."
assert polygon.addPart([QgsPoint(4, 0), QgsPoint(5, 0), QgsPoint(4, 0)]) == 2, "addPart with 'closed' three point ring unexpectedly succeeded."
assert polygon.addPart(points[1][0]) == 0, "addPart failed"
expwkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
mp = QgsGeometry.fromMultiPolygon(points[:1])
p = QgsGeometry.fromPolygon(points[1])
assert mp.addPartGeometry(p) == 0
wkt = mp.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
mp = QgsGeometry.fromMultiPolygon(points[:1])
mp2 = QgsGeometry.fromMultiPolygon(points[1:])
assert mp.addPartGeometry(mp2) == 0
wkt = mp.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# test adding a part with Z values
polygon = QgsGeometry.fromPolygon(points[0])
polygon.geometry().addZValue(4.0)
points2 = [QgsPointV2(QgsWKBTypes.PointZ, p[0], p[1], 3.0) for p in points[1][0]]
assert polygon.addPart(points2) == 0
expwkt = "MultiPolygonZ (((0 0 4, 1 0 4, 1 1 4, 2 1 4, 2 2 4, 0 2 4, 0 0 4)),((4 0 3, 5 0 3, 5 2 3, 3 2 3, 3 1 3, 4 1 3, 4 0 3)))"
wkt = polygon.exportToWkt()
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# Test adding parts to empty geometry, should become first part
empty = QgsGeometry()
# if not default type specified, addPart should fail
result = empty.addPart([QgsPoint(4, 0)])
assert result != 0, 'Got return code {}'.format(result)
result = empty.addPart([QgsPoint(4, 0)], QGis.Point)
assert result == 0, 'Got return code {}'.format(result)
wkt = empty.exportToWkt()
expwkt = 'MultiPoint ((4 0))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
result = empty.addPart([QgsPoint(5, 1)])
assert result == 0, 'Got return code {}'.format(result)
wkt = empty.exportToWkt()
expwkt = 'MultiPoint ((4 0),(5 1))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# next try with lines
empty = QgsGeometry()
result = empty.addPart(points[0][0], QGis.Line)
assert result == 0, 'Got return code {}'.format(result)
wkt = empty.exportToWkt()
expwkt = 'MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
result = empty.addPart(points[1][0])
assert result == 0, 'Got return code {}'.format(result)
wkt = empty.exportToWkt()
expwkt = 'MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0),(4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
# finally try with polygons
empty = QgsGeometry()
result = empty.addPart(points[0][0], QGis.Polygon)
assert result == 0, 'Got return code {}'.format(result)
wkt = empty.exportToWkt()
expwkt = 'MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
result = empty.addPart(points[1][0])
assert result == 0, 'Got return code {}'.format(result)
wkt = empty.exportToWkt()
expwkt = 'MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))'
assert compareWkt(expwkt, wkt), "Expected:\n%s\nGot:\n%s\n" % (expwkt, wkt)
def testConvertToType(self):
# 5-+-4 0-+-9 13-+-+-12
# | | | | | |
# | 2-3 1-2 | + 18-17 +
# | | | | | | | |
# 0-1 7-8 + 15-16 +
# | |
# 10-+-+-11
points = [
[[QgsPoint(0, 0), QgsPoint(1, 0), QgsPoint(1, 1), QgsPoint(2, 1), QgsPoint(2, 2), QgsPoint(0, 2), QgsPoint(0, 0)], ],
[[QgsPoint(4, 0), QgsPoint(5, 0), QgsPoint(5, 2), QgsPoint(3, 2), QgsPoint(3, 1), QgsPoint(4, 1), QgsPoint(4, 0)], ],
[[QgsPoint(10, 0), QgsPoint(13, 0), QgsPoint(13, 3), QgsPoint(10, 3), QgsPoint(10, 0)], [QgsPoint(11, 1), QgsPoint(12, 1), QgsPoint(12, 2), QgsPoint(11, 2), QgsPoint(11, 1)]]
]
######## TO POINT ########
# POINT TO POINT
point = QgsGeometry.fromPoint(QgsPoint(1, 1))
wkt = point.convertToType(QGis.Point, False).exportToWkt()
expWkt = "Point (1 1)"
assert compareWkt(expWkt, wkt), "convertToType failed: from point to point. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# POINT TO MultiPoint
point = QgsGeometry.fromPoint(QgsPoint(1, 1))
wkt = point.convertToType(QGis.Point, True).exportToWkt()
expWkt = "MultiPoint ((1 1))"
assert compareWkt(expWkt, wkt), "convertToType failed: from point to multipoint. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# LINE TO MultiPoint
line = QgsGeometry.fromPolyline(points[0][0])
wkt = line.convertToType(QGis.Point, True).exportToWkt()
expWkt = "MultiPoint ((0 0),(1 0),(1 1),(2 1),(2 2),(0 2),(0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to multipoint. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MULTILINE TO MultiPoint
multiLine = QgsGeometry.fromMultiPolyline(points[2])
wkt = multiLine.convertToType(QGis.Point, True).exportToWkt()
expWkt = "MultiPoint ((10 0),(13 0),(13 3),(10 3),(10 0),(11 1),(12 1),(12 2),(11 2),(11 1))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to multipoint. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Polygon TO MultiPoint
polygon = QgsGeometry.fromPolygon(points[0])
wkt = polygon.convertToType(QGis.Point, True).exportToWkt()
expWkt = "MultiPoint ((0 0),(1 0),(1 1),(2 1),(2 2),(0 2),(0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from poylgon to multipoint. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MultiPolygon TO MultiPoint
multiPolygon = QgsGeometry.fromMultiPolygon(points)
wkt = multiPolygon.convertToType(QGis.Point, True).exportToWkt()
expWkt = "MultiPoint ((0 0),(1 0),(1 1),(2 1),(2 2),(0 2),(0 0),(4 0),(5 0),(5 2),(3 2),(3 1),(4 1),(4 0),(10 0),(13 0),(13 3),(10 3),(10 0),(11 1),(12 1),(12 2),(11 2),(11 1))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipoylgon to multipoint. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
######## TO LINE ########
# POINT TO LINE
point = QgsGeometry.fromPoint(QgsPoint(1, 1))
assert point.convertToType(QGis.Line, False) is None, "convertToType with a point should return a null geometry"
# MultiPoint TO LINE
multipoint = QgsGeometry.fromMultiPoint(points[0][0])
wkt = multipoint.convertToType(QGis.Line, False).exportToWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipoint to line. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MultiPoint TO MULTILINE
multipoint = QgsGeometry.fromMultiPoint(points[0][0])
wkt = multipoint.convertToType(QGis.Line, True).exportToWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipoint to multiline. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MULTILINE (which has a single part) TO LINE
multiLine = QgsGeometry.fromMultiPolyline(points[0])
wkt = multiLine.convertToType(QGis.Line, False).exportToWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to line. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# LINE TO MULTILINE
line = QgsGeometry.fromPolyline(points[0][0])
wkt = line.convertToType(QGis.Line, True).exportToWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to multiline. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Polygon TO LINE
polygon = QgsGeometry.fromPolygon(points[0])
wkt = polygon.convertToType(QGis.Line, False).exportToWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt, wkt), "convertToType failed: from polygon to line. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Polygon TO MULTILINE
polygon = QgsGeometry.fromPolygon(points[0])
wkt = polygon.convertToType(QGis.Line, True).exportToWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from polygon to multiline. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Polygon with ring TO MULTILINE
polygon = QgsGeometry.fromPolygon(points[2])
wkt = polygon.convertToType(QGis.Line, True).exportToWkt()
expWkt = "MultiLineString ((10 0, 13 0, 13 3, 10 3, 10 0), (11 1, 12 1, 12 2, 11 2, 11 1))"
assert compareWkt(expWkt, wkt), "convertToType failed: from polygon with ring to multiline. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MultiPolygon (which has a single part) TO LINE
multiPolygon = QgsGeometry.fromMultiPolygon([points[0]])
wkt = multiPolygon.convertToType(QGis.Line, False).exportToWkt()
expWkt = "LineString (0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipolygon to multiline. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MultiPolygon TO MULTILINE
multiPolygon = QgsGeometry.fromMultiPolygon(points)
wkt = multiPolygon.convertToType(QGis.Line, True).exportToWkt()
expWkt = "MultiLineString ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0), (4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0), (10 0, 13 0, 13 3, 10 3, 10 0), (11 1, 12 1, 12 2, 11 2, 11 1))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipolygon to multiline. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
######## TO Polygon ########
# MultiPoint TO Polygon
multipoint = QgsGeometry.fromMultiPoint(points[0][0])
wkt = multipoint.convertToType(QGis.Polygon, False).exportToWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipoint to polygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MultiPoint TO MultiPolygon
multipoint = QgsGeometry.fromMultiPoint(points[0][0])
wkt = multipoint.convertToType(QGis.Polygon, True).exportToWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multipoint to multipolygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# LINE TO Polygon
line = QgsGeometry.fromPolyline(points[0][0])
wkt = line.convertToType(QGis.Polygon, False).exportToWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to polygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# LINE ( 3 vertices, with first = last ) TO Polygon
line = QgsGeometry.fromPolyline([QgsPoint(1, 1), QgsPoint(0, 0), QgsPoint(1, 1)])
assert line.convertToType(QGis.Polygon, False) is None, "convertToType to polygon of a 3 vertices lines with first and last vertex identical should return a null geometry"
# MULTILINE ( with a part of 3 vertices, with first = last ) TO MultiPolygon
multiline = QgsGeometry.fromMultiPolyline([points[0][0], [QgsPoint(1, 1), QgsPoint(0, 0), QgsPoint(1, 1)]])
assert multiline.convertToType(QGis.Polygon, True) is None, "convertToType to polygon of a 3 vertices lines with first and last vertex identical should return a null geometry"
# LINE TO MultiPolygon
line = QgsGeometry.fromPolyline(points[0][0])
wkt = line.convertToType(QGis.Polygon, True).exportToWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))"
assert compareWkt(expWkt, wkt), "convertToType failed: from line to multipolygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MULTILINE (which has a single part) TO Polygon
multiLine = QgsGeometry.fromMultiPolyline(points[0])
wkt = multiLine.convertToType(QGis.Polygon, False).exportToWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to polygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MULTILINE TO MultiPolygon
multiLine = QgsGeometry.fromMultiPolyline([points[0][0], points[1][0]])
wkt = multiLine.convertToType(QGis.Polygon, True).exportToWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)),((4 0, 5 0, 5 2, 3 2, 3 1, 4 1, 4 0)))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to multipolygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Polygon TO MultiPolygon
polygon = QgsGeometry.fromPolygon(points[0])
wkt = polygon.convertToType(QGis.Polygon, True).exportToWkt()
expWkt = "MultiPolygon (((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0)))"
assert compareWkt(expWkt, wkt), "convertToType failed: from polygon to multipolygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# MultiPolygon (which has a single part) TO Polygon
multiPolygon = QgsGeometry.fromMultiPolygon([points[0]])
wkt = multiPolygon.convertToType(QGis.Polygon, False).exportToWkt()
expWkt = "Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))"
assert compareWkt(expWkt, wkt), "convertToType failed: from multiline to polygon. Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testRegression13053(self):
""" See http://hub.qgis.org/issues/13053 """
p = QgsGeometry.fromWkt('MULTIPOLYGON(((62.0 18.0, 62.0 19.0, 63.0 19.0, 63.0 18.0, 62.0 18.0)), ((63.0 19.0, 63.0 20.0, 64.0 20.0, 64.0 19.0, 63.0 19.0)))')
assert p is not None
expWkt = 'MultiPolygon (((62 18, 62 19, 63 19, 63 18, 62 18)),((63 19, 63 20, 64 20, 64 19, 63 19)))'
wkt = p.exportToWkt()
assert compareWkt(expWkt, wkt), "testRegression13053 failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testRegression13055(self):
""" See http://hub.qgis.org/issues/13055
Testing that invalid WKT with z values but not using PolygonZ is still parsed
by QGIS.
"""
p = QgsGeometry.fromWkt('Polygon((0 0 0, 0 1 0, 1 1 0, 0 0 0 ))')
assert p is not None
expWkt = 'PolygonZ ((0 0 0, 0 1 0, 1 1 0, 0 0 0 ))'
wkt = p.exportToWkt()
assert compareWkt(expWkt, wkt), "testRegression13055 failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testRegression13274(self):
""" See http://hub.qgis.org/issues/13274
Testing that two combined linestrings produce another line string if possible
"""
a = QgsGeometry.fromWkt('LineString (0 0, 1 0)')
b = QgsGeometry.fromWkt('LineString (1 0, 2 0)')
c = a.combine(b)
expWkt = 'LineString (0 0, 1 0, 2 0)'
wkt = c.exportToWkt()
assert compareWkt(expWkt, wkt), "testRegression13274 failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testConvertToMultiType(self):
""" Test converting geometries to multi type """
point = QgsGeometry.fromWkt('Point (1 2)')
assert point.convertToMultiType()
expWkt = 'MultiPoint ((1 2))'
wkt = point.exportToWkt()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# test conversion of MultiPoint
assert point.convertToMultiType()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
line = QgsGeometry.fromWkt('LineString (1 0, 2 0)')
assert line.convertToMultiType()
expWkt = 'MultiLineString ((1 0, 2 0))'
wkt = line.exportToWkt()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# test conversion of MultiLineString
assert line.convertToMultiType()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
poly = QgsGeometry.fromWkt('Polygon ((1 0, 2 0, 2 1, 1 1, 1 0))')
assert poly.convertToMultiType()
expWkt = 'MultiPolygon (((1 0, 2 0, 2 1, 1 1, 1 0)))'
wkt = poly.exportToWkt()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# test conversion of MultiPolygon
assert poly.convertToMultiType()
assert compareWkt(expWkt, wkt), "testConvertToMultiType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testConvertToSingleType(self):
""" Test converting geometries to single type """
point = QgsGeometry.fromWkt('MultiPoint ((1 2),(2 3))')
assert point.convertToSingleType()
expWkt = 'Point (1 2)'
wkt = point.exportToWkt()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# test conversion of Point
assert point.convertToSingleType()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
line = QgsGeometry.fromWkt('MultiLineString ((1 0, 2 0),(2 3, 4 5))')
assert line.convertToSingleType()
expWkt = 'LineString (1 0, 2 0)'
wkt = line.exportToWkt()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# test conversion of LineString
assert line.convertToSingleType()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
poly = QgsGeometry.fromWkt('MultiPolygon (((1 0, 2 0, 2 1, 1 1, 1 0)),((2 3,2 4, 3 4, 3 3, 2 3)))')
assert poly.convertToSingleType()
expWkt = 'Polygon ((1 0, 2 0, 2 1, 1 1, 1 0))'
wkt = poly.exportToWkt()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# test conversion of Polygon
assert poly.convertToSingleType()
assert compareWkt(expWkt, wkt), "testConvertToSingleType failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testAddZValue(self):
""" Test adding z dimension to geometries """
# circular string
geom = QgsGeometry.fromWkt('CircularString (1 5, 6 2, 7 3)')
assert geom.geometry().addZValue(2)
assert geom.geometry().wkbType() == QgsWKBTypes.CircularStringZ
expWkt = 'CircularStringZ (1 5 2, 6 2 2, 7 3 2)'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addZValue to CircularString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# compound curve
geom = QgsGeometry.fromWkt('CompoundCurve ((5 3, 5 13),CircularString (5 13, 7 15, 9 13),(9 13, 9 3),CircularString (9 3, 7 1, 5 3))')
assert geom.geometry().addZValue(2)
assert geom.geometry().wkbType() == QgsWKBTypes.CompoundCurveZ
expWkt = 'CompoundCurveZ ((5 3 2, 5 13 2),CircularStringZ (5 13 2, 7 15 2, 9 13 2),(9 13 2, 9 3 2),CircularStringZ (9 3 2, 7 1 2, 5 3 2))'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addZValue to CompoundCurve failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# curve polygon
geom = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))')
assert geom.geometry().addZValue(3)
assert geom.geometry().wkbType() == QgsWKBTypes.PolygonZ
assert geom.wkbType() == QGis.WKBPolygon25D
expWkt = 'PolygonZ ((0 0 3, 1 0 3, 1 1 3, 2 1 3, 2 2 3, 0 2 3, 0 0 3))'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addZValue to CurvePolygon failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# geometry collection
geom = QgsGeometry.fromWkt('MultiPoint ((1 2),(2 3))')
assert geom.geometry().addZValue(4)
assert geom.geometry().wkbType() == QgsWKBTypes.MultiPointZ
assert geom.wkbType() == QGis.WKBMultiPoint25D
expWkt = 'MultiPointZ ((1 2 4),(2 3 4))'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addZValue to GeometryCollection failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# LineString
geom = QgsGeometry.fromWkt('LineString (1 2, 2 3)')
assert geom.geometry().addZValue(4)
assert geom.geometry().wkbType() == QgsWKBTypes.LineStringZ
assert geom.wkbType() == QGis.WKBLineString25D
expWkt = 'LineStringZ (1 2 4, 2 3 4)'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addZValue to LineString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Point
geom = QgsGeometry.fromWkt('Point (1 2)')
assert geom.geometry().addZValue(4)
assert geom.geometry().wkbType() == QgsWKBTypes.PointZ
assert geom.wkbType() == QGis.WKBPoint25D
expWkt = 'PointZ (1 2 4)'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addZValue to Point failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testAddMValue(self):
""" Test adding m dimension to geometries """
# circular string
geom = QgsGeometry.fromWkt('CircularString (1 5, 6 2, 7 3)')
assert geom.geometry().addMValue(2)
assert geom.geometry().wkbType() == QgsWKBTypes.CircularStringM
expWkt = 'CircularStringM (1 5 2, 6 2 2, 7 3 2)'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addMValue to CircularString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# compound curve
geom = QgsGeometry.fromWkt('CompoundCurve ((5 3, 5 13),CircularString (5 13, 7 15, 9 13),(9 13, 9 3),CircularString (9 3, 7 1, 5 3))')
assert geom.geometry().addMValue(2)
assert geom.geometry().wkbType() == QgsWKBTypes.CompoundCurveM
expWkt = 'CompoundCurveM ((5 3 2, 5 13 2),CircularStringM (5 13 2, 7 15 2, 9 13 2),(9 13 2, 9 3 2),CircularStringM (9 3 2, 7 1 2, 5 3 2))'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addMValue to CompoundCurve failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# curve polygon
geom = QgsGeometry.fromWkt('Polygon ((0 0, 1 0, 1 1, 2 1, 2 2, 0 2, 0 0))')
assert geom.geometry().addMValue(3)
assert geom.geometry().wkbType() == QgsWKBTypes.PolygonM
expWkt = 'PolygonM ((0 0 3, 1 0 3, 1 1 3, 2 1 3, 2 2 3, 0 2 3, 0 0 3))'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addMValue to CurvePolygon failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# geometry collection
geom = QgsGeometry.fromWkt('MultiPoint ((1 2),(2 3))')
assert geom.geometry().addMValue(4)
assert geom.geometry().wkbType() == QgsWKBTypes.MultiPointM
expWkt = 'MultiPointM ((1 2 4),(2 3 4))'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addMValue to GeometryCollection failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# LineString
geom = QgsGeometry.fromWkt('LineString (1 2, 2 3)')
assert geom.geometry().addMValue(4)
assert geom.geometry().wkbType() == QgsWKBTypes.LineStringM
expWkt = 'LineStringM (1 2 4, 2 3 4)'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addMValue to LineString failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
# Point
geom = QgsGeometry.fromWkt('Point (1 2)')
assert geom.geometry().addMValue(4)
assert geom.geometry().wkbType() == QgsWKBTypes.PointM
expWkt = 'PointM (1 2 4)'
wkt = geom.exportToWkt()
assert compareWkt(expWkt, wkt), "addMValue to Point failed: mismatch Expected:\n%s\nGot:\n%s\n" % (expWkt, wkt)
def testRelates(self):
""" Test relationships between geometries. Note the bulk of these tests were taken from the PostGIS relate testdata """
with open(os.path.join(TEST_DATA_DIR, 'relates_data.csv'), 'r') as d:
for i, t in enumerate(d):
test_data = t.strip().split('|')
geom1 = QgsGeometry.fromWkt(test_data[0])
assert geom1, "Relates {} failed: could not create geom:\n{}\n".format(i + 1, test_data[0])
geom2 = QgsGeometry.fromWkt(test_data[1])
assert geom2, "Relates {} failed: could not create geom:\n{}\n".format(i + 1, test_data[1])
result = QgsGeometry.createGeometryEngine(geom1.geometry()).relate(geom2.geometry())
exp = test_data[2]
assert result == exp, "Relates {} failed: mismatch Expected:\n{}\nGot:\n{}\nGeom1:\n{}\nGeom2:\n{}\n".format(i + 1, exp, result, test_data[0], test_data[1])
def testWkbTypes(self):
""" Test QgsWKBTypes methods """
# test singleType method
assert QgsWKBTypes.singleType(QgsWKBTypes.Unknown) == QgsWKBTypes.Unknown
assert QgsWKBTypes.singleType(QgsWKBTypes.Point) == QgsWKBTypes.Point
assert QgsWKBTypes.singleType(QgsWKBTypes.PointZ) == QgsWKBTypes.PointZ
assert QgsWKBTypes.singleType(QgsWKBTypes.PointM) == QgsWKBTypes.PointM
assert QgsWKBTypes.singleType(QgsWKBTypes.PointZM) == QgsWKBTypes.PointZM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPoint) == QgsWKBTypes.Point
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.PointZ
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPointM) == QgsWKBTypes.PointM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.PointZM
assert QgsWKBTypes.singleType(QgsWKBTypes.LineString) == QgsWKBTypes.LineString
assert QgsWKBTypes.singleType(QgsWKBTypes.LineStringZ) == QgsWKBTypes.LineStringZ
assert QgsWKBTypes.singleType(QgsWKBTypes.LineStringM) == QgsWKBTypes.LineStringM
assert QgsWKBTypes.singleType(QgsWKBTypes.LineStringZM) == QgsWKBTypes.LineStringZM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiLineString) == QgsWKBTypes.LineString
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.LineStringZ
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.LineStringM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.LineStringZM
assert QgsWKBTypes.singleType(QgsWKBTypes.Polygon) == QgsWKBTypes.Polygon
assert QgsWKBTypes.singleType(QgsWKBTypes.PolygonZ) == QgsWKBTypes.PolygonZ
assert QgsWKBTypes.singleType(QgsWKBTypes.PolygonM) == QgsWKBTypes.PolygonM
assert QgsWKBTypes.singleType(QgsWKBTypes.PolygonZM) == QgsWKBTypes.PolygonZM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.Polygon
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.PolygonZ
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.PolygonM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.PolygonZM
assert QgsWKBTypes.singleType(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.Unknown
assert QgsWKBTypes.singleType(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.Unknown
assert QgsWKBTypes.singleType(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.Unknown
assert QgsWKBTypes.singleType(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.Unknown
assert QgsWKBTypes.singleType(QgsWKBTypes.CircularString) == QgsWKBTypes.CircularString
assert QgsWKBTypes.singleType(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.CircularStringZ
assert QgsWKBTypes.singleType(QgsWKBTypes.CircularStringM) == QgsWKBTypes.CircularStringM
assert QgsWKBTypes.singleType(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.CircularStringZM
assert QgsWKBTypes.singleType(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.singleType(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.CompoundCurveZ
assert QgsWKBTypes.singleType(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.CompoundCurveM
assert QgsWKBTypes.singleType(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.CompoundCurveZM
assert QgsWKBTypes.singleType(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.singleType(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.CurvePolygonZ
assert QgsWKBTypes.singleType(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.CurvePolygonM
assert QgsWKBTypes.singleType(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.CurvePolygonZM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiCurve) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.CompoundCurveZ
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.CompoundCurveM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.CompoundCurveZM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiSurface) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.CurvePolygonZ
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.CurvePolygonM
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.CurvePolygonZM
assert QgsWKBTypes.singleType(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NoGeometry
assert QgsWKBTypes.singleType(QgsWKBTypes.Point25D) == QgsWKBTypes.Point25D
assert QgsWKBTypes.singleType(QgsWKBTypes.LineString25D) == QgsWKBTypes.LineString25D
assert QgsWKBTypes.singleType(QgsWKBTypes.Polygon25D) == QgsWKBTypes.Polygon25D
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.Point25D
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.LineString25D
assert QgsWKBTypes.singleType(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.Polygon25D
# test multiType method
assert QgsWKBTypes.multiType(QgsWKBTypes.Unknown) == QgsWKBTypes.Unknown
assert QgsWKBTypes.multiType(QgsWKBTypes.Point) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.multiType(QgsWKBTypes.PointZ) == QgsWKBTypes.MultiPointZ
assert QgsWKBTypes.multiType(QgsWKBTypes.PointM) == QgsWKBTypes.MultiPointM
assert QgsWKBTypes.multiType(QgsWKBTypes.PointZM) == QgsWKBTypes.MultiPointZM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPoint) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.MultiPointZ
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPointM) == QgsWKBTypes.MultiPointM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.MultiPointZM
assert QgsWKBTypes.multiType(QgsWKBTypes.LineString) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.multiType(QgsWKBTypes.LineStringZ) == QgsWKBTypes.MultiLineStringZ
assert QgsWKBTypes.multiType(QgsWKBTypes.LineStringM) == QgsWKBTypes.MultiLineStringM
assert QgsWKBTypes.multiType(QgsWKBTypes.LineStringZM) == QgsWKBTypes.MultiLineStringZM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiLineString) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.MultiLineStringZ
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.MultiLineStringM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.MultiLineStringZM
assert QgsWKBTypes.multiType(QgsWKBTypes.Polygon) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.multiType(QgsWKBTypes.PolygonZ) == QgsWKBTypes.MultiPolygonZ
assert QgsWKBTypes.multiType(QgsWKBTypes.PolygonM) == QgsWKBTypes.MultiPolygonM
assert QgsWKBTypes.multiType(QgsWKBTypes.PolygonZM) == QgsWKBTypes.MultiPolygonZM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.MultiPolygonZ
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.MultiPolygonM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.MultiPolygonZM
assert QgsWKBTypes.multiType(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.multiType(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.GeometryCollectionZ
assert QgsWKBTypes.multiType(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.GeometryCollectionM
assert QgsWKBTypes.multiType(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.GeometryCollectionZM
assert QgsWKBTypes.multiType(QgsWKBTypes.CircularString) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.multiType(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.MultiCurveZ
assert QgsWKBTypes.multiType(QgsWKBTypes.CircularStringM) == QgsWKBTypes.MultiCurveM
assert QgsWKBTypes.multiType(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.MultiCurveZM
assert QgsWKBTypes.multiType(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.multiType(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.MultiCurveZ
assert QgsWKBTypes.multiType(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.MultiCurveM
assert QgsWKBTypes.multiType(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.MultiCurveZM
assert QgsWKBTypes.multiType(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.multiType(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.MultiSurfaceZ
assert QgsWKBTypes.multiType(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.MultiSurfaceM
assert QgsWKBTypes.multiType(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.MultiSurfaceZM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiCurve) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.MultiCurveZ
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.MultiCurveM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.MultiCurveZM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiSurface) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.MultiSurfaceZ
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.MultiSurfaceM
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.MultiSurfaceZM
assert QgsWKBTypes.multiType(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NoGeometry
assert QgsWKBTypes.multiType(QgsWKBTypes.Point25D) == QgsWKBTypes.MultiPoint25D
assert QgsWKBTypes.multiType(QgsWKBTypes.LineString25D) == QgsWKBTypes.MultiLineString25D
assert QgsWKBTypes.multiType(QgsWKBTypes.Polygon25D) == QgsWKBTypes.MultiPolygon25D
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.MultiPoint25D
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.MultiLineString25D
assert QgsWKBTypes.multiType(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.MultiPolygon25D
# test flatType method
assert QgsWKBTypes.flatType(QgsWKBTypes.Unknown) == QgsWKBTypes.Unknown
assert QgsWKBTypes.flatType(QgsWKBTypes.Point) == QgsWKBTypes.Point
assert QgsWKBTypes.flatType(QgsWKBTypes.PointZ) == QgsWKBTypes.Point
assert QgsWKBTypes.flatType(QgsWKBTypes.PointM) == QgsWKBTypes.Point
assert QgsWKBTypes.flatType(QgsWKBTypes.PointZM) == QgsWKBTypes.Point
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPoint) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPointM) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.flatType(QgsWKBTypes.LineString) == QgsWKBTypes.LineString
assert QgsWKBTypes.flatType(QgsWKBTypes.LineStringZ) == QgsWKBTypes.LineString
assert QgsWKBTypes.flatType(QgsWKBTypes.LineStringM) == QgsWKBTypes.LineString
assert QgsWKBTypes.flatType(QgsWKBTypes.LineStringZM) == QgsWKBTypes.LineString
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiLineString) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.flatType(QgsWKBTypes.Polygon) == QgsWKBTypes.Polygon
assert QgsWKBTypes.flatType(QgsWKBTypes.PolygonZ) == QgsWKBTypes.Polygon
assert QgsWKBTypes.flatType(QgsWKBTypes.PolygonM) == QgsWKBTypes.Polygon
assert QgsWKBTypes.flatType(QgsWKBTypes.PolygonZM) == QgsWKBTypes.Polygon
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.flatType(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.flatType(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.flatType(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.flatType(QgsWKBTypes.CircularString) == QgsWKBTypes.CircularString
assert QgsWKBTypes.flatType(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.CircularString
assert QgsWKBTypes.flatType(QgsWKBTypes.CircularStringM) == QgsWKBTypes.CircularString
assert QgsWKBTypes.flatType(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.CircularString
assert QgsWKBTypes.flatType(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiCurve) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiSurface) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.flatType(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NoGeometry
assert QgsWKBTypes.flatType(QgsWKBTypes.Point25D) == QgsWKBTypes.Point
assert QgsWKBTypes.flatType(QgsWKBTypes.LineString25D) == QgsWKBTypes.LineString
assert QgsWKBTypes.flatType(QgsWKBTypes.Polygon25D) == QgsWKBTypes.Polygon
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.flatType(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.MultiPolygon
# test geometryType method
assert QgsWKBTypes.geometryType(QgsWKBTypes.Unknown) == QgsWKBTypes.UnknownGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.Point) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.PointZ) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.PointM) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.PointZM) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPoint) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPointM) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.LineString) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.LineStringZ) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.LineStringM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.LineStringZM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiLineString) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.Polygon) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.PolygonZ) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.PolygonM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.PolygonZM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.UnknownGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.UnknownGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.UnknownGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.UnknownGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CircularString) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CircularStringM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiCurve) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiSurface) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NullGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.Point25D) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.LineString25D) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.Polygon25D) == QgsWKBTypes.PolygonGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.PointGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.LineGeometry
assert QgsWKBTypes.geometryType(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.PolygonGeometry
# test displayString method
assert QgsWKBTypes.displayString(QgsWKBTypes.Unknown) == 'Unknown'
assert QgsWKBTypes.displayString(QgsWKBTypes.Point) == 'Point'
assert QgsWKBTypes.displayString(QgsWKBTypes.PointZ) == 'PointZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.PointM) == 'PointM'
assert QgsWKBTypes.displayString(QgsWKBTypes.PointZM) == 'PointZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPoint) == 'MultiPoint'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPointZ) == 'MultiPointZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPointM) == 'MultiPointM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPointZM) == 'MultiPointZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.LineString) == 'LineString'
assert QgsWKBTypes.displayString(QgsWKBTypes.LineStringZ) == 'LineStringZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.LineStringM) == 'LineStringM'
assert QgsWKBTypes.displayString(QgsWKBTypes.LineStringZM) == 'LineStringZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiLineString) == 'MultiLineString'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiLineStringZ) == 'MultiLineStringZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiLineStringM) == 'MultiLineStringM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiLineStringZM) == 'MultiLineStringZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.Polygon) == 'Polygon'
assert QgsWKBTypes.displayString(QgsWKBTypes.PolygonZ) == 'PolygonZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.PolygonM) == 'PolygonM'
assert QgsWKBTypes.displayString(QgsWKBTypes.PolygonZM) == 'PolygonZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPolygon) == 'MultiPolygon'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPolygonZ) == 'MultiPolygonZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPolygonM) == 'MultiPolygonM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPolygonZM) == 'MultiPolygonZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.GeometryCollection) == 'GeometryCollection'
assert QgsWKBTypes.displayString(QgsWKBTypes.GeometryCollectionZ) == 'GeometryCollectionZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.GeometryCollectionM) == 'GeometryCollectionM'
assert QgsWKBTypes.displayString(QgsWKBTypes.GeometryCollectionZM) == 'GeometryCollectionZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.CircularString) == 'CircularString'
assert QgsWKBTypes.displayString(QgsWKBTypes.CircularStringZ) == 'CircularStringZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.CircularStringM) == 'CircularStringM'
assert QgsWKBTypes.displayString(QgsWKBTypes.CircularStringZM) == 'CircularStringZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.CompoundCurve) == 'CompoundCurve'
assert QgsWKBTypes.displayString(QgsWKBTypes.CompoundCurveZ) == 'CompoundCurveZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.CompoundCurveM) == 'CompoundCurveM'
assert QgsWKBTypes.displayString(QgsWKBTypes.CompoundCurveZM) == 'CompoundCurveZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.CurvePolygon) == 'CurvePolygon'
assert QgsWKBTypes.displayString(QgsWKBTypes.CurvePolygonZ) == 'CurvePolygonZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.CurvePolygonM) == 'CurvePolygonM'
assert QgsWKBTypes.displayString(QgsWKBTypes.CurvePolygonZM) == 'CurvePolygonZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiCurve) == 'MultiCurve'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiCurveZ) == 'MultiCurveZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiCurveM) == 'MultiCurveM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiCurveZM) == 'MultiCurveZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiSurface) == 'MultiSurface'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiSurfaceZ) == 'MultiSurfaceZ'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiSurfaceM) == 'MultiSurfaceM'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiSurfaceZM) == 'MultiSurfaceZM'
assert QgsWKBTypes.displayString(QgsWKBTypes.NoGeometry) == 'NoGeometry'
assert QgsWKBTypes.displayString(QgsWKBTypes.Point25D) == 'Point25D'
assert QgsWKBTypes.displayString(QgsWKBTypes.LineString25D) == 'LineString25D'
assert QgsWKBTypes.displayString(QgsWKBTypes.Polygon25D) == 'Polygon25D'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPoint25D) == 'MultiPoint25D'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiLineString25D) == 'MultiLineString25D'
assert QgsWKBTypes.displayString(QgsWKBTypes.MultiPolygon25D) == 'MultiPolygon25D'
# test parseType method
assert QgsWKBTypes.parseType('point( 1 2 )') == QgsWKBTypes.Point
assert QgsWKBTypes.parseType('POINT( 1 2 )') == QgsWKBTypes.Point
assert QgsWKBTypes.parseType(' point ( 1 2 ) ') == QgsWKBTypes.Point
assert QgsWKBTypes.parseType('point') == QgsWKBTypes.Point
assert QgsWKBTypes.parseType('LINE STRING( 1 2, 3 4 )') == QgsWKBTypes.LineString
assert QgsWKBTypes.parseType('POINTZ( 1 2 )') == QgsWKBTypes.PointZ
assert QgsWKBTypes.parseType('POINT z m') == QgsWKBTypes.PointZM
assert QgsWKBTypes.parseType('bad') == QgsWKBTypes.Unknown
# test wkbDimensions method
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.Unknown) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.Point) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.PointZ) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.PointM) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.PointZM) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPoint) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPointZ) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPointM) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPointZM) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.LineString) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.LineStringZ) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.LineStringM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.LineStringZM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiLineString) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiLineStringZ) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiLineStringM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiLineStringZM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.Polygon) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.PolygonZ) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.PolygonM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.PolygonZM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPolygon) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPolygonZ) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPolygonM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPolygonZM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.GeometryCollection) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.GeometryCollectionZ) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.GeometryCollectionM) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.GeometryCollectionZM) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CircularString) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CircularStringZ) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CircularStringM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CircularStringZM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CompoundCurve) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CompoundCurveZ) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CompoundCurveM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CompoundCurveZM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CurvePolygon) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CurvePolygonZ) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CurvePolygonM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.CurvePolygonZM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiCurve) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiCurveZ) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiCurveM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiCurveZM) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiSurface) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiSurfaceZ) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiSurfaceM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiSurfaceZM) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.NoGeometry) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.Point25D) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.LineString25D) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.Polygon25D) == 2
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPoint25D) == 0
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiLineString25D) == 1
assert QgsWKBTypes.wkbDimensions(QgsWKBTypes.MultiPolygon25D) == 2
# test coordDimensions method
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.Unknown) == 0
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.Point) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.PointZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.PointM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.PointZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPoint) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPointZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPointM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPointZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.LineString) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.LineStringZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.LineStringM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.LineStringZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiLineString) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiLineStringZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiLineStringM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiLineStringZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.Polygon) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.PolygonZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.PolygonM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.PolygonZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPolygon) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPolygonZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPolygonM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPolygonZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.GeometryCollection) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.GeometryCollectionZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.GeometryCollectionM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.GeometryCollectionZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CircularString) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CircularStringZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CircularStringM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CircularStringZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CompoundCurve) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CompoundCurveZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CompoundCurveM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CompoundCurveZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CurvePolygon) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CurvePolygonZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CurvePolygonM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.CurvePolygonZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiCurve) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiCurveZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiCurveM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiCurveZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiSurface) == 2
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiSurfaceZ) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiSurfaceM) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiSurfaceZM) == 4
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.NoGeometry) == 0
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.Point25D) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.LineString25D) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.Polygon25D) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPoint25D) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiLineString25D) == 3
assert QgsWKBTypes.coordDimensions(QgsWKBTypes.MultiPolygon25D) == 3
# test isSingleType methods
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.Unknown)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.Point)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.LineString)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.Polygon)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPoint)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiLineString)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPolygon)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.GeometryCollection)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CircularString)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CompoundCurve)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CurvePolygon)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiCurve)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiSurface)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.NoGeometry)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.PointZ)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.LineStringZ)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.PolygonZ)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPointZ)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiLineStringZ)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPolygonZ)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.GeometryCollectionZ)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CircularStringZ)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CompoundCurveZ)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CurvePolygonZ)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiCurveZ)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiSurfaceZ)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.PointM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.LineStringM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.PolygonM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPointM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiLineStringM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPolygonM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.GeometryCollectionM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CircularStringM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CompoundCurveM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CurvePolygonM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiCurveM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiSurfaceM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.PointZM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.LineStringZM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.PolygonZM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPointZM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiLineStringZM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPolygonZM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.GeometryCollectionZM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CircularStringZM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CompoundCurveZM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.CurvePolygonZM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiCurveZM)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiSurfaceZM)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.Point25D)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.LineString25D)
assert QgsWKBTypes.isSingleType(QgsWKBTypes.Polygon25D)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPoint25D)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiLineString25D)
assert not QgsWKBTypes.isSingleType(QgsWKBTypes.MultiPolygon25D)
# test isMultiType methods
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.Unknown)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.Point)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.LineString)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.Polygon)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPoint)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiLineString)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPolygon)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.GeometryCollection)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CircularString)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CompoundCurve)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CurvePolygon)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiCurve)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiSurface)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.NoGeometry)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.PointZ)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.LineStringZ)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.PolygonZ)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPointZ)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiLineStringZ)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPolygonZ)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.GeometryCollectionZ)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CircularStringZ)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CompoundCurveZ)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CurvePolygonZ)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiCurveZ)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiSurfaceZ)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.PointM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.LineStringM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.PolygonM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPointM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiLineStringM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPolygonM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.GeometryCollectionM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CircularStringM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CompoundCurveM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CurvePolygonM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiCurveM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiSurfaceM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.PointZM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.LineStringZM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.PolygonZM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPointZM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiLineStringZM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPolygonZM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.GeometryCollectionZM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CircularStringZM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CompoundCurveZM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.CurvePolygonZM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiCurveZM)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiSurfaceZM)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.Point25D)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.LineString25D)
assert not QgsWKBTypes.isMultiType(QgsWKBTypes.Polygon25D)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPoint25D)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiLineString25D)
assert QgsWKBTypes.isMultiType(QgsWKBTypes.MultiPolygon25D)
# test isCurvedType methods
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.Unknown)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.Point)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.LineString)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.Polygon)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPoint)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiLineString)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPolygon)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.GeometryCollection)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CircularString)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CompoundCurve)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CurvePolygon)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiCurve)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiSurface)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.NoGeometry)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.PointZ)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.LineStringZ)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.PolygonZ)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPointZ)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiLineStringZ)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPolygonZ)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.GeometryCollectionZ)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CircularStringZ)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CompoundCurveZ)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CurvePolygonZ)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiCurveZ)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiSurfaceZ)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.PointM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.LineStringM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.PolygonM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPointM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiLineStringM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPolygonM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.GeometryCollectionM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CircularStringM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CompoundCurveM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CurvePolygonM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiCurveM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiSurfaceM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.PointZM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.LineStringZM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.PolygonZM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPointZM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiLineStringZM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPolygonZM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.GeometryCollectionZM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CircularStringZM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CompoundCurveZM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.CurvePolygonZM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiCurveZM)
assert QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiSurfaceZM)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.Point25D)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.LineString25D)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.Polygon25D)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPoint25D)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiLineString25D)
assert not QgsWKBTypes.isCurvedType(QgsWKBTypes.MultiPolygon25D)
# test hasZ methods
assert not QgsWKBTypes.hasZ(QgsWKBTypes.Unknown)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.Point)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.LineString)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.Polygon)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiPoint)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiLineString)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiPolygon)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.GeometryCollection)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.CircularString)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.CompoundCurve)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.CurvePolygon)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiCurve)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiSurface)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.NoGeometry)
assert QgsWKBTypes.hasZ(QgsWKBTypes.PointZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.LineStringZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.PolygonZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiPointZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiLineStringZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiPolygonZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.GeometryCollectionZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.CircularStringZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.CompoundCurveZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.CurvePolygonZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiCurveZ)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiSurfaceZ)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.PointM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.LineStringM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.PolygonM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiPointM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiLineStringM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiPolygonM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.GeometryCollectionM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.CircularStringM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.CompoundCurveM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.CurvePolygonM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiCurveM)
assert not QgsWKBTypes.hasZ(QgsWKBTypes.MultiSurfaceM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.PointZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.LineStringZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.PolygonZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiPointZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiLineStringZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiPolygonZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.GeometryCollectionZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.CircularStringZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.CompoundCurveZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.CurvePolygonZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiCurveZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiSurfaceZM)
assert QgsWKBTypes.hasZ(QgsWKBTypes.Point25D)
assert QgsWKBTypes.hasZ(QgsWKBTypes.LineString25D)
assert QgsWKBTypes.hasZ(QgsWKBTypes.Polygon25D)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiPoint25D)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiLineString25D)
assert QgsWKBTypes.hasZ(QgsWKBTypes.MultiPolygon25D)
# test hasM methods
assert not QgsWKBTypes.hasM(QgsWKBTypes.Unknown)
assert not QgsWKBTypes.hasM(QgsWKBTypes.Point)
assert not QgsWKBTypes.hasM(QgsWKBTypes.LineString)
assert not QgsWKBTypes.hasM(QgsWKBTypes.Polygon)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiPoint)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiLineString)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiPolygon)
assert not QgsWKBTypes.hasM(QgsWKBTypes.GeometryCollection)
assert not QgsWKBTypes.hasM(QgsWKBTypes.CircularString)
assert not QgsWKBTypes.hasM(QgsWKBTypes.CompoundCurve)
assert not QgsWKBTypes.hasM(QgsWKBTypes.CurvePolygon)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiCurve)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiSurface)
assert not QgsWKBTypes.hasM(QgsWKBTypes.NoGeometry)
assert not QgsWKBTypes.hasM(QgsWKBTypes.PointZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.LineStringZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.PolygonZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiPointZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiLineStringZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiPolygonZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.GeometryCollectionZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.CircularStringZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.CompoundCurveZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.CurvePolygonZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiCurveZ)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiSurfaceZ)
assert QgsWKBTypes.hasM(QgsWKBTypes.PointM)
assert QgsWKBTypes.hasM(QgsWKBTypes.LineStringM)
assert QgsWKBTypes.hasM(QgsWKBTypes.PolygonM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiPointM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiLineStringM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiPolygonM)
assert QgsWKBTypes.hasM(QgsWKBTypes.GeometryCollectionM)
assert QgsWKBTypes.hasM(QgsWKBTypes.CircularStringM)
assert QgsWKBTypes.hasM(QgsWKBTypes.CompoundCurveM)
assert QgsWKBTypes.hasM(QgsWKBTypes.CurvePolygonM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiCurveM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiSurfaceM)
assert QgsWKBTypes.hasM(QgsWKBTypes.PointZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.LineStringZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.PolygonZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiPointZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiLineStringZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiPolygonZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.GeometryCollectionZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.CircularStringZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.CompoundCurveZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.CurvePolygonZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiCurveZM)
assert QgsWKBTypes.hasM(QgsWKBTypes.MultiSurfaceZM)
assert not QgsWKBTypes.hasM(QgsWKBTypes.Point25D)
assert not QgsWKBTypes.hasM(QgsWKBTypes.LineString25D)
assert not QgsWKBTypes.hasM(QgsWKBTypes.Polygon25D)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiPoint25D)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiLineString25D)
assert not QgsWKBTypes.hasM(QgsWKBTypes.MultiPolygon25D)
# test adding z dimension to types
assert QgsWKBTypes.addZ(QgsWKBTypes.Unknown) == QgsWKBTypes.Unknown
assert QgsWKBTypes.addZ(QgsWKBTypes.Point) == QgsWKBTypes.PointZ
assert QgsWKBTypes.addZ(QgsWKBTypes.PointZ) == QgsWKBTypes.PointZ
assert QgsWKBTypes.addZ(QgsWKBTypes.PointM) == QgsWKBTypes.PointZM
assert QgsWKBTypes.addZ(QgsWKBTypes.PointZM) == QgsWKBTypes.PointZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPoint) == QgsWKBTypes.MultiPointZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.MultiPointZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPointM) == QgsWKBTypes.MultiPointZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.MultiPointZM
assert QgsWKBTypes.addZ(QgsWKBTypes.LineString) == QgsWKBTypes.LineStringZ
assert QgsWKBTypes.addZ(QgsWKBTypes.LineStringZ) == QgsWKBTypes.LineStringZ
assert QgsWKBTypes.addZ(QgsWKBTypes.LineStringM) == QgsWKBTypes.LineStringZM
assert QgsWKBTypes.addZ(QgsWKBTypes.LineStringZM) == QgsWKBTypes.LineStringZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiLineString) == QgsWKBTypes.MultiLineStringZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.MultiLineStringZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.MultiLineStringZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.MultiLineStringZM
assert QgsWKBTypes.addZ(QgsWKBTypes.Polygon) == QgsWKBTypes.PolygonZ
assert QgsWKBTypes.addZ(QgsWKBTypes.PolygonZ) == QgsWKBTypes.PolygonZ
assert QgsWKBTypes.addZ(QgsWKBTypes.PolygonM) == QgsWKBTypes.PolygonZM
assert QgsWKBTypes.addZ(QgsWKBTypes.PolygonZM) == QgsWKBTypes.PolygonZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.MultiPolygonZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.MultiPolygonZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.MultiPolygonZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.MultiPolygonZM
assert QgsWKBTypes.addZ(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.GeometryCollectionZ
assert QgsWKBTypes.addZ(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.GeometryCollectionZ
assert QgsWKBTypes.addZ(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.GeometryCollectionZM
assert QgsWKBTypes.addZ(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.GeometryCollectionZM
assert QgsWKBTypes.addZ(QgsWKBTypes.CircularString) == QgsWKBTypes.CircularStringZ
assert QgsWKBTypes.addZ(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.CircularStringZ
assert QgsWKBTypes.addZ(QgsWKBTypes.CircularStringM) == QgsWKBTypes.CircularStringZM
assert QgsWKBTypes.addZ(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.CircularStringZM
assert QgsWKBTypes.addZ(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.CompoundCurveZ
assert QgsWKBTypes.addZ(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.CompoundCurveZ
assert QgsWKBTypes.addZ(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.CompoundCurveZM
assert QgsWKBTypes.addZ(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.CompoundCurveZM
assert QgsWKBTypes.addZ(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.CurvePolygonZ
assert QgsWKBTypes.addZ(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.CurvePolygonZ
assert QgsWKBTypes.addZ(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.CurvePolygonZM
assert QgsWKBTypes.addZ(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.CurvePolygonZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiCurve) == QgsWKBTypes.MultiCurveZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.MultiCurveZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.MultiCurveZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.MultiCurveZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiSurface) == QgsWKBTypes.MultiSurfaceZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.MultiSurfaceZ
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.MultiSurfaceZM
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.MultiSurfaceZM
assert QgsWKBTypes.addZ(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NoGeometry
assert QgsWKBTypes.addZ(QgsWKBTypes.Point25D) == QgsWKBTypes.Point25D
assert QgsWKBTypes.addZ(QgsWKBTypes.LineString25D) == QgsWKBTypes.LineString25D
assert QgsWKBTypes.addZ(QgsWKBTypes.Polygon25D) == QgsWKBTypes.Polygon25D
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.MultiPoint25D
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.MultiLineString25D
assert QgsWKBTypes.addZ(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.MultiPolygon25D
# test to25D
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.Unknown), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.Point), QgsWKBTypes.Point25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.PointZ), QgsWKBTypes.Point25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.PointM), QgsWKBTypes.Point25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.PointZM), QgsWKBTypes.Point25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPoint), QgsWKBTypes.MultiPoint25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPointZ), QgsWKBTypes.MultiPoint25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPointM), QgsWKBTypes.MultiPoint25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPointZM), QgsWKBTypes.MultiPoint25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.LineString), QgsWKBTypes.LineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.LineStringZ), QgsWKBTypes.LineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.LineStringM), QgsWKBTypes.LineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.LineStringZM), QgsWKBTypes.LineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiLineString), QgsWKBTypes.MultiLineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiLineStringZ), QgsWKBTypes.MultiLineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiLineStringM), QgsWKBTypes.MultiLineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiLineStringZM), QgsWKBTypes.MultiLineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.Polygon), QgsWKBTypes.Polygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.PolygonZ), QgsWKBTypes.Polygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.PolygonM), QgsWKBTypes.Polygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.PolygonZM), QgsWKBTypes.Polygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPolygon), QgsWKBTypes.MultiPolygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPolygonZ), QgsWKBTypes.MultiPolygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPolygonM), QgsWKBTypes.MultiPolygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPolygonZM), QgsWKBTypes.MultiPolygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.GeometryCollection), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.GeometryCollectionZ), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.GeometryCollectionM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.GeometryCollectionZM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CircularString), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CircularStringZ), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CircularStringM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CircularStringZM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CompoundCurve), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CompoundCurveZ), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CompoundCurveM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CompoundCurveZM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CurvePolygon), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CurvePolygonZ), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CurvePolygonM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.CurvePolygonZM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiCurve), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiCurveZ), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiCurveM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiCurveZM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiSurface), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiSurfaceZ), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiSurfaceM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiSurfaceZM), QgsWKBTypes.Unknown)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.NoGeometry), QgsWKBTypes.NoGeometry)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.Point25D), QgsWKBTypes.Point25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.LineString25D), QgsWKBTypes.LineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.Polygon25D), QgsWKBTypes.Polygon25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPoint25D), QgsWKBTypes.MultiPoint25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiLineString25D), QgsWKBTypes.MultiLineString25D)
self.assertEqual(QgsWKBTypes.to25D(QgsWKBTypes.MultiPolygon25D), QgsWKBTypes.MultiPolygon25D)
# test adding m dimension to types
assert QgsWKBTypes.addM(QgsWKBTypes.Unknown) == QgsWKBTypes.Unknown
assert QgsWKBTypes.addM(QgsWKBTypes.Point) == QgsWKBTypes.PointM
assert QgsWKBTypes.addM(QgsWKBTypes.PointZ) == QgsWKBTypes.PointZM
assert QgsWKBTypes.addM(QgsWKBTypes.PointM) == QgsWKBTypes.PointM
assert QgsWKBTypes.addM(QgsWKBTypes.PointZM) == QgsWKBTypes.PointZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPoint) == QgsWKBTypes.MultiPointM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.MultiPointZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPointM) == QgsWKBTypes.MultiPointM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.MultiPointZM
assert QgsWKBTypes.addM(QgsWKBTypes.LineString) == QgsWKBTypes.LineStringM
assert QgsWKBTypes.addM(QgsWKBTypes.LineStringZ) == QgsWKBTypes.LineStringZM
assert QgsWKBTypes.addM(QgsWKBTypes.LineStringM) == QgsWKBTypes.LineStringM
assert QgsWKBTypes.addM(QgsWKBTypes.LineStringZM) == QgsWKBTypes.LineStringZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiLineString) == QgsWKBTypes.MultiLineStringM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.MultiLineStringZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.MultiLineStringM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.MultiLineStringZM
assert QgsWKBTypes.addM(QgsWKBTypes.Polygon) == QgsWKBTypes.PolygonM
assert QgsWKBTypes.addM(QgsWKBTypes.PolygonZ) == QgsWKBTypes.PolygonZM
assert QgsWKBTypes.addM(QgsWKBTypes.PolygonM) == QgsWKBTypes.PolygonM
assert QgsWKBTypes.addM(QgsWKBTypes.PolygonZM) == QgsWKBTypes.PolygonZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.MultiPolygonM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.MultiPolygonZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.MultiPolygonM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.MultiPolygonZM
assert QgsWKBTypes.addM(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.GeometryCollectionM
assert QgsWKBTypes.addM(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.GeometryCollectionZM
assert QgsWKBTypes.addM(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.GeometryCollectionM
assert QgsWKBTypes.addM(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.GeometryCollectionZM
assert QgsWKBTypes.addM(QgsWKBTypes.CircularString) == QgsWKBTypes.CircularStringM
assert QgsWKBTypes.addM(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.CircularStringZM
assert QgsWKBTypes.addM(QgsWKBTypes.CircularStringM) == QgsWKBTypes.CircularStringM
assert QgsWKBTypes.addM(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.CircularStringZM
assert QgsWKBTypes.addM(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.CompoundCurveM
assert QgsWKBTypes.addM(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.CompoundCurveZM
assert QgsWKBTypes.addM(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.CompoundCurveM
assert QgsWKBTypes.addM(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.CompoundCurveZM
assert QgsWKBTypes.addM(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.CurvePolygonM
assert QgsWKBTypes.addM(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.CurvePolygonZM
assert QgsWKBTypes.addM(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.CurvePolygonM
assert QgsWKBTypes.addM(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.CurvePolygonZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiCurve) == QgsWKBTypes.MultiCurveM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.MultiCurveZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.MultiCurveM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.MultiCurveZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiSurface) == QgsWKBTypes.MultiSurfaceM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.MultiSurfaceZM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.MultiSurfaceM
assert QgsWKBTypes.addM(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.MultiSurfaceZM
assert QgsWKBTypes.addM(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NoGeometry
# can't be added to these types
assert QgsWKBTypes.addM(QgsWKBTypes.Point25D) == QgsWKBTypes.Point25D
assert QgsWKBTypes.addM(QgsWKBTypes.LineString25D) == QgsWKBTypes.LineString25D
assert QgsWKBTypes.addM(QgsWKBTypes.Polygon25D) == QgsWKBTypes.Polygon25D
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.MultiPoint25D
assert QgsWKBTypes.addM(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.MultiLineString25D
assert QgsWKBTypes.addM(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.MultiPolygon25D
# test dropping z dimension from types
assert QgsWKBTypes.dropZ(QgsWKBTypes.Unknown) == QgsWKBTypes.Unknown
assert QgsWKBTypes.dropZ(QgsWKBTypes.Point) == QgsWKBTypes.Point
assert QgsWKBTypes.dropZ(QgsWKBTypes.PointZ) == QgsWKBTypes.Point
assert QgsWKBTypes.dropZ(QgsWKBTypes.PointM) == QgsWKBTypes.PointM
assert QgsWKBTypes.dropZ(QgsWKBTypes.PointZM) == QgsWKBTypes.PointM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPoint) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPointM) == QgsWKBTypes.MultiPointM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.MultiPointM
assert QgsWKBTypes.dropZ(QgsWKBTypes.LineString) == QgsWKBTypes.LineString
assert QgsWKBTypes.dropZ(QgsWKBTypes.LineStringZ) == QgsWKBTypes.LineString
assert QgsWKBTypes.dropZ(QgsWKBTypes.LineStringM) == QgsWKBTypes.LineStringM
assert QgsWKBTypes.dropZ(QgsWKBTypes.LineStringZM) == QgsWKBTypes.LineStringM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiLineString) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.MultiLineStringM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.MultiLineStringM
assert QgsWKBTypes.dropZ(QgsWKBTypes.Polygon) == QgsWKBTypes.Polygon
assert QgsWKBTypes.dropZ(QgsWKBTypes.PolygonZ) == QgsWKBTypes.Polygon
assert QgsWKBTypes.dropZ(QgsWKBTypes.PolygonM) == QgsWKBTypes.PolygonM
assert QgsWKBTypes.dropZ(QgsWKBTypes.PolygonZM) == QgsWKBTypes.PolygonM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.MultiPolygonM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.MultiPolygonM
assert QgsWKBTypes.dropZ(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.dropZ(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.dropZ(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.GeometryCollectionM
assert QgsWKBTypes.dropZ(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.GeometryCollectionM
assert QgsWKBTypes.dropZ(QgsWKBTypes.CircularString) == QgsWKBTypes.CircularString
assert QgsWKBTypes.dropZ(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.CircularString
assert QgsWKBTypes.dropZ(QgsWKBTypes.CircularStringM) == QgsWKBTypes.CircularStringM
assert QgsWKBTypes.dropZ(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.CircularStringM
assert QgsWKBTypes.dropZ(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.dropZ(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.dropZ(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.CompoundCurveM
assert QgsWKBTypes.dropZ(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.CompoundCurveM
assert QgsWKBTypes.dropZ(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.dropZ(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.dropZ(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.CurvePolygonM
assert QgsWKBTypes.dropZ(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.CurvePolygonM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiCurve) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.MultiCurveM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.MultiCurveM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiSurface) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.MultiSurfaceM
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.MultiSurfaceM
assert QgsWKBTypes.dropZ(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NoGeometry
assert QgsWKBTypes.dropZ(QgsWKBTypes.Point25D) == QgsWKBTypes.Point
assert QgsWKBTypes.dropZ(QgsWKBTypes.LineString25D) == QgsWKBTypes.LineString
assert QgsWKBTypes.dropZ(QgsWKBTypes.Polygon25D) == QgsWKBTypes.Polygon
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.dropZ(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.MultiPolygon
# test dropping m dimension from types
assert QgsWKBTypes.dropM(QgsWKBTypes.Unknown) == QgsWKBTypes.Unknown
assert QgsWKBTypes.dropM(QgsWKBTypes.Point) == QgsWKBTypes.Point
assert QgsWKBTypes.dropM(QgsWKBTypes.PointZ) == QgsWKBTypes.PointZ
assert QgsWKBTypes.dropM(QgsWKBTypes.PointM) == QgsWKBTypes.Point
assert QgsWKBTypes.dropM(QgsWKBTypes.PointZM) == QgsWKBTypes.PointZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPoint) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPointZ) == QgsWKBTypes.MultiPointZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPointM) == QgsWKBTypes.MultiPoint
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPointZM) == QgsWKBTypes.MultiPointZ
assert QgsWKBTypes.dropM(QgsWKBTypes.LineString) == QgsWKBTypes.LineString
assert QgsWKBTypes.dropM(QgsWKBTypes.LineStringZ) == QgsWKBTypes.LineStringZ
assert QgsWKBTypes.dropM(QgsWKBTypes.LineStringM) == QgsWKBTypes.LineString
assert QgsWKBTypes.dropM(QgsWKBTypes.LineStringZM) == QgsWKBTypes.LineStringZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiLineString) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiLineStringZ) == QgsWKBTypes.MultiLineStringZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiLineStringM) == QgsWKBTypes.MultiLineString
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiLineStringZM) == QgsWKBTypes.MultiLineStringZ
assert QgsWKBTypes.dropM(QgsWKBTypes.Polygon) == QgsWKBTypes.Polygon
assert QgsWKBTypes.dropM(QgsWKBTypes.PolygonZ) == QgsWKBTypes.PolygonZ
assert QgsWKBTypes.dropM(QgsWKBTypes.PolygonM) == QgsWKBTypes.Polygon
assert QgsWKBTypes.dropM(QgsWKBTypes.PolygonZM) == QgsWKBTypes.PolygonZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPolygon) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPolygonZ) == QgsWKBTypes.MultiPolygonZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPolygonM) == QgsWKBTypes.MultiPolygon
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPolygonZM) == QgsWKBTypes.MultiPolygonZ
assert QgsWKBTypes.dropM(QgsWKBTypes.GeometryCollection) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.dropM(QgsWKBTypes.GeometryCollectionZ) == QgsWKBTypes.GeometryCollectionZ
assert QgsWKBTypes.dropM(QgsWKBTypes.GeometryCollectionM) == QgsWKBTypes.GeometryCollection
assert QgsWKBTypes.dropM(QgsWKBTypes.GeometryCollectionZM) == QgsWKBTypes.GeometryCollectionZ
assert QgsWKBTypes.dropM(QgsWKBTypes.CircularString) == QgsWKBTypes.CircularString
assert QgsWKBTypes.dropM(QgsWKBTypes.CircularStringZ) == QgsWKBTypes.CircularStringZ
assert QgsWKBTypes.dropM(QgsWKBTypes.CircularStringM) == QgsWKBTypes.CircularString
assert QgsWKBTypes.dropM(QgsWKBTypes.CircularStringZM) == QgsWKBTypes.CircularStringZ
assert QgsWKBTypes.dropM(QgsWKBTypes.CompoundCurve) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.dropM(QgsWKBTypes.CompoundCurveZ) == QgsWKBTypes.CompoundCurveZ
assert QgsWKBTypes.dropM(QgsWKBTypes.CompoundCurveM) == QgsWKBTypes.CompoundCurve
assert QgsWKBTypes.dropM(QgsWKBTypes.CompoundCurveZM) == QgsWKBTypes.CompoundCurveZ
assert QgsWKBTypes.dropM(QgsWKBTypes.CurvePolygon) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.dropM(QgsWKBTypes.CurvePolygonZ) == QgsWKBTypes.CurvePolygonZ
assert QgsWKBTypes.dropM(QgsWKBTypes.CurvePolygonM) == QgsWKBTypes.CurvePolygon
assert QgsWKBTypes.dropM(QgsWKBTypes.CurvePolygonZM) == QgsWKBTypes.CurvePolygonZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiCurve) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiCurveZ) == QgsWKBTypes.MultiCurveZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiCurveM) == QgsWKBTypes.MultiCurve
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiCurveZM) == QgsWKBTypes.MultiCurveZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiSurface) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiSurfaceZ) == QgsWKBTypes.MultiSurfaceZ
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiSurfaceM) == QgsWKBTypes.MultiSurface
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiSurfaceZM) == QgsWKBTypes.MultiSurfaceZ
assert QgsWKBTypes.dropM(QgsWKBTypes.NoGeometry) == QgsWKBTypes.NoGeometry
assert QgsWKBTypes.dropM(QgsWKBTypes.Point25D) == QgsWKBTypes.Point25D
assert QgsWKBTypes.dropM(QgsWKBTypes.LineString25D) == QgsWKBTypes.LineString25D
assert QgsWKBTypes.dropM(QgsWKBTypes.Polygon25D) == QgsWKBTypes.Polygon25D
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPoint25D) == QgsWKBTypes.MultiPoint25D
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiLineString25D) == QgsWKBTypes.MultiLineString25D
assert QgsWKBTypes.dropM(QgsWKBTypes.MultiPolygon25D) == QgsWKBTypes.MultiPolygon25D
if __name__ == '__main__':
unittest.main()
|
klnprj/testapp | refs/heads/master | django/utils/cache.py | 88 | """
This module contains helper functions for controlling caching. It does so by
managing the "Vary" header of responses. It includes functions to patch the
header of response objects directly and decorators that change functions to do
that header-patching themselves.
For information on the Vary header, see:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
Essentially, the "Vary" HTTP header defines which headers a cache should take
into account when building its cache key. Requests with the same path but
different header content for headers named in "Vary" need to get different
cache keys to prevent delivery of wrong content.
An example: i18n middleware would need to distinguish caches by the
"Accept-language" header.
"""
import hashlib
import re
import time
from django.conf import settings
from django.core.cache import get_cache
from django.utils.encoding import smart_str, iri_to_uri, force_unicode
from django.utils.http import http_date
from django.utils.timezone import get_current_timezone_name
from django.utils.translation import get_language
cc_delim_re = re.compile(r'\s*,\s*')
def patch_cache_control(response, **kwargs):
"""
This function patches the Cache-Control header by adding all
keyword arguments to it. The transformation is as follows:
* All keyword parameter names are turned to lowercase, and underscores
are converted to hyphens.
* If the value of a parameter is True (exactly True, not just a
true value), only the parameter name is added to the header.
* All other parameters are added with their value, after applying
str() to it.
"""
def dictitem(s):
t = s.split('=', 1)
if len(t) > 1:
return (t[0].lower(), t[1])
else:
return (t[0].lower(), True)
def dictvalue(t):
if t[1] is True:
return t[0]
else:
return t[0] + '=' + smart_str(t[1])
if response.has_header('Cache-Control'):
cc = cc_delim_re.split(response['Cache-Control'])
cc = dict([dictitem(el) for el in cc])
else:
cc = {}
# If there's already a max-age header but we're being asked to set a new
# max-age, use the minimum of the two ages. In practice this happens when
# a decorator and a piece of middleware both operate on a given view.
if 'max-age' in cc and 'max_age' in kwargs:
kwargs['max_age'] = min(cc['max-age'], kwargs['max_age'])
# Allow overriding private caching and vice versa
if 'private' in cc and 'public' in kwargs:
del cc['private']
elif 'public' in cc and 'private' in kwargs:
del cc['public']
for (k, v) in kwargs.items():
cc[k.replace('_', '-')] = v
cc = ', '.join([dictvalue(el) for el in cc.items()])
response['Cache-Control'] = cc
def get_max_age(response):
"""
Returns the max-age from the response Cache-Control header as an integer
(or ``None`` if it wasn't found or wasn't an integer.
"""
if not response.has_header('Cache-Control'):
return
cc = dict([_to_tuple(el) for el in
cc_delim_re.split(response['Cache-Control'])])
if 'max-age' in cc:
try:
return int(cc['max-age'])
except (ValueError, TypeError):
pass
def _set_response_etag(response):
response['ETag'] = '"%s"' % hashlib.md5(response.content).hexdigest()
return response
def patch_response_headers(response, cache_timeout=None):
"""
Adds some useful headers to the given HttpResponse object:
ETag, Last-Modified, Expires and Cache-Control
Each header is only added if it isn't already set.
cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used
by default.
"""
if cache_timeout is None:
cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
if cache_timeout < 0:
cache_timeout = 0 # Can't have max-age negative
if settings.USE_ETAGS and not response.has_header('ETag'):
if hasattr(response, 'render') and callable(response.render):
response.add_post_render_callback(_set_response_etag)
else:
response = _set_response_etag(response)
if not response.has_header('Last-Modified'):
response['Last-Modified'] = http_date()
if not response.has_header('Expires'):
response['Expires'] = http_date(time.time() + cache_timeout)
patch_cache_control(response, max_age=cache_timeout)
def add_never_cache_headers(response):
"""
Adds headers to a response to indicate that a page should never be cached.
"""
patch_response_headers(response, cache_timeout=-1)
def patch_vary_headers(response, newheaders):
"""
Adds (or updates) the "Vary" header in the given HttpResponse object.
newheaders is a list of header names that should be in "Vary". Existing
headers in "Vary" aren't removed.
"""
# Note that we need to keep the original order intact, because cache
# implementations may rely on the order of the Vary contents in, say,
# computing an MD5 hash.
if response.has_header('Vary'):
vary_headers = cc_delim_re.split(response['Vary'])
else:
vary_headers = []
# Use .lower() here so we treat headers as case-insensitive.
existing_headers = set([header.lower() for header in vary_headers])
additional_headers = [newheader for newheader in newheaders
if newheader.lower() not in existing_headers]
response['Vary'] = ', '.join(vary_headers + additional_headers)
def has_vary_header(response, header_query):
"""
Checks to see if the response has a given header name in its Vary header.
"""
if not response.has_header('Vary'):
return False
vary_headers = cc_delim_re.split(response['Vary'])
existing_headers = set([header.lower() for header in vary_headers])
return header_query.lower() in existing_headers
def _i18n_cache_key_suffix(request, cache_key):
"""If necessary, adds the current locale or time zone to the cache key."""
if settings.USE_I18N or settings.USE_L10N:
# first check if LocaleMiddleware or another middleware added
# LANGUAGE_CODE to request, then fall back to the active language
# which in turn can also fall back to settings.LANGUAGE_CODE
cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
if settings.USE_TZ:
# The datetime module doesn't restrict the output of tzname().
# Windows is known to use non-standard, locale-dependant names.
# User-defined tzinfo classes may return absolutely anything.
# Hence this paranoid conversion to create a valid cache key.
tz_name = force_unicode(get_current_timezone_name(), errors='ignore')
cache_key += '.%s' % tz_name.encode('ascii', 'ignore').replace(' ', '_')
return cache_key
def _generate_cache_key(request, method, headerlist, key_prefix):
"""Returns a cache key from the headers given in the header list."""
ctx = hashlib.md5()
for header in headerlist:
value = request.META.get(header, None)
if value is not None:
ctx.update(value)
path = hashlib.md5(iri_to_uri(request.get_full_path()))
cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
key_prefix, method, path.hexdigest(), ctx.hexdigest())
return _i18n_cache_key_suffix(request, cache_key)
def _generate_cache_header_key(key_prefix, request):
"""Returns a cache key for the header cache."""
path = hashlib.md5(iri_to_uri(request.get_full_path()))
cache_key = 'views.decorators.cache.cache_header.%s.%s' % (
key_prefix, path.hexdigest())
return _i18n_cache_key_suffix(request, cache_key)
def get_cache_key(request, key_prefix=None, method='GET', cache=None):
"""
Returns a cache key based on the request path and query. It can be used
in the request phase because it pulls the list of headers to take into
account from the global path registry and uses those to build a cache key
to check against.
If there is no headerlist stored, the page needs to be rebuilt, so this
function returns None.
"""
if key_prefix is None:
key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
cache_key = _generate_cache_header_key(key_prefix, request)
if cache is None:
cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS)
headerlist = cache.get(cache_key, None)
if headerlist is not None:
return _generate_cache_key(request, method, headerlist, key_prefix)
else:
return None
def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
"""
Learns what headers to take into account for some request path from the
response object. It stores those headers in a global path registry so that
later access to that path will know what headers to take into account
without building the response object itself. The headers are named in the
Vary header of the response, but we want to prevent response generation.
The list of headers to use for cache key generation is stored in the same
cache as the pages themselves. If the cache ages some data out of the
cache, this just means that we have to build the response once to get at
the Vary header and so at the list of headers to use for the cache key.
"""
if key_prefix is None:
key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
if cache_timeout is None:
cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
cache_key = _generate_cache_header_key(key_prefix, request)
if cache is None:
cache = get_cache(settings.CACHE_MIDDLEWARE_ALIAS)
if response.has_header('Vary'):
headerlist = ['HTTP_'+header.upper().replace('-', '_')
for header in cc_delim_re.split(response['Vary'])]
cache.set(cache_key, headerlist, cache_timeout)
return _generate_cache_key(request, request.method, headerlist, key_prefix)
else:
# if there is no Vary header, we still need a cache key
# for the request.get_full_path()
cache.set(cache_key, [], cache_timeout)
return _generate_cache_key(request, request.method, [], key_prefix)
def _to_tuple(s):
t = s.split('=',1)
if len(t) == 2:
return t[0].lower(), t[1]
return t[0].lower(), True
|
jordotech/satchmofork | refs/heads/master | satchmo/apps/satchmo_ext/productratings/models.py | 4 | from django.contrib.comments.models import Comment
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
from satchmo_utils.signals import collect_urls
import product
import satchmo_store
class ProductRating(models.Model):
"""A rating attached to a comment"""
comment = models.OneToOneField(Comment, verbose_name="Rating", primary_key=True)
rating = models.IntegerField(_("Rating"))
import config
from urls import add_product_urls, add_comment_urls
collect_urls.connect(add_product_urls, sender=product)
collect_urls.connect(add_comment_urls, sender=satchmo_store)
|
tangposmarvin/CodeIgniter | refs/heads/develop | user_guide_src/source/conf.py | 86 | # -*- coding: utf-8 -*-
#
# CodeIgniter documentation build configuration file, created by
# sphinx-quickstart on Sun Aug 28 07:24:38 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.ifconfig', 'sphinxcontrib.phpdomain']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'CodeIgniter'
copyright = u'2014 - 2015, British Columbia Institute of Technology'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '3.1.0-dev'
# The full version, including alpha/beta/rc tags.
release = '3.1.0-dev'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :php:func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. php:function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'trac'
highlight_language = 'ci'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# Specifying a few options; just a starting point & we can play with it.
html_theme_options = {
}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["./_themes"]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = 'images/ci-icon.ico'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'CodeIgniterdoc'
html_copy_source = False
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'CodeIgniter.tex', u'CodeIgniter Documentation',
u'British Columbia Institute of Technology', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'codeigniter', u'CodeIgniter Documentation',
[u'British Columbia Institute of Technology'], 1)
]
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'CodeIgniter'
epub_author = u'British Columbia Institute of Technology'
epub_publisher = u'British Columbia Institute of Technology'
epub_copyright = u'2014 - 2015, British Columbia Institute of Technology'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
|
ojii/sandlib | refs/heads/master | lib/lib-python/2.7/test/test_lib2to3.py | 137 | # Skipping test_parser and test_all_fixers
# because of running
from lib2to3.tests import (test_fixers, test_pytree, test_util, test_refactor,
test_parser, test_main as test_main_)
import unittest
from test.test_support import run_unittest
def suite():
tests = unittest.TestSuite()
loader = unittest.TestLoader()
for m in (test_fixers, test_pytree,test_util, test_refactor, test_parser,
test_main_):
tests.addTests(loader.loadTestsFromModule(m))
return tests
def test_main():
run_unittest(suite())
if __name__ == '__main__':
test_main()
|
kgiusti/gofer | refs/heads/master | src/gofer/rmi/policy.py | 1 | #
# Copyright (c) 2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU Lesser General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (LGPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the implied warranties of MERCHANTABILITY,
# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should
# have received a copy of LGPLv2 along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/lgpl-2.0.txt.
#
# Jeff Ortel <jortel@redhat.com>
#
"""
Contains request delivery policies.
"""
from logging import getLogger
from uuid import uuid4
from gofer.common import Thread, Options, nvl, utf8
from gofer.messaging import Document, DocumentError
from gofer.messaging import Producer, Reader, Queue, Exchange
from gofer.rmi.dispatcher import Return, RemoteException
from gofer.metrics import Timer
log = getLogger(__name__)
class Timeout:
"""
Policy timeout.
:cvar MINUTE: Minutes in seconds.
:cvar HOUR: Hour is seconds
:cvar DAY: Day in seconds
:cvar SUFFIX: Suffix to multiplier mapping.
"""
SECOND = 1
MINUTE = 60
HOUR = (MINUTE * 60)
DAY = (HOUR * 24)
SUFFIX = {
's': SECOND,
'm': MINUTE,
'h': HOUR,
'd': DAY,
}
@classmethod
def seconds(cls, thing):
"""
Convert tm to seconds based on suffix.
:param thing: A timeout value.
The string value may have a suffix of:
(s) = seconds
(m) = minutes
(h) = hours
(d) = days
:type thing: (None|int|float|str)
"""
if thing is None:
return thing
if isinstance(thing, int):
return thing
if isinstance(thing, float):
return int(thing)
if not isinstance(thing, basestring):
raise TypeError(thing)
if not len(thing):
raise ValueError(thing)
if cls.has_suffix(thing):
multiplier = cls.SUFFIX[thing[-1]]
return multiplier * int(thing[:-1])
else:
return int(thing)
@classmethod
def has_suffix(cls, tm):
for k in cls.SUFFIX.keys():
if tm.endswith(k):
return True
return False
def __init__(self, start=None, duration=None):
self.start = self.seconds(start)
self.duration = self.seconds(duration)
def tuple(self):
return self.start, self.duration
class RequestTimeout(Exception):
"""
Request timeout.
"""
def __init__(self, sn, timeout):
"""
:param sn: The request serial number.
:type sn: str
"""
Exception.__init__(self, sn, timeout)
def sn(self):
return self.args[0]
def timeout(self):
return self.args[1]
class Policy(object):
"""
The method invocation policy.
:ivar url: The broker URL.
:type url: str
:ivar address: The AMQP address.
:type address: str
:ivar options: The RMI options.
:type options: gofer.Options
"""
def __init__(self, url, address, options):
"""
:param url: The broker URL.
:type url: str
:param address: The AMQP address.
:type address: str
:param options: The RMI options.
:type options: gofer.Options
"""
self.url = url
self.address = address
self.options = options
@property
def ttl(self):
if self.options.ttl:
return Timeout.seconds(self.options.ttl)
else:
return None
@property
def wait(self):
return Timeout.seconds(nvl(self.options.wait, 90))
@property
def progress(self):
return self.options.progress
@property
def authenticator(self):
return self.options.authenticator
@property
def reply(self):
return self.options.reply
@property
def trigger(self):
return self.options.trigger or 0
@property
def pam(self):
if self.options.user:
return Options(user=self.options.user, password=self.options.password)
else:
return None
@property
def secret(self):
return self.options.secret
@property
def data(self):
return self.options.data
@property
def exchange(self):
return self.options.exchange
def get_reply(self, sn, reader):
"""
Get the reply matched by serial number.
:param sn: The request serial number.
:type sn: str
:param reader: A reader.
:type reader: gofer.messaging.consumer.Reader
:return: The matched reply document.
:rtype: Document
"""
timer = Timer()
timeout = float(self.wait)
while not Thread.aborted():
timer.start()
document = reader.search(sn, int(timeout))
timer.stop()
elapsed = timer.duration()
if elapsed > timeout:
raise RequestTimeout(sn, self.wait)
else:
timeout -= elapsed
if not document:
raise RequestTimeout(sn, self.wait)
# rejected
if document.status == 'rejected':
raise DocumentError(
document.code,
document.description,
document.document,
document.details)
# accepted | started
if document.status in ('accepted', 'started'):
continue
# progress reported
if document.status == 'progress':
self.on_progress(document)
continue
# reply
return self.on_reply(document)
def on_reply(self, document):
"""
Handle the reply.
:param document: The reply document.
:type document: Document
:return: The matched reply document.
:rtype: Document
"""
reply = Return(document.result)
if reply.succeeded():
return reply.retval
else:
raise RemoteException.instance(reply)
def on_progress(self, document):
"""
Handle the progress report.
:param document: The status document.
:type document: Document
"""
try:
reporter = self.progress
if callable(reporter):
report = dict(
sn=document.sn,
data=document.data,
total=document.total,
completed=document.completed,
details=document.details)
reporter(report)
except Exception:
log.error('progress callback failed', exc_info=1)
def __call__(self, request):
"""
Send the request then read the reply.
:param request: A request to send.
:type request: object
:rtype: object
:raise Exception: returned by the peer.
"""
trigger = Trigger(self, request)
if self.trigger == Trigger.MANUAL:
return trigger
else:
return trigger()
class Trigger:
"""
Asynchronous trigger.
:ivar _pending: pending flag.
:type _pending: bool
:ivar _sn: request serial number
:type _sn: str
:ivar _policy: The policy object.
:type _policy: Policy
:ivar _request: A request to send.
:type _request: object
"""
MANUAL = 1 # trigger
NOWAIT = 0 # wait (seconds)
def __init__(self, policy, request):
"""
:param policy: The policy object.
:type policy: Policy
:param request: A request to send.
:type request: object
"""
self._sn = utf8(uuid4())
self._policy = policy
self._request = request
self._pending = True
@property
def sn(self):
return self._sn
def _send(self, reply=None, queue=None):
"""
Send the request using the specified policy
object and generated serial number.
:param reply: The AMQP reply address.
:type reply: str
:param queue: The reply queue for synchronous calls.
:type queue: Queue
"""
producer = Producer(self._policy.url)
producer.authenticator = self._policy.authenticator
producer.open()
try:
producer.send(
self._policy.address,
self._policy.ttl,
# body
sn=self.sn,
replyto=reply,
request=self._request,
secret=self._policy.secret,
pam=self._policy.pam,
data=self._policy.data)
finally:
producer.close()
log.debug('sent (%s): %s', self._policy.address, self._request)
if queue is None:
# no reply expected
return self._sn
reader = Reader(queue, self._policy.url)
reader.authenticator = self._policy.authenticator
reader.open()
try:
policy = self._policy
return policy.get_reply(self.sn, reader)
finally:
reader.close()
def __call__(self):
"""
Trigger pulled.
Execute the request.
"""
if not self._pending:
raise Exception('trigger already executed')
self._pending = False
# asynchronous
if self._policy.reply:
return self._send(reply=self._policy.reply)
if self._policy.wait == Trigger.NOWAIT:
return self._send()
# synchronous
queue = Queue()
queue.durable = False
queue.declare(self._policy.url)
reply = queue.name
if self._policy.exchange:
exchange = Exchange(self._policy.exchange)
exchange.bind(queue, self._policy.url)
reply = '/'.join((self._policy.exchange, queue.name))
try:
return self._send(reply=reply, queue=queue)
finally:
queue.purge(self._policy.url)
queue.delete(self._policy.url)
def __unicode__(self):
return self._sn
def __str__(self):
return utf8(self)
|
dayatz/taiga-back | refs/heads/stable | taiga/projects/tagging/services.py | 1 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.db import connection
def tag_exist_for_project_elements(project, tag):
return tag in dict(project.tags_colors).keys()
def create_tags(project, new_tags_colors):
project.tags_colors += [[k.lower(), v] for k, v in new_tags_colors.items()]
project.save(update_fields=["tags_colors"])
def create_tag(project, tag, color):
project.tags_colors.append([tag.lower(), color])
project.save(update_fields=["tags_colors"])
def edit_tag(project, from_tag, to_tag, color):
to_tag = to_tag.lower()
sql = """
UPDATE userstories_userstory
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
UPDATE tasks_task
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
UPDATE issues_issue
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
UPDATE epics_epic
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
"""
cursor = connection.cursor()
cursor.execute(sql, params={"from_tag": from_tag, "to_tag": to_tag, "project_id": project.id})
tags_colors = dict(project.tags_colors)
tags_colors.pop(from_tag)
tags_colors[to_tag] = color
project.tags_colors = list(tags_colors.items())
project.save(update_fields=["tags_colors"])
def rename_tag(project, from_tag, to_tag, **kwargs):
# Kwargs can have a color parameter
update_color = "color" in kwargs
to_tag = to_tag.lower()
if update_color:
color = kwargs.get("color")
else:
color = dict(project.tags_colors)[from_tag]
sql = """
UPDATE userstories_userstory
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
UPDATE tasks_task
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
UPDATE issues_issue
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
UPDATE epics_epic
SET tags = array_distinct(array_replace(tags, %(from_tag)s, %(to_tag)s))
WHERE project_id = %(project_id)s;
"""
cursor = connection.cursor()
cursor.execute(sql, params={"from_tag": from_tag, "to_tag": to_tag, "project_id": project.id})
tags_colors = dict(project.tags_colors)
tags_colors.pop(from_tag)
tags_colors[to_tag] = color
project.tags_colors = list(tags_colors.items())
project.save(update_fields=["tags_colors"])
def delete_tag(project, tag):
sql = """
UPDATE userstories_userstory
SET tags = array_remove(tags, %(tag)s)
WHERE project_id = %(project_id)s;
UPDATE tasks_task
SET tags = array_remove(tags, %(tag)s)
WHERE project_id = %(project_id)s;
UPDATE issues_issue
SET tags = array_remove(tags, %(tag)s)
WHERE project_id = %(project_id)s;
UPDATE epics_epic
SET tags = array_remove(tags, %(tag)s)
WHERE project_id = %(project_id)s;
"""
cursor = connection.cursor()
cursor.execute(sql, params={"tag": tag, "project_id": project.id})
tags_colors = dict(project.tags_colors)
del tags_colors[tag]
project.tags_colors = list(tags_colors.items())
project.save(update_fields=["tags_colors"])
def mix_tags(project, from_tags, to_tag):
color = dict(project.tags_colors)[to_tag]
for from_tag in from_tags:
rename_tag(project, from_tag, to_tag, color=color)
|
blink1073/imageio | refs/heads/master | imageio/core/__init__.py | 1 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, imageio contributors
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
""" This subpackage provides the core functionality of imageio
(everything but the plugins).
"""
from .util import Image, Dict, asarray, image_as_uint8, urlopen # noqa
from .util import BaseProgressIndicator, StdoutProgressIndicator # noqa
from .util import string_types, text_type, binary_type, IS_PYPY # noqa
from .util import get_platform, appdata_dir, resource_dirs # noqa
from .findlib import load_lib # noqa
from .fetching import get_remote_file, InternetNotAllowedError # noqa
from .request import Request, read_n_bytes, RETURN_BYTES # noqa
from .format import Format, FormatManager # noqa
|
AndreyPopovNew/asuswrt-merlin-rt-n | refs/heads/master | release/src/router/samba3/source/stf/strings.py | 55 | #! /usr/bin/python
# Comfychair test cases for Samba string functions.
# Copyright (C) 2003 by Martin Pool <mbp@samba.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
# XXX: All this code assumes that the Unix character set is UTF-8,
# which is the most common setting. I guess it would be better to
# force it to that value while running the tests. I'm not sure of the
# best way to do that yet.
#
# Note that this is NOT the case in C code until the loadparm table is
# intialized -- the default seems to be ASCII, which rather lets Samba
# off the hook. :-) The best way seems to be to put this in the test
# harnesses:
#
# lp_load("/dev/null", True, False, False);
#
# -- mbp
import sys, re, comfychair
from unicodenames import *
def signum(a):
if a < 0:
return -1
elif a > 0:
return +1
else:
return 0
class PushUCS2_Tests(comfychair.TestCase):
"""Conversion to/from UCS2"""
def runtest(self):
OE = LATIN_CAPITAL_LETTER_O_WITH_DIARESIS
oe = LATIN_CAPITAL_LETTER_O_WITH_DIARESIS
cases = ['hello',
'hello world',
'g' + OE + OE + 'gomobile',
'g' + OE + oe + 'gomobile',
u'foo\u0100',
KATAKANA_LETTER_A * 20,
]
for u8str in cases:
out, err = self.runcmd("t_push_ucs2 \"%s\"" % u8str.encode('utf-8'))
self.assert_equal(out, "0\n")
class StrCaseCmp(comfychair.TestCase):
"""String comparisons in simple ASCII"""
def run_strcmp(self, a, b, expect):
out, err = self.runcmd('t_strcmp \"%s\" \"%s\"' % (a.encode('utf-8'), b.encode('utf-8')))
if signum(int(out)) != expect:
self.fail("comparison failed:\n"
" a=%s\n"
" b=%s\n"
" expected=%s\n"
" result=%s\n" % (`a`, `b`, `expect`, `out`))
def runtest(self):
# A, B, strcasecmp(A, B)
cases = [('hello', 'hello', 0),
('hello', 'goodbye', +1),
('goodbye', 'hello', -1),
('hell', 'hello', -1),
('', '', 0),
('a', '', +1),
('', 'a', -1),
('a', 'A', 0),
('aa', 'aA', 0),
('Aa', 'aa', 0),
('longstring ' * 100, 'longstring ' * 100, 0),
('longstring ' * 100, 'longstring ' * 100 + 'a', -1),
('longstring ' * 100 + 'a', 'longstring ' * 100, +1),
(KATAKANA_LETTER_A, KATAKANA_LETTER_A, 0),
(KATAKANA_LETTER_A, 'a', 1),
]
for a, b, expect in cases:
self.run_strcmp(a, b, expect)
class strstr_m(comfychair.TestCase):
"""String comparisons in simple ASCII"""
def run_strstr(self, a, b, expect):
out, err = self.runcmd('t_strstr \"%s\" \"%s\"' % (a.encode('utf-8'), b.encode('utf-8')))
if (out != (expect + '\n').encode('utf-8')):
self.fail("comparison failed:\n"
" a=%s\n"
" b=%s\n"
" expected=%s\n"
" result=%s\n" % (`a`, `b`, `expect+'\n'`, `out`))
def runtest(self):
# A, B, strstr_m(A, B)
cases = [('hello', 'hello', 'hello'),
('hello', 'goodbye', '(null)'),
('goodbye', 'hello', '(null)'),
('hell', 'hello', '(null)'),
('hello', 'hell', 'hello'),
('', '', ''),
('a', '', 'a'),
('', 'a', '(null)'),
('a', 'A', '(null)'),
('aa', 'aA', '(null)'),
('Aa', 'aa', '(null)'),
('%v foo', '%v', '%v foo'),
('foo %v foo', '%v', '%v foo'),
('foo %v', '%v', '%v'),
('longstring ' * 100, 'longstring ' * 99, 'longstring ' * 100),
('longstring ' * 99, 'longstring ' * 100, '(null)'),
('longstring a' * 99, 'longstring ' * 100 + 'a', '(null)'),
('longstring ' * 100 + 'a', 'longstring ' * 100, 'longstring ' * 100 + 'a'),
(KATAKANA_LETTER_A, KATAKANA_LETTER_A + 'bcd', '(null)'),
(KATAKANA_LETTER_A + 'bcde', KATAKANA_LETTER_A + 'bcd', KATAKANA_LETTER_A + 'bcde'),
('d'+KATAKANA_LETTER_A + 'bcd', KATAKANA_LETTER_A + 'bcd', KATAKANA_LETTER_A + 'bcd'),
('d'+KATAKANA_LETTER_A + 'bd', KATAKANA_LETTER_A + 'bcd', '(null)'),
('e'+KATAKANA_LETTER_A + 'bcdf', KATAKANA_LETTER_A + 'bcd', KATAKANA_LETTER_A + 'bcdf'),
(KATAKANA_LETTER_A, KATAKANA_LETTER_A + 'bcd', '(null)'),
(KATAKANA_LETTER_A*3, 'a', '(null)'),
]
for a, b, expect in cases:
self.run_strstr(a, b, expect)
# Define the tests exported by this module
tests = [StrCaseCmp,
strstr_m,
PushUCS2_Tests]
# Handle execution of this file as a main program
if __name__ == '__main__':
comfychair.main(tests)
# Local variables:
# coding: utf-8
# End:
|
MartinHjelmare/home-assistant | refs/heads/dev | homeassistant/components/onewire/sensor.py | 7 | """Support for 1-Wire environment sensors."""
import os
import time
import logging
from glob import glob
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.const import TEMP_CELSIUS
from homeassistant.components.sensor import PLATFORM_SCHEMA
_LOGGER = logging.getLogger(__name__)
CONF_MOUNT_DIR = 'mount_dir'
CONF_NAMES = 'names'
DEFAULT_MOUNT_DIR = '/sys/bus/w1/devices/'
DEVICE_SENSORS = {'10': {'temperature': 'temperature'},
'12': {'temperature': 'TAI8570/temperature',
'pressure': 'TAI8570/pressure'},
'22': {'temperature': 'temperature'},
'26': {'temperature': 'temperature',
'humidity': 'humidity',
'pressure': 'B1-R1-A/pressure',
'illuminance': 'S3-R1-A/illuminance'},
'28': {'temperature': 'temperature'},
'3B': {'temperature': 'temperature'},
'42': {'temperature': 'temperature'}}
SENSOR_TYPES = {
'temperature': ['temperature', TEMP_CELSIUS],
'humidity': ['humidity', '%'],
'pressure': ['pressure', 'mb'],
'illuminance': ['illuminance', 'lux'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAMES): {cv.string: cv.string},
vol.Optional(CONF_MOUNT_DIR, default=DEFAULT_MOUNT_DIR): cv.string,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the one wire Sensors."""
base_dir = config.get(CONF_MOUNT_DIR)
devs = []
device_names = {}
if 'names' in config:
if isinstance(config['names'], dict):
device_names = config['names']
if base_dir == DEFAULT_MOUNT_DIR:
for device_family in DEVICE_SENSORS:
for device_folder in glob(os.path.join(base_dir, device_family +
'[.-]*')):
sensor_id = os.path.split(device_folder)[1]
device_file = os.path.join(device_folder, 'w1_slave')
devs.append(OneWireDirect(device_names.get(sensor_id,
sensor_id),
device_file, 'temperature'))
else:
for family_file_path in glob(os.path.join(base_dir, '*', 'family')):
with open(family_file_path, "r") as family_file:
family = family_file.read()
if family in DEVICE_SENSORS:
for sensor_key, sensor_value in DEVICE_SENSORS[family].items():
sensor_id = os.path.split(
os.path.split(family_file_path)[0])[1]
device_file = os.path.join(
os.path.split(family_file_path)[0], sensor_value)
devs.append(OneWireOWFS(device_names.get(sensor_id,
sensor_id),
device_file, sensor_key))
if devs == []:
_LOGGER.error("No onewire sensor found. Check if dtoverlay=w1-gpio "
"is in your /boot/config.txt. "
"Check the mount_dir parameter if it's defined")
return
add_entities(devs, True)
class OneWire(Entity):
"""Implementation of an One wire Sensor."""
def __init__(self, name, device_file, sensor_type):
"""Initialize the sensor."""
self._name = name+' '+sensor_type.capitalize()
self._device_file = device_file
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._state = None
def _read_value_raw(self):
"""Read the value as it is returned by the sensor."""
with open(self._device_file, 'r') as ds_device_file:
lines = ds_device_file.readlines()
return lines
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
class OneWireDirect(OneWire):
"""Implementation of an One wire Sensor directly connected to RPI GPIO."""
def update(self):
"""Get the latest data from the device."""
value = None
lines = self._read_value_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = self._read_value_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
value_string = lines[1][equals_pos + 2:]
value = round(float(value_string) / 1000.0, 1)
self._state = value
class OneWireOWFS(OneWire):
"""Implementation of an One wire Sensor through owfs."""
def update(self):
"""Get the latest data from the device."""
value = None
try:
value_read = self._read_value_raw()
if len(value_read) == 1:
value = round(float(value_read[0]), 1)
except ValueError:
_LOGGER.warning("Invalid value read from %s", self._device_file)
except FileNotFoundError:
_LOGGER.warning("Cannot read from sensor: %s", self._device_file)
self._state = value
|
kiran/bart-sign | refs/heads/master | venv/lib/python2.7/site-packages/numpy/distutils/__version__.py | 264 | from __future__ import division, absolute_import, print_function
major = 0
minor = 4
micro = 0
version = '%(major)d.%(minor)d.%(micro)d' % (locals())
|
rcatwood/Savu | refs/heads/master | savu/test/travis/framework_tests/plugins_util_test.py | 1 | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
.. module:: plugins_util_test
:platform: Unix
:synopsis: unittest test class for plugin utils
.. moduleauthor:: Mark Basham <scientificsoftware@diamond.ac.uk>
"""
import unittest
import savu
import os
from savu.plugins import utils as pu
from savu.plugins import plugin as test_plugin
class Test(unittest.TestCase):
def testGetPlugin(self):
plugin = pu.load_plugin("savu.plugins.plugin")
self.assertEqual(plugin.__class__, test_plugin.Plugin,
"Failed to load the correct class")
self.assertRaises(NotImplementedError, plugin.process_frames, None, None)
def testfind_args(self):
plugin = pu.load_plugin("savu.plugins.filters.denoise_bregman_filter")
params = pu.find_args(plugin)
self.assertEqual(len(params), 4)
def test_get_plugin_external_path(self):
savu_path = os.path.split(savu.__path__[0])[0]
plugin = pu.load_plugin(os.path.join(savu_path, "plugin_examples", "example_median_filter"))
self.assertEqual(plugin.name, "ExampleMedianFilter")
if __name__ == "__main__":
unittest.main()
|
Apoc2400/Reftag | refs/heads/master | atom/data.py | 18 | #!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
__author__ = 'j.s@google.com (Jeff Scudder)'
import atom.core
ATOM_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
APP_TEMPLATE_V1 = '{http://purl.org/atom/app#}%s'
APP_TEMPLATE_V2 = '{http://www.w3.org/2007/app}%s'
class Name(atom.core.XmlElement):
"""The atom:name element."""
_qname = ATOM_TEMPLATE % 'name'
class Email(atom.core.XmlElement):
"""The atom:email element."""
_qname = ATOM_TEMPLATE % 'email'
class Uri(atom.core.XmlElement):
"""The atom:uri element."""
_qname = ATOM_TEMPLATE % 'uri'
class Person(atom.core.XmlElement):
"""A foundation class which atom:author and atom:contributor extend.
A person contains information like name, email address, and web page URI for
an author or contributor to an Atom feed.
"""
name = Name
email = Email
uri = Uri
class Author(Person):
"""The atom:author element.
An author is a required element in Feed unless each Entry contains an Author.
"""
_qname = ATOM_TEMPLATE % 'author'
class Contributor(Person):
"""The atom:contributor element."""
_qname = ATOM_TEMPLATE % 'contributor'
class Link(atom.core.XmlElement):
"""The atom:link element."""
_qname = ATOM_TEMPLATE % 'link'
href = 'href'
rel = 'rel'
type = 'type'
hreflang = 'hreflang'
title = 'title'
length = 'length'
class Generator(atom.core.XmlElement):
"""The atom:generator element."""
_qname = ATOM_TEMPLATE % 'generator'
uri = 'uri'
version = 'version'
class Text(atom.core.XmlElement):
"""A foundation class from which atom:title, summary, etc. extend.
This class should never be instantiated.
"""
type = 'type'
class Title(Text):
"""The atom:title element."""
_qname = ATOM_TEMPLATE % 'title'
class Subtitle(Text):
"""The atom:subtitle element."""
_qname = ATOM_TEMPLATE % 'subtitle'
class Rights(Text):
"""The atom:rights element."""
_qname = ATOM_TEMPLATE % 'rights'
class Summary(Text):
"""The atom:summary element."""
_qname = ATOM_TEMPLATE % 'summary'
class Content(Text):
"""The atom:content element."""
_qname = ATOM_TEMPLATE % 'content'
src = 'src'
class Category(atom.core.XmlElement):
"""The atom:category element."""
_qname = ATOM_TEMPLATE % 'category'
term = 'term'
scheme = 'scheme'
label = 'label'
class Id(atom.core.XmlElement):
"""The atom:id element."""
_qname = ATOM_TEMPLATE % 'id'
class Icon(atom.core.XmlElement):
"""The atom:icon element."""
_qname = ATOM_TEMPLATE % 'icon'
class Logo(atom.core.XmlElement):
"""The atom:logo element."""
_qname = ATOM_TEMPLATE % 'logo'
class Draft(atom.core.XmlElement):
"""The app:draft element which indicates if this entry should be public."""
_qname = (APP_TEMPLATE_V1 % 'draft', APP_TEMPLATE_V2 % 'draft')
class Control(atom.core.XmlElement):
"""The app:control element indicating restrictions on publication.
The APP control element may contain a draft element indicating whether or
not this entry should be publicly available.
"""
_qname = (APP_TEMPLATE_V1 % 'control', APP_TEMPLATE_V2 % 'control')
draft = Draft
class Date(atom.core.XmlElement):
"""A parent class for atom:updated, published, etc."""
class Updated(Date):
"""The atom:updated element."""
_qname = ATOM_TEMPLATE % 'updated'
class Published(Date):
"""The atom:published element."""
_qname = ATOM_TEMPLATE % 'published'
class LinkFinder(object):
"""An "interface" providing methods to find link elements
Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in Atom entries and feeds.
"""
def find_url(self, rel):
"""Returns the URL in a link with the desired rel value."""
for link in self.link:
if link.rel == rel and link.href:
return link.href
return None
FindUrl = find_url
def get_link(self, rel):
"""Returns a link object which has the desired rel value.
If you are interested in the URL instead of the link object,
consider using find_url instead.
"""
for link in self.link:
if link.rel == rel and link.href:
return link
return None
GetLink = get_link
def find_self_link(self):
"""Find the first link with rel set to 'self'
Returns:
A str containing the link's href or None if none of the links had rel
equal to 'self'
"""
return self.find_url('self')
FindSelfLink = find_self_link
def get_self_link(self):
return self.get_link('self')
GetSelfLink = get_self_link
def find_edit_link(self):
return self.find_url('edit')
FindEditLink = find_edit_link
def get_edit_link(self):
return self.get_link('edit')
GetEditLink = get_edit_link
def find_edit_media_link(self):
link = self.find_url('edit-media')
# Search for media-edit as well since Picasa API used media-edit instead.
if link is None:
return self.find_url('media-edit')
return link
FindEditMediaLink = find_edit_media_link
def get_edit_media_link(self):
link = self.get_link('edit-media')
if link is None:
return self.get_link('media-edit')
return link
GetEditMediaLink = get_edit_media_link
def find_next_link(self):
return self.find_url('next')
FindNextLink = find_next_link
def get_next_link(self):
return self.get_link('next')
GetNextLink = get_next_link
def find_license_link(self):
return self.find_url('license')
FindLicenseLink = find_license_link
def get_license_link(self):
return self.get_link('license')
GetLicenseLink = get_license_link
def find_alternate_link(self):
return self.find_url('alternate')
FindAlternateLink = find_alternate_link
def get_alternate_link(self):
return self.get_link('alternate')
GetAlternateLink = get_alternate_link
class FeedEntryParent(atom.core.XmlElement, LinkFinder):
"""A super class for atom:feed and entry, contains shared attributes"""
author = [Author]
category = [Category]
contributor = [Contributor]
id = Id
link = [Link]
rights = Rights
title = Title
updated = Updated
def __init__(self, atom_id=None, text=None, *args, **kwargs):
if atom_id is not None:
self.id = atom_id
atom.core.XmlElement.__init__(self, text=text, *args, **kwargs)
class Source(FeedEntryParent):
"""The atom:source element."""
_qname = ATOM_TEMPLATE % 'source'
generator = Generator
icon = Icon
logo = Logo
subtitle = Subtitle
class Entry(FeedEntryParent):
"""The atom:entry element."""
_qname = ATOM_TEMPLATE % 'entry'
content = Content
published = Published
source = Source
summary = Summary
control = Control
class Feed(Source):
"""The atom:feed element which contains entries."""
_qname = ATOM_TEMPLATE % 'feed'
entry = [Entry]
class ExtensionElement(atom.core.XmlElement):
"""Provided for backwards compatibility to the v1 atom.ExtensionElement."""
def __init__(self, tag=None, namespace=None, attributes=None,
children=None, text=None, *args, **kwargs):
if namespace:
self._qname = '{%s}%s' % (namespace, tag)
else:
self._qname = tag
self.children = children or []
self.attributes = attributes or {}
self.text = text
_BecomeChildElement = atom.core.XmlElement._become_child
|
broferek/ansible | refs/heads/devel | test/units/module_utils/conftest.py | 80 | # Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import json
import sys
from io import BytesIO
import pytest
import ansible.module_utils.basic
from ansible.module_utils.six import PY3, string_types
from ansible.module_utils._text import to_bytes
from ansible.module_utils.common._collections_compat import MutableMapping
@pytest.fixture
def stdin(mocker, request):
old_args = ansible.module_utils.basic._ANSIBLE_ARGS
ansible.module_utils.basic._ANSIBLE_ARGS = None
old_argv = sys.argv
sys.argv = ['ansible_unittest']
if isinstance(request.param, string_types):
args = request.param
elif isinstance(request.param, MutableMapping):
if 'ANSIBLE_MODULE_ARGS' not in request.param:
request.param = {'ANSIBLE_MODULE_ARGS': request.param}
if '_ansible_remote_tmp' not in request.param['ANSIBLE_MODULE_ARGS']:
request.param['ANSIBLE_MODULE_ARGS']['_ansible_remote_tmp'] = '/tmp'
if '_ansible_keep_remote_files' not in request.param['ANSIBLE_MODULE_ARGS']:
request.param['ANSIBLE_MODULE_ARGS']['_ansible_keep_remote_files'] = False
args = json.dumps(request.param)
else:
raise Exception('Malformed data to the stdin pytest fixture')
fake_stdin = BytesIO(to_bytes(args, errors='surrogate_or_strict'))
if PY3:
mocker.patch('ansible.module_utils.basic.sys.stdin', mocker.MagicMock())
mocker.patch('ansible.module_utils.basic.sys.stdin.buffer', fake_stdin)
else:
mocker.patch('ansible.module_utils.basic.sys.stdin', fake_stdin)
yield fake_stdin
ansible.module_utils.basic._ANSIBLE_ARGS = old_args
sys.argv = old_argv
@pytest.fixture
def am(stdin, request):
old_args = ansible.module_utils.basic._ANSIBLE_ARGS
ansible.module_utils.basic._ANSIBLE_ARGS = None
old_argv = sys.argv
sys.argv = ['ansible_unittest']
argspec = {}
if hasattr(request, 'param'):
if isinstance(request.param, dict):
argspec = request.param
am = ansible.module_utils.basic.AnsibleModule(
argument_spec=argspec,
)
am._name = 'ansible_unittest'
yield am
ansible.module_utils.basic._ANSIBLE_ARGS = old_args
sys.argv = old_argv
|
tangfeixiong/nova | refs/heads/stable/juno | nova/tests/functional/v3/test_extended_status.py | 28 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from nova.tests.functional.v3 import test_servers
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.extensions')
class ExtendedStatusSampleJsonTests(test_servers.ServersSampleBase):
extension_name = "os-extended-status"
extra_extensions_to_load = ["os-access-ips"]
_api_version = 'v2'
def _get_flags(self):
f = super(ExtendedStatusSampleJsonTests, self)._get_flags()
f['osapi_compute_extension'] = CONF.osapi_compute_extension[:]
f['osapi_compute_extension'].append(
'nova.api.openstack.compute.contrib.keypairs.Keypairs')
f['osapi_compute_extension'].append(
'nova.api.openstack.compute.contrib.extended_ips.Extended_ips')
f['osapi_compute_extension'].append(
'nova.api.openstack.compute.contrib.extended_ips_mac.'
'Extended_ips_mac')
f['osapi_compute_extension'].append(
'nova.api.openstack.compute.contrib.extended_status.'
'Extended_status')
return f
def test_show(self):
uuid = self._post_server()
response = self._do_get('servers/%s' % uuid)
subs = self._get_regexes()
subs['hostid'] = '[a-f0-9]+'
subs['access_ip_v4'] = '1.2.3.4'
subs['access_ip_v6'] = '80fe::'
self._verify_response('server-get-resp', subs, response, 200)
def test_detail(self):
uuid = self._post_server()
response = self._do_get('servers/detail')
subs = self._get_regexes()
subs['id'] = uuid
subs['hostid'] = '[a-f0-9]+'
subs['access_ip_v4'] = '1.2.3.4'
subs['access_ip_v6'] = '80fe::'
self._verify_response('servers-detail-resp', subs, response, 200)
|
risicle/django | refs/heads/master | tests/cache/__init__.py | 12133432 | |
sestrella/ansible | refs/heads/devel | lib/ansible/modules/net_tools/ldap/__init__.py | 12133432 | |
thisispuneet/potato-blog | refs/heads/master | django/contrib/localflavor/pe/__init__.py | 12133432 | |
eyohansa/django | refs/heads/master | django/contrib/gis/db/backends/spatialite/__init__.py | 12133432 | |
submitconsulting/backenddj | refs/heads/master | apps/sad/tests/__init__.py | 12133432 | |
coll-gate/collgate | refs/heads/master | messenger/tcpserver/appsettings.py | 1 | # -*- coding: utf-8; -*-
#
# @file appsettings.py
# @brief coll-gate messenger tcp server application settings
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2017-10-09
# @copyright Copyright (c) 2017 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
# Default settings of the application
APP_DB_DEFAULT_SETTINGS = {
}
APP_VERBOSE_NAME = "Coll-Gate :: Messenger TCP server"
APP_SETTINGS_MODEL = 'main.models.Settings'
# defines the string to build the path of the 4xx, 5xx templates
HTTP_TEMPLATE_STRING = "main/%s.html"
APP_VERSION = (0, 1, 0)
|
aspose-email/Aspose.Email-for-Java | refs/heads/master | Plugins/Aspose-Email-Java-for-Jython/asposeemail/ProgrammingOutlook/CreateOutlookContact.py | 4 | from asposeemail import Settings
from com.aspose.email import MapiContact
from com.aspose.email import MapiContactNamePropertySet
from com.aspose.email import MapiContactProfessionalPropertySet
from com.aspose.email import MapiContactTelephonePropertySet
from com.aspose.email import MapiContactPhysicalAddress
from com.aspose.email import MapiContactPhysicalAddressPropertySet
from com.aspose.email import MapiContactElectronicAddress
from com.aspose.email import MapiContactElectronicAddressPropertySet
from com.aspose.email import ContactSaveFormat
class CreateOutlookContact:
def __init__(self):
dataDir = Settings.dataDir + 'ProgrammingOutlook/WorkingWithOutlookMessageFiles/CreateOutlookContact/'
contact = MapiContact()
# Set different properties of this Contact Item.
# Set Name properties using MapiContactNamePropertySet
name_prop_set = MapiContactNamePropertySet()
name_prop_set.setSurname("Mellissa")
name_prop_set.setGivenName("MacBeth")
contact.setNameInfo(name_prop_set)
# Set professional properties using MapiContactProfessionalPropertySet
prof_prop_set = MapiContactProfessionalPropertySet()
prof_prop_set.setTitle("Account Representative")
prof_prop_set.setCompanyName("Contoso Ltd.")
prof_prop_set.setOfficeLocation("36/2529")
contact.setProfessionalInfo(prof_prop_set)
# Telephones
telephone = MapiContactTelephonePropertySet()
telephone.setAssistantTelephoneNumber("(831) 758-7214")
telephone.setBusiness2TelephoneNumber("(831) 759-2518")
telephone.setBusinessTelephoneNumber("(831) 758-7285")
telephone.setCallbackTelephoneNumber("(831) 758-7321 (After hours")
telephone.setCarTelephoneNumber("(831) 758-7201")
telephone.setCompanyMainTelephoneNumber("(831) 758-7368")
telephone.setHome2TelephoneNumber("(831) 758-7256")
telephone.setHomeTelephoneNumber("(831) 758-7257")
telephone.setIsdnNumber("(831) 758-7381")
telephone.setMobileTelephoneNumber("(831) 758-7368")
telephone.setOtherTelephoneNumber("(831) 758-7201")
telephone.setPagerTelephoneNumber("(831) 758-7368")
telephone.setPrimaryTelephoneNumber("(831) 758-7334")
telephone.setRadioTelephoneNumber("(831) 758-7234")
telephone.setTelexNumber("(831) 758-7408")
telephone.setTtyTddPhoneNumber("(800) 806-4474")
contact.setTelephones(telephone)
# Set Physical Address using MapiContactPhysicalAddress and MapiContactPhysicalAddressPropertySet
phys_addrss = MapiContactPhysicalAddress()
phys_addrss.setPostOfficeBox("144 Hitchcock Rd, Salinas, CA 93908")
phys_addr_prop_set = MapiContactPhysicalAddressPropertySet()
phys_addr_prop_set.setWorkAddress(phys_addrss)
contact.setPhysicalAddresses(phys_addr_prop_set)
# Set email information using MapiContactElectronicAddress and MapiContactElectronicAddressPropertySet
email = MapiContactElectronicAddress()
email.setAddressType("SMTP")
email.setDisplayName("Melissa MacBeth (mellissa@contoso.com)")
email.setEmailAddress("melissa@contoso.com")
elec_addr_prop_set = MapiContactElectronicAddressPropertySet()
elec_addr_prop_set.setEmail1(email)
contact.setElectronicAddresses(elec_addr_prop_set)
contactSaveFormat=ContactSaveFormat
contact.save(dataDir + "OutlookContact.vcf", contactSaveFormat.VCard)
print "Created outlook contact successfully."
if __name__ == '__main__':
CreateOutlookContact() |
MrSurly/micropython-esp32 | refs/heads/esp32 | tests/unicode/unicode_str_format.py | 78 | # test handling of unicode chars in format strings
print('α'.format())
print('{α}'.format(α=1))
|
vmahuli/tempest | refs/heads/master | tempest/api/network/admin/test_external_network_extension.py | 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.api.network import base
from tempest.common.utils import data_utils
class ExternalNetworksTestJSON(base.BaseAdminNetworkTest):
_interface = 'json'
@classmethod
def setUpClass(cls):
super(ExternalNetworksTestJSON, cls).setUpClass()
cls.network = cls.create_network()
def _create_network(self, external=True):
post_body = {'name': data_utils.rand_name('network-')}
if external:
post_body['router:external'] = external
resp, body = self.admin_client.create_network(**post_body)
network = body['network']
self.assertEqual('201', resp['status'])
self.addCleanup(self.admin_client.delete_network, network['id'])
return network
def test_create_external_network(self):
# Create a network as an admin user specifying the
# external network extension attribute
ext_network = self._create_network()
# Verifies router:external parameter
self.assertIsNotNone(ext_network['id'])
self.assertTrue(ext_network['router:external'])
def test_update_external_network(self):
# Update a network as an admin user specifying the
# external network extension attribute
network = self._create_network(external=False)
self.assertFalse(network.get('router:external', False))
update_body = {'router:external': True}
resp, body = self.admin_client.update_network(network['id'],
**update_body)
self.assertEqual('200', resp['status'])
updated_network = body['network']
# Verify that router:external parameter was updated
self.assertTrue(updated_network['router:external'])
def test_list_external_networks(self):
# Create external_net
external_network = self._create_network()
# List networks as a normal user and confirm the external
# network extension attribute is returned for those networks
# that were created as external
resp, body = self.client.list_networks()
self.assertEqual('200', resp['status'])
networks_list = [net['id'] for net in body['networks']]
self.assertIn(external_network['id'], networks_list)
self.assertIn(self.network['id'], networks_list)
for net in body['networks']:
if net['id'] == self.network['id']:
self.assertFalse(net['router:external'])
elif net['id'] == external_network['id']:
self.assertTrue(net['router:external'])
def test_show_external_networks_attribute(self):
# Create external_net
external_network = self._create_network()
# Show an external network as a normal user and confirm the
# external network extension attribute is returned.
resp, body = self.client.show_network(external_network['id'])
self.assertEqual('200', resp['status'])
show_ext_net = body['network']
self.assertEqual(external_network['name'], show_ext_net['name'])
self.assertEqual(external_network['id'], show_ext_net['id'])
self.assertTrue(show_ext_net['router:external'])
resp, body = self.client.show_network(self.network['id'])
self.assertEqual('200', resp['status'])
show_net = body['network']
# Verify with show that router:external is False for network
self.assertEqual(self.network['name'], show_net['name'])
self.assertEqual(self.network['id'], show_net['id'])
self.assertFalse(show_net['router:external'])
class ExternalNetworksTestXML(ExternalNetworksTestJSON):
_interface = 'xml'
|
salomon1184/bite-project | refs/heads/master | deps/mrtaskman/third_party/gflags/tests/flags_modules_for_testing/__init__.py | 12133432 | |
craynot/django | refs/heads/master | tests/test_discovery_sample/empty.py | 12133432 | |
freakboy3742/django | refs/heads/main | tests/staticfiles_tests/apps/no_label/__init__.py | 12133432 | |
tedder/ansible | refs/heads/devel | test/units/plugins/terminal/__init__.py | 12133432 | |
RuiNascimento/krepo | refs/heads/master | script.module.lambdascrapers/lib/lambdascrapers/sources_placenta/en_placenta-1.7.8/solarmovie.py | 1 | # -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return. - Muad'Dib
# ----------------------------------------------------------------------------
#######################################################################
# Addon Name: Placenta
# Addon id: plugin.video.placenta
# Addon Provider: Mr.Blamo
import re,traceback,urllib,urlparse,hashlib,random,string,json,base64,sys,xbmc,resolveurl
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import log_utils
from resources.lib.modules import source_utils
from resources.lib.modules import cache
from resources.lib.modules import directstream
from resources.lib.modules import jsunfuck
CODE = '''def retA():
class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __rlshift__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __rshift__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
def my_add(x, y):
try: return x + y
except Exception: return str(x) + str(y)
x = Infix(my_add)
return %s
param = retA()'''
class source:
def __init__(self):
self.priority = 1
self.language = ['en']
self.domains = ['solarmovie.ms']
self.base_link = 'http://www.solarmovie.ms'
self.search_link = '/keywords/%s'
# Testing: Star Wars: Episode II - Attack Of The Clones
# Failed: http://www.solarmovie.ms/keywords/star%20wars%20%20episode%20ii%20%20%20attack%20of%20the%20clones
# Working: http://www.solarmovie.ms/keywords/Star%20Wars:%20Episode%20II%20-%20Attack%20Of%20The%20Clones
# Changing ANY punctuation or spaces results in failure!!! (different case is fine)
# http://www.solarmovie.ms/watch-star-wars-episode-ii-attack-of-the-clones-online.html
def movie(self, imdb, title, localtitle, aliases, year):
try:
# search_id = title.lower().replace(':', ' ').replace('-', ' ') # see __init__
# start_url = urlparse.urljoin(self.base_link, (self.search_link % (search_id.replace(' ','%20'))))
start_url = urlparse.urljoin(self.base_link, (self.search_link % (title.replace(' ','%20'))))
headers={'User-Agent':client.randomagent()}
html = client.request(start_url,headers=headers)
match = re.compile('<span class="name"><a title="(.+?)" href="(.+?)".+?title="(.+?)"',re.DOTALL).findall(html)
for name,item_url, link_year in match:
if year in link_year:
if cleantitle.get(title) in cleantitle.get(name):
return item_url
return
except:
failure = traceback.format_exc()
log_utils.log('SolarMovie - Exception: \n' + str(failure))
self.domains = ['solarmoviez.to', 'solarmoviez.ru']
self.base_link = 'https://solarmoviez.ru'
self.search_link = '/movie/search/%s.html'
self.info_link = '/ajax/movie_info/%s.html?is_login=false'
self.server_link = '/ajax/v4_movie_episodes/%s'
self.embed_link = '/ajax/movie_embed/%s'
self.token_link = '/ajax/movie_token?eid=%s&mid=%s'
self.source_link = '/ajax/movie_sources/%s?x=%s&y=%s'
def matchAlias(self, title, aliases):
try:
for alias in aliases:
if cleantitle.get(title) == cleantitle.get(alias['title']):
return True
except:
return False
def movie(self, imdb, title, localtitle, aliases, year):
try:
aliases.append({'country': 'us', 'title': title})
url = {'imdb': imdb, 'title': title, 'year': year, 'aliases': aliases}
url = urllib.urlencode(url)
return url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
aliases.append({'country': 'us', 'title': tvshowtitle})
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year, 'aliases': aliases}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None: return
url = urlparse.parse_qs(url)
url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url])
url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode
url = urllib.urlencode(url)
return url
except:
return
def searchShow(self, title, season, aliases, headers):
try:
title = cleantitle.normalize(title)
search = '%s Season %s' % (title, season)
url = urlparse.urljoin(self.base_link, self.search_link % urllib.quote_plus(cleantitle.getsearch(search)))
r = client.request(url)
url = re.findall('<a href=\"(.+?\/movie\/%s-season-%s-.+?\.html)\"' % (cleantitle.geturl(title), season), r)[0]
return url
except:
return
def searchMovie(self, title, year, aliases, headers):
try:
title = cleantitle.normalize(title)
url = urlparse.urljoin(self.base_link, self.search_link % urllib.quote_plus(cleantitle.getsearch(title)))
r = client.request(url, headers=headers, timeout='15')
r = client.parseDOM(r, 'div', attrs={'class': 'ml-item'})
r = zip(client.parseDOM(r, 'a', ret='href'), client.parseDOM(r, 'a', ret='title'))
results = [(i[0], i[1], re.findall('\((\d{4})', i[1])) for i in r]
try:
r = [(i[0], i[1], i[2][0]) for i in results if len(i[2]) > 0]
url = [i[0] for i in r if self.matchAlias(i[1], aliases) and (year == i[2])][0]
except:
url = None
pass
if (url == None):
url = [i[0] for i in results if self.matchAlias(i[1], aliases)][0]
return url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
if url is None: return sources
headers={'User-Agent':client.randomagent()}
html = client.request(url,headers=headers)
Links = re.compile('id="link_.+?target="_blank" id="(.+?)"',re.DOTALL).findall(html)
for vid_url in Links:
if 'openload' in vid_url:
try:
source_html = client.request(vid_url,headers=headers)
source_string = re.compile('description" content="(.+?)"',re.DOTALL).findall(source_html)[0]
quality,info = source_utils.get_release_quality(source_string, vid_url)
except:
quality = 'DVD'
info = []
sources.append({'source': 'Openload','quality': quality,'language': 'en','url':vid_url,'info':info,'direct': False,'debridonly': False})
elif 'streamango' in vid_url:
try:
source_html = client.request(vid_url,headers=headers)
source_string = re.compile('description" content="(.+?)"',re.DOTALL).findall(source_html)[0]
quality,info = source_utils.get_release_quality(source_string, vid_url)
except:
quality = 'DVD'
info = []
sources.append({'source': 'Streamango','quality': quality,'language': 'en','url':vid_url,'info':info,'direct': False,'debridonly': False})
else:
if resolveurl.HostedMediaFile(vid_url):
quality,info = source_utils.get_release_quality(vid_url, vid_url)
host = vid_url.split('//')[1].replace('www.','')
host = host.split('/')[0].split('.')[0].title()
sources.append({'source': host,'quality': quality,'language': 'en','url':vid_url,'info':info,'direct': False,'debridonly': False})
return sources
except:
failure = traceback.format_exc()
log_utils.log('SolarMovie - Exception: \n' + str(failure))
return sources
def resolve(self, url):
return url
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
aliases = eval(data['aliases'])
headers = {}
if 'tvshowtitle' in data:
episode = int(data['episode'])
url = self.searchShow(data['tvshowtitle'], data['season'], aliases, headers)
else:
episode = 0
url = self.searchMovie(data['title'], data['year'], aliases, headers)
mid = re.findall('-(\d+)', url)[-1]
try:
headers = {'Referer': url}
u = urlparse.urljoin(self.base_link, self.server_link % mid)
r = client.request(u, headers=headers, XHR=True)
r = json.loads(r)['html']
r = client.parseDOM(r, 'div', attrs = {'class': 'pas-list'})
ids = client.parseDOM(r, 'li', ret='data-id')
servers = client.parseDOM(r, 'li', ret='data-server')
labels = client.parseDOM(r, 'a', ret='title')
r = zip(ids, servers, labels)
for eid in r:
try:
try:
ep = re.findall('episode.*?(\d+).*?', eid[2].lower())[0]
except:
ep = 0
if (episode == 0) or (int(ep) == episode):
url = urlparse.urljoin(self.base_link, self.token_link % (eid[0], mid))
script = client.request(url)
if '$_$' in script:
params = self.uncensored1(script)
elif script.startswith('[]') and script.endswith('()'):
params = self.uncensored2(script)
elif '_x=' in script:
x = re.search('''_x=['"]([^"']+)''', script).group(1)
y = re.search('''_y=['"]([^"']+)''', script).group(1)
params = {'x': x, 'y': y}
else:
raise Exception()
u = urlparse.urljoin(self.base_link, self.source_link % (eid[0], params['x'], params['y']))
r = client.request(u, XHR=True)
json_sources = json.loads(r)['playlist'][0]['sources']
try:
if 'google' in json_sources['file']:
quality = 'HD'
if 'bluray' in json_sources['file'].lower():
quality = '1080p'
sources.append({'source': 'gvideo', 'quality': quality, 'language': 'en',
'url': json_sources['file'], 'direct': True, 'debridonly': False})
except Exception:
if 'blogspot' in json_sources[0]['file']:
url = [i['file'] for i in json_sources if 'file' in i]
url = [directstream.googletag(i) for i in url]
url = [i[0] for i in url if i]
for s in url:
sources.append({'source': 'gvideo', 'quality': s['quality'], 'language': 'en',
'url': s['url'], 'direct': True, 'debridonly': False})
elif 'lemonstream' in json_sources[0]['file']:
sources.append({
'source': 'CDN',
'quality': 'HD',
'language': 'en',
'url': json_sources[0]['file'] + '|Referer=' + self.base_link,
'direct': True,
'debridonly': False})
except:
pass
except:
pass
return sources
except:
return sources
def resolve(self, url):
return url
def uncensored(a, b):
x = '' ; i = 0
for i, y in enumerate(a):
z = b[i % len(b) - 1]
y = int(ord(str(y)[0])) + int(ord(str(z)[0]))
x += chr(y)
x = base64.b64encode(x)
return x
def uncensored1(self, script):
try:
script = '(' + script.split("(_$$)) ('_');")[0].split("/* `$$` */")[-1].strip()
script = script.replace('(__$)[$$$]', '\'"\'')
script = script.replace('(__$)[_$]', '"\\\\"')
script = script.replace('(o^_^o)', '3')
script = script.replace('(c^_^o)', '0')
script = script.replace('(_$$)', '1')
script = script.replace('($$_)', '4')
vGlobals = {"__builtins__": None, '__name__': __name__, 'str': str, 'Exception': Exception}
vLocals = {'param': None}
exec (CODE % script.replace('+', '|x|'), vGlobals, vLocals)
data = vLocals['param'].decode('string_escape')
x = re.search('''_x=['"]([^"']+)''', data).group(1)
y = re.search('''_y=['"]([^"']+)''', data).group(1)
return {'x': x, 'y': y}
except:
pass
def uncensored2(self, script):
try:
js = jsunfuck.JSUnfuck(script).decode()
x = re.search('''_x=['"]([^"']+)''', js).group(1)
y = re.search('''_y=['"]([^"']+)''', js).group(1)
return {'x': x, 'y': y}
except:
pass
|
Kussie/HTPC-Manager | refs/heads/master2 | libs/pySMART/device_list.py | 2 | #Copyright (C) 2014 Marc Herndon
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License,
#version 2, as published by the Free Software Foundation.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
This module contains the definition of the `DeviceList` class, used to
represent all physical storage devices connected to the system.
Once initialized, the sole member `devices` will contain a list of `Device`
objects.
This class has no public methods. All interaction should be through the
`Device` class API.
"""
# Python built-ins
from subprocess import Popen, PIPE
# pySMART module imports
from .device import Device
from .utils import OS, rescan_device_busses, path_append
# Calling path_append before executing anything else in the file
path_append()
class DeviceList(object):
"""
Represents a list of all the storage devices connected to this computer.
"""
def __init__(self, init=True):
"""
Instantiates and optionally initializes the `DeviceList`.
###Args:
* **init (bool):** By default, `pySMART.device_list.DeviceList.devices`
is populated with `Device` objects during instantiation. Setting init to
False will skip initialization and create an empty
`pySMART.device_list.DeviceList` object instead.
"""
self.devices = []
"""
**(list of `Device`):** Contains all storage devices detected during
instantiation, as `Device` objects.
"""
if init:
self._initialize()
def __repr__(self):
"""Define a basic representation of the class object."""
rep = "<DeviceList contents:\n"
for device in self.devices:
rep += str(device) + '\n'
return rep + '>'
#return "<DeviceList contents:%r>" % (self.devices)
def _cleanup(self):
"""
Removes duplicate ATA devices that correspond to an existing CSMI
device. Also removes any device with no capacity value, as this
indicates removable storage, ie: CD/DVD-ROM, ZIP, etc.
"""
# We can't operate directly on the list while we're iterating
# over it, so we collect indeces to delete and remove them later
to_delete = []
# Enumerate the list to get tuples containing indeces and values
for index, device in enumerate(self.devices):
if device.interface == 'csmi':
for otherindex, otherdevice in enumerate(self.devices):
if (otherdevice.interface == 'ata' or
otherdevice.interface == 'sata'):
if device.serial == otherdevice.serial:
to_delete.append(otherindex)
device._sd_name = otherdevice.name
if device.capacity == None and index not in to_delete:
to_delete.append(index)
# Recreate the self.devices list without the marked indeces
self.devices[:] = [v for i, v in enumerate(self.devices)
if i not in to_delete]
def _initialize(self):
"""
Scans system busses for attached devices and add them to the
`DeviceList` as `Device` objects.
"""
# On Windows machines we should re-initialize the system busses
# before scanning for disks
if OS == 'Windows':
rescan_device_busses()
cmd = Popen('smartctl --scan-open', shell=True,
stdout=PIPE, stderr=PIPE)
_stdout, _stderr = cmd.communicate()
for line in _stdout.split('\n'):
if not ('failed:' in line or line == ''):
name = line.split(' ')[0].replace('/dev/', '')
# CSMI devices are explicitly of the 'csmi' type and do not
# require further disambiguation
if name[0:4] == 'csmi':
self.devices.append(Device(name, interface='csmi'))
# Other device types will be disambiguated by Device.__init__
else:
self.devices.append(Device(name))
# Remove duplicates and unwanted devices (optical, etc.) from the list
self._cleanup()
# Sort the list alphabetically by device name
self.devices.sort(key=lambda device: device.name)
__all__ = ['DeviceList']
|
vsajip/django | refs/heads/django3 | django/conf/locale/sv/__init__.py | 12133432 | |
hkawasaki/kawasaki-aio8-1 | refs/heads/gacco2/master | lms/djangoapps/verify_student/management/commands/__init__.py | 12133432 | |
Batterfii/django | refs/heads/master | django/views/__init__.py | 12133432 | |
cetic/python-msp430-tools | refs/heads/master | msp430/shell/__init__.py | 12133432 | |
qtm2/qtm2 | refs/heads/master | contrib/bitrpc/bitrpc.py | 2348 | from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:8332")
else:
access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:8332")
cmd = sys.argv[1].lower()
if cmd == "backupwallet":
try:
path = raw_input("Enter destination path/filename: ")
print access.backupwallet(path)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccount":
try:
addr = raw_input("Enter a Bitcoin address: ")
print access.getaccount(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccountaddress":
try:
acct = raw_input("Enter an account name: ")
print access.getaccountaddress(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getaddressesbyaccount":
try:
acct = raw_input("Enter an account name: ")
print access.getaddressesbyaccount(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getbalance":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getbalance(acct, mc)
except:
print access.getbalance()
except:
print "\n---An error occurred---\n"
elif cmd == "getblockbycount":
try:
height = raw_input("Height: ")
print access.getblockbycount(height)
except:
print "\n---An error occurred---\n"
elif cmd == "getblockcount":
try:
print access.getblockcount()
except:
print "\n---An error occurred---\n"
elif cmd == "getblocknumber":
try:
print access.getblocknumber()
except:
print "\n---An error occurred---\n"
elif cmd == "getconnectioncount":
try:
print access.getconnectioncount()
except:
print "\n---An error occurred---\n"
elif cmd == "getdifficulty":
try:
print access.getdifficulty()
except:
print "\n---An error occurred---\n"
elif cmd == "getgenerate":
try:
print access.getgenerate()
except:
print "\n---An error occurred---\n"
elif cmd == "gethashespersec":
try:
print access.gethashespersec()
except:
print "\n---An error occurred---\n"
elif cmd == "getinfo":
try:
print access.getinfo()
except:
print "\n---An error occurred---\n"
elif cmd == "getnewaddress":
try:
acct = raw_input("Enter an account name: ")
try:
print access.getnewaddress(acct)
except:
print access.getnewaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaccount":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaccount(acct, mc)
except:
print access.getreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaddress":
try:
addr = raw_input("Enter a Bitcoin address (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaddress(addr, mc)
except:
print access.getreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "gettransaction":
try:
txid = raw_input("Enter a transaction ID: ")
print access.gettransaction(txid)
except:
print "\n---An error occurred---\n"
elif cmd == "getwork":
try:
data = raw_input("Data (optional): ")
try:
print access.gettransaction(data)
except:
print access.gettransaction()
except:
print "\n---An error occurred---\n"
elif cmd == "help":
try:
cmd = raw_input("Command (optional): ")
try:
print access.help(cmd)
except:
print access.help()
except:
print "\n---An error occurred---\n"
elif cmd == "listaccounts":
try:
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.listaccounts(mc)
except:
print access.listaccounts()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaccount":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaccount(mc, incemp)
except:
print access.listreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaddress":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaddress(mc, incemp)
except:
print access.listreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "listtransactions":
try:
acct = raw_input("Account (optional): ")
count = raw_input("Number of transactions (optional): ")
frm = raw_input("Skip (optional):")
try:
print access.listtransactions(acct, count, frm)
except:
print access.listtransactions()
except:
print "\n---An error occurred---\n"
elif cmd == "move":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.move(frm, to, amt, mc, comment)
except:
print access.move(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendfrom":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendfrom(frm, to, amt, mc, comment, commentto)
except:
print access.sendfrom(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendmany":
try:
frm = raw_input("From: ")
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.sendmany(frm,to,mc,comment)
except:
print access.sendmany(frm,to)
except:
print "\n---An error occurred---\n"
elif cmd == "sendtoaddress":
try:
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
amt = raw_input("Amount:")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendtoaddress(to,amt,comment,commentto)
except:
print access.sendtoaddress(to,amt)
except:
print "\n---An error occurred---\n"
elif cmd == "setaccount":
try:
addr = raw_input("Address: ")
acct = raw_input("Account:")
print access.setaccount(addr,acct)
except:
print "\n---An error occurred---\n"
elif cmd == "setgenerate":
try:
gen= raw_input("Generate? (true/false): ")
cpus = raw_input("Max processors/cores (-1 for unlimited, optional):")
try:
print access.setgenerate(gen, cpus)
except:
print access.setgenerate(gen)
except:
print "\n---An error occurred---\n"
elif cmd == "settxfee":
try:
amt = raw_input("Amount:")
print access.settxfee(amt)
except:
print "\n---An error occurred---\n"
elif cmd == "stop":
try:
print access.stop()
except:
print "\n---An error occurred---\n"
elif cmd == "validateaddress":
try:
addr = raw_input("Address: ")
print access.validateaddress(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrase":
try:
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrasechange":
try:
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
print
print "\n---Passphrase changed---\n"
except:
print
print "\n---An error occurred---\n"
print
else:
print "Command not found or not supported" |
jmiserez/sts | refs/heads/hb | tools/nox_link_analyzer.py | 2 | #! /usr/bin/python
import re
import sys
path = re.compile("WARN:new link detected [(](00:)+?(?P<from_id>\w{2}) p:(?P<from_port>\w+) -> (00:)+?(?P<to_id>\w{2}) p:(?P<to_port>\w+)")
def make_id(switch_id, port):
'''make a string id for'''
return switch_id + ":" + port
argv = sys.argv
if len(argv) != 2:
print "Please provide exactly one filename argument"
sys.exit(2)
connectivity = {} # a dict of k,v = from_id, to_id
occupied_ports = {} # k,v = switch_id, set(ports)
with open(argv[1], 'r') as f:
for line in f:
m = re.search(path, line)
if m:
frm_id = m.group("from_id")
from_port = m.group("from_port")
from_id = make_id(frm_id, from_port)
to_id = make_id(m.group("to_id"), m.group("to_port"))
if from_id in connectivity:
print "from_id already connected to", connectivity[from_id]
print " this round's to_id:", to_id
continue
connectivity[from_id] = to_id
if not occupied_ports.has_key(frm_id):
occupied_ports[frm_id] = set()
occupied_ports[frm_id].add(from_port)
# Now compare the things
print "Path count:", len(connectivity)
def print_link(from_id, to_id):
'''pretty print the paths from the switch at from_id to all the ids in its to_bag'''
print "from_id:", from_id, "to_id:", to_id
for from_id, to_id in connectivity.iteritems():
print "---"
print_link(from_id, to_id)
if to_id in connectivity:
if from_id != connectivity[to_id]:
print " Bad reverse path! connectivity[to_id] =", connectivity[to_id]
else:
print " ERROR: no reverse path!"
print "Printing port count"
for switch in sorted(occupied_ports.iterkeys()):
ports = occupied_ports[switch]
print switch, ":", sorted(list(ports))
|
gdi2290/django | refs/heads/master | tests/defer/models.py | 112 | """
Tests for defer() and only().
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
class Secondary(models.Model):
first = models.CharField(max_length=50)
second = models.CharField(max_length=50)
@python_2_unicode_compatible
class Primary(models.Model):
name = models.CharField(max_length=50)
value = models.CharField(max_length=50)
related = models.ForeignKey(Secondary)
def __str__(self):
return self.name
class Child(Primary):
pass
class BigChild(Primary):
other = models.CharField(max_length=50)
class ChildProxy(Child):
class Meta:
proxy = True
class RefreshPrimaryProxy(Primary):
class Meta:
proxy = True
def refresh_from_db(self, using=None, fields=None, **kwargs):
# Reloads all deferred fields if any of the fields is deferred.
if fields is not None:
fields = set(fields)
deferred_fields = self.get_deferred_fields()
if fields.intersection(deferred_fields):
fields = fields.union(deferred_fields)
super(RefreshPrimaryProxy, self).refresh_from_db(using, fields, **kwargs)
|
chubbymaggie/remodel | refs/heads/master | testing/gtest-1.7.0/test/gtest_color_test.py | 3259 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Verifies that Google Test correctly determines whether to use colors."""
__author__ = 'wan@google.com (Zhanyong Wan)'
import os
import gtest_test_utils
IS_WINDOWS = os.name = 'nt'
COLOR_ENV_VAR = 'GTEST_COLOR'
COLOR_FLAG = 'gtest_color'
COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_color_test_')
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
os.environ[env_var] = value
elif env_var in os.environ:
del os.environ[env_var]
def UsesColor(term, color_env_var, color_flag):
"""Runs gtest_color_test_ and returns its exit code."""
SetEnvVar('TERM', term)
SetEnvVar(COLOR_ENV_VAR, color_env_var)
if color_flag is None:
args = []
else:
args = ['--%s=%s' % (COLOR_FLAG, color_flag)]
p = gtest_test_utils.Subprocess([COMMAND] + args)
return not p.exited or p.exit_code
class GTestColorTest(gtest_test_utils.TestCase):
def testNoEnvVarNoFlag(self):
"""Tests the case when there's neither GTEST_COLOR nor --gtest_color."""
if not IS_WINDOWS:
self.assert_(not UsesColor('dumb', None, None))
self.assert_(not UsesColor('emacs', None, None))
self.assert_(not UsesColor('xterm-mono', None, None))
self.assert_(not UsesColor('unknown', None, None))
self.assert_(not UsesColor(None, None, None))
self.assert_(UsesColor('linux', None, None))
self.assert_(UsesColor('cygwin', None, None))
self.assert_(UsesColor('xterm', None, None))
self.assert_(UsesColor('xterm-color', None, None))
self.assert_(UsesColor('xterm-256color', None, None))
def testFlagOnly(self):
"""Tests the case when there's --gtest_color but not GTEST_COLOR."""
self.assert_(not UsesColor('dumb', None, 'no'))
self.assert_(not UsesColor('xterm-color', None, 'no'))
if not IS_WINDOWS:
self.assert_(not UsesColor('emacs', None, 'auto'))
self.assert_(UsesColor('xterm', None, 'auto'))
self.assert_(UsesColor('dumb', None, 'yes'))
self.assert_(UsesColor('xterm', None, 'yes'))
def testEnvVarOnly(self):
"""Tests the case when there's GTEST_COLOR but not --gtest_color."""
self.assert_(not UsesColor('dumb', 'no', None))
self.assert_(not UsesColor('xterm-color', 'no', None))
if not IS_WINDOWS:
self.assert_(not UsesColor('dumb', 'auto', None))
self.assert_(UsesColor('xterm-color', 'auto', None))
self.assert_(UsesColor('dumb', 'yes', None))
self.assert_(UsesColor('xterm-color', 'yes', None))
def testEnvVarAndFlag(self):
"""Tests the case when there are both GTEST_COLOR and --gtest_color."""
self.assert_(not UsesColor('xterm-color', 'no', 'no'))
self.assert_(UsesColor('dumb', 'no', 'yes'))
self.assert_(UsesColor('xterm-color', 'no', 'auto'))
def testAliasesOfYesAndNo(self):
"""Tests using aliases in specifying --gtest_color."""
self.assert_(UsesColor('dumb', None, 'true'))
self.assert_(UsesColor('dumb', None, 'YES'))
self.assert_(UsesColor('dumb', None, 'T'))
self.assert_(UsesColor('dumb', None, '1'))
self.assert_(not UsesColor('xterm', None, 'f'))
self.assert_(not UsesColor('xterm', None, 'false'))
self.assert_(not UsesColor('xterm', None, '0'))
self.assert_(not UsesColor('xterm', None, 'unknown'))
if __name__ == '__main__':
gtest_test_utils.Main()
|
mattnenterprise/servo | refs/heads/master | tests/wpt/web-platform-tests/tools/third_party/attrs/src/attr/_config.py | 99 | from __future__ import absolute_import, division, print_function
__all__ = ["set_run_validators", "get_run_validators"]
_run_validators = True
def set_run_validators(run):
"""
Set whether or not validators are run. By default, they are run.
"""
if not isinstance(run, bool):
raise TypeError("'run' must be bool.")
global _run_validators
_run_validators = run
def get_run_validators():
"""
Return whether or not validators are run.
"""
return _run_validators
|
Armored-Dragon/goldmine | refs/heads/master | default_cogs/discord_bots.py | 1 | """guild stats reporting."""
import util.json as json
import aiohttp
import asyncio
import async_timeout
from discord.ext import commands
from .cog import Cog
try:
from ex_props import discord_bots_token
except ImportError:
discord_bots_token = None
try:
from ex_props import discordlist_token
except ImportError:
discordlist_token = None
class DiscordBots(Cog):
"""Reporter of guild stats to services like Discord Bots."""
def __init__(self, bot):
super().__init__(bot)
self.logger = self.logger.getChild('stats')
def update(self):
"""Report the current guild count to bot lists."""
return asyncio.gather(self.update_dbots(), self.update_discordlist(), loop=self.loop)
async def update_dbots(self):
if not discord_bots_token:
self.logger.warning('Tried to contact Discord Bots, but no token set!')
return False
data = dict(guild_count=len(self.bot.guilds))
dest = 'https://bots.discord.pw/api/bots/' + str(self.bot.user.id) + '/stats'
headers = {
'Authorization': discord_bots_token,
'Content-Type': 'application/json'
}
with async_timeout.timeout(6):
async with self.bot.cog_http.post(dest, data=json.dumps(data), headers=headers) as r:
resp_key = f'(got {r.status} {r.reason})'
if r.status == 200:
self.logger.info('Successfully sent Discord Bots our guild count (got 200 OK)')
else:
self.logger.warning('Failed sending our guild count to Discord Bots! ' + resp_key)
async def update_discordlist(self):
if not discordlist_token:
self.logger.warning('Tried to contact DiscordList, but no token set!')
return False
data = {
'token': discordlist_token,
'guilds': len(self.bot.guilds)
}
dest = 'https://bots.discordlist.net/api'
headers = {'Content-Type': 'application/json'}
with async_timeout.timeout(6):
async with self.bot.cog_http.post(dest, data=json.dumps(data), headers=headers) as r:
resp_key = f'(got {r.status} {r.reason})'
if r.status == 200:
self.logger.info('Successfully sent DiscordList our guild count! (got 200 OK)')
else:
self.logger.warning('Failed sending our guild count to DiscordList! ' + resp_key)
async def on_ready(self):
return await self.update()
async def on_guild_join(self, guild):
return await self.update()
async def on_guild_remove(self, guild):
return await self.update()
def setup(bot):
if bot.selfbot:
bot.logger.warning('Tried to load cog Discord Bots, but we\'re a selfbot. Not loading.')
else:
bot.add_cog(DiscordBots(bot))
|
deKupini/erp | refs/heads/master | addons/membership/report/__init__.py | 8 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import report_membership
|
trezorg/django | refs/heads/master | django/core/management/commands/dbshell.py | 313 | from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
class Command(BaseCommand):
help = ("Runs the command-line client for specified database, or the "
"default database if none is provided.")
option_list = BaseCommand.option_list + (
make_option('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS, help='Nominates a database onto which to '
'open a shell. Defaults to the "default" database.'),
)
requires_model_validation = False
def handle(self, **options):
connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
try:
connection.client.runshell()
except OSError:
# Note that we're assuming OSError means that the client program
# isn't installed. There's a possibility OSError would be raised
# for some other reason, in which case this error message would be
# inaccurate. Still, this message catches the common case.
raise CommandError('You appear not to have the %r program installed or on your path.' % \
connection.client.executable_name)
|
chenjun0210/tensorflow | refs/heads/master | tensorflow/examples/tutorials/mnist/mnist.py | 65 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Builds the MNIST network.
Implements the inference/loss/training pattern for model building.
1. inference() - Builds the model as far as is required for running the network
forward to make predictions.
2. loss() - Adds to the inference model the layers required to generate loss.
3. training() - Adds to the loss model the Ops required to generate and
apply gradients.
This file is used by the various "fully_connected_*.py" files and not meant to
be run.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import tensorflow as tf
# The MNIST dataset has 10 classes, representing the digits 0 through 9.
NUM_CLASSES = 10
# The MNIST images are always 28x28 pixels.
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE
def inference(images, hidden1_units, hidden2_units):
"""Build the MNIST model up to where it may be used for inference.
Args:
images: Images placeholder, from inputs().
hidden1_units: Size of the first hidden layer.
hidden2_units: Size of the second hidden layer.
Returns:
softmax_linear: Output tensor with the computed logits.
"""
# Hidden 1
with tf.name_scope('hidden1'):
weights = tf.Variable(
tf.truncated_normal([IMAGE_PIXELS, hidden1_units],
stddev=1.0 / math.sqrt(float(IMAGE_PIXELS))),
name='weights')
biases = tf.Variable(tf.zeros([hidden1_units]),
name='biases')
hidden1 = tf.nn.relu(tf.matmul(images, weights) + biases)
# Hidden 2
with tf.name_scope('hidden2'):
weights = tf.Variable(
tf.truncated_normal([hidden1_units, hidden2_units],
stddev=1.0 / math.sqrt(float(hidden1_units))),
name='weights')
biases = tf.Variable(tf.zeros([hidden2_units]),
name='biases')
hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)
# Linear
with tf.name_scope('softmax_linear'):
weights = tf.Variable(
tf.truncated_normal([hidden2_units, NUM_CLASSES],
stddev=1.0 / math.sqrt(float(hidden2_units))),
name='weights')
biases = tf.Variable(tf.zeros([NUM_CLASSES]),
name='biases')
logits = tf.matmul(hidden2, weights) + biases
return logits
def loss(logits, labels):
"""Calculates the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor of type float.
"""
labels = tf.to_int64(labels)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=logits, name='xentropy')
return tf.reduce_mean(cross_entropy, name='xentropy_mean')
def training(loss, learning_rate):
"""Sets up the training Ops.
Creates a summarizer to track the loss over time in TensorBoard.
Creates an optimizer and applies the gradients to all trainable variables.
The Op returned by this function is what must be passed to the
`sess.run()` call to cause the model to train.
Args:
loss: Loss tensor, from loss().
learning_rate: The learning rate to use for gradient descent.
Returns:
train_op: The Op for training.
"""
# Add a scalar summary for the snapshot loss.
tf.summary.scalar('loss', loss)
# Create the gradient descent optimizer with the given learning rate.
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
# Create a variable to track the global step.
global_step = tf.Variable(0, name='global_step', trainable=False)
# Use the optimizer to apply the gradients that minimize the loss
# (and also increment the global step counter) as a single training step.
train_op = optimizer.minimize(loss, global_step=global_step)
return train_op
def evaluation(logits, labels):
"""Evaluate the quality of the logits at predicting the label.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size], with values in the
range [0, NUM_CLASSES).
Returns:
A scalar int32 tensor with the number of examples (out of batch_size)
that were predicted correctly.
"""
# For a classifier model, we can use the in_top_k Op.
# It returns a bool tensor with shape [batch_size] that is true for
# the examples where the label is in the top k (here k=1)
# of all logits for that example.
correct = tf.nn.in_top_k(logits, labels, 1)
# Return the number of true entries.
return tf.reduce_sum(tf.cast(correct, tf.int32))
|
ChenJunor/hue | refs/heads/master | desktop/core/ext-py/Django-1.6.10/tests/one_to_one_regress/models.py | 53 | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self):
return "%s the place" % self.name
@python_2_unicode_compatible
class Restaurant(models.Model):
place = models.OneToOneField(Place)
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
def __str__(self):
return "%s the restaurant" % self.place.name
@python_2_unicode_compatible
class Bar(models.Model):
place = models.OneToOneField(Place)
serves_cocktails = models.BooleanField(default=True)
def __str__(self):
return "%s the bar" % self.place.name
class UndergroundBar(models.Model):
place = models.OneToOneField(Place, null=True)
serves_cocktails = models.BooleanField(default=True)
@python_2_unicode_compatible
class Favorites(models.Model):
name = models.CharField(max_length = 50)
restaurants = models.ManyToManyField(Restaurant)
def __str__(self):
return "Favorites for %s" % self.name
class Target(models.Model):
pass
class Pointer(models.Model):
other = models.OneToOneField(Target, primary_key=True)
class Pointer2(models.Model):
other = models.OneToOneField(Target)
|
kamalx/edx-platform | refs/heads/release | common/djangoapps/reverification/migrations/0002_auto__del_midcoursereverificationwindow.py | 70 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'MidcourseReverificationWindow'
db.delete_table('reverification_midcoursereverificationwindow')
def backwards(self, orm):
# Adding model 'MidcourseReverificationWindow'
db.create_table('reverification_midcoursereverificationwindow', (
('course_id', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('end_date', self.gf('django.db.models.fields.DateTimeField')(default=None, null=True, blank=True)),
('start_date', self.gf('django.db.models.fields.DateTimeField')(default=None, null=True, blank=True)),
))
db.send_create_signal('reverification', ['MidcourseReverificationWindow'])
models = {
}
complete_apps = ['reverification']
|
odicraig/kodi2odi | refs/heads/master | addons/plugin.video.cartoons8/requests/models.py | 151 | # -*- coding: utf-8 -*-
"""
requests.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power Requests.
"""
import collections
import datetime
from io import BytesIO, UnsupportedOperation
from .hooks import default_hooks
from .structures import CaseInsensitiveDict
from .auth import HTTPBasicAuth
from .cookies import cookiejar_from_dict, get_cookie_header
from .packages.urllib3.fields import RequestField
from .packages.urllib3.filepost import encode_multipart_formdata
from .packages.urllib3.util import parse_url
from .packages.urllib3.exceptions import (
DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)
from .exceptions import (
HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,
ContentDecodingError, ConnectionError, StreamConsumedError)
from .utils import (
guess_filename, get_auth_from_url, requote_uri,
stream_decode_response_unicode, to_key_val_list, parse_header_links,
iter_slices, guess_json_utf, super_len, to_native_string)
from .compat import (
cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
is_py2, chardet, json, builtin_str, basestring)
from .status_codes import codes
#: The set of HTTP status codes that indicate an automatically
#: processable redirect.
REDIRECT_STATI = (
codes.moved, # 301
codes.found, # 302
codes.other, # 303
codes.temporary_redirect, # 307
codes.permanent_redirect, # 308
)
DEFAULT_REDIRECT_LIMIT = 30
CONTENT_CHUNK_SIZE = 10 * 1024
ITER_CHUNK_SIZE = 512
json_dumps = json.dumps
class RequestEncodingMixin(object):
@property
def path_url(self):
"""Build the path URL to use."""
url = []
p = urlsplit(self.url)
path = p.path
if not path:
path = '/'
url.append(path)
query = p.query
if query:
url.append('?')
url.append(query)
return ''.join(url)
@staticmethod
def _encode_params(data):
"""Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
if isinstance(data, (str, bytes)):
return data
elif hasattr(data, 'read'):
return data
elif hasattr(data, '__iter__'):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
return urlencode(result, doseq=True)
else:
return data
@staticmethod
def _encode_files(files, data):
"""Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
if (not files):
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
new_fields = []
fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, '__iter__'):
val = [val]
for v in val:
if v is not None:
# Don't call str() on bytestrings: in Py3 it all goes wrong.
if not isinstance(v, bytes):
v = str(v)
new_fields.append(
(field.decode('utf-8') if isinstance(field, bytes) else field,
v.encode('utf-8') if isinstance(v, str) else v))
for (k, v) in files:
# support for explicit filename
ft = None
fh = None
if isinstance(v, (tuple, list)):
if len(v) == 2:
fn, fp = v
elif len(v) == 3:
fn, fp, ft = v
else:
fn, fp, ft, fh = v
else:
fn = guess_filename(v) or k
fp = v
if isinstance(fp, (str, bytes, bytearray)):
fdata = fp
else:
fdata = fp.read()
rf = RequestField(name=k, data=fdata,
filename=fn, headers=fh)
rf.make_multipart(content_type=ft)
new_fields.append(rf)
body, content_type = encode_multipart_formdata(new_fields)
return body, content_type
class RequestHooksMixin(object):
def register_hook(self, event, hook):
"""Properly register a hook."""
if event not in self.hooks:
raise ValueError('Unsupported event specified, with event name "%s"' % (event))
if isinstance(hook, collections.Callable):
self.hooks[event].append(hook)
elif hasattr(hook, '__iter__'):
self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))
def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
Returns True if the hook existed, False if not.
"""
try:
self.hooks[event].remove(hook)
return True
except ValueError:
return False
class Request(RequestHooksMixin):
"""A user-created :class:`Request <Request>` object.
Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
:param method: HTTP method to use.
:param url: URL to send.
:param headers: dictionary of headers to send.
:param files: dictionary of {filename: fileobject} files to multipart upload.
:param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.
:param json: json for the body to attach to the request (if data is not specified).
:param params: dictionary of URL parameters to append to the URL.
:param auth: Auth handler or (user, pass) tuple.
:param cookies: dictionary or CookieJar of cookies to attach to this request.
:param hooks: dictionary of callback hooks, for internal usage.
Usage::
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
"""
def __init__(self,
method=None,
url=None,
headers=None,
files=None,
data=None,
params=None,
auth=None,
cookies=None,
hooks=None,
json=None):
# Default empty dicts for dict params.
data = [] if data is None else data
files = [] if files is None else files
headers = {} if headers is None else headers
params = {} if params is None else params
hooks = {} if hooks is None else hooks
self.hooks = default_hooks()
for (k, v) in list(hooks.items()):
self.register_hook(event=k, hook=v)
self.method = method
self.url = url
self.headers = headers
self.files = files
self.data = data
self.json = json
self.params = params
self.auth = auth
self.cookies = cookies
def __repr__(self):
return '<Request [%s]>' % (self.method)
def prepare(self):
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
p = PreparedRequest()
p.prepare(
method=self.method,
url=self.url,
headers=self.headers,
files=self.files,
data=self.data,
json=self.json,
params=self.params,
auth=self.auth,
cookies=self.cookies,
hooks=self.hooks,
)
return p
class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
"""The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
containing the exact bytes that will be sent to the server.
Generated from either a :class:`Request <Request>` object or manually.
Usage::
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> r = req.prepare()
<PreparedRequest [GET]>
>>> s = requests.Session()
>>> s.send(r)
<Response [200]>
"""
def __init__(self):
#: HTTP verb to send to the server.
self.method = None
#: HTTP URL to send the request to.
self.url = None
#: dictionary of HTTP headers.
self.headers = None
# The `CookieJar` used to create the Cookie header will be stored here
# after prepare_cookies is called
self._cookies = None
#: request body to send to the server.
self.body = None
#: dictionary of callback hooks, for internal usage.
self.hooks = default_hooks()
def prepare(self, method=None, url=None, headers=None, files=None,
data=None, params=None, auth=None, cookies=None, hooks=None,
json=None):
"""Prepares the entire request with the given parameters."""
self.prepare_method(method)
self.prepare_url(url, params)
self.prepare_headers(headers)
self.prepare_cookies(cookies)
self.prepare_body(data, files, json)
self.prepare_auth(auth, url)
# Note that prepare_auth must be last to enable authentication schemes
# such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
self.prepare_hooks(hooks)
def __repr__(self):
return '<PreparedRequest [%s]>' % (self.method)
def copy(self):
p = PreparedRequest()
p.method = self.method
p.url = self.url
p.headers = self.headers.copy() if self.headers is not None else None
p._cookies = self._cookies.copy() if self._cookies is not None else None
p.body = self.body
p.hooks = self.hooks
return p
def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = self.method.upper()
def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
#: Accept objects that have string representations.
#: We're unable to blindy call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/kennethreitz/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
raise MissingSchema("Invalid URL {0!r}: No schema supplied. "
"Perhaps you meant http://{0}?".format(url))
if not host:
raise InvalidURL("Invalid URL %r: No host supplied" % url)
# Only want to apply IDNA to the hostname
try:
host = host.encode('idna').decode('utf-8')
except UnicodeError:
raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location
netloc = auth or ''
if netloc:
netloc += '@'
netloc += host
if port:
netloc += ':' + str(port)
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url
def prepare_headers(self, headers):
"""Prepares the given HTTP headers."""
if headers:
self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
else:
self.headers = CaseInsensitiveDict()
def prepare_body(self, data, files, json=None):
"""Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
length = None
if json is not None:
content_type = 'application/json'
body = json_dumps(json)
is_stream = all([
hasattr(data, '__iter__'),
not isinstance(data, (basestring, list, tuple, dict))
])
try:
length = super_len(data)
except (TypeError, AttributeError, UnsupportedOperation):
length = None
if is_stream:
body = data
if files:
raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
if length is not None:
self.headers['Content-Length'] = builtin_str(length)
else:
self.headers['Transfer-Encoding'] = 'chunked'
else:
# Multi-part file uploads.
if files:
(body, content_type) = self._encode_files(files, data)
else:
if data and json is None:
body = self._encode_params(data)
if isinstance(data, basestring) or hasattr(data, 'read'):
content_type = None
else:
content_type = 'application/x-www-form-urlencoded'
self.prepare_content_length(body)
# Add content-type if it wasn't explicitly provided.
if content_type and ('content-type' not in self.headers):
self.headers['Content-Type'] = content_type
self.body = body
def prepare_content_length(self, body):
if hasattr(body, 'seek') and hasattr(body, 'tell'):
body.seek(0, 2)
self.headers['Content-Length'] = builtin_str(body.tell())
body.seek(0, 0)
elif body is not None:
l = super_len(body)
if l:
self.headers['Content-Length'] = builtin_str(l)
elif (self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None):
self.headers['Content-Length'] = '0'
def prepare_auth(self, auth, url=''):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body)
def prepare_cookies(self, cookies):
"""Prepares the given HTTP cookie data."""
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from_dict(cookies)
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
self.headers['Cookie'] = cookie_header
def prepare_hooks(self, hooks):
"""Prepares the given hooks."""
for event in hooks:
self.register_hook(event, hooks[event])
class Response(object):
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
"""
__attrs__ = [
'_content',
'status_code',
'headers',
'url',
'history',
'encoding',
'reason',
'cookies',
'elapsed',
'request',
]
def __init__(self):
super(Response, self).__init__()
self._content = False
self._content_consumed = False
#: Integer Code of responded HTTP Status, e.g. 404 or 200.
self.status_code = None
#: Case-insensitive Dictionary of Response Headers.
#: For example, ``headers['content-encoding']`` will return the
#: value of a ``'Content-Encoding'`` response header.
self.headers = CaseInsensitiveDict()
#: File-like object representation of response (for advanced usage).
#: Use of ``raw`` requires that ``stream=True`` be set on the request.
# This requirement does not apply for use internally to Requests.
self.raw = None
#: Final URL location of Response.
self.url = None
#: Encoding to decode with when accessing r.text.
self.encoding = None
#: A list of :class:`Response <Response>` objects from
#: the history of the Request. Any redirect responses will end
#: up here. The list is sorted from the oldest to the most recent request.
self.history = []
#: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
self.reason = None
#: A CookieJar of Cookies the server sent back.
self.cookies = cookiejar_from_dict({})
#: The amount of time elapsed between sending the request
#: and the arrival of the response (as a timedelta)
self.elapsed = datetime.timedelta(0)
#: The :class:`PreparedRequest <PreparedRequest>` object to which this
#: is a response.
self.request = None
def __getstate__(self):
# Consume everything; accessing the content attribute makes
# sure the content has been fully read.
if not self._content_consumed:
self.content
return dict(
(attr, getattr(self, attr, None))
for attr in self.__attrs__
)
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
# pickled objects do not have .raw
setattr(self, '_content_consumed', True)
setattr(self, 'raw', None)
def __repr__(self):
return '<Response [%s]>' % (self.status_code)
def __bool__(self):
"""Returns true if :attr:`status_code` is 'OK'."""
return self.ok
def __nonzero__(self):
"""Returns true if :attr:`status_code` is 'OK'."""
return self.ok
def __iter__(self):
"""Allows you to use a response as an iterator."""
return self.iter_content(128)
@property
def ok(self):
try:
self.raise_for_status()
except HTTPError:
return False
return True
@property
def is_redirect(self):
"""True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
"""
return ('location' in self.headers and self.status_code in REDIRECT_STATI)
@property
def is_permanent_redirect(self):
"""True if this Response one of the permanant versions of redirect"""
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
@property
def apparent_encoding(self):
"""The apparent encoding, provided by the chardet library"""
return chardet.detect(self.content)['encoding']
def iter_content(self, chunk_size=1, decode_unicode=False):
"""Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
If decode_unicode is True, content will be decoded using the best
available encoding based on the response.
"""
def generate():
try:
# Special case for urllib3.
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
except AttributeError:
# Standard file-like object.
while True:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
stream_chunks = generate()
chunks = reused_chunks if self._content_consumed else stream_chunks
if decode_unicode:
chunks = stream_decode_response_unicode(chunks, self)
return chunks
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
"""Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
.. note:: This method is not reentrant safe.
"""
pending = None
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
if delimiter:
lines = chunk.split(delimiter)
else:
lines = chunk.splitlines()
if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
pending = lines.pop()
else:
pending = None
for line in lines:
yield line
if pending is not None:
yield pending
@property
def content(self):
"""Content of the response, in bytes."""
if self._content is False:
# Read the contents.
try:
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed')
if self.status_code == 0:
self._content = None
else:
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
except AttributeError:
self._content = None
self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
# since we exhausted the data.
return self._content
@property
def text(self):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
# Try charset from content-type
content = None
encoding = self.encoding
if not self.content:
return str('')
# Fallback to auto-detected encoding.
if self.encoding is None:
encoding = self.apparent_encoding
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors='replace')
return content
def json(self, **kwargs):
"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
"""
if not self.encoding and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using chardet to make
# a best guess).
encoding = guess_json_utf(self.content)
if encoding is not None:
try:
return json.loads(self.content.decode(encoding), **kwargs)
except UnicodeDecodeError:
# Wrong UTF codec detected; usually because it's not UTF-8
# but some other 8-bit codec. This is an RFC violation,
# and the server didn't bother to tell us what codec *was*
# used.
pass
return json.loads(self.text, **kwargs)
@property
def links(self):
"""Returns the parsed header links of the response, if any."""
header = self.headers.get('link')
# l = MultiDict()
l = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return l
def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if 400 <= self.status_code < 500:
http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
elif 500 <= self.status_code < 600:
http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
def close(self):
"""Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
return self.raw.release_conn()
|
GauriGNaik/servo | refs/heads/master | tests/wpt/web-platform-tests/tools/wptserve/wptserve/logger.py | 489 | class NoOpLogger(object):
def critical(self, msg):
pass
def error(self, msg):
pass
def info(self, msg):
pass
def warning(self, msg):
pass
def debug(self, msg):
pass
logger = NoOpLogger()
_set_logger = False
def set_logger(new_logger):
global _set_logger
if _set_logger:
raise Exception("Logger must be set at most once")
global logger
logger = new_logger
_set_logger = True
def get_logger():
return logger
|
ccrook/Quantum-GIS | refs/heads/master | python/PyQt/PyQt5/QtTest.py | 17 | # -*- coding: utf-8 -*-
"""
***************************************************************************
QtTest.py
---------------------
Date : March 2016
Copyright : (C) 2016 by Juergen E. Fischer
Email : jef at norbit dot de
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Juergen E. Fischer'
__date__ = 'March 2016'
__copyright__ = '(C) 2016, Juergen E. Fischer'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from PyQt5.QtTest import *
|
moijes12/oh-mainline | refs/heads/master | vendor/packages/django-kombu/djkombu/__init__.py | 20 | """Kombu transport using the Django database as a message store."""
VERSION = (0, 9, 4)
__version__ = ".".join(map(str, VERSION))
__author__ = "Ask Solem"
__contact__ = "ask@celeryproject.org"
__homepage__ = "http://github.com/ask/django-kombu/"
__docformat__ = "restructuredtext"
__license__ = "BSD"
|
jaxkodex/odoo | refs/heads/8.0 | openerp/addons/test_exceptions/models.py | 336 | # -*- coding: utf-8 -*-
import openerp.exceptions
import openerp.osv.orm
import openerp.osv.osv
import openerp.tools.safe_eval
class m(openerp.osv.osv.Model):
""" This model exposes a few methods that will raise the different
exceptions that must be handled by the server (and its RPC layer)
and the clients.
"""
_name = 'test.exceptions.model'
def generate_except_osv(self, cr, uid, ids, context=None):
# title is ignored in the new (6.1) exceptions
raise openerp.osv.osv.except_osv('title', 'description')
def generate_except_orm(self, cr, uid, ids, context=None):
# title is ignored in the new (6.1) exceptions
raise openerp.osv.orm.except_orm('title', 'description')
def generate_warning(self, cr, uid, ids, context=None):
raise openerp.exceptions.Warning('description')
def generate_redirect_warning(self, cr, uid, ids, context=None):
dummy, action_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'test_exceptions', 'action_test_exceptions')
raise openerp.exceptions.RedirectWarning('description', action_id, 'go to the redirection')
def generate_access_denied(self, cr, uid, ids, context=None):
raise openerp.exceptions.AccessDenied()
def generate_access_error(self, cr, uid, ids, context=None):
raise openerp.exceptions.AccessError('description')
def generate_exc_access_denied(self, cr, uid, ids, context=None):
raise Exception('AccessDenied')
def generate_undefined(self, cr, uid, ids, context=None):
self.surely_undefined_symbol
def generate_except_osv_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_except_osv, context)
def generate_except_orm_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_except_orm, context)
def generate_warning_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_warning, context)
def generate_redirect_warning_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_redirect_warning, context)
def generate_access_denied_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_access_denied, context)
def generate_access_error_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_access_error, context)
def generate_exc_access_denied_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_exc_access_denied, context)
def generate_undefined_safe_eval(self, cr, uid, ids, context=None):
self.generate_safe_eval(cr, uid, ids, self.generate_undefined, context)
def generate_safe_eval(self, cr, uid, ids, f, context):
globals_dict = { 'generate': lambda *args: f(cr, uid, ids, context) }
openerp.tools.safe_eval.safe_eval("generate()", mode='exec', globals_dict=globals_dict)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
CCI-Tools/cate-core | refs/heads/master | cate/util/cache.py | 2 | # The MIT License (MIT)
# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Description
===========
This module defines the :py:class:`Cache` class which represents a general-purpose cache.
A cache is configured by a :py:class:`CacheStore` which is responsible for storing and reloading cached items.
The default cache stores are
* :py:class:`MemoryCacheStore`
* :py:class:`FileCacheStore`
Every cache has capacity in physical units defined by the :py:class:`CacheStore`. When the cache capacity is exceeded
a replacement policy for cached items is applied until the cache size falls below a given ratio of the total capacity.
The default replacement policies are
* :py:data:`POLICY_LRU`
* :py:data:`POLICY_MRU`
* :py:data:`POLICY_LFU`
* :py:data:`POLICY_RR`
This package is independent of other ``cate.*``packages and can therefore be used stand-alone.
Components
==========
"""
import os
import os.path
import sys
import time
from abc import ABCMeta, abstractmethod
from threading import RLock
__author__ = "Norman Fomferra (Brockmann Consult GmbH)"
# _DEBUG_CACHE = True
_DEBUG_CACHE = False
class CacheStore(metaclass=ABCMeta):
"""
Represents a store to which cached values can be stored into and restored from.
"""
@abstractmethod
def can_load_from_key(self, key) -> bool:
"""
Test whether a stored value representation can be loaded from the given key.
:param key: the key
:return: True, if so
"""
pass
@abstractmethod
def load_from_key(self, key):
"""
Load a stored value representation of the value and its size from the given key.
:param key: the key
:return: a 2-element sequence containing the stored representation of the value and it's size
"""
pass
@abstractmethod
def store_value(self, key, value):
"""
Store a value and return it's stored representation and size in any unit, e.g. in bytes.
:param key: the key
:param value: the value
:return: a 2-element sequence containing the stored representation of the value and it's size
"""
pass
@abstractmethod
def restore_value(self, key, stored_value):
"""
Restore a vale from its stored representation.
:param key: the key
:param stored_value: the stored representation of the value
:return: the item
"""
pass
@abstractmethod
def discard_value(self, key, stored_value):
"""
Discard a value from it's storage.
:param key: the key
:param stored_value: the stored representation of the value
"""
pass
class MemoryCacheStore(CacheStore):
"""
Simple memory store.
"""
def can_load_from_key(self, key) -> bool:
# This store type does not maintain key-value pairs on its own
return False
def load_from_key(self, key):
raise NotImplementedError()
def store_value(self, key, value):
"""
Return (value, 1).
:param key: the key
:param value: the original value
:return: the tuple (stored value, size) where stored value is the sequence [key, value].
"""
return [key, value], _compute_object_size(value)
def restore_value(self, key, stored_value):
"""
:param key: the key
:param stored_value: the stored representation of the value
:return: the original value.
"""
if key != stored_value[0]:
raise ValueError('key does not match stored value')
return stored_value[1]
def discard_value(self, key, stored_value):
"""
Clears the value in the given stored_value.
:param key: the key
:param stored_value: the stored representation of the value
"""
if key != stored_value[0]:
raise ValueError('key does not match stored value')
stored_value[1] = None
class FileCacheStore(CacheStore):
"""
Simple file store for values which can be written and read as bytes, e.g. encoded PNG images.
"""
def __init__(self, cache_dir: str, ext: str):
self.cache_dir = cache_dir
self.ext = ext
def can_load_from_key(self, key) -> bool:
path = self._key_to_path(key)
return os.path.exists(path)
def load_from_key(self, key):
path = self._key_to_path(key)
return path, os.path.getsize(path)
def store_value(self, key, value):
path = self._key_to_path(key)
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
os.makedirs(dir_path, exist_ok=True)
with open(path, 'wb') as fp:
fp.write(value)
return path, os.path.getsize(path)
def restore_value(self, key, stored_value):
path = self._key_to_path(key)
with open(path, 'rb') as fp:
return fp.read()
def discard_value(self, key, stored_value):
path = self._key_to_path(key)
try:
os.remove(path)
# TODO (forman): also remove empty directories up to self.cache_dir
except IOError:
pass
def _key_to_path(self, key):
return os.path.join(self.cache_dir, str(key) + self.ext)
def _policy_lru(item):
return item.access_time
def _policy_mru(item):
return -item.access_time
def _policy_lfu(item):
return item.access_count
def _policy_rr(item):
return item.access_count % 2
#: Discard Least Recently Used items first
POLICY_LRU = _policy_lru
#: Discard Most Recently Used first
POLICY_MRU = _policy_mru
#: Discard Least Frequently Used first
POLICY_LFU = _policy_lfu
#: Discard items by Random Replacement
POLICY_RR = _policy_rr
_T0 = time.perf_counter()
class Cache:
"""
An implementation of a cache.
See https://en.wikipedia.org/wiki/Cache_algorithms
"""
class Item:
"""
Cache-private class representing an item in the cache.
"""
def __init__(self):
self.key = None
self.stored_value = None
self.stored_size = 0
self.creation_time = 0
self.access_time = 0
self.access_count = 0
@staticmethod
def load_from_key(store, key):
if not store.can_load_from_key(key):
return None
item = Cache.Item()
item._load_from_key(store, key)
return item
def store(self, store, key, value):
self.key = key
self.access_count = 0
self._access()
stored_value, stored_size = store.store_value(key, value)
self.stored_value = stored_value
self.stored_size = stored_size
def restore(self, store, key):
self._access()
return store.restore_value(key, self.stored_value)
def discard(self, store, key):
store.discard_value(key, self.stored_value)
self.__init__()
def _load_from_key(self, store, key):
self.key = key
self.access_count = 0
self._access()
stored_value, stored_size = store.load_from_key(key)
self.stored_value = stored_value
self.stored_size = stored_size
def _access(self):
self.access_time = time.perf_counter() - _T0
self.access_count += 1
def __init__(self, store=MemoryCacheStore(), capacity=1000, threshold=0.75, policy=POLICY_LRU, parent_cache=None):
"""
Constructor.
:param store: the cache store, see CacheStore interface
:param capacity: the size capacity in units used by the store's store() method
:param threshold: a number greater than zero and less than one
:param policy: cache replacement policy. This is a function that maps a :py:class:`Cache.Item`
to a numerical value. See :py:data:`POLICY_LRU`,
:py:data:`POLICY_MRU`, :py:data:`POLICY_LFU`, :py:data:`POLICY_RR`
"""
self._store = store
self._capacity = capacity
self._threshold = threshold
self._policy = policy
self._parent_cache = parent_cache
self._size = 0
self._max_size = self._capacity * self._threshold
self._item_dict = {}
self._item_list = []
self._lock = RLock()
@property
def policy(self):
return self._policy
@property
def store(self):
return self._store
@property
def capacity(self):
return self._capacity
@property
def threshold(self):
return self._threshold
@property
def size(self):
return self._size
@property
def max_size(self):
return self._max_size
def get_value(self, key):
self._lock.acquire()
item = self._item_dict.get(key)
value = None
restored = False
if item:
value = item.restore(self._store, key)
restored = True
if _DEBUG_CACHE:
_debug_print('restored value for key "%s" from cache' % key)
elif self._parent_cache:
item = self._parent_cache.get_value(key)
if item:
value = item.restore(self._parent_cache.store, key)
restored = True
if _DEBUG_CACHE:
_debug_print('restored value for key "%s" from parent cache' % key)
if not restored:
item = Cache.Item.load_from_key(self._store, key)
if item:
self._add_item(item)
value = item.restore(self._store, key)
if _DEBUG_CACHE:
_debug_print('restored value for key "%s" from cache' % key)
self._lock.release()
return value
def put_value(self, key, value):
self._lock.acquire()
if self._parent_cache:
# remove value from parent cache, because this cache will now take over
self._parent_cache.remove_value(key)
item = self._item_dict.get(key)
if item:
self._remove_item(item)
item.discard(self._store, key)
if _DEBUG_CACHE:
_debug_print('discarded value for key "%s" from cache' % key)
else:
item = Cache.Item()
item.store(self._store, key, value)
if _DEBUG_CACHE:
_debug_print('stored value for key "%s" in cache' % key)
self._add_item(item)
self._lock.release()
def remove_value(self, key):
self._lock.acquire()
if self._parent_cache:
self._parent_cache.remove_value(key)
item = self._item_dict.get(key)
if item:
self._remove_item(item)
item.discard(self._store, key)
if _DEBUG_CACHE:
_debug_print('cate.util.im.cache.Cache: discarded value for key "%s" from parent cache' % key)
self._lock.release()
def _add_item(self, item):
self._item_dict[item.key] = item
self._item_list.append(item)
if self._size + item.stored_size > self._max_size:
self.trim(item.stored_size)
self._size += item.stored_size
def _remove_item(self, item):
self._item_dict.pop(item.key)
self._item_list.remove(item)
self._size -= item.stored_size
def trim(self, extra_size=0):
if _DEBUG_CACHE:
_debug_print('trimming...')
self._lock.acquire()
self._item_list.sort(key=self._policy)
keys = []
size = self._size
max_size = self._max_size
for item in self._item_list:
if size + extra_size > max_size:
keys.append(item.key)
size -= item.stored_size
self._lock.release()
# release lock to give another thread a chance then require lock again
self._lock.acquire()
for key in keys:
if self._parent_cache:
# Before discarding item fully, put its value into the parent cache
value = self.get_value(key)
self.remove_value(key)
if value:
self._parent_cache.put_value(key, value)
else:
self.remove_value(key)
self._lock.release()
def clear(self, clear_parent=True):
self._lock.acquire()
if self._parent_cache and clear_parent:
self._parent_cache.clear(clear_parent)
keys = list(self._item_dict.keys())
self._lock.release()
for key in keys:
if self._parent_cache and not clear_parent:
value = self.get_value(key)
if value:
self._parent_cache.put_value(key, value)
self.remove_value(key)
def _debug_print(msg):
print("cate.util.cache.Cache:", msg)
def _compute_object_size(obj):
if hasattr(obj, 'nbytes'):
# A numpy ndarray instance
return obj.nbytes
elif hasattr(obj, 'size') and hasattr(obj, 'mode'):
# A PIL Image instance
w, h = obj.size
m = obj.mode
return w * h * (4 if m in ('RGBA', 'RGBx', 'I', 'F') else
3 if m in ('RGB', 'YCbCr', 'LAB', 'HSV') else
1. / 8. if m == '1' else
1)
else:
return sys.getsizeof(obj)
|
Firefly-Automation/Firefly | refs/heads/firefly3 | Firefly/core/core.py | 1 | import asyncio
import importlib
import json
import signal
import sys
from concurrent.futures import ThreadPoolExecutor
from os import path
from pathlib import Path
from typing import Any
from time import sleep
from aiohttp import web
from Firefly import aliases, logging, scheduler
from Firefly.const import COMPONENT_MAP, DEVICE_FILE, EVENT_TYPE_BROADCAST, LOCATION_FILE, REQUIRED_FILES, TIME, TYPE_DEVICE, VERSION
from Firefly.core.service_handler import ServiceHandler
from Firefly.helpers.events import Event, Request, Command
from Firefly.helpers.groups.groups import import_groups, build_rooms, export_groups
from Firefly.helpers.location import Location
from Firefly.helpers.subscribers import Subscriptions
from Firefly.services.firefly_security_and_monitoring.firefly_monitoring import FireflySecurityAndMonitoring
from Firefly.services.firebase.event_logging import EventLogger
app = web.Application()
FIREBASE_SERVICE = 'service_firebase'
def sigterm_handler(_signo, _stack_frame):
# Raises SystemExit(0):
logging.notify('Firefly is shutting down...')
sys.exit(0)
class Firefly(object):
''' Core running loop and scheduler of Firefly'''
def __init__(self, settings):
signal.signal(signal.SIGTERM, sigterm_handler)
signal.signal(signal.SIGHUP, sigterm_handler)
signal.signal(signal.SIGQUIT, sigterm_handler)
self.done_starting_up = False
# TODO: Most of this should be in startup not init.
logging.Startup(self)
logging.message('Initializing Firefly')
self.check_required_files()
# TODO (zpriddy): Add import and export of current state.
self.current_state = {}
self._firebase_enabled = False
self._rooms = None
self._components = {}
self.settings = settings
self.loop = asyncio.get_event_loop()
self.executor = ThreadPoolExecutor(max_workers=10)
self.loop.set_default_executor(self.executor)
self._subscriptions = Subscriptions()
self.location = self.import_location()
self.location.add_status_message('firefly_startup', 'Firefly is starting up. This can take up to 5 minutes.')
self.device_initial_values = {}
# Get the beacon ID.
self.beacon_id = settings.beacon_id
# Start Security and Monitoring Service
self.security_and_monitoring = FireflySecurityAndMonitoring(self)
# Start Notification service
self.install_package('Firefly.services.notification', alias='service notification')
# self.install_package('Firefly.components.notification.pushover', alias='Pushover', api_key='KEY', user_key='KEY')
for c in COMPONENT_MAP:
self.import_components(c['file'])
self.service_handler = ServiceHandler()
self.service_handler.install_services(self)
logging.info('[CORE] services installed: %s' % str(self.service_handler.get_installed_services(self)))
# TODO: Rooms will be replaced by groups subclass rooms.
# self._rooms = Rooms(self)
# self._rooms.build_rooms()
# Import Groups
import_groups(self)
build_rooms(self)
logging.error(code='FF.COR.INI.001') # this is a test error message
logging.notify('Firefly is starting up in mode: %s' % self.location.mode)
# TODO: Leave In.
scheduler.runEveryH(1, self.export_all_components)
# Set the current state for all devices.
# TODO (zpriddy): Remove this when import and export is done.
all_devices = set([c_id for c_id, c in self.components.items() if (c.type == TYPE_DEVICE or c.type == 'ROOM')])
self.current_state = self.get_device_states(all_devices)
# self.async_send_command(Command('service_zwave', 'core_startup', 'initialize'))
# TODO: Run this line after some delay (1 min) and re-set device initial values
scheduler.runInM(2, self.finish_starting_up, 'finish_startup')
#self.done_starting_up = True
self.security_and_monitoring.generate_status()
self.event_logger = EventLogger(self)
def finish_starting_up(self):
self.done_starting_up = True
self.set_initial_values()
self.security_and_monitoring.startup()
self.location.remove_status_message('firefly_startup')
def set_initial_values(self):
for ff_id, device in self.components.items():
if device.type != TYPE_DEVICE:
continue
for attr, value in self.device_initial_values.get(ff_id, {}).items():
device.__setattr__(attr, value)
scheduler.runInS(10, self.refresh_firebase, job_id='FIREBASE_REFRESH_CORE')
scheduler.runInS(15, self.export_all_components, job_id='CORE_EXPORT_ALL')
def import_components(self, config_file=DEVICE_FILE):
''' Import all components from the devices file
Args:
config_file: json file of all components
Returns:
'''
logging.message('Importing components from config file: %s' % config_file)
try:
with open(config_file) as file:
components = json.loads(file.read())
for component in components:
self.install_package(component.get('package'), **component)
except Exception as e:
logging.error('Error importing data from: %s - %s' % (config_file, str(e)))
def install_package(self, module: str, **kwargs):
"""
Installs a package from the module. The package must support the Setup(firefly, **kwargs) function.
The setup function can (and should) add the ff_id (if a ff_id) to the firefly._devices dict.
Args:
module (str): path to module being imported
**kwargs (): If possible supply alias and/or device_id
"""
logging.message('Installing module from %s %s' % (module, str(kwargs)))
package = importlib.import_module(module)
if kwargs.get('package'):
kwargs.pop('package')
setup_return = package.Setup(self, module, **kwargs)
ff_id = kwargs.get('ff_id')
initial_values = kwargs.get('initial_values')
if ff_id and initial_values:
self.device_initial_values[ff_id] = initial_values
scheduler.runInS(10, self.refresh_firebase, job_id='FIREBASE_REFRESH_CORE')
scheduler.runInS(15, self.export_all_components, job_id='CORE_EXPORT_ALL')
return setup_return
def install_component(self, component):
''' Install a component into the core components.
Args:
component: Component object
Returns:
'''
logging.info('[CORE INSTALL COMPONENT] Installing Component: %s' % component.id)
try:
self.components[component.id] = component
return component.id
except Exception as e:
logging.error('[CORE INSTALL COMPONENT] ERROR INSTALLING: %s' % str(e))
return None
def import_location(self) -> Location:
''' Import location data.
Returns:
'''
return Location(self, LOCATION_FILE)
def export_location(self) -> None:
''' Export location data.
Returns:
'''
self.location.export_to_file()
def check_required_files(self, **kwargs):
''' Make sure all required files are there. If not set to default content.
Args:
**kwargs:
Returns:
'''
logging.info('[CORE] checking required files')
for file_path, default_content in REQUIRED_FILES.items():
if not path.isfile(file_path):
if default_content is None:
Path(file_path).touch()
elif type(default_content) is dict or type(default_content) is list:
with open(file_path, 'w') as new_file:
json.dump(default_content, new_file)
def start(self) -> None:
"""
Start up Firefly.
"""
try:
web.run_app(app, host=self.settings.firefly_host, port=self.settings.firefly_port)
except KeyboardInterrupt:
logging.message('Firefly was manually killed')
except SystemExit:
logging.message('Firefly was killed by system process. Probably due to automatic updates')
finally:
self.stop()
def stop(self) -> None:
''' Shutdown firefly.
Shutdown process should export the current state of all components so it can be imported on reboot and startup.
'''
logging.notify('Stopping Firefly')
self.export_all_components()
self.export_location()
self.security_and_monitoring.shutdown()
try:
logging.message('Stopping zwave service')
if self.components.get('service_zwave'):
self.components['service_zwave'].stop()
except Exception as e:
logging.notify(e)
sleep(10)
self.loop.stop()
self.loop.close()
@asyncio.coroutine
def add_task(self, task):
logging.debug('Adding task to Firefly scheduler: %s' % str(task))
future = asyncio.Future()
r = yield from asyncio.ensure_future(task)
future.set_result(r)
return r
def delete_device(self, ff_id):
self.components.pop(ff_id)
aliases.aliases.pop(ff_id)
if FIREBASE_SERVICE in self.service_handler.get_installed_services(self):
self.components[FIREBASE_SERVICE].refresh_all()
def export_all_components(self) -> None:
"""
Export current values to backup files to restore current config on reboot.
"""
logging.message('Exporting current config.')
for c in COMPONENT_MAP:
self.export_components(c['file'], c['type'])
aliases.export_aliases()
export_groups(self)
def export_components(self, config_file: str, component_type: str, current_values: bool = True) -> None:
"""
Export all components with config and optional current states to a config file.
Args:
config_file (str): Path to config file.
current_values (bool): Include current values.
"""
logging.message('Exporting component and states to config file. - %s' % component_type)
components = []
for ff_id, device in self.components.items():
if device.type == component_type:
try:
components.append(device.export(current_values=current_values))
except Exception as e:
logging.error('[CORE] ERROR EXPORTING %s - %s' % (ff_id, e))
with open(config_file, 'w') as file:
json.dump(components, file, indent=4, sort_keys=True)
def send_firebase(self, event: Event):
''' Send and event to firebase
Args:
event: event to be sent
Returns:
'''
if self.components.get(FIREBASE_SERVICE):
self.components[FIREBASE_SERVICE].push(event.source, event.event_action)
def update_security_firebase(self, security_status):
if self.components.get(FIREBASE_SERVICE):
try:
self.components[FIREBASE_SERVICE].security_update(security_status)
except:
logging.warn('[CORE - SECURITY] Could not send event to security and monitoring. This is probably due to the service not being active yet.')
def send_security_monitor(self, event: Event):
""" Send event to security and monitoring service.
Args:
event: Event to be sent
Returns:
"""
try:
self.security_and_monitoring.event(event)
except AttributeError:
logging.warn('[CORE - SECURITY] Could not send event to security and monitoring. This is probably due to the service not being active yet.')
def refresh_firebase(self, **kwargs):
if FIREBASE_SERVICE in self.service_handler.get_installed_services(self):
self.components[FIREBASE_SERVICE].refresh_all()
@asyncio.coroutine
def async_send_event(self, event):
logging.info('Received event: %s' % event)
s = True
fut = asyncio.Future(loop=self.loop)
send_to = self._subscriptions.get_subscribers(event.source, event_action=event.event_action)
for s in send_to:
s &= yield from self._send_event(event, s, fut)
self.send_firebase(event)
return s
def send_event(self, event: Event) -> Any:
logging.info('Received event: %s' % event)
if not self.done_starting_up:
logging.info('[CORE] firefly still starting up. No events will be sent')
return
self.loop.run_in_executor(None, self._test_send_event, event)
self.loop.run_in_executor(None, self.send_security_monitor, event)
def _test_send_event(self, event:Event):
send_to = self._subscriptions.get_subscribers(event.source, event_action=event.event_action)
for s in send_to:
try:
self.components[s].event(event)
logging.info('[CORE] EVENT SENT!!! YAY!')
except Exception as e:
logging.error('Error sending event %s' % str(e))
self.update_current_state(event)
self.send_firebase(event)
self.event_logger.event(event.source, event.event_action, self.location.now.timestamp())
def _test_send_command(self, command:Command):
try:
self.components[command.device].command(command)
except Exception as e:
logging.error('[CORE] error sending command: %s' % e)
@asyncio.coroutine
def _send_event(self, event, ff_id, fut):
result = self.components[ff_id].event(event)
# fut.set_result(result)
return result
@asyncio.coroutine
def async_send_request(self, request):
fut = asyncio.Future(loop=self.loop)
r = yield from self._send_request(request, fut)
return r
def send_request(self, request: Request) -> Any:
fut = asyncio.Future(loop=self.loop)
result = asyncio.ensure_future(self._send_request(request, fut), loop=self.loop)
return result
@asyncio.coroutine
def _send_request(self, request, fut):
result = self.components[request.ff_id].request(request)
fut.set_result(result)
return result
def send_command(self, command: Command, wait=False):
if command.device not in self.components:
return False
self.loop.run_in_executor(None, self._test_send_command, command)
#try:
# if wait:
# fut = asyncio.run_coroutine_threadsafe(self.new_send_command(command, None, self.loop), self.loop)
# return fut.result(10)
# else:
# # asyncio.run_coroutine_threadsafe(self.send_command_no_wait(command, self.loop), self.loop)
# self.components[command.device].command(command)
# return True
#except Exception as e:
# logging.error(code='FF.COR.SEN.001') # unknown error sending command
# logging.error(e)
# # TODO: Figure out how to wait for result
#return False
async def new_send_command(self, command, fut, loop):
fut = await asyncio.ensure_future(loop.run_in_executor(None, self.components[command.device].command, command))
return fut
async def send_command_no_wait(self, command, loop):
# await asyncio.ensure_future(loop.run_in_executor(None, self.components[command.device].command, command))
self.components[command.device].command(command)
# loop.run_in_executor(None, self.components[command.device].command, command)
return True
@asyncio.coroutine
def async_send_command(self, command):
fut = asyncio.Future(loop=self.loop)
result = yield from asyncio.ensure_future(self._send_command(command, fut), loop=self.loop)
return result
@asyncio.coroutine
def _send_command(self, command, fut):
if command.device in self.components:
result = self.components[command.device].command(command)
fut.set_result(result)
return result
logging.error(code='FF.COR._SE.001', args=(command.device)) # device not found %s
return None
def add_route(self, route, method, handler):
app.router.add_route(method, route, handler)
def add_get(self, route, handler, *args):
app.router.add_get(route, handler)
# TODO(zpriddy): Remove this function.
def get_device_states(self, devices: set) -> dict:
logging.warn('This is now deprecated.')
current_state = {}
if TIME in devices:
devices.remove(TIME)
if 'location' in devices:
devices.remove('location')
for device in devices:
current_state[device] = self.components[device].get_all_request_values(True)
return current_state
def update_current_state(self, event: Event) -> None:
"""
Update the global current state when a broadcast event is sent.
Args:
event (Event): the broadcast event.
"""
# Do not update time.
if event.source == TIME:
return
# Only look at broadcast events.
if event.event_type != EVENT_TYPE_BROADCAST:
return
if event.source not in self.current_state:
self.current_state[event.source] = {}
self.current_state[event.source].update(event.event_action)
def get_current_states(self):
return self.current_state
@property
def components(self):
return self._components
@property
def subscriptions(self):
return self._subscriptions
@property
def firebase_enabled(self):
return self._firebase_enabled
@property
def version(self):
return VERSION
|
shitolepriya/test-erp | refs/heads/develop | erpnext/selling/report/customers_not_buying_since_long_time/__init__.py | 12133432 | |
brett-patterson/pyface | refs/heads/master | pyface/ui/wx/dialog.py | 2 | #------------------------------------------------------------------------------
#
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
# Author: Enthought, Inc.
#
#------------------------------------------------------------------------------
""" Enthought pyface package component
"""
# Major package imports.
import sys
import wx
# Enthought library imports.
from traits.api import Bool, Enum, Int, provides, Str, Unicode
# Local imports.
from pyface.i_dialog import IDialog, MDialog
from pyface.constant import OK, CANCEL, YES, NO
from window import Window
# Map wx dialog related constants to the pyface equivalents.
_RESULT_MAP = {
wx.ID_OK : OK,
wx.ID_CANCEL : CANCEL,
wx.ID_YES : YES,
wx.ID_NO : NO,
wx.ID_CLOSE : CANCEL,
# There seems to be a bug in wx.SingleChoiceDialog that allows it to return
# 0 when it is closed via the window (closing it via the buttons works just
# fine).
0 : CANCEL
}
@provides(IDialog)
class Dialog(MDialog, Window):
""" The toolkit specific implementation of a Dialog. See the IDialog
interface for the API documentation.
"""
#### 'IDialog' interface ##################################################
cancel_label = Unicode
help_id = Str
help_label = Unicode
ok_label = Unicode
resizeable = Bool(True)
return_code = Int(OK)
style = Enum('modal', 'nonmodal')
#### 'IWindow' interface ##################################################
title = Unicode("Dialog")
###########################################################################
# Protected 'IDialog' interface.
###########################################################################
def _create_buttons(self, parent):
sizer = wx.BoxSizer(wx.HORIZONTAL)
# The 'OK' button.
if self.ok_label:
label = self.ok_label
else:
label = "OK"
self._wx_ok = ok = wx.Button(parent, wx.ID_OK, label)
ok.SetDefault()
wx.EVT_BUTTON(parent, wx.ID_OK, self._wx_on_ok)
sizer.Add(ok)
# The 'Cancel' button.
if self.cancel_label:
label = self.cancel_label
else:
label = "Cancel"
self._wx_cancel = cancel = wx.Button(parent, wx.ID_CANCEL, label)
wx.EVT_BUTTON(parent, wx.ID_CANCEL, self._wx_on_cancel)
sizer.Add(cancel, 0, wx.LEFT, 10)
# The 'Help' button.
if len(self.help_id) > 0:
if self.help_label:
label = self.help_label
else:
label = "Help"
help = wx.Button(parent, wx.ID_HELP, label)
wx.EVT_BUTTON(parent, wx.ID_HELP, self._wx_on_help)
sizer.Add(help, 0, wx.LEFT, 10)
return sizer
def _create_contents(self, parent):
sizer = wx.BoxSizer(wx.VERTICAL)
parent.SetSizer(sizer)
parent.SetAutoLayout(True)
# The 'guts' of the dialog.
dialog_area = self._create_dialog_area(parent)
sizer.Add(dialog_area, 1, wx.EXPAND | wx.ALL, 5)
# The buttons.
buttons = self._create_buttons(parent)
sizer.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALL, 5)
# Resize the dialog to match the sizer's minimal size.
if self.size != (-1, -1):
parent.SetSize(self.size)
else:
sizer.Fit(parent)
parent.CentreOnParent()
def _create_dialog_area(self, parent):
panel = wx.Panel(parent, -1)
panel.SetBackgroundColour("red")
panel.SetSize((100, 200))
return panel
def _show_modal(self):
if sys.platform == 'darwin':
# Calling Show(False) is needed on the Mac for the modal dialog
# to show up at all.
self.control.Show(False)
return _RESULT_MAP[self.control.ShowModal()]
###########################################################################
# Protected 'IWidget' interface.
###########################################################################
def _create_control(self, parent):
style = wx.DEFAULT_DIALOG_STYLE | wx.CLIP_CHILDREN
if self.resizeable:
style |= wx.RESIZE_BORDER
return wx.Dialog(parent, -1, self.title, style=style)
#### wx event handlers ####################################################
def _wx_on_ok(self, event):
""" Called when the 'OK' button is pressed. """
self.return_code = OK
# Let the default handler close the dialog appropriately.
event.Skip()
def _wx_on_cancel(self, event):
""" Called when the 'Cancel' button is pressed. """
self.return_code = CANCEL
# Let the default handler close the dialog appropriately.
event.Skip()
def _wx_on_help(self, event):
""" Called when the 'Help' button is pressed. """
print 'Heeeeelllllllllllllpppppppppppppppppppp'
#### EOF ######################################################################
|
simonwydooghe/ansible | refs/heads/devel | test/integration/targets/win_unzip/files/create_zip.py | 7 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import tempfile
import zipfile
def main():
filename = b"caf\xc3\xa9.txt"
with tempfile.NamedTemporaryFile() as temp:
with open(temp.name, mode="wb") as fd:
fd.write(filename)
with open(sys.argv[1], mode="wb") as fd:
with zipfile.ZipFile(fd, "w") as zip:
zip.write(temp.name, filename.decode('utf-8'))
if __name__ == '__main__':
main()
|
teeple/pns_server | refs/heads/master | work/install/Python-2.7.4/Lib/email/parser.py | 392 | # Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw, Thomas Wouters, Anthony Baxter
# Contact: email-sig@python.org
"""A parser of RFC 2822 and MIME email messages."""
__all__ = ['Parser', 'HeaderParser']
import warnings
from cStringIO import StringIO
from email.feedparser import FeedParser
from email.message import Message
class Parser:
def __init__(self, *args, **kws):
"""Parser of RFC 2822 and MIME email messages.
Creates an in-memory object tree representing the email message, which
can then be manipulated and turned over to a Generator to return the
textual representation of the message.
The string must be formatted as a block of RFC 2822 headers and header
continuation lines, optionally preceeded by a `Unix-from' header. The
header block is terminated either by the end of the string or by a
blank line.
_class is the class to instantiate for new message objects when they
must be created. This class must have a constructor that can take
zero arguments. Default is Message.Message.
"""
if len(args) >= 1:
if '_class' in kws:
raise TypeError("Multiple values for keyword arg '_class'")
kws['_class'] = args[0]
if len(args) == 2:
if 'strict' in kws:
raise TypeError("Multiple values for keyword arg 'strict'")
kws['strict'] = args[1]
if len(args) > 2:
raise TypeError('Too many arguments')
if '_class' in kws:
self._class = kws['_class']
del kws['_class']
else:
self._class = Message
if 'strict' in kws:
warnings.warn("'strict' argument is deprecated (and ignored)",
DeprecationWarning, 2)
del kws['strict']
if kws:
raise TypeError('Unexpected keyword arguments')
def parse(self, fp, headersonly=False):
"""Create a message structure from the data in a file.
Reads all the data from the file and returns the root of the message
structure. Optional headersonly is a flag specifying whether to stop
parsing after reading the headers or not. The default is False,
meaning it parses the entire contents of the file.
"""
feedparser = FeedParser(self._class)
if headersonly:
feedparser._set_headersonly()
while True:
data = fp.read(8192)
if not data:
break
feedparser.feed(data)
return feedparser.close()
def parsestr(self, text, headersonly=False):
"""Create a message structure from a string.
Returns the root of the message structure. Optional headersonly is a
flag specifying whether to stop parsing after reading the headers or
not. The default is False, meaning it parses the entire contents of
the file.
"""
return self.parse(StringIO(text), headersonly=headersonly)
class HeaderParser(Parser):
def parse(self, fp, headersonly=True):
return Parser.parse(self, fp, True)
def parsestr(self, text, headersonly=True):
return Parser.parsestr(self, text, True)
|
opendroid-Team/enigma2-4.1 | refs/heads/master | lib/python/Tools/CList.py | 176 | class CList(list):
def __getattr__(self, attr):
return CList([getattr(a, attr) for a in self])
def __call__(self, *args, **kwargs):
for x in self:
x(*args, **kwargs)
|
Reivajar/jasanche-byte1 | refs/heads/master | lib/werkzeug/contrib/profiler.py | 315 | # -*- coding: utf-8 -*-
"""
werkzeug.contrib.profiler
~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides a simple WSGI profiler middleware for finding
bottlenecks in web application. It uses the :mod:`profile` or
:mod:`cProfile` module to do the profiling and writes the stats to the
stream provided (defaults to stderr).
Example usage::
from werkzeug.contrib.profiler import ProfilerMiddleware
app = ProfilerMiddleware(app)
:copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import sys, time, os.path
try:
try:
from cProfile import Profile
except ImportError:
from profile import Profile
from pstats import Stats
available = True
except ImportError:
available = False
class MergeStream(object):
"""An object that redirects `write` calls to multiple streams.
Use this to log to both `sys.stdout` and a file::
f = open('profiler.log', 'w')
stream = MergeStream(sys.stdout, f)
profiler = ProfilerMiddleware(app, stream)
"""
def __init__(self, *streams):
if not streams:
raise TypeError('at least one stream must be given')
self.streams = streams
def write(self, data):
for stream in self.streams:
stream.write(data)
class ProfilerMiddleware(object):
"""Simple profiler middleware. Wraps a WSGI application and profiles
a request. This intentionally buffers the response so that timings are
more exact.
By giving the `profile_dir` argument, pstat.Stats files are saved to that
directory, one file per request. Without it, a summary is printed to
`stream` instead.
For the exact meaning of `sort_by` and `restrictions` consult the
:mod:`profile` documentation.
.. versionadded:: 0.9
Added support for `restrictions` and `profile_dir`.
:param app: the WSGI application to profile.
:param stream: the stream for the profiled stats. defaults to stderr.
:param sort_by: a tuple of columns to sort the result by.
:param restrictions: a tuple of profiling strictions, not used if dumping
to `profile_dir`.
:param profile_dir: directory name to save pstat files
"""
def __init__(self, app, stream=None,
sort_by=('time', 'calls'), restrictions=(), profile_dir=None):
if not available:
raise RuntimeError('the profiler is not available because '
'profile or pstat is not installed.')
self._app = app
self._stream = stream or sys.stdout
self._sort_by = sort_by
self._restrictions = restrictions
self._profile_dir = profile_dir
def __call__(self, environ, start_response):
response_body = []
def catching_start_response(status, headers, exc_info=None):
start_response(status, headers, exc_info)
return response_body.append
def runapp():
appiter = self._app(environ, catching_start_response)
response_body.extend(appiter)
if hasattr(appiter, 'close'):
appiter.close()
p = Profile()
start = time.time()
p.runcall(runapp)
body = ''.join(response_body)
elapsed = time.time() - start
if self._profile_dir is not None:
prof_filename = os.path.join(self._profile_dir,
'%s.%s.%06dms.%d.prof' % (
environ['REQUEST_METHOD'],
environ.get('PATH_INFO').strip('/').replace('/', '.') or 'root',
elapsed * 1000.0,
time.time()
))
p.dump_stats(prof_filename)
else:
stats = Stats(p, stream=self._stream)
stats.sort_stats(*self._sort_by)
self._stream.write('-' * 80)
self._stream.write('\nPATH: %r\n' % environ.get('PATH_INFO'))
stats.print_stats(*self._restrictions)
self._stream.write('-' * 80 + '\n\n')
return [body]
def make_action(app_factory, hostname='localhost', port=5000,
threaded=False, processes=1, stream=None,
sort_by=('time', 'calls'), restrictions=()):
"""Return a new callback for :mod:`werkzeug.script` that starts a local
server with the profiler enabled.
::
from werkzeug.contrib import profiler
action_profile = profiler.make_action(make_app)
"""
def action(hostname=('h', hostname), port=('p', port),
threaded=threaded, processes=processes):
"""Start a new development server."""
from werkzeug.serving import run_simple
app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions)
run_simple(hostname, port, app, False, None, threaded, processes)
return action
|
gbaty/pyside2 | refs/heads/master | tests/QtCore/bug_PYSIDE-164.py | 3 | from __future__ import print_function
import unittest
from PySide2.QtCore import QCoreApplication, QEventLoop, QObject, Qt, QThread, QTimer, SIGNAL
class Emitter(QThread):
def __init__(self):
QThread.__init__(self)
def run(self):
print("Before emit.")
self.emit(SIGNAL("signal(int)"), 0)
print("After emit.")
class Receiver(QObject):
def __init__(self, eventloop):
QObject.__init__(self)
self.eventloop = eventloop
def receive(self, number):
print("Received number: %d" % number)
self.eventloop.exit(0)
class TestBugPYSIDE164(unittest.TestCase):
def testBlockingSignal(self):
app = QCoreApplication.instance() or QCoreApplication([])
eventloop = QEventLoop()
emitter = Emitter()
receiver = Receiver(eventloop)
emitter.connect(emitter, SIGNAL("signal(int)"),
receiver.receive, Qt.BlockingQueuedConnection)
emitter.start()
retval = eventloop.exec_()
emitter.wait()
self.assertEqual(retval, 0)
if __name__ == '__main__':
unittest.main()
|
r39132/airflow | refs/heads/master | airflow/www/security.py | 1 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
from flask import g
from flask_appbuilder.security.sqla import models as sqla_models
from flask_appbuilder.security.sqla.manager import SecurityManager
from sqlalchemy import or_
from airflow import models
from airflow.exceptions import AirflowException
from airflow.www.app import appbuilder
from airflow.utils.db import provide_session
from airflow.utils.log.logging_mixin import LoggingMixin
###########################################################################
# VIEW MENUS
###########################################################################
VIEWER_VMS = {
'Airflow',
'DagModelView',
'Browse',
'DAG Runs',
'DagRunModelView',
'Task Instances',
'TaskInstanceModelView',
'SLA Misses',
'SlaMissModelView',
'Jobs',
'JobModelView',
'Logs',
'LogModelView',
'Docs',
'Documentation',
'Github',
'About',
'Version',
'VersionView',
}
USER_VMS = VIEWER_VMS
OP_VMS = {
'Admin',
'Configurations',
'ConfigurationView',
'Connections',
'ConnectionModelView',
'Pools',
'PoolModelView',
'Variables',
'VariableModelView',
'XComs',
'XComModelView',
}
###########################################################################
# PERMISSIONS
###########################################################################
VIEWER_PERMS = {
'menu_access',
'can_index',
'can_list',
'can_show',
'can_chart',
'can_dag_stats',
'can_dag_details',
'can_task_stats',
'can_code',
'can_log',
'can_get_logs_with_metadata',
'can_tries',
'can_graph',
'can_tree',
'can_task',
'can_task_instances',
'can_xcom',
'can_gantt',
'can_landing_times',
'can_duration',
'can_blocked',
'can_rendered',
'can_pickle_info',
'can_version',
}
USER_PERMS = {
'can_dagrun_clear',
'can_run',
'can_trigger',
'can_add',
'can_edit',
'can_delete',
'can_paused',
'can_refresh',
'can_success',
'muldelete',
'set_failed',
'set_running',
'set_success',
'clear',
'can_clear',
}
OP_PERMS = {
'can_conf',
'can_varimport',
}
# global view-menu for dag-level access
DAG_VMS = {
'all_dags'
}
WRITE_DAG_PERMS = {
'can_dag_edit',
}
READ_DAG_PERMS = {
'can_dag_read',
}
DAG_PERMS = WRITE_DAG_PERMS | READ_DAG_PERMS
###########################################################################
# DEFAULT ROLE CONFIGURATIONS
###########################################################################
ROLE_CONFIGS = [
{
'role': 'Viewer',
'perms': VIEWER_PERMS | READ_DAG_PERMS,
'vms': VIEWER_VMS | DAG_VMS
},
{
'role': 'User',
'perms': VIEWER_PERMS | USER_PERMS | DAG_PERMS,
'vms': VIEWER_VMS | DAG_VMS | USER_VMS,
},
{
'role': 'Op',
'perms': VIEWER_PERMS | USER_PERMS | OP_PERMS | DAG_PERMS,
'vms': VIEWER_VMS | DAG_VMS | USER_VMS | OP_VMS,
},
]
EXISTING_ROLES = {
'Admin',
'Viewer',
'User',
'Op',
'Public',
}
class AirflowSecurityManager(SecurityManager, LoggingMixin):
def init_role(self, role_name, role_vms, role_perms):
"""
Initialize the role with the permissions and related view-menus.
:param role_name:
:param role_vms:
:param role_perms:
:return:
"""
pvms = self.get_session.query(sqla_models.PermissionView).all()
pvms = [p for p in pvms if p.permission and p.view_menu]
role = self.find_role(role_name)
if not role:
role = self.add_role(role_name)
if len(role.permissions) == 0:
self.log.info('Initializing permissions for role:%s in the database.', role_name)
role_pvms = set()
for pvm in pvms:
if pvm.view_menu.name in role_vms and pvm.permission.name in role_perms:
role_pvms.add(pvm)
role.permissions = list(role_pvms)
self.get_session.merge(role)
self.get_session.commit()
else:
self.log.debug('Existing permissions for the role:%s '
'within the database will persist.', role_name)
def delete_role(self, role_name):
"""Delete the given Role
:param role_name: the name of a role in the ab_role table
"""
session = self.get_session
role = session.query(sqla_models.Role)\
.filter(sqla_models.Role.name == role_name)\
.first()
if role:
self.log.info("Deleting role '%s'", role_name)
session.delete(role)
session.commit()
else:
raise AirflowException("Role named '{}' does not exist".format(
role_name))
def get_user_roles(self, user=None):
"""
Get all the roles associated with the user.
:param user: the ab_user in FAB model.
:return: a list of roles associated with the user.
"""
if user is None:
user = g.user
if user.is_anonymous:
public_role = appbuilder.config.get('AUTH_ROLE_PUBLIC')
return [appbuilder.security_manager.find_role(public_role)] \
if public_role else []
return user.roles
def get_all_permissions_views(self):
"""
Returns a set of tuples with the perm name and view menu name
"""
perms_views = set()
for role in self.get_user_roles():
perms_views.update({(perm_view.permission.name, perm_view.view_menu.name)
for perm_view in role.permissions})
return perms_views
def get_accessible_dag_ids(self, username=None):
"""
Return a set of dags that user has access to(either read or write).
:param username: Name of the user.
:return: A set of dag ids that the user could access.
"""
if not username:
username = g.user
if username.is_anonymous or 'Public' in username.roles:
# return an empty set if the role is public
return set()
roles = {role.name for role in username.roles}
if {'Admin', 'Viewer', 'User', 'Op'} & roles:
return DAG_VMS
user_perms_views = self.get_all_permissions_views()
# return a set of all dags that the user could access
return set([view for perm, view in user_perms_views if perm in DAG_PERMS])
def has_access(self, permission, view_name, user=None):
"""
Verify whether a given user could perform certain permission
(e.g can_read, can_write) on the given dag_id.
:param permission: permission on dag_id(e.g can_read, can_edit).
:type permission: str
:param view_name: name of view-menu(e.g dag id is a view-menu as well).
:type view_name: str
:param user: user name
:type user: str
:return: a bool whether user could perform certain permission on the dag_id.
:rtype bool
"""
if not user:
user = g.user
if user.is_anonymous:
return self.is_item_public(permission, view_name)
return self._has_view_access(user, permission, view_name)
def _get_and_cache_perms(self):
"""
Cache permissions-views
"""
self.perms = self.get_all_permissions_views()
def _has_role(self, role_name_or_list):
"""
Whether the user has this role name
"""
if not isinstance(role_name_or_list, list):
role_name_or_list = [role_name_or_list]
return any(
[r.name in role_name_or_list for r in self.get_user_roles()])
def _has_perm(self, permission_name, view_menu_name):
"""
Whether the user has this perm
"""
if hasattr(self, 'perms'):
if (permission_name, view_menu_name) in self.perms:
return True
# rebuild the permissions set
self._get_and_cache_perms()
return (permission_name, view_menu_name) in self.perms
def has_all_dags_access(self):
"""
Has all the dag access in any of the 3 cases:
1. Role needs to be in (Admin, Viewer, User, Op).
2. Has can_dag_read permission on all_dags view.
3. Has can_dag_edit permission on all_dags view.
"""
return (
self._has_role(['Admin', 'Viewer', 'Op', 'User']) or
self._has_perm('can_dag_read', 'all_dags') or
self._has_perm('can_dag_edit', 'all_dags'))
def clean_perms(self):
"""
FAB leaves faulty permissions that need to be cleaned up
"""
self.log.debug('Cleaning faulty perms')
sesh = self.get_session
pvms = (
sesh.query(sqla_models.PermissionView)
.filter(or_(
sqla_models.PermissionView.permission == None, # NOQA
sqla_models.PermissionView.view_menu == None, # NOQA
))
)
deleted_count = pvms.delete()
sesh.commit()
if deleted_count:
self.log.info('Deleted %s faulty permissions', deleted_count)
def _merge_perm(self, permission_name, view_menu_name):
"""
Add the new permission , view_menu to ab_permission_view_role if not exists.
It will add the related entry to ab_permission
and ab_view_menu two meta tables as well.
:param permission_name: Name of the permission.
:type permission_name: str
:param view_menu_name: Name of the view-menu
:type view_menu_name: str
:return:
"""
permission = self.find_permission(permission_name)
view_menu = self.find_view_menu(view_menu_name)
pv = None
if permission and view_menu:
pv = self.get_session.query(self.permissionview_model).filter_by(
permission=permission, view_menu=view_menu).first()
if not pv and permission_name and view_menu_name:
self.add_permission_view_menu(permission_name, view_menu_name)
@provide_session
def create_custom_dag_permission_view(self, session=None):
"""
Workflow:
1. Fetch all the existing (permissions, view-menu) from Airflow DB.
2. Fetch all the existing dag models that are either active or paused. Exclude the subdags.
3. Create both read and write permission view-menus relation for every dags from step 2
4. Find out all the dag specific roles(excluded pubic, admin, viewer, op, user)
5. Get all the permission-vm owned by the user role.
6. Grant all the user role's permission-vm except the all-dag view-menus to the dag roles.
7. Commit the updated permission-vm-role into db
:return: None.
"""
self.log.debug('Fetching a set of all permission, view_menu from FAB meta-table')
def merge_pv(perm, view_menu):
"""Create permission view menu only if it doesn't exist"""
if view_menu and perm and (view_menu, perm) not in all_pvs:
self._merge_perm(perm, view_menu)
all_pvs = set()
for pv in self.get_session.query(self.permissionview_model).all():
if pv.permission and pv.view_menu:
all_pvs.add((pv.permission.name, pv.view_menu.name))
# Get all the active / paused dags and insert them into a set
all_dags_models = session.query(models.DagModel)\
.filter(or_(models.DagModel.is_active, models.DagModel.is_paused))\
.filter(~models.DagModel.is_subdag).all()
# create can_dag_edit and can_dag_read permissions for every dag(vm)
for dag in all_dags_models:
for perm in DAG_PERMS:
merge_pv(perm, dag.dag_id)
# for all the dag-level role, add the permission of viewer
# with the dag view to ab_permission_view
all_roles = self.get_all_roles()
user_role = self.find_role('User')
dag_role = [role for role in all_roles if role.name not in EXISTING_ROLES]
update_perm_views = []
# need to remove all_dag vm from all the existing view-menus
dag_vm = self.find_view_menu('all_dags')
ab_perm_view_role = sqla_models.assoc_permissionview_role
perm_view = self.permissionview_model
view_menu = self.viewmenu_model
all_perm_view_by_user = session.query(ab_perm_view_role)\
.join(perm_view, perm_view.id == ab_perm_view_role
.columns.permission_view_id)\
.filter(ab_perm_view_role.columns.role_id == user_role.id)\
.join(view_menu)\
.filter(perm_view.view_menu_id != dag_vm.id)
all_perm_views = set([role.permission_view_id for role in all_perm_view_by_user])
for role in dag_role:
# Get all the perm-view of the role
existing_perm_view_by_user = self.get_session.query(ab_perm_view_role)\
.filter(ab_perm_view_role.columns.role_id == role.id)
existing_perms_views = set([pv.permission_view_id
for pv in existing_perm_view_by_user])
missing_perm_views = all_perm_views - existing_perms_views
for perm_view_id in missing_perm_views:
update_perm_views.append({'permission_view_id': perm_view_id,
'role_id': role.id})
if update_perm_views:
self.get_session.execute(ab_perm_view_role.insert(), update_perm_views)
self.get_session.commit()
def update_admin_perm_view(self):
"""
Admin should have all the permission-views.
Add the missing ones to the table for admin.
:return: None.
"""
pvms = self.get_session.query(sqla_models.PermissionView).all()
pvms = [p for p in pvms if p.permission and p.view_menu]
admin = self.find_role('Admin')
admin.permissions = list(set(admin.permissions) | set(pvms))
self.get_session.commit()
def sync_roles(self):
"""
1. Init the default role(Admin, Viewer, User, Op, public)
with related permissions.
2. Init the custom role(dag-user) with related permissions.
:return: None.
"""
self.log.debug('Start syncing user roles.')
# Create global all-dag VM
self.create_perm_vm_for_all_dag()
# Create default user role.
for config in ROLE_CONFIGS:
role = config['role']
vms = config['vms']
perms = config['perms']
self.init_role(role, vms, perms)
self.create_custom_dag_permission_view()
# init existing roles, the rest role could be created through UI.
self.update_admin_perm_view()
self.clean_perms()
def sync_perm_for_dag(self, dag_id, access_control=None):
"""
Sync permissions for given dag id. The dag id surely exists in our dag bag
as only / refresh button or cli.sync_perm will call this function
:param dag_id: the ID of the DAG whose permissions should be updated
:type dag_id: string
:param access_control: a dict where each key is a rolename and
each value is a set() of permission names (e.g.,
{'can_dag_read'}
:type access_control: dict
:return:
"""
for dag_perm in DAG_PERMS:
perm_on_dag = self.find_permission_view_menu(dag_perm, dag_id)
if perm_on_dag is None:
self.add_permission_view_menu(dag_perm, dag_id)
if access_control:
self._sync_dag_view_permissions(dag_id, access_control)
def _sync_dag_view_permissions(self, dag_id, access_control):
"""Set the access policy on the given DAG's ViewModel.
:param dag_id: the ID of the DAG whose permissions should be updated
:type dag_id: string
:param access_control: a dict where each key is a rolename and
each value is a set() of permission names (e.g.,
{'can_dag_read'}
:type access_control: dict
"""
def _get_or_create_dag_permission(perm_name):
dag_perm = self.find_permission_view_menu(perm_name, dag_id)
if not dag_perm:
self.log.info(
"Creating new permission '%s' on view '%s'",
perm_name, dag_id
)
dag_perm = self.add_permission_view_menu(perm_name, dag_id)
return dag_perm
def _revoke_stale_permissions(dag_view):
existing_dag_perms = self.find_permissions_view_menu(dag_view)
for perm in existing_dag_perms:
non_admin_roles = [role for role in perm.role
if role.name != 'Admin']
for role in non_admin_roles:
target_perms_for_role = access_control.get(role.name, {})
if perm.permission.name not in target_perms_for_role:
self.log.info(
"Revoking '%s' on DAG '%s' for role '%s'",
perm.permission, dag_id, role.name
)
self.del_permission_role(role, perm)
dag_view = self.find_view_menu(dag_id)
if dag_view:
_revoke_stale_permissions(dag_view)
for rolename, perms in access_control.items():
role = self.find_role(rolename)
if not role:
raise AirflowException(
"The access_control mapping for DAG '{}' includes a role "
"named '{}', but that role does not exist".format(
dag_id,
rolename))
perms = set(perms)
invalid_perms = perms - DAG_PERMS
if invalid_perms:
raise AirflowException(
"The access_control map for DAG '{}' includes the following "
"invalid permissions: {}; The set of valid permissions "
"is: {}".format(dag_id,
(perms - DAG_PERMS),
DAG_PERMS))
for perm_name in perms:
dag_perm = _get_or_create_dag_permission(perm_name)
self.add_permission_role(role, dag_perm)
def create_perm_vm_for_all_dag(self):
"""
Create perm-vm if not exist and insert into FAB security model for all-dags.
"""
# create perm for global logical dag
for dag_vm in DAG_VMS:
for perm in DAG_PERMS:
self._merge_perm(permission_name=perm,
view_menu_name=dag_vm)
|
Kagee/youtube-dl | refs/heads/master | youtube_dl/extractor/cmt.py | 139 | from __future__ import unicode_literals
from .mtv import MTVIE
class CMTIE(MTVIE):
IE_NAME = 'cmt.com'
_VALID_URL = r'https?://www\.cmt\.com/videos/.+?/(?P<videoid>[^/]+)\.jhtml'
_FEED_URL = 'http://www.cmt.com/sitewide/apps/player/embed/rss/'
_TESTS = [{
'url': 'http://www.cmt.com/videos/garth-brooks/989124/the-call-featuring-trisha-yearwood.jhtml#artist=30061',
'md5': 'e6b7ef3c4c45bbfae88061799bbba6c2',
'info_dict': {
'id': '989124',
'ext': 'mp4',
'title': 'Garth Brooks - "The Call (featuring Trisha Yearwood)"',
'description': 'Blame It All On My Roots',
},
}]
|
mdworks2016/work_development | refs/heads/master | Python/20_Third_Certification/venv/lib/python3.7/site-packages/django/dispatch/__init__.py | 77 | """Multi-consumer multi-producer dispatching mechanism
Originally based on pydispatch (BSD) https://pypi.org/project/PyDispatcher/2.0.1/
See license.txt for original license.
Heavily modified for Django's purposes.
"""
from django.dispatch.dispatcher import Signal, receiver # NOQA
|
orekyuu/intellij-community | refs/heads/master | python/testData/MockSdk3.4/python_stubs/builtins.py | 15 | # encoding: utf-8
# module builtins
# from (built-in)
# by generator 1.137
"""
Built-in functions, exceptions, and other objects.
Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.
"""
# no imports
# Variables with simple values
# definition of False omitted
# definition of None omitted
# definition of True omitted
# definition of __debug__ omitted
# functions
def abs(*args, **kwargs): # real signature unknown
""" Return the absolute value of the argument. """
pass
def all(*args, **kwargs): # real signature unknown
"""
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty, return True.
"""
pass
def any(*args, **kwargs): # real signature unknown
"""
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty, return False.
"""
pass
def ascii(*args, **kwargs): # real signature unknown
"""
Return an ASCII-only representation of an object.
As repr(), return a string containing a printable representation of an
object, but escape the non-ASCII characters in the string returned by
repr() using \\x, \\u or \\U escapes. This generates a string similar
to that returned by repr() in Python 2.
"""
pass
def bin(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
Return the binary representation of an integer.
>>> bin(2796202)
'0b1010101010101010101010'
"""
pass
def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
"""
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances of classes with a
__call__() method.
"""
pass
def chr(*args, **kwargs): # real signature unknown
""" Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """
pass
def compile(*args, **kwargs): # real signature unknown
"""
Compile source into a code object that can be executed by exec() or eval().
The source code may represent a Python module, statement or expression.
The filename will be used for run-time error messages.
The mode must be 'exec' to compile a module, 'single' to compile a
single (interactive) statement, or 'eval' to compile an expression.
The flags argument, if present, controls which future statements influence
the compilation of the code.
The dont_inherit argument, if true, stops the compilation inheriting
the effects of any future statements in effect in the code calling
compile; if absent or false these statements do influence the compilation,
in addition to any features explicitly specified.
"""
pass
def copyright(*args, **kwargs): # real signature unknown
"""
interactive prompt objects for printing the license text, a list of
contributors and the copyright notice.
"""
pass
def credits(*args, **kwargs): # real signature unknown
"""
interactive prompt objects for printing the license text, a list of
contributors and the copyright notice.
"""
pass
def delattr(x, y): # real signature unknown; restored from __doc__
"""
Deletes the named attribute from the given object.
delattr(x, 'y') is equivalent to ``del x.y''
"""
pass
def dir(p_object=None): # real signature unknown; restored from __doc__
"""
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies a method named __dir__, it will be used; otherwise
the default dir() logic is used and returns:
for a module object: the module's attributes.
for a class object: its attributes, and recursively the attributes
of its bases.
for any other object: its attributes, its class's attributes, and
recursively the attributes of its class's base classes.
"""
return []
def divmod(x, y): # known case of builtins.divmod
""" Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x. """
return (0, 0)
def eval(*args, **kwargs): # real signature unknown
"""
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
"""
pass
def exec(*args, **kwargs): # real signature unknown
"""
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
"""
pass
def exit(*args, **kwargs): # real signature unknown
pass
def format(*args, **kwargs): # real signature unknown
"""
Return value.__format__(format_spec)
format_spec defaults to the empty string
"""
pass
def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass
def globals(*args, **kwargs): # real signature unknown
"""
Return the dictionary containing the current scope's global variables.
NOTE: Updates to this dictionary *will* affect name lookups in the current
global scope and vice-versa.
"""
pass
def hasattr(*args, **kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass
def hash(*args, **kwargs): # real signature unknown
"""
Return the hash value for the given object.
Two objects that compare equal must also have the same hash value, but the
reverse is not necessarily true.
"""
pass
def help(): # real signature unknown; restored from __doc__
"""
Define the builtin 'help'.
This is a wrapper around pydoc.help that provides a helpful message
when 'help' is typed at the Python interactive prompt.
Calling help() at the Python prompt starts an interactive help session.
Calling help(thing) prints help for the python object 'thing'.
"""
pass
def hex(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
Return the hexadecimal representation of an integer.
>>> hex(12648430)
'0xc0ffee'
"""
pass
def id(*args, **kwargs): # real signature unknown
"""
Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects.
(CPython uses the object's memory address.)
"""
pass
def input(*args, **kwargs): # real signature unknown
"""
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
"""
pass
def isinstance(x, A_tuple): # real signature unknown; restored from __doc__
"""
Return whether an object is an instance of a class or of a subclass thereof.
A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
or ...`` etc.
"""
pass
def issubclass(x, A_tuple): # real signature unknown; restored from __doc__
"""
Return whether 'cls' is a derived from another class or is the same class.
A tuple, as in ``issubclass(x, (A, B, ...))``, may be given as the target to
check against. This is equivalent to ``issubclass(x, A) or issubclass(x, B)
or ...`` etc.
"""
pass
def iter(source, sentinel=None): # known special case of iter
"""
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
"""
pass
def len(*args, **kwargs): # real signature unknown
""" Return the number of items in a container. """
pass
def license(*args, **kwargs): # real signature unknown
"""
interactive prompt objects for printing the license text, a list of
contributors and the copyright notice.
"""
pass
def locals(*args, **kwargs): # real signature unknown
"""
Return a dictionary containing the current scope's local variables.
NOTE: Whether or not updates to this dictionary will affect name lookups in
the local scope and vice-versa is *implementation dependent* and not
covered by any backwards compatibility guarantees.
"""
pass
def max(*args, key=None): # known special case of max
"""
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
"""
pass
def min(*args, key=None): # known special case of min
"""
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
"""
pass
def next(iterator, default=None): # real signature unknown; restored from __doc__
"""
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""
pass
def oct(*args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
Return the octal representation of an integer.
>>> oct(342391)
'0o1234567'
"""
pass
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
"""
Open file and return a stream. Raise IOError upon failure.
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode. Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run 'help(codecs.Codec)'
for a list of the permitted encoding error strings.
newline controls how universal newlines works (it only applies to text
mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.
If closefd is False, the underlying file descriptor will be kept open
when the file is closed. This does not work when a file name is given
and must be True in that case.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by
calling *opener* with (*file*, *flags*). *opener* must return an open
file descriptor (passing os.open as *opener* results in functionality
similar to passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
pass
def ord(*args, **kwargs): # real signature unknown
""" Return the Unicode code point for a one-character string. """
pass
def pow(*args, **kwargs): # real signature unknown
"""
Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
"""
pass
def print(*args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
def quit(*args, **kwargs): # real signature unknown
pass
def repr(obj): # real signature unknown; restored from __doc__
"""
Return the canonical string representation of the object.
For many object types, including most builtins, eval(repr(obj)) == obj.
"""
pass
def round(number, ndigits=None): # real signature unknown; restored from __doc__
"""
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits).
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
"""
return 0
def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
pass
def sorted(*args, **kwargs): # real signature unknown
"""
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
"""
pass
def sum(*args, **kwargs): # real signature unknown
"""
Return the sum of a 'start' value (default: 0) plus an iterable of numbers
When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
"""
pass
def vars(p_object=None): # real signature unknown; restored from __doc__
"""
vars([object]) -> dictionary
Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.
"""
return {}
def __build_class__(func, name, *bases, metaclass=None, **kwds): # real signature unknown; restored from __doc__
"""
__build_class__(func, name, *bases, metaclass=None, **kwds) -> class
Internal helper function used by the class statement.
"""
pass
def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__
"""
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.
The globals argument is only used to determine the context;
they are not modified. The locals argument is unused. The fromlist
should be a list of names to emulate ``from name import ...'', or an
empty list to emulate ``import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty. Level is used to determine whether to perform
absolute or relative imports. 0 is absolute while a positive number
is the number of parent directories to search relative to the current module.
"""
pass
# classes
class __generator(object):
'''A mock class representing the generator function type.'''
def __init__(self):
self.gi_code = None
self.gi_frame = None
self.gi_running = 0
def __iter__(self):
'''Defined to support iteration over container.'''
pass
def __next__(self):
'''Return the next item from the container.'''
pass
def close(self):
'''Raises new GeneratorExit exception inside the generator to terminate the iteration.'''
pass
def send(self, value):
'''Resumes the generator and "sends" a value that becomes the result of the current yield-expression.'''
pass
def throw(self, type, value=None, traceback=None):
'''Used to raise an exception inside the generator.'''
pass
class __function(object):
'''A mock class representing function type.'''
def __init__(self):
self.__name__ = ''
self.__doc__ = ''
self.__dict__ = ''
self.__module__ = ''
self.__defaults__ = {}
self.__globals__ = {}
self.__closure__ = None
self.__code__ = None
self.__name__ = ''
self.__annotations__ = {}
self.__kwdefaults__ = {}
self.__qualname__ = ''
class __method(object):
'''A mock class representing method type.'''
def __init__(self):
self.__func__ = None
self.__self__ = None
class __coroutine(object):
'''A mock class representing coroutine type.'''
def __init__(self):
self.__name__ = ''
self.__qualname__ = ''
self.cr_await = None
self.cr_frame = None
self.cr_running = False
self.cr_code = None
def __await__(self):
return []
def __iter__(self):
return []
def close(self):
pass
def send(self, value):
pass
def throw(self, type, value=None, traceback=None):
pass
class __namedtuple(tuple):
'''A mock base class for named tuples.'''
__slots__ = ()
_fields = ()
def __new__(cls, *args, **kwargs):
'Create a new instance of the named tuple.'
return tuple.__new__(cls, *args)
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new named tuple object from a sequence or iterable.'
return new(cls, iterable)
def __repr__(self):
return ''
def _asdict(self):
'Return a new dict which maps field types to their values.'
return {}
def _replace(self, **kwargs):
'Return a new named tuple object replacing specified fields with new values.'
return self
def __getnewargs__(self):
return tuple(self)
class object:
""" The most base type """
def __delattr__(self, *args, **kwargs): # real signature unknown
""" Implement delattr(self, name). """
pass
def __dir__(self): # real signature unknown; restored from __doc__
"""
__dir__() -> list
default dir() implementation
"""
return []
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __format__(self, *args, **kwargs): # real signature unknown
""" default object formatter """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self): # known special case of object.__init__
""" Initialize self. See help(type(self)) for accurate signature. """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(cls, *more): # known special case of object.__new__
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce_ex__(self, *args, **kwargs): # real signature unknown
""" helper for pickle """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" helper for pickle """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setattr__(self, *args, **kwargs): # real signature unknown
""" Implement setattr(self, name, value). """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
"""
__sizeof__() -> int
size of object in memory, in bytes
"""
return 0
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
@classmethod # known case
def __subclasshook__(cls, subclass): # known special case of object.__subclasshook__
"""
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__().
It should return True, False or NotImplemented. If it returns
NotImplemented, the normal algorithm is used. Otherwise, it
overrides the normal algorithm (and the outcome is cached).
"""
pass
__class__ = None # (!) forward: type, real value is ''
__dict__ = {}
__doc__ = ''
__module__ = ''
class BaseException(object):
""" Common base class for all exceptions """
def with_traceback(self, tb): # real signature unknown; restored from __doc__
"""
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.
"""
pass
def __delattr__(self, *args, **kwargs): # real signature unknown
""" Implement delattr(self, name). """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setattr__(self, *args, **kwargs): # real signature unknown
""" Implement setattr(self, name, value). """
pass
def __setstate__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
args = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__cause__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception cause"""
__context__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception context"""
__suppress_context__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__traceback__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__dict__ = None # (!) real value is ''
class Exception(BaseException):
""" Common base class for all non-exit exceptions. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class ArithmeticError(Exception):
""" Base class for arithmetic errors. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class AssertionError(Exception):
""" Assertion failed. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class AttributeError(Exception):
""" Attribute not found. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class OSError(Exception):
""" Base class for I/O related errors. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
characters_written = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
errno = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""POSIX exception code"""
filename = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception filename"""
filename2 = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""second exception filename"""
strerror = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception strerror"""
IOError = OSError
EnvironmentError = OSError
class BlockingIOError(OSError):
""" I/O operation would block. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class int(object):
"""
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
"""
def bit_length(self): # real signature unknown; restored from __doc__
"""
int.bit_length() -> int
Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
"""
return 0
def conjugate(self, *args, **kwargs): # real signature unknown
""" Returns self, the complex conjugate of any int. """
pass
@classmethod # known case
def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
int.from_bytes(bytes, byteorder, *, signed=False) -> int
Return the integer represented by the given array of bytes.
The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument indicates whether two's complement is
used to represent the integer.
"""
pass
def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
int.to_bytes(length, byteorder, *, signed=False) -> bytes
Return an array of bytes representing an integer.
The integer is represented using length bytes. An OverflowError is
raised if the integer is not representable with the given number of
bytes.
The byteorder argument determines the byte order used to represent the
integer. If byteorder is 'big', the most significant byte is at the
beginning of the byte array. If byteorder is 'little', the most
significant byte is at the end of the byte array. To request the native
byte order of the host system, use `sys.byteorder' as the byte order value.
The signed keyword-only argument determines whether two's complement is
used to represent the integer. If signed is False and a negative integer
is given, an OverflowError is raised.
"""
pass
def __abs__(self, *args, **kwargs): # real signature unknown
""" abs(self) """
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass
def __bool__(self, *args, **kwargs): # real signature unknown
""" self != 0 """
pass
def __ceil__(self, *args, **kwargs): # real signature unknown
""" Ceiling of an Integral returns itself. """
pass
def __divmod__(self, *args, **kwargs): # real signature unknown
""" Return divmod(self, value). """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __float__(self, *args, **kwargs): # real signature unknown
""" float(self) """
pass
def __floordiv__(self, *args, **kwargs): # real signature unknown
""" Return self//value. """
pass
def __floor__(self, *args, **kwargs): # real signature unknown
""" Flooring an Integral returns itself. """
pass
def __format__(self, *args, **kwargs): # real signature unknown
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __index__(self, *args, **kwargs): # real signature unknown
""" Return self converted to an integer, if self is suitable for use as an index into a list. """
pass
def __init__(self, x, base=10): # known special case of int.__init__
"""
int(x=0) -> integer
int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments
are given. If x is a number, return x.__int__(). For floating point
numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
# (copied from class doc)
"""
pass
def __int__(self, *args, **kwargs): # real signature unknown
""" int(self) """
pass
def __invert__(self, *args, **kwargs): # real signature unknown
""" ~self """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lshift__(self, *args, **kwargs): # real signature unknown
""" Return self<<value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __neg__(self, *args, **kwargs): # real signature unknown
""" -self """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass
def __pos__(self, *args, **kwargs): # real signature unknown
""" +self """
pass
def __pow__(self, *args, **kwargs): # real signature unknown
""" Return pow(self, value, mod). """
pass
def __radd__(self, *args, **kwargs): # real signature unknown
""" Return value+self. """
pass
def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass
def __rdivmod__(self, *args, **kwargs): # real signature unknown
""" Return divmod(value, self). """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __rfloordiv__(self, *args, **kwargs): # real signature unknown
""" Return value//self. """
pass
def __rlshift__(self, *args, **kwargs): # real signature unknown
""" Return value<<self. """
pass
def __rmod__(self, *args, **kwargs): # real signature unknown
""" Return value%self. """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return value*self. """
pass
def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass
def __round__(self, *args, **kwargs): # real signature unknown
"""
Rounding an Integral returns itself.
Rounding with an ndigits argument also returns an integer.
"""
pass
def __rpow__(self, *args, **kwargs): # real signature unknown
""" Return pow(value, self, mod). """
pass
def __rrshift__(self, *args, **kwargs): # real signature unknown
""" Return value>>self. """
pass
def __rshift__(self, *args, **kwargs): # real signature unknown
""" Return self>>value. """
pass
def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass
def __rtruediv__(self, *args, **kwargs): # real signature unknown
""" Return value/self. """
pass
def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Returns size in memory, in bytes """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass
def __truediv__(self, *args, **kwargs): # real signature unknown
""" Return self/value. """
pass
def __trunc__(self, *args, **kwargs): # real signature unknown
""" Truncating an Integral returns itself. """
pass
def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass
denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the denominator of a rational number in lowest terms"""
imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the imaginary part of a complex number"""
numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the numerator of a rational number in lowest terms"""
real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the real part of a complex number"""
class bool(int):
"""
bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
"""
def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass
def __init__(self, x): # real signature unknown; restored from __doc__
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass
def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass
def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass
class ConnectionError(OSError):
""" Connection error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class BrokenPipeError(ConnectionError):
""" Broken pipe. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class BufferError(Exception):
""" Buffer error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class bytearray(object):
"""
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array
Construct an mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
"""
def append(self, *args, **kwargs): # real signature unknown
"""
Append a single item to the end of the bytearray.
item
The item to be appended.
"""
pass
def capitalize(self): # real signature unknown; restored from __doc__
"""
B.capitalize() -> copy of B
Return a copy of B with only its first character capitalized (ASCII)
and the rest lower-cased.
"""
pass
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.center(width[, fillchar]) -> copy of B
Return B centered in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
pass
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all items from the bytearray. """
pass
def copy(self, *args, **kwargs): # real signature unknown
""" Return a copy of B. """
pass
def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of subsection sub in
bytes B[start:end]. Optional arguments start and end are interpreted
as in slice notation.
"""
return 0
def decode(self, *args, **kwargs): # real signature unknown
"""
Decode the bytearray using the codec registered for encoding.
encoding
The encoding with which to decode the bytearray.
errors
The error handling scheme to use for the handling of decoding errors.
The default is 'strict' meaning that decoding errors raise a
UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that
can handle UnicodeDecodeErrors.
"""
pass
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.endswith(suffix[, start[, end]]) -> bool
Return True if B ends with the specified suffix, False otherwise.
With optional start, test B beginning at that position.
With optional end, stop comparing B at that position.
suffix can also be a tuple of bytes to try.
"""
return False
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
"""
B.expandtabs(tabsize=8) -> copy of B
Return a copy of B where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
pass
def extend(self, *args, **kwargs): # real signature unknown
"""
Append all the items from the iterator or sequence to the end of the bytearray.
iterable_of_ints
The iterable of items to append.
"""
pass
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.find(sub[, start[, end]]) -> int
Return the lowest index in B where subsection sub is found,
such that sub is contained within B[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return 0
@classmethod # known case
def fromhex(cls, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
Create a bytearray object from a string of hexadecimal numbers.
Spaces between two numbers are accepted.
Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef')
"""
pass
def hex(self): # real signature unknown; restored from __doc__
"""
B.hex() -> string
Create a string of hexadecimal numbers from a bytearray object.
Example: bytearray([0xb9, 0x01, 0xef]).hex() -> 'b901ef'.
"""
return ""
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.index(sub[, start[, end]]) -> int
Like B.find() but raise ValueError when the subsection is not found.
"""
return 0
def insert(self, *args, **kwargs): # real signature unknown
"""
Insert a single item into the bytearray before the given index.
index
The index where the value is to be inserted.
item
The item to be inserted.
"""
pass
def isalnum(self): # real signature unknown; restored from __doc__
"""
B.isalnum() -> bool
Return True if all characters in B are alphanumeric
and there is at least one character in B, False otherwise.
"""
return False
def isalpha(self): # real signature unknown; restored from __doc__
"""
B.isalpha() -> bool
Return True if all characters in B are alphabetic
and there is at least one character in B, False otherwise.
"""
return False
def isdigit(self): # real signature unknown; restored from __doc__
"""
B.isdigit() -> bool
Return True if all characters in B are digits
and there is at least one character in B, False otherwise.
"""
return False
def islower(self): # real signature unknown; restored from __doc__
"""
B.islower() -> bool
Return True if all cased characters in B are lowercase and there is
at least one cased character in B, False otherwise.
"""
return False
def isspace(self): # real signature unknown; restored from __doc__
"""
B.isspace() -> bool
Return True if all characters in B are whitespace
and there is at least one character in B, False otherwise.
"""
return False
def istitle(self): # real signature unknown; restored from __doc__
"""
B.istitle() -> bool
Return True if B is a titlecased string and there is at least one
character in B, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
"""
return False
def isupper(self): # real signature unknown; restored from __doc__
"""
B.isupper() -> bool
Return True if all cased characters in B are uppercase and there is
at least one cased character in B, False otherwise.
"""
return False
def join(self, *args, **kwargs): # real signature unknown
"""
Concatenate any number of bytes/bytearray objects.
The bytearray whose method is called is inserted in between each pair.
The result is returned as a new bytearray object.
"""
pass
def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.ljust(width[, fillchar]) -> copy of B
Return B left justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
pass
def lower(self): # real signature unknown; restored from __doc__
"""
B.lower() -> copy of B
Return a copy of B with all ASCII characters converted to lowercase.
"""
pass
def lstrip(self, *args, **kwargs): # real signature unknown
"""
Strip leading bytes contained in the argument.
If the argument is omitted or None, strip leading ASCII whitespace.
"""
pass
@staticmethod # known case
def maketrans(*args, **kwargs): # real signature unknown
"""
Return a translation table useable for the bytes or bytearray translate method.
The returned table will be one where each byte in frm is mapped to the byte at
the same position in to.
The bytes objects frm and to must be of the same length.
"""
pass
def partition(self, *args, **kwargs): # real signature unknown
"""
Partition the bytearray into three parts using the given separator.
This will search for the separator sep in the bytearray. If the separator is
found, returns a 3-tuple containing the part before the separator, the
separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original
bytearray object and two empty bytearray objects.
"""
pass
def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return a single item from B.
index
The index from where to remove the item.
-1 (the default value) means remove the last item.
If no index argument is given, will pop the last item.
"""
pass
def remove(self, *args, **kwargs): # real signature unknown
"""
Remove the first occurrence of a value in the bytearray.
value
The value to remove.
"""
pass
def replace(self, *args, **kwargs): # real signature unknown
"""
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
"""
pass
def reverse(self, *args, **kwargs): # real signature unknown
""" Reverse the order of the values in B in place. """
pass
def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.rfind(sub[, start[, end]]) -> int
Return the highest index in B where subsection sub is found,
such that sub is contained within B[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return 0
def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.rindex(sub[, start[, end]]) -> int
Like B.rfind() but raise ValueError when the subsection is not found.
"""
return 0
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.rjust(width[, fillchar]) -> copy of B
Return B right justified in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
pass
def rpartition(self, *args, **kwargs): # real signature unknown
"""
Partition the bytes into three parts using the given separator.
This will search for the separator sep in the bytearray, starting and the end.
If the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty bytearray
objects and the original bytearray object.
"""
pass
def rsplit(self, *args, **kwargs): # real signature unknown
"""
Return a list of the sections in the bytearray, using sep as the delimiter.
sep
The delimiter according which to split the bytearray.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
Splitting is done starting at the end of the bytearray and working to the front.
"""
pass
def rstrip(self, *args, **kwargs): # real signature unknown
"""
Strip trailing bytes contained in the argument.
If the argument is omitted or None, strip trailing ASCII whitespace.
"""
pass
def split(self, *args, **kwargs): # real signature unknown
"""
Return a list of the sections in the bytearray, using sep as the delimiter.
sep
The delimiter according which to split the bytearray.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
"""
pass
def splitlines(self, *args, **kwargs): # real signature unknown
"""
Return a list of the lines in the bytearray, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and
true.
"""
pass
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.startswith(prefix[, start[, end]]) -> bool
Return True if B starts with the specified prefix, False otherwise.
With optional start, test B beginning at that position.
With optional end, stop comparing B at that position.
prefix can also be a tuple of bytes to try.
"""
return False
def strip(self, *args, **kwargs): # real signature unknown
"""
Strip leading and trailing bytes contained in the argument.
If the argument is omitted or None, strip leading and trailing ASCII whitespace.
"""
pass
def swapcase(self): # real signature unknown; restored from __doc__
"""
B.swapcase() -> copy of B
Return a copy of B with uppercase ASCII characters converted
to lowercase ASCII and vice versa.
"""
pass
def title(self): # real signature unknown; restored from __doc__
"""
B.title() -> copy of B
Return a titlecased version of B, i.e. ASCII words start with uppercase
characters, all remaining cased characters have lowercase.
"""
pass
def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__
"""
translate(table, [deletechars])
Return a copy with each character mapped by the given translation table.
table
Translation table, which must be a bytes object of length 256.
All characters occurring in the optional argument deletechars are removed.
The remaining characters are mapped through the given translation table.
"""
pass
def upper(self): # real signature unknown; restored from __doc__
"""
B.upper() -> copy of B
Return a copy of B with all ASCII characters converted to uppercase.
"""
pass
def zfill(self, width): # real signature unknown; restored from __doc__
"""
B.zfill(width) -> copy of B
Pad a numeric string B with zeros on the left, to fill a field
of the specified width. B is never truncated.
"""
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __alloc__(self): # real signature unknown; restored from __doc__
"""
B.__alloc__() -> int
Return the number of bytes actually allocated.
"""
return 0
def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __iadd__(self, *args, **kwargs): # real signature unknown
""" Implement self+=value. """
pass
def __imul__(self, *args, **kwargs): # real signature unknown
""" Implement self*=value. """
pass
def __init__(self, source=None, encoding=None, errors='strict'): # known special case of bytearray.__init__
"""
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array
Construct an mutable bytearray object from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- a bytes or a buffer object
- any object implementing the buffer API.
- an integer
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce_ex__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __rmod__(self, *args, **kwargs): # real signature unknown
""" Return value%self. """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass
def __sizeof__(self, *args, **kwargs): # real signature unknown
""" Returns the size of the bytearray object in memory, in bytes. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
__hash__ = None
class bytes(object):
"""
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
"""
def capitalize(self): # real signature unknown; restored from __doc__
"""
B.capitalize() -> copy of B
Return a copy of B with only its first character capitalized (ASCII)
and the rest lower-cased.
"""
pass
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.center(width[, fillchar]) -> copy of B
Return B centered in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
pass
def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string B[start:end]. Optional arguments start and end are interpreted
as in slice notation.
"""
return 0
def decode(self, *args, **kwargs): # real signature unknown
"""
Decode the bytes using the codec registered for encoding.
encoding
The encoding with which to decode the bytes.
errors
The error handling scheme to use for the handling of decoding errors.
The default is 'strict' meaning that decoding errors raise a
UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
as well as any other name registered with codecs.register_error that
can handle UnicodeDecodeErrors.
"""
pass
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.endswith(suffix[, start[, end]]) -> bool
Return True if B ends with the specified suffix, False otherwise.
With optional start, test B beginning at that position.
With optional end, stop comparing B at that position.
suffix can also be a tuple of bytes to try.
"""
return False
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
"""
B.expandtabs(tabsize=8) -> copy of B
Return a copy of B where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
pass
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.find(sub[, start[, end]]) -> int
Return the lowest index in B where substring sub is found,
such that sub is contained within B[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return 0
@classmethod # known case
def fromhex(cls, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
Create a bytes object from a string of hexadecimal numbers.
Spaces between two numbers are accepted.
Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
"""
pass
def hex(self): # real signature unknown; restored from __doc__
"""
B.hex() -> string
Create a string of hexadecimal numbers from a bytes object.
Example: b'\xb9\x01\xef'.hex() -> 'b901ef'.
"""
return ""
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.index(sub[, start[, end]]) -> int
Like B.find() but raise ValueError when the substring is not found.
"""
return 0
def isalnum(self): # real signature unknown; restored from __doc__
"""
B.isalnum() -> bool
Return True if all characters in B are alphanumeric
and there is at least one character in B, False otherwise.
"""
return False
def isalpha(self): # real signature unknown; restored from __doc__
"""
B.isalpha() -> bool
Return True if all characters in B are alphabetic
and there is at least one character in B, False otherwise.
"""
return False
def isdigit(self): # real signature unknown; restored from __doc__
"""
B.isdigit() -> bool
Return True if all characters in B are digits
and there is at least one character in B, False otherwise.
"""
return False
def islower(self): # real signature unknown; restored from __doc__
"""
B.islower() -> bool
Return True if all cased characters in B are lowercase and there is
at least one cased character in B, False otherwise.
"""
return False
def isspace(self): # real signature unknown; restored from __doc__
"""
B.isspace() -> bool
Return True if all characters in B are whitespace
and there is at least one character in B, False otherwise.
"""
return False
def istitle(self): # real signature unknown; restored from __doc__
"""
B.istitle() -> bool
Return True if B is a titlecased string and there is at least one
character in B, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise.
"""
return False
def isupper(self): # real signature unknown; restored from __doc__
"""
B.isupper() -> bool
Return True if all cased characters in B are uppercase and there is
at least one cased character in B, False otherwise.
"""
return False
def join(self, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
"""
Concatenate any number of bytes objects.
The bytes whose method is called is inserted in between each pair.
The result is returned as a new bytes object.
Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
"""
pass
def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.ljust(width[, fillchar]) -> copy of B
Return B left justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
pass
def lower(self): # real signature unknown; restored from __doc__
"""
B.lower() -> copy of B
Return a copy of B with all ASCII characters converted to lowercase.
"""
pass
def lstrip(self, *args, **kwargs): # real signature unknown
"""
Strip leading bytes contained in the argument.
If the argument is omitted or None, strip leading ASCII whitespace.
"""
pass
@staticmethod # known case
def maketrans(*args, **kwargs): # real signature unknown
"""
Return a translation table useable for the bytes or bytearray translate method.
The returned table will be one where each byte in frm is mapped to the byte at
the same position in to.
The bytes objects frm and to must be of the same length.
"""
pass
def partition(self, *args, **kwargs): # real signature unknown
"""
Partition the bytes into three parts using the given separator.
This will search for the separator sep in the bytes. If the separator is found,
returns a 3-tuple containing the part before the separator, the separator
itself, and the part after it.
If the separator is not found, returns a 3-tuple containing the original bytes
object and two empty bytes objects.
"""
pass
def replace(self, *args, **kwargs): # real signature unknown
"""
Return a copy with all occurrences of substring old replaced by new.
count
Maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
If the optional argument count is given, only the first count occurrences are
replaced.
"""
pass
def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.rfind(sub[, start[, end]]) -> int
Return the highest index in B where substring sub is found,
such that sub is contained within B[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return 0
def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.rindex(sub[, start[, end]]) -> int
Like B.rfind() but raise ValueError when the substring is not found.
"""
return 0
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
B.rjust(width[, fillchar]) -> copy of B
Return B right justified in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
pass
def rpartition(self, *args, **kwargs): # real signature unknown
"""
Partition the bytes into three parts using the given separator.
This will search for the separator sep in the bytes, starting and the end. If
the separator is found, returns a 3-tuple containing the part before the
separator, the separator itself, and the part after it.
If the separator is not found, returns a 3-tuple containing two empty bytes
objects and the original bytes object.
"""
pass
def rsplit(self, *args, **kwargs): # real signature unknown
"""
Return a list of the sections in the bytes, using sep as the delimiter.
sep
The delimiter according which to split the bytes.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
Splitting is done starting at the end of the bytes and working to the front.
"""
pass
def rstrip(self, *args, **kwargs): # real signature unknown
"""
Strip trailing bytes contained in the argument.
If the argument is omitted or None, strip trailing ASCII whitespace.
"""
pass
def split(self, *args, **kwargs): # real signature unknown
"""
Return a list of the sections in the bytes, using sep as the delimiter.
sep
The delimiter according which to split the bytes.
None (the default value) means split on ASCII whitespace characters
(space, tab, return, newline, formfeed, vertical tab).
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.
"""
pass
def splitlines(self, *args, **kwargs): # real signature unknown
"""
Return a list of the lines in the bytes, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends is given and
true.
"""
pass
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
"""
B.startswith(prefix[, start[, end]]) -> bool
Return True if B starts with the specified prefix, False otherwise.
With optional start, test B beginning at that position.
With optional end, stop comparing B at that position.
prefix can also be a tuple of bytes to try.
"""
return False
def strip(self, *args, **kwargs): # real signature unknown
"""
Strip leading and trailing bytes contained in the argument.
If the argument is omitted or None, strip leading and trailing ASCII whitespace.
"""
pass
def swapcase(self): # real signature unknown; restored from __doc__
"""
B.swapcase() -> copy of B
Return a copy of B with uppercase ASCII characters converted
to lowercase ASCII and vice versa.
"""
pass
def title(self): # real signature unknown; restored from __doc__
"""
B.title() -> copy of B
Return a titlecased version of B, i.e. ASCII words start with uppercase
characters, all remaining cased characters have lowercase.
"""
pass
def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__
"""
translate(table, [deletechars])
Return a copy with each character mapped by the given translation table.
table
Translation table, which must be a bytes object of length 256.
All characters occurring in the optional argument deletechars are removed.
The remaining characters are mapped through the given translation table.
"""
pass
def upper(self): # real signature unknown; restored from __doc__
"""
B.upper() -> copy of B
Return a copy of B with all ASCII characters converted to uppercase.
"""
pass
def zfill(self, width): # real signature unknown; restored from __doc__
"""
B.zfill(width) -> copy of B
Pad a numeric string B with zeros on the left, to fill a field
of the specified width. B is never truncated.
"""
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, value=b'', encoding=None, errors='strict'): # known special case of bytes.__init__
"""
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object
Construct an immutable array of bytes from:
- an iterable yielding integers in range(256)
- a text string encoded using the specified encoding
- any object implementing the buffer API.
- an integer
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __rmod__(self, *args, **kwargs): # real signature unknown
""" Return value%self. """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
class Warning(Exception):
""" Base class for warning categories. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class BytesWarning(Warning):
"""
Base class for warnings about bytes and buffer related problems, mostly
related to conversion from str or comparing to str.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class ChildProcessError(OSError):
""" Child process error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class classmethod(object):
"""
classmethod(function) -> method
Convert a function to be a class method.
A class method receives the class as implicit first argument,
just like an instance method receives the instance.
To declare a class method, use this idiom:
class C:
def f(cls, arg1, arg2, ...): ...
f = classmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()). The instance is ignored except for its class.
If a class method is called for a derived class, the derived class
object is passed as the implied first argument.
Class methods are different than C++ or Java static methods.
If you want those, see the staticmethod builtin.
"""
def __get__(self, *args, **kwargs): # real signature unknown
""" Return an attribute of instance, which is of type owner. """
pass
def __init__(self, function): # real signature unknown; restored from __doc__
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
__func__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__isabstractmethod__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__dict__ = None # (!) real value is ''
class complex(object):
"""
complex(real[, imag]) -> complex number
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.
"""
def conjugate(self): # real signature unknown; restored from __doc__
"""
complex.conjugate() -> complex
Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.
"""
return complex
def __abs__(self, *args, **kwargs): # real signature unknown
""" abs(self) """
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __bool__(self, *args, **kwargs): # real signature unknown
""" self != 0 """
pass
def __divmod__(self, *args, **kwargs): # real signature unknown
""" Return divmod(self, value). """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __float__(self, *args, **kwargs): # real signature unknown
""" float(self) """
pass
def __floordiv__(self, *args, **kwargs): # real signature unknown
""" Return self//value. """
pass
def __format__(self): # real signature unknown; restored from __doc__
"""
complex.__format__() -> str
Convert to a string according to format_spec.
"""
return ""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, real, imag=None): # real signature unknown; restored from __doc__
pass
def __int__(self, *args, **kwargs): # real signature unknown
""" int(self) """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __neg__(self, *args, **kwargs): # real signature unknown
""" -self """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __pos__(self, *args, **kwargs): # real signature unknown
""" +self """
pass
def __pow__(self, *args, **kwargs): # real signature unknown
""" Return pow(self, value, mod). """
pass
def __radd__(self, *args, **kwargs): # real signature unknown
""" Return value+self. """
pass
def __rdivmod__(self, *args, **kwargs): # real signature unknown
""" Return divmod(value, self). """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __rfloordiv__(self, *args, **kwargs): # real signature unknown
""" Return value//self. """
pass
def __rmod__(self, *args, **kwargs): # real signature unknown
""" Return value%self. """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return value*self. """
pass
def __rpow__(self, *args, **kwargs): # real signature unknown
""" Return pow(value, self, mod). """
pass
def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass
def __rtruediv__(self, *args, **kwargs): # real signature unknown
""" Return value/self. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass
def __truediv__(self, *args, **kwargs): # real signature unknown
""" Return self/value. """
pass
imag = property(lambda self: 0.0)
"""the imaginary part of a complex number
:type: float
"""
real = property(lambda self: 0.0)
"""the real part of a complex number
:type: float
"""
class ConnectionAbortedError(ConnectionError):
""" Connection aborted. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class ConnectionRefusedError(ConnectionError):
""" Connection refused. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class ConnectionResetError(ConnectionError):
""" Connection reset. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class DeprecationWarning(Warning):
""" Base class for warnings about deprecated features. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class dict(object):
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
"""
def clear(self): # real signature unknown; restored from __doc__
""" D.clear() -> None. Remove all items from D. """
pass
def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D """
pass
@staticmethod # known case
def fromkeys(*args, **kwargs): # real signature unknown
""" Returns a new dict with keys from iterable and values equal to value. """
pass
def get(self, k, d=None): # real signature unknown; restored from __doc__
""" D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """
pass
def items(self): # real signature unknown; restored from __doc__
""" D.items() -> a set-like object providing a view on D's items """
pass
def keys(self): # real signature unknown; restored from __doc__
""" D.keys() -> a set-like object providing a view on D's keys """
pass
def pop(self, k, d=None): # real signature unknown; restored from __doc__
"""
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised
"""
pass
def popitem(self): # real signature unknown; restored from __doc__
"""
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
"""
pass
def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
""" D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
pass
def update(self, E=None, **F): # known special case of dict.update
"""
D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
"""
pass
def values(self): # real signature unknown; restored from __doc__
""" D.values() -> an object providing a view on D's values """
pass
def __contains__(self, *args, **kwargs): # real signature unknown
""" True if D has a key k, else False. """
pass
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
"""
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -> size of D in memory, in bytes """
pass
__hash__ = None
class enumerate(object):
"""
enumerate(iterable[, start]) -> iterator for index, value of iterable
Return an enumerate object. iterable must be another object that supports
iteration. The enumerate object yields pairs containing a count (from
start, which defaults to zero) and a value yielded by the iterable argument.
enumerate is useful for obtaining an indexed list:
(0, seq[0]), (1, seq[1]), (2, seq[2]), ...
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, iterable, start=0): # known special case of enumerate.__init__
""" Initialize self. See help(type(self)) for accurate signature. """
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
class EOFError(Exception):
""" Read beyond end of file. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class FileExistsError(OSError):
""" File already exists. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class FileNotFoundError(OSError):
""" File not found. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class filter(object):
"""
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, function_or_None, iterable): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
class float(object):
"""
float(x) -> floating point number
Convert a string or number to a floating point number, if possible.
"""
def as_integer_ratio(self): # real signature unknown; restored from __doc__
"""
float.as_integer_ratio() -> (int, int)
Return a pair of integers, whose ratio is exactly equal to the original
float and with a positive denominator.
Raise OverflowError on infinities and a ValueError on NaNs.
>>> (10.0).as_integer_ratio()
(10, 1)
>>> (0.0).as_integer_ratio()
(0, 1)
>>> (-.25).as_integer_ratio()
(-1, 4)
"""
pass
def conjugate(self, *args, **kwargs): # real signature unknown
""" Return self, the complex conjugate of any float. """
pass
def fromhex(self, string): # real signature unknown; restored from __doc__
"""
float.fromhex(string) -> float
Create a floating-point number from a hexadecimal string.
>>> float.fromhex('0x1.ffffp10')
2047.984375
>>> float.fromhex('-0x1p-1074')
-5e-324
"""
return 0.0
def hex(self): # real signature unknown; restored from __doc__
"""
float.hex() -> string
Return a hexadecimal representation of a floating-point number.
>>> (-0.1).hex()
'-0x1.999999999999ap-4'
>>> 3.14159.hex()
'0x1.921f9f01b866ep+1'
"""
return ""
def is_integer(self, *args, **kwargs): # real signature unknown
""" Return True if the float is an integer. """
pass
def __abs__(self, *args, **kwargs): # real signature unknown
""" abs(self) """
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __bool__(self, *args, **kwargs): # real signature unknown
""" self != 0 """
pass
def __divmod__(self, *args, **kwargs): # real signature unknown
""" Return divmod(self, value). """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __float__(self, *args, **kwargs): # real signature unknown
""" float(self) """
pass
def __floordiv__(self, *args, **kwargs): # real signature unknown
""" Return self//value. """
pass
def __format__(self, format_spec): # real signature unknown; restored from __doc__
"""
float.__format__(format_spec) -> string
Formats the float according to format_spec.
"""
return ""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getformat__(self, typestr): # real signature unknown; restored from __doc__
"""
float.__getformat__(typestr) -> string
You probably don't want to use this function. It exists mainly to be
used in Python's test suite.
typestr must be 'double' or 'float'. This function returns whichever of
'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the
format of floating point numbers used by the C type named by typestr.
"""
return ""
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, x): # real signature unknown; restored from __doc__
pass
def __int__(self, *args, **kwargs): # real signature unknown
""" int(self) """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __neg__(self, *args, **kwargs): # real signature unknown
""" -self """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __pos__(self, *args, **kwargs): # real signature unknown
""" +self """
pass
def __pow__(self, *args, **kwargs): # real signature unknown
""" Return pow(self, value, mod). """
pass
def __radd__(self, *args, **kwargs): # real signature unknown
""" Return value+self. """
pass
def __rdivmod__(self, *args, **kwargs): # real signature unknown
""" Return divmod(value, self). """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __rfloordiv__(self, *args, **kwargs): # real signature unknown
""" Return value//self. """
pass
def __rmod__(self, *args, **kwargs): # real signature unknown
""" Return value%self. """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return value*self. """
pass
def __round__(self, *args, **kwargs): # real signature unknown
"""
Return the Integral closest to x, rounding half toward even.
When an argument is passed, work like built-in round(x, ndigits).
"""
pass
def __rpow__(self, *args, **kwargs): # real signature unknown
""" Return pow(value, self, mod). """
pass
def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass
def __rtruediv__(self, *args, **kwargs): # real signature unknown
""" Return value/self. """
pass
def __setformat__(self, typestr, fmt): # real signature unknown; restored from __doc__
"""
float.__setformat__(typestr, fmt) -> None
You probably don't want to use this function. It exists mainly to be
used in Python's test suite.
typestr must be 'double' or 'float'. fmt must be one of 'unknown',
'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
one of the latter two if it appears to match the underlying C reality.
Override the automatic determination of C-level floating point type.
This affects how floats are converted to and from binary strings.
"""
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass
def __truediv__(self, *args, **kwargs): # real signature unknown
""" Return self/value. """
pass
def __trunc__(self, *args, **kwargs): # real signature unknown
""" Return the Integral closest to x between 0 and x. """
pass
imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the imaginary part of a complex number"""
real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""the real part of a complex number"""
class FloatingPointError(ArithmeticError):
""" Floating point operation failed. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class frozenset(object):
"""
frozenset() -> empty frozenset object
frozenset(iterable) -> frozenset object
Build an immutable unordered collection of unique elements.
"""
def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
pass
def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
"""
pass
def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
"""
pass
def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. """
pass
def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. """
pass
def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. """
pass
def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
"""
pass
def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set.
(i.e. all elements that are in either set.)
"""
pass
def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, seq=()): # known special case of frozenset.__init__
""" Initialize self. See help(type(self)) for accurate signature. """
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass
def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass
def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass
def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass
def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass
def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass
class FutureWarning(Warning):
"""
Base class for warnings about constructs that will change semantically
in the future.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class GeneratorExit(BaseException):
""" Request that a generator exit. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class ImportError(Exception):
""" Import can't find module, or can't find name in module. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
msg = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception message"""
name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""module name"""
path = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""module path"""
class ImportWarning(Warning):
""" Base class for warnings about probable mistakes in module imports """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class SyntaxError(Exception):
""" Invalid syntax. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
filename = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception filename"""
lineno = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception lineno"""
msg = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception msg"""
offset = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception offset"""
print_file_and_line = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception print_file_and_line"""
text = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception text"""
class IndentationError(SyntaxError):
""" Improper indentation. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class LookupError(Exception):
""" Base class for lookup errors. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class IndexError(LookupError):
""" Sequence index out of range. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class InterruptedError(OSError):
""" Interrupted by signal. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class IsADirectoryError(OSError):
""" Operation doesn't work on directories. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class KeyboardInterrupt(BaseException):
""" Program interrupted by user. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class KeyError(LookupError):
""" Mapping key not found. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
class list(object):
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
"""
def append(self, p_object): # real signature unknown; restored from __doc__
""" L.append(object) -> None -- append object to end """
pass
def clear(self): # real signature unknown; restored from __doc__
""" L.clear() -> None -- remove all items from L """
pass
def copy(self): # real signature unknown; restored from __doc__
""" L.copy() -> list -- a shallow copy of L """
return []
def count(self, value): # real signature unknown; restored from __doc__
""" L.count(value) -> integer -- return number of occurrences of value """
return 0
def extend(self, iterable): # real signature unknown; restored from __doc__
""" L.extend(iterable) -> None -- extend list by appending elements from the iterable """
pass
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0
def insert(self, index, p_object): # real signature unknown; restored from __doc__
""" L.insert(index, object) -- insert object before index """
pass
def pop(self, index=None): # real signature unknown; restored from __doc__
"""
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
"""
pass
def remove(self, value): # real signature unknown; restored from __doc__
"""
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
"""
pass
def reverse(self): # real signature unknown; restored from __doc__
""" L.reverse() -- reverse *IN PLACE* """
pass
def sort(self, key=None, reverse=False): # real signature unknown; restored from __doc__
""" L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
pass
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __iadd__(self, *args, **kwargs): # real signature unknown
""" Implement self+=value. """
pass
def __imul__(self, *args, **kwargs): # real signature unknown
""" Implement self*=value. """
pass
def __init__(self, seq=()): # known special case of list.__init__
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __reversed__(self): # real signature unknown; restored from __doc__
""" L.__reversed__() -- return a reverse iterator over the list """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" L.__sizeof__() -- size of L in memory, in bytes """
pass
__hash__ = None
class map(object):
"""
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
class MemoryError(Exception):
""" Out of memory. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class memoryview(object):
""" Create a new memoryview object which references the given object. """
def cast(self, *args, **kwargs): # real signature unknown
""" Cast a memoryview to a new format or shape. """
pass
def hex(self, *args, **kwargs): # real signature unknown
""" Return the data in the buffer as a string of hexadecimal numbers. """
pass
def release(self, *args, **kwargs): # real signature unknown
""" Release the underlying buffer exposed by the memoryview object. """
pass
def tobytes(self, *args, **kwargs): # real signature unknown
""" Return the data in the buffer as a byte string. """
pass
def tolist(self, *args, **kwargs): # real signature unknown
""" Return the data in the buffer as a list of elements. """
pass
def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass
def __enter__(self, *args, **kwargs): # real signature unknown
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __exit__(self, *args, **kwargs): # real signature unknown
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass
contiguous = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A bool indicating whether the memory is contiguous."""
c_contiguous = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A bool indicating whether the memory is C contiguous."""
format = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A string containing the format (in struct module style)
for each element in the view."""
f_contiguous = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A bool indicating whether the memory is Fortran contiguous."""
itemsize = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The size in bytes of each element of the memoryview."""
nbytes = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The amount of space in bytes that the array would use in
a contiguous representation."""
ndim = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""An integer indicating how many dimensions of a multi-dimensional
array the memory represents."""
obj = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""The underlying object of the memoryview."""
readonly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A bool indicating whether the memory is read only."""
shape = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A tuple of ndim integers giving the shape of the memory
as an N-dimensional array."""
strides = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A tuple of ndim integers giving the size in bytes to access
each element for each dimension of the array."""
suboffsets = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""A tuple of integers used internally for PIL-style arrays."""
class NameError(Exception):
""" Name not found globally. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class NotADirectoryError(OSError):
""" Operation only works on directories. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class RuntimeError(Exception):
""" Unspecified run-time error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class NotImplementedError(RuntimeError):
""" Method or function hasn't been implemented yet. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class OverflowError(ArithmeticError):
""" Result too large to be represented. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class PendingDeprecationWarning(Warning):
"""
Base class for warnings about features which will be deprecated
in the future.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class PermissionError(OSError):
""" Not enough permissions. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class ProcessLookupError(OSError):
""" Process not found. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class property(object):
"""
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for del'ing, an
attribute. Typical use is to define a managed attribute x:
class C(object):
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
Decorators make defining new properties or modifying existing ones easy:
class C(object):
@property
def x(self):
"I am the 'x' property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
"""
def deleter(self, *args, **kwargs): # real signature unknown
""" Descriptor to change the deleter on a property. """
pass
def getter(self, *args, **kwargs): # real signature unknown
""" Descriptor to change the getter on a property. """
pass
def setter(self, *args, **kwargs): # real signature unknown
""" Descriptor to change the setter on a property. """
pass
def __delete__(self, *args, **kwargs): # real signature unknown
""" Delete an attribute of instance. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __get__(self, *args, **kwargs): # real signature unknown
""" Return an attribute of instance, which is of type owner. """
pass
def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__
"""
property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
fget is a function to be used for getting an attribute value, and likewise
fset is a function for setting, and fdel a function for del'ing, an
attribute. Typical use is to define a managed attribute x:
class C(object):
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
Decorators make defining new properties or modifying existing ones easy:
class C(object):
@property
def x(self):
"I am the 'x' property."
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
# (copied from class doc)
"""
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __set__(self, *args, **kwargs): # real signature unknown
""" Set an attribute of instance to value. """
pass
fdel = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
fget = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
fset = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__isabstractmethod__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
class range(object):
"""
range(stop) -> range object
range(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
"""
def count(self, value): # real signature unknown; restored from __doc__
""" rangeobject.count(value) -> integer -- return number of occurrences of value """
return 0
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
rangeobject.index(value, [start, [stop]]) -> integer -- return index of value.
Raise ValueError if the value is not present.
"""
return 0
def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, stop): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __reversed__(self, *args, **kwargs): # real signature unknown
""" Return a reverse iterator. """
pass
start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
step = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
stop = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
class RecursionError(RuntimeError):
""" Recursion limit exceeded. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class ReferenceError(Exception):
""" Weak ref proxy used after referent went away. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class ResourceWarning(Warning):
""" Base class for warnings about resource usage. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class reversed(object):
"""
reversed(sequence) -> reverse iterator over values of the sequence
Return a reverse iterator
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, sequence): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __length_hint__(self, *args, **kwargs): # real signature unknown
""" Private method returning an estimate of len(list(it)). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __setstate__(self, *args, **kwargs): # real signature unknown
""" Set state information for unpickling. """
pass
class RuntimeWarning(Warning):
""" Base class for warnings about dubious runtime behavior. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set.
This has no effect if the element is already present.
"""
pass
def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass
def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
pass
def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
"""
pass
def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set. """
pass
def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member.
If the element is not a member, do nothing.
"""
pass
def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set.
(i.e. all elements that are in both sets.)
"""
pass
def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another. """
pass
def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. """
pass
def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. """
pass
def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. """
pass
def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pass
def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError.
"""
pass
def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
"""
pass
def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. """
pass
def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set.
(i.e. all elements that are in either set.)
"""
pass
def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. """
pass
def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass
def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __iand__(self, *args, **kwargs): # real signature unknown
""" Return self&=value. """
pass
def __init__(self, seq=()): # known special case of set.__init__
"""
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
# (copied from class doc)
"""
pass
def __ior__(self, *args, **kwargs): # real signature unknown
""" Return self|=value. """
pass
def __isub__(self, *args, **kwargs): # real signature unknown
""" Return self-=value. """
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __ixor__(self, *args, **kwargs): # real signature unknown
""" Return self^=value. """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass
def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass
def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass
def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass
def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass
def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass
__hash__ = None
class slice(object):
"""
slice(stop)
slice(start, stop[, step])
Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).
"""
def indices(self, len): # real signature unknown; restored from __doc__
"""
S.indices(len) -> (start, stop, stride)
Assuming a sequence of length len, calculate the start and stop
indices, and the stride length of the extended slice described by
S. Out of bounds indices are clipped in a manner consistent with the
handling of normal slices.
"""
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __init__(self, stop): # real signature unknown; restored from __doc__
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
start = property(lambda self: 0)
""":type: int"""
step = property(lambda self: 0)
""":type: int"""
stop = property(lambda self: 0)
""":type: int"""
__hash__ = None
class staticmethod(object):
"""
staticmethod(function) -> method
Convert a function to be a static method.
A static method does not receive an implicit first argument.
To declare a static method, use this idiom:
class C:
def f(arg1, arg2, ...): ...
f = staticmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()). The instance is ignored except for its class.
Static methods in Python are similar to those found in Java or C++.
For a more advanced concept, see the classmethod builtin.
"""
def __get__(self, *args, **kwargs): # real signature unknown
""" Return an attribute of instance, which is of type owner. """
pass
def __init__(self, function): # real signature unknown; restored from __doc__
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
__func__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__isabstractmethod__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__dict__ = None # (!) real value is ''
class StopAsyncIteration(Exception):
""" Signal the end from iterator.__anext__(). """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class StopIteration(Exception):
""" Signal the end from iterator.__next__(). """
def __init__(self, *args, **kwargs): # real signature unknown
pass
value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""generator return value"""
class str(object):
"""
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
"""
def capitalize(self): # real signature unknown; restored from __doc__
"""
S.capitalize() -> str
Return a capitalized version of S, i.e. make the first character
have upper case and the rest lower case.
"""
return ""
def casefold(self): # real signature unknown; restored from __doc__
"""
S.casefold() -> str
Return a version of S suitable for caseless comparisons.
"""
return ""
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.center(width[, fillchar]) -> str
Return S centered in a string of length width. Padding is
done using the specified fill character (default is a space)
"""
return ""
def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.count(sub[, start[, end]]) -> int
Return the number of non-overlapping occurrences of substring sub in
string S[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return 0
def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
"""
S.encode(encoding='utf-8', errors='strict') -> bytes
Encode S using the codec registered for encoding. Default encoding
is 'utf-8'. errors may be given to set a different error
handling scheme. Default is 'strict' meaning that encoding errors raise
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any other name registered with
codecs.register_error that can handle UnicodeEncodeErrors.
"""
return b""
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.endswith(suffix[, start[, end]]) -> bool
Return True if S ends with the specified suffix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
suffix can also be a tuple of strings to try.
"""
return False
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
"""
S.expandtabs(tabsize=8) -> str
Return a copy of S where all tab characters are expanded using spaces.
If tabsize is not given, a tab size of 8 characters is assumed.
"""
return ""
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.find(sub[, start[, end]]) -> int
Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return 0
def format(*args, **kwargs): # known special case of str.format
"""
S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
pass
def format_map(self, mapping): # real signature unknown; restored from __doc__
"""
S.format_map(mapping) -> str
Return a formatted version of S, using substitutions from mapping.
The substitutions are identified by braces ('{' and '}').
"""
return ""
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.index(sub[, start[, end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
"""
return 0
def isalnum(self): # real signature unknown; restored from __doc__
"""
S.isalnum() -> bool
Return True if all characters in S are alphanumeric
and there is at least one character in S, False otherwise.
"""
return False
def isalpha(self): # real signature unknown; restored from __doc__
"""
S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
"""
return False
def isdecimal(self): # real signature unknown; restored from __doc__
"""
S.isdecimal() -> bool
Return True if there are only decimal characters in S,
False otherwise.
"""
return False
def isdigit(self): # real signature unknown; restored from __doc__
"""
S.isdigit() -> bool
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
"""
return False
def isidentifier(self): # real signature unknown; restored from __doc__
"""
S.isidentifier() -> bool
Return True if S is a valid identifier according
to the language definition.
Use keyword.iskeyword() to test for reserved identifiers
such as "def" and "class".
"""
return False
def islower(self): # real signature unknown; restored from __doc__
"""
S.islower() -> bool
Return True if all cased characters in S are lowercase and there is
at least one cased character in S, False otherwise.
"""
return False
def isnumeric(self): # real signature unknown; restored from __doc__
"""
S.isnumeric() -> bool
Return True if there are only numeric characters in S,
False otherwise.
"""
return False
def isprintable(self): # real signature unknown; restored from __doc__
"""
S.isprintable() -> bool
Return True if all characters in S are considered
printable in repr() or S is empty, False otherwise.
"""
return False
def isspace(self): # real signature unknown; restored from __doc__
"""
S.isspace() -> bool
Return True if all characters in S are whitespace
and there is at least one character in S, False otherwise.
"""
return False
def istitle(self): # real signature unknown; restored from __doc__
"""
S.istitle() -> bool
Return True if S is a titlecased string and there is at least one
character in S, i.e. upper- and titlecase characters may only
follow uncased characters and lowercase characters only cased ones.
Return False otherwise.
"""
return False
def isupper(self): # real signature unknown; restored from __doc__
"""
S.isupper() -> bool
Return True if all cased characters in S are uppercase and there is
at least one cased character in S, False otherwise.
"""
return False
def join(self, iterable): # real signature unknown; restored from __doc__
"""
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
"""
return ""
def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.ljust(width[, fillchar]) -> str
Return S left-justified in a Unicode string of length width. Padding is
done using the specified fill character (default is a space).
"""
return ""
def lower(self): # real signature unknown; restored from __doc__
"""
S.lower() -> str
Return a copy of the string S converted to lowercase.
"""
return ""
def lstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.lstrip([chars]) -> str
Return a copy of the string S with leading whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
def maketrans(self, *args, **kwargs): # real signature unknown
"""
Return a translation table usable for str.translate().
If there is only one argument, it must be a dictionary mapping Unicode
ordinals (integers) or characters to Unicode ordinals, strings or None.
Character keys will be then converted to ordinals.
If there are two arguments, they must be strings of equal length, and
in the resulting dictionary, each character in x will be mapped to the
character at the same position in y. If there is a third argument, it
must be a string, whose characters will be mapped to None in the result.
"""
pass
def partition(self, sep): # real signature unknown; restored from __doc__
"""
S.partition(sep) -> (head, sep, tail)
Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
"""
pass
def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
"""
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
"""
return ""
def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.rfind(sub[, start[, end]]) -> int
Return the highest index in S where substring sub is found,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return 0
def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.rindex(sub[, start[, end]]) -> int
Like S.rfind() but raise ValueError when the substring is not found.
"""
return 0
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
"""
S.rjust(width[, fillchar]) -> str
Return S right-justified in a string of length width. Padding is
done using the specified fill character (default is a space).
"""
return ""
def rpartition(self, sep): # real signature unknown; restored from __doc__
"""
S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return
the part before it, the separator itself, and the part after it. If the
separator is not found, return two empty strings and S.
"""
pass
def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
"""
S.rsplit(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string, starting at the end of the string and
working to the front. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified, any whitespace string
is a separator.
"""
return []
def rstrip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.rstrip([chars]) -> str
Return a copy of the string S with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
"""
S.split(sep=None, maxsplit=-1) -> list of strings
Return a list of the words in S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are
removed from the result.
"""
return []
def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
"""
S.splitlines([keepends]) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
return []
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
"""
S.startswith(prefix[, start[, end]]) -> bool
Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.
"""
return False
def strip(self, chars=None): # real signature unknown; restored from __doc__
"""
S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
"""
return ""
def swapcase(self): # real signature unknown; restored from __doc__
"""
S.swapcase() -> str
Return a copy of S with uppercase characters converted to lowercase
and vice versa.
"""
return ""
def title(self): # real signature unknown; restored from __doc__
"""
S.title() -> str
Return a titlecased version of S, i.e. words start with title case
characters, all remaining cased characters have lower case.
"""
return ""
def translate(self, table): # real signature unknown; restored from __doc__
"""
S.translate(table) -> str
Return a copy of the string S in which each character has been mapped
through the given translation table. The table must implement
lookup/indexing via __getitem__, for instance a dictionary or list,
mapping Unicode ordinals to Unicode ordinals, strings, or None. If
this operation raises LookupError, the character is left untouched.
Characters mapped to None are deleted.
"""
return ""
def upper(self): # real signature unknown; restored from __doc__
"""
S.upper() -> str
Return a copy of S converted to uppercase.
"""
return ""
def zfill(self, width): # real signature unknown; restored from __doc__
"""
S.zfill(width) -> str
Pad a numeric string S with zeros on the left, to fill a field
of the specified width. The string S is never truncated.
"""
return ""
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __format__(self, format_spec): # real signature unknown; restored from __doc__
"""
S.__format__(format_spec) -> str
Return a formatted version of S as described by format_spec.
"""
return ""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__
"""
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mod__(self, *args, **kwargs): # real signature unknown
""" Return self%value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __rmod__(self, *args, **kwargs): # real signature unknown
""" Return value%self. """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
class super(object):
"""
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
def meth(self, arg):
super().meth(arg)
This works for class methods too:
class C(B):
@classmethod
def cmeth(cls, arg):
super().cmeth(arg)
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __get__(self, *args, **kwargs): # real signature unknown
""" Return an attribute of instance, which is of type owner. """
pass
def __init__(self, type1=None, type2=None): # known special case of super.__init__
"""
super() -> same as super(__class__, <first argument>)
super(type) -> unbound super object
super(type, obj) -> bound super object; requires isinstance(obj, type)
super(type, type2) -> bound super object; requires issubclass(type2, type)
Typical use to call a cooperative superclass method:
class C(B):
def meth(self, arg):
super().meth(arg)
This works for class methods too:
class C(B):
@classmethod
def cmeth(cls, arg):
super().cmeth(arg)
# (copied from class doc)
"""
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
__self_class__ = property(lambda self: type(object))
"""the type of the instance invoking super(); may be None
:type: type
"""
__self__ = property(lambda self: type(object))
"""the instance invoking super(); may be None
:type: type
"""
__thisclass__ = property(lambda self: type(object))
"""the class invoking super()
:type: type
"""
class SyntaxWarning(Warning):
""" Base class for warnings about dubious syntax. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class SystemError(Exception):
"""
Internal error in the Python interpreter.
Please report this to the Python maintainer, along with the traceback,
the Python version, and the hardware/OS platform and version.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class SystemExit(BaseException):
""" Request to exit from the interpreter. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
code = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception code"""
class TabError(IndentationError):
""" Improper mixture of spaces and tabs. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class TimeoutError(OSError):
""" Timeout expired. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
class tuple(object):
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items
If the argument is a tuple, the return value is the same object.
"""
def count(self, value): # real signature unknown; restored from __doc__
""" T.count(value) -> integer -- return number of occurrences of value """
return 0
def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
"""
return 0
def __add__(self, *args, **kwargs): # real signature unknown
""" Return self+value. """
pass
def __contains__(self, *args, **kwargs): # real signature unknown
""" Return key in self. """
pass
def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass
def __getnewargs__(self, *args, **kwargs): # real signature unknown
pass
def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass
def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass
def __hash__(self, *args, **kwargs): # real signature unknown
""" Return hash(self). """
pass
def __init__(self, seq=()): # known special case of tuple.__init__
"""
tuple() -> empty tuple
tuple(iterable) -> tuple initialized from iterable's items
If the argument is a tuple, the return value is the same object.
# (copied from class doc)
"""
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass
def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass
def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass
def __mul__(self, *args, **kwargs): # real signature unknown
""" Return self*value.n """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __rmul__(self, *args, **kwargs): # real signature unknown
""" Return self*value. """
pass
class type(object):
"""
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
"""
def mro(self): # real signature unknown; restored from __doc__
"""
mro() -> list
return a type's method resolution order
"""
return []
def __call__(self, *args, **kwargs): # real signature unknown
""" Call self as a function. """
pass
def __delattr__(self, *args, **kwargs): # real signature unknown
""" Implement delattr(self, name). """
pass
def __dir__(self): # real signature unknown; restored from __doc__
"""
__dir__() -> list
specialized __dir__ implementation for types
"""
return []
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__
"""
type(object_or_name, bases, dict)
type(object) -> the object's type
type(name, bases, dict) -> a new type
# (copied from class doc)
"""
pass
def __instancecheck__(self): # real signature unknown; restored from __doc__
"""
__instancecheck__() -> bool
check if an object is an instance
"""
return False
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __prepare__(self): # real signature unknown; restored from __doc__
"""
__prepare__() -> dict
used to create the namespace for the class statement
"""
return {}
def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass
def __setattr__(self, *args, **kwargs): # real signature unknown
""" Implement setattr(self, name, value). """
pass
def __sizeof__(self): # real signature unknown; restored from __doc__
"""
__sizeof__() -> int
return memory consumption of the type object
"""
return 0
def __subclasscheck__(self): # real signature unknown; restored from __doc__
"""
__subclasscheck__() -> bool
check if a class is a subclass
"""
return False
def __subclasses__(self): # real signature unknown; restored from __doc__
""" __subclasses__() -> list of immediate subclasses """
return []
__abstractmethods__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
__bases__ = (
object,
)
__base__ = object
__basicsize__ = 864
__dictoffset__ = 264
__dict__ = None # (!) real value is ''
__flags__ = 2148291584
__itemsize__ = 40
__mro__ = (
None, # (!) forward: type, real value is ''
object,
)
__name__ = 'type'
__qualname__ = 'type'
__text_signature__ = None
__weakrefoffset__ = 368
class TypeError(Exception):
""" Inappropriate argument type. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class UnboundLocalError(NameError):
""" Local name referenced but not bound to a value. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class ValueError(Exception):
""" Inappropriate argument value (of correct type). """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class UnicodeError(ValueError):
""" Unicode related error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class UnicodeDecodeError(UnicodeError):
""" Unicode decoding error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception encoding"""
end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception end"""
object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception object"""
reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception reason"""
start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception start"""
class UnicodeEncodeError(UnicodeError):
""" Unicode encoding error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception encoding"""
end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception end"""
object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception object"""
reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception reason"""
start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception start"""
class UnicodeTranslateError(UnicodeError):
""" Unicode translation error. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __str__(self, *args, **kwargs): # real signature unknown
""" Return str(self). """
pass
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception encoding"""
end = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception end"""
object = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception object"""
reason = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception reason"""
start = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""exception start"""
class UnicodeWarning(Warning):
"""
Base class for warnings about Unicode related problems, mostly
related to conversion problems.
"""
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class UserWarning(Warning):
""" Base class for warnings generated by user code. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class ZeroDivisionError(ArithmeticError):
""" Second argument to a division or modulo operation was zero. """
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
class zip(object):
"""
zip(iter1 [,iter2 [...]]) --> zip object
Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, iter1, iter2=None, *some): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
class __loader__(object):
"""
Meta path import for built-in modules.
All methods are either class or static methods to avoid the need to
instantiate the class.
"""
def create_module(self, *args, **kwargs): # real signature unknown
""" Create a built-in module """
pass
def exec_module(self, *args, **kwargs): # real signature unknown
""" Exec a built-in module """
pass
def find_module(self, *args, **kwargs): # real signature unknown
"""
Find the built-in module.
If 'path' is ever specified then the search is considered a failure.
This method is deprecated. Use find_spec() instead.
"""
pass
def find_spec(self, *args, **kwargs): # real signature unknown
pass
def get_code(self, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have code objects. """
pass
def get_source(self, *args, **kwargs): # real signature unknown
""" Return None as built-in modules do not have source code. """
pass
def is_package(self, *args, **kwargs): # real signature unknown
""" Return False as built-in modules are never packages. """
pass
def load_module(self, *args, **kwargs): # real signature unknown
"""
Load the specified module into sys.modules and return it.
This method is deprecated. Use loader.exec_module instead.
"""
pass
def module_repr(module): # reliably restored by inspect
"""
Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__dict__ = None # (!) real value is ''
# variables with complex values
Ellipsis = None # (!) real value is ''
NotImplemented = None # (!) real value is ''
__spec__ = None # (!) real value is ''
|
jelugbo/ddi | refs/heads/master | lms/lib/comment_client/models.py | 63 | import logging
from .utils import extract, perform_request, CommentClientRequestError
log = logging.getLogger(__name__)
class Model(object):
accessible_fields = ['id']
updatable_fields = ['id']
initializable_fields = ['id']
base_url = None
default_retrieve_params = {}
metric_tag_fields = []
DEFAULT_ACTIONS_WITH_ID = ['get', 'put', 'delete']
DEFAULT_ACTIONS_WITHOUT_ID = ['get_all', 'post']
DEFAULT_ACTIONS = DEFAULT_ACTIONS_WITH_ID + DEFAULT_ACTIONS_WITHOUT_ID
def __init__(self, *args, **kwargs):
self.attributes = extract(kwargs, self.accessible_fields)
self.retrieved = False
def __getattr__(self, name):
if name == 'id':
return self.attributes.get('id', None)
try:
return self.attributes[name]
except KeyError:
if self.retrieved or self.id is None:
raise AttributeError("Field {0} does not exist".format(name))
self.retrieve()
return self.__getattr__(name)
def __setattr__(self, name, value):
if name == 'attributes' or name not in (self.accessible_fields + self.updatable_fields):
super(Model, self).__setattr__(name, value)
else:
self.attributes[name] = value
def __getitem__(self, key):
if key not in self.accessible_fields:
raise KeyError("Field {0} does not exist".format(key))
return self.attributes.get(key)
def __setitem__(self, key, value):
if key not in (self.accessible_fields + self.updatable_fields):
raise KeyError("Field {0} does not exist".format(key))
self.attributes.__setitem__(key, value)
def items(self, *args, **kwargs):
return self.attributes.items(*args, **kwargs)
def get(self, *args, **kwargs):
return self.attributes.get(*args, **kwargs)
def to_dict(self):
self.retrieve()
return self.attributes
def retrieve(self, *args, **kwargs):
if not self.retrieved:
self._retrieve(*args, **kwargs)
self.retrieved = True
return self
def _retrieve(self, *args, **kwargs):
url = self.url(action='get', params=self.attributes)
response = perform_request(
'get',
url,
self.default_retrieve_params,
metric_tags=self._metric_tags,
metric_action='model.retrieve'
)
self._update_from_response(response)
@property
def _metric_tags(self):
"""
Returns a list of tags to be used when recording metrics about this model.
Each field named in ``self.metric_tag_fields`` is used as a tag value,
under the key ``<class>.<metric_field>``. The tag model_class is used to
record the class name of the model.
"""
tags = [
u'{}.{}:{}'.format(self.__class__.__name__, attr, self[attr])
for attr in self.metric_tag_fields
if attr in self.attributes
]
tags.append(u'model_class:{}'.format(self.__class__.__name__))
return tags
@classmethod
def find(cls, id):
return cls(id=id)
def _update_from_response(self, response_data):
for k, v in response_data.items():
if k in self.accessible_fields:
self.__setattr__(k, v)
else:
log.warning(
"Unexpected field {field_name} in model {model_name}".format(
field_name=k,
model_name=self.__class__.__name__
)
)
def updatable_attributes(self):
return extract(self.attributes, self.updatable_fields)
def initializable_attributes(self):
return extract(self.attributes, self.initializable_fields)
@classmethod
def before_save(cls, instance):
pass
@classmethod
def after_save(cls, instance):
pass
def save(self):
self.before_save(self)
if self.id: # if we have id already, treat this as an update
url = self.url(action='put', params=self.attributes)
response = perform_request(
'put',
url,
self.updatable_attributes(),
metric_tags=self._metric_tags,
metric_action='model.update'
)
else: # otherwise, treat this as an insert
url = self.url(action='post', params=self.attributes)
response = perform_request(
'post',
url,
self.initializable_attributes(),
metric_tags=self._metric_tags,
metric_action='model.insert'
)
self.retrieved = True
self._update_from_response(response)
self.after_save(self)
def delete(self):
url = self.url(action='delete', params=self.attributes)
response = perform_request('delete', url, metric_tags=self._metric_tags, metric_action='model.delete')
self.retrieved = True
self._update_from_response(response)
@classmethod
def url_with_id(cls, params={}):
return cls.base_url + '/' + str(params['id'])
@classmethod
def url_without_id(cls, params={}):
return cls.base_url
@classmethod
def url(cls, action, params={}):
if cls.base_url is None:
raise CommentClientRequestError("Must provide base_url when using default url function")
if action not in cls.DEFAULT_ACTIONS:
raise ValueError("Invalid action {0}. The supported action must be in {1}".format(action, str(cls.DEFAULT_ACTIONS)))
elif action in cls.DEFAULT_ACTIONS_WITH_ID:
try:
return cls.url_with_id(params)
except KeyError:
raise CommentClientRequestError("Cannot perform action {0} without id".format(action))
else: # action must be in DEFAULT_ACTIONS_WITHOUT_ID now
return cls.url_without_id()
|
nirmalvp/python-social-auth | refs/heads/master | social/backends/weibo.py | 67 | # coding:utf8
# author:hepochen@gmail.com https://github.com/hepochen
"""
Weibo OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/weibo.html
"""
from social.backends.oauth import BaseOAuth2
class WeiboOAuth2(BaseOAuth2):
"""Weibo (of sina) OAuth authentication backend"""
name = 'weibo'
ID_KEY = 'uid'
AUTHORIZATION_URL = 'https://api.weibo.com/oauth2/authorize'
REQUEST_TOKEN_URL = 'https://api.weibo.com/oauth2/request_token'
ACCESS_TOKEN_URL = 'https://api.weibo.com/oauth2/access_token'
ACCESS_TOKEN_METHOD = 'POST'
REDIRECT_STATE = False
EXTRA_DATA = [
('id', 'id'),
('name', 'username'),
('profile_image_url', 'profile_image_url'),
('gender', 'gender')
]
def get_user_details(self, response):
"""Return user details from Weibo. API URL is:
https://api.weibo.com/2/users/show.json/?uid=<UID>&access_token=<TOKEN>
"""
if self.setting('DOMAIN_AS_USERNAME'):
username = response.get('domain', '')
else:
username = response.get('name', '')
fullname, first_name, last_name = self.get_user_names(
first_name=response.get('screen_name', '')
)
return {'username': username,
'fullname': fullname,
'first_name': first_name,
'last_name': last_name}
def get_uid(self, access_token):
"""Return uid by access_token"""
data = self.get_json(
'https://api.weibo.com/oauth2/get_token_info',
method='POST',
params={'access_token': access_token}
)
return data['uid']
def user_data(self, access_token, response=None, *args, **kwargs):
"""Return user data"""
# If user id was not retrieved in the response, then get it directly
# from weibo get_token_info endpoint
uid = response and response.get('uid') or self.get_uid(access_token)
user_data = self.get_json(
'https://api.weibo.com/2/users/show.json',
params={'access_token': access_token, 'uid': uid}
)
user_data['uid'] = uid
return user_data
|
thefinn93/CouchPotatoServer | refs/heads/master | libs/pyutil/xor/__init__.py | 12133432 | |
Vixionar/django | refs/heads/master | tests/fixtures/__init__.py | 12133432 | |
openNSS/enigma2 | refs/heads/master | lib/python/Plugins/SystemPlugins/CableScan/__init__.py | 12133432 | |
skg-net/ansible | refs/heads/devel | lib/ansible/module_utils/network/cloudengine/__init__.py | 12133432 | |
katrid/django | refs/heads/master | django/core/management/commands/sqlsequencereset.py | 467 | from __future__ import unicode_literals
from django.core.management.base import AppCommand
from django.db import DEFAULT_DB_ALIAS, connections
class Command(AppCommand):
help = 'Prints the SQL statements for resetting sequences for the given app name(s).'
output_transaction = True
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument('--database', default=DEFAULT_DB_ALIAS,
help='Nominates a database to print the SQL for. Defaults to the '
'"default" database.')
def handle_app_config(self, app_config, **options):
if app_config.models_module is None:
return
connection = connections[options.get('database')]
models = app_config.get_models(include_auto_created=True)
statements = connection.ops.sequence_reset_sql(self.style, models)
return '\n'.join(statements)
|
mikelambert/flask-admin | refs/heads/master | examples/auth/config.py | 33 | # Create dummy secrey key so we can use sessions
SECRET_KEY = '123456790'
# Create in-memory database
DATABASE_FILE = 'sample_db.sqlite'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_FILE
SQLALCHEMY_ECHO = True
# Flask-Security config
SECURITY_URL_PREFIX = "/admin"
SECURITY_PASSWORD_HASH = "pbkdf2_sha512"
SECURITY_PASSWORD_SALT = "ATGUOHAELKiubahiughaerGOJAEGj"
# Flask-Security URLs, overridden because they don't put a / at the end
SECURITY_LOGIN_URL = "/login/"
SECURITY_LOGOUT_URL = "/logout/"
SECURITY_REGISTER_URL = "/register/"
SECURITY_POST_LOGIN_VIEW = "/admin/"
SECURITY_POST_LOGOUT_VIEW = "/admin/"
SECURITY_POST_REGISTER_VIEW = "/admin/"
# Flask-Security features
SECURITY_REGISTERABLE = True
SECURITY_SEND_REGISTER_EMAIL = False |
elba7r/lite-system | refs/heads/master | erpnext/stock/doctype/stock_reconciliation/test_stock_reconciliation.py | 10 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
# ERPNext - web based ERP (http://erpnext.com)
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, unittest
from frappe.utils import flt, nowdate, nowtime
from erpnext.accounts.utils import get_stock_and_account_difference
from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_perpetual_inventory
from erpnext.stock.stock_ledger import get_previous_sle, update_entries_after
from erpnext.stock.doctype.stock_reconciliation.stock_reconciliation import EmptyStockReconciliationItemsError
class TestStockReconciliation(unittest.TestCase):
def setUp(self):
frappe.db.set_value("Stock Settings", None, "allow_negative_stock", 1)
self.insert_existing_sle()
def test_reco_for_fifo(self):
self._test_reco_sle_gle("FIFO")
def test_reco_for_moving_average(self):
self._test_reco_sle_gle("Moving Average")
def _test_reco_sle_gle(self, valuation_method):
set_perpetual_inventory()
# [[qty, valuation_rate, posting_date,
# posting_time, expected_stock_value, bin_qty, bin_valuation]]
input_data = [
[50, 1000, "2012-12-26", "12:00"],
[25, 900, "2012-12-26", "12:00"],
["", 1000, "2012-12-20", "12:05"],
[20, "", "2012-12-26", "12:05"],
[0, "", "2012-12-31", "12:10"]
]
for d in input_data:
set_valuation_method("_Test Item", valuation_method)
last_sle = get_previous_sle({
"item_code": "_Test Item",
"warehouse": "_Test Warehouse - _TC",
"posting_date": d[2],
"posting_time": d[3]
})
# submit stock reconciliation
stock_reco = create_stock_reconciliation(qty=d[0], rate=d[1],
posting_date=d[2], posting_time=d[3])
# check stock value
sle = frappe.db.sql("""select * from `tabStock Ledger Entry`
where voucher_type='Stock Reconciliation' and voucher_no=%s""", stock_reco.name, as_dict=1)
qty_after_transaction = flt(d[0]) if d[0] != "" else flt(last_sle.get("qty_after_transaction"))
valuation_rate = flt(d[1]) if d[1] != "" else flt(last_sle.get("valuation_rate"))
if qty_after_transaction == last_sle.get("qty_after_transaction") \
and valuation_rate == last_sle.get("valuation_rate"):
self.assertFalse(sle)
else:
self.assertEqual(sle[0].qty_after_transaction, qty_after_transaction)
self.assertEqual(sle[0].stock_value, qty_after_transaction * valuation_rate)
# no gl entries
self.assertTrue(frappe.db.get_value("Stock Ledger Entry",
{"voucher_type": "Stock Reconciliation", "voucher_no": stock_reco.name}))
self.assertFalse(get_stock_and_account_difference(["_Test Account Stock In Hand - _TC"]))
stock_reco.cancel()
self.assertFalse(frappe.db.get_value("Stock Ledger Entry",
{"voucher_type": "Stock Reconciliation", "voucher_no": stock_reco.name}))
self.assertFalse(frappe.db.get_value("GL Entry",
{"voucher_type": "Stock Reconciliation", "voucher_no": stock_reco.name}))
set_perpetual_inventory(0)
def insert_existing_sle(self):
from erpnext.stock.doctype.stock_entry.test_stock_entry import make_stock_entry
make_stock_entry(posting_date="2012-12-15", posting_time="02:00", item_code="_Test Item",
target="_Test Warehouse - _TC", qty=10, basic_rate=700)
make_stock_entry(posting_date="2012-12-25", posting_time="03:00", item_code="_Test Item",
source="_Test Warehouse - _TC", qty=15)
make_stock_entry(posting_date="2013-01-05", posting_time="07:00", item_code="_Test Item",
target="_Test Warehouse - _TC", qty=15, basic_rate=1200)
def create_stock_reconciliation(**args):
args = frappe._dict(args)
sr = frappe.new_doc("Stock Reconciliation")
sr.posting_date = args.posting_date or nowdate()
sr.posting_time = args.posting_time or nowtime()
sr.company = args.company or "_Test Company"
sr.expense_account = args.expense_account or \
("Stock Adjustment - _TC" if frappe.get_all("Stock Ledger Entry") else "Temporary Opening - _TC")
sr.cost_center = args.cost_center or "_Test Cost Center - _TC"
sr.append("items", {
"item_code": args.item_code or "_Test Item",
"warehouse": args.warehouse or "_Test Warehouse - _TC",
"qty": args.qty,
"valuation_rate": args.rate
})
try:
sr.submit()
except EmptyStockReconciliationItemsError:
pass
return sr
def set_valuation_method(item_code, valuation_method):
frappe.db.set_value("Item", item_code, "valuation_method", valuation_method)
for warehouse in frappe.get_all("Warehouse", filters={"company": "_Test Company"}, fields=["name", "is_group"]):
if not warehouse.is_group:
update_entries_after({
"item_code": item_code,
"warehouse": warehouse.name
}, allow_negative_stock=1)
test_dependencies = ["Item", "Warehouse"]
|
Cenorius/practica-final-verificacion | refs/heads/master | app/forms.py | 1 | from flask import Flask, render_template, request, flash
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField, DateField, RadioField
class TextProcessorForm(Form):
date = DateField('Date: ',format='%m/%d/%Y', validators=[validators.required()])
source = RadioField('Source', choices=[('MostUsed','Most used words'),('Articles','Words per article')])
|
a-parhom/edx-platform | refs/heads/master | common/djangoapps/student/management/commands/anonymized_id_mapping.py | 18 | # -*- coding: utf-8 -*-
"""Dump username, per-student anonymous id, and per-course anonymous id triples as CSV.
Give instructors easy access to the mapping from anonymized IDs to user IDs
with a simple Django management command to generate a CSV mapping. To run, use
the following:
./manage.py lms anonymized_id_mapping COURSE_ID
"""
import csv
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from student.models import anonymous_id_for_user
from opaque_keys.edx.keys import CourseKey
from six import text_type
class Command(BaseCommand):
"""Add our handler to the space where django-admin looks up commands."""
help = """Export a CSV mapping usernames to anonymized ids
Exports a CSV document mapping each username in the specified course to
the anonymized, unique user ID.
"""
def add_arguments(self, parser):
parser.add_argument('course_id')
def handle(self, *args, **options):
course_key = CourseKey.from_string(options['course_id'])
# Generate the output filename from the course ID.
# Change slashes to dashes first, and then append .csv extension.
output_filename = text_type(course_key).replace('/', '-') + ".csv"
# Figure out which students are enrolled in the course
students = User.objects.filter(courseenrollment__course_id=course_key)
if len(students) == 0:
self.stdout.write("No students enrolled in %s" % text_type(course_key))
return
# Write mapping to output file in CSV format with a simple header
try:
with open(output_filename, 'wb') as output_file:
csv_writer = csv.writer(output_file)
csv_writer.writerow((
"User ID",
"Per-Student anonymized user ID",
"Per-course anonymized user id"
))
for student in students:
csv_writer.writerow((
student.id,
anonymous_id_for_user(student, None),
anonymous_id_for_user(student, course_key)
))
except IOError:
raise CommandError("Error writing to file: %s" % output_filename)
|
hectord/lettuce | refs/heads/master | tests/integration/lib/Django-1.2.5/django/contrib/localflavor/at/at_states.py | 537 | # -*- coding: utf-8 -*
from django.utils.translation import ugettext_lazy as _
STATE_CHOICES = (
('BL', _('Burgenland')),
('KA', _('Carinthia')),
('NO', _('Lower Austria')),
('OO', _('Upper Austria')),
('SA', _('Salzburg')),
('ST', _('Styria')),
('TI', _('Tyrol')),
('VO', _('Vorarlberg')),
('WI', _('Vienna')),
) |
SciTools/iris | refs/heads/main | lib/iris/tests/unit/fileformats/pyke_rules/compiled_krb/fc_rules_cf_fc/test_build_lambert_azimuthal_equal_area_coordinate_system.py | 1 | # Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_lambert_azimuthal_equal_area_coordinate_system`.
"""
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests # isort:skip
from unittest import mock
import iris
from iris.coord_systems import LambertAzimuthalEqualArea
from iris.fileformats._pyke_rules.compiled_krb.fc_rules_cf_fc import \
build_lambert_azimuthal_equal_area_coordinate_system
class TestBuildLambertAzimuthalEqualAreaCoordinateSystem(tests.IrisTest):
def _test(self, inverse_flattening=False, no_optionals=False):
if no_optionals:
# Most properties are optional for this system.
gridvar_props = {}
# Setup all the expected default values
test_lat = 0
test_lon = 0
test_easting = 0
test_northing = 0
else:
# Choose test values and setup corresponding named properties.
test_lat = -35
test_lon = 175
test_easting = -100
test_northing = 200
gridvar_props = dict(
latitude_of_projection_origin=test_lat,
longitude_of_projection_origin=test_lon,
false_easting=test_easting,
false_northing=test_northing)
# Add ellipsoid args.
gridvar_props['semi_major_axis'] = 6377563.396
if inverse_flattening:
gridvar_props['inverse_flattening'] = 299.3249646
expected_ellipsoid = iris.coord_systems.GeogCS(
6377563.396,
inverse_flattening=299.3249646)
else:
gridvar_props['semi_minor_axis'] = 6356256.909
expected_ellipsoid = iris.coord_systems.GeogCS(
6377563.396, 6356256.909)
cf_grid_var = mock.Mock(spec=[], **gridvar_props)
cs = build_lambert_azimuthal_equal_area_coordinate_system(
None, cf_grid_var)
expected = LambertAzimuthalEqualArea(
latitude_of_projection_origin=test_lat,
longitude_of_projection_origin=test_lon,
false_easting=test_easting,
false_northing=test_northing,
ellipsoid=expected_ellipsoid)
self.assertEqual(cs, expected)
def test_basic(self):
self._test()
def test_inverse_flattening(self):
# Check when inverse_flattening is provided instead of semi_minor_axis.
self._test(inverse_flattening=True)
def test_no_optionals(self):
# Check defaults, when all optional attributes are absent.
self._test(no_optionals=True)
if __name__ == "__main__":
tests.main()
|
plotly/python-api | refs/heads/master | packages/python/plotly/plotly/validators/scatterpolar/marker/_line.py | 2 | import _plotly_utils.basevalidators
class LineValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="line", parent_name="scatterpolar.marker", **kwargs):
super(LineValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str=kwargs.pop("data_class_str", "Line"),
data_docs=kwargs.pop(
"data_docs",
"""
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.line.colorscale`. Has an
effect only if in `marker.line.color`is set to
a numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.line.color`) or the bounds set in
`marker.line.cmin` and `marker.line.cmax` Has
an effect only if in `marker.line.color`is set
to a numerical array. Defaults to `false` when
`marker.line.cmin` and `marker.line.cmax` are
set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.line.cmin` and/or
`marker.line.cmax` to be equidistant to this
point. Has an effect only if in
`marker.line.color`is set to a numerical array.
Value should have the same units as in
`marker.line.color`. Has no effect when
`marker.line.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.line.color`is set
to a numerical array. Value should have the
same units as in `marker.line.color` and if
set, `marker.line.cmax` must be set as well.
color
Sets themarker.linecolor. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.line.cmin` and `marker.line.cmax` if
set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorscale
Sets the colorscale. Has an effect only if in
`marker.line.color`is set to a numerical array.
The colorscale must be an array containing
arrays mapping a normalized value to an rgb,
rgba, hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use`marker.line.cmin` and
`marker.line.cmax`. Alternatively, `colorscale`
may be a palette name string of the following
list: Greys,YlGnBu,Greens,YlOrRd,Bluered,RdBu,R
eds,Blues,Picnic,Rainbow,Portland,Jet,Hot,Black
body,Earth,Electric,Viridis,Cividis.
colorsrc
Sets the source reference on Chart Studio Cloud
for color .
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.line.color`is set to
a numerical array. If true, `marker.line.cmin`
will correspond to the last color in the array
and `marker.line.cmax` will correspond to the
first color.
width
Sets the width (in px) of the lines bounding
the marker points.
widthsrc
Sets the source reference on Chart Studio Cloud
for width .
""",
),
**kwargs
)
|
0k/OpenUpgrade | refs/heads/8.0 | addons/share/res_users.py | 269 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
from openerp import SUPERUSER_ID
class res_users(osv.osv):
_name = 'res.users'
_inherit = 'res.users'
def _is_share(self, cr, uid, ids, name, args, context=None):
res = {}
for user in self.browse(cr, uid, ids, context=context):
res[user.id] = not self.has_group(cr, user.id, 'base.group_user')
return res
def _get_users_from_group(self, cr, uid, ids, context=None):
result = set()
groups = self.pool['res.groups'].browse(cr, uid, ids, context=context)
# Clear cache to avoid perf degradation on databases with thousands of users
groups.invalidate_cache()
for group in groups:
result.update(user.id for user in group.users)
return list(result)
_columns = {
'share': fields.function(_is_share, string='Share User', type='boolean',
store={
'res.users': (lambda self, cr, uid, ids, c={}: ids, None, 50),
'res.groups': (_get_users_from_group, None, 50),
}, help="External user with limited access, created only for the purpose of sharing data."),
}
class res_groups(osv.osv):
_name = "res.groups"
_inherit = 'res.groups'
_columns = {
'share': fields.boolean('Share Group', readonly=True,
help="Group created to set access rights for sharing data with some users.")
}
def init(self, cr):
# force re-generation of the user groups view without the shared groups
self.update_user_groups_view(cr, SUPERUSER_ID)
parent_class = super(res_groups, self)
if hasattr(parent_class, 'init'):
parent_class.init(cr)
def get_application_groups(self, cr, uid, domain=None, context=None):
if domain is None:
domain = []
domain.append(('share', '=', False))
return super(res_groups, self).get_application_groups(cr, uid, domain=domain, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
bvernoux/micropython | refs/heads/master | tests/basics/class_super.py | 21 | class Base:
def __init__(self):
self.a = 1
def meth(self):
print("in Base meth", self.a)
class Sub(Base):
def meth(self):
print("in Sub meth")
return super().meth()
a = Sub()
a.meth()
|
ucsb-seclab/ictf-framework | refs/heads/master | database/support/mysql-connector-python-2.1.3/lib/mysql/connector/locales/eng/__init__.py | 39 | # MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""English Content
"""
|
sirk390/coinpy | refs/heads/master | coinpy-lib/src/coinpy/model/__init__.py | 12133432 | |
Kamik423/uni_plan | refs/heads/master | plan/plan/lib/python3.4/encodings/shift_jis_2004.py | 816 | #
# shift_jis_2004.py: Python Unicode Codec for SHIFT_JIS_2004
#
# Written by Hye-Shik Chang <perky@FreeBSD.org>
#
import _codecs_jp, codecs
import _multibytecodec as mbc
codec = _codecs_jp.getcodec('shift_jis_2004')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.MultibyteIncrementalEncoder,
codecs.IncrementalEncoder):
codec = codec
class IncrementalDecoder(mbc.MultibyteIncrementalDecoder,
codecs.IncrementalDecoder):
codec = codec
class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):
codec = codec
class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):
codec = codec
def getregentry():
return codecs.CodecInfo(
name='shift_jis_2004',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
|
JetBrains/intellij-community | refs/heads/master | python/testData/inspections/PyCallingNonCallableInspection/getattrCallable.py | 83 | class value():
pass
class MyClass(object):
def bar(self):
foo = getattr(self, 'foo')
foo()
|
darionyaphet/flink | refs/heads/master | flink-python/pyflink/datastream/tests/__init__.py | 406 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
|
coderbone/SickRage-alt | refs/heads/master | lib/unidecode/x0fe.py | 252 | data = (
'[?]', # 0x00
'[?]', # 0x01
'[?]', # 0x02
'[?]', # 0x03
'[?]', # 0x04
'[?]', # 0x05
'[?]', # 0x06
'[?]', # 0x07
'[?]', # 0x08
'[?]', # 0x09
'[?]', # 0x0a
'[?]', # 0x0b
'[?]', # 0x0c
'[?]', # 0x0d
'[?]', # 0x0e
'[?]', # 0x0f
'[?]', # 0x10
'[?]', # 0x11
'[?]', # 0x12
'[?]', # 0x13
'[?]', # 0x14
'[?]', # 0x15
'[?]', # 0x16
'[?]', # 0x17
'[?]', # 0x18
'[?]', # 0x19
'[?]', # 0x1a
'[?]', # 0x1b
'[?]', # 0x1c
'[?]', # 0x1d
'[?]', # 0x1e
'[?]', # 0x1f
'', # 0x20
'', # 0x21
'', # 0x22
'~', # 0x23
'[?]', # 0x24
'[?]', # 0x25
'[?]', # 0x26
'[?]', # 0x27
'[?]', # 0x28
'[?]', # 0x29
'[?]', # 0x2a
'[?]', # 0x2b
'[?]', # 0x2c
'[?]', # 0x2d
'[?]', # 0x2e
'[?]', # 0x2f
'..', # 0x30
'--', # 0x31
'-', # 0x32
'_', # 0x33
'_', # 0x34
'(', # 0x35
') ', # 0x36
'{', # 0x37
'} ', # 0x38
'[', # 0x39
'] ', # 0x3a
'[(', # 0x3b
')] ', # 0x3c
'<<', # 0x3d
'>> ', # 0x3e
'<', # 0x3f
'> ', # 0x40
'[', # 0x41
'] ', # 0x42
'{', # 0x43
'}', # 0x44
'[?]', # 0x45
'[?]', # 0x46
'[?]', # 0x47
'[?]', # 0x48
'', # 0x49
'', # 0x4a
'', # 0x4b
'', # 0x4c
'', # 0x4d
'', # 0x4e
'', # 0x4f
',', # 0x50
',', # 0x51
'.', # 0x52
'', # 0x53
';', # 0x54
':', # 0x55
'?', # 0x56
'!', # 0x57
'-', # 0x58
'(', # 0x59
')', # 0x5a
'{', # 0x5b
'}', # 0x5c
'{', # 0x5d
'}', # 0x5e
'#', # 0x5f
'&', # 0x60
'*', # 0x61
'+', # 0x62
'-', # 0x63
'<', # 0x64
'>', # 0x65
'=', # 0x66
'', # 0x67
'\\', # 0x68
'$', # 0x69
'%', # 0x6a
'@', # 0x6b
'[?]', # 0x6c
'[?]', # 0x6d
'[?]', # 0x6e
'[?]', # 0x6f
'', # 0x70
'', # 0x71
'', # 0x72
'[?]', # 0x73
'', # 0x74
'[?]', # 0x75
'', # 0x76
'', # 0x77
'', # 0x78
'', # 0x79
'', # 0x7a
'', # 0x7b
'', # 0x7c
'', # 0x7d
'', # 0x7e
'', # 0x7f
'', # 0x80
'', # 0x81
'', # 0x82
'', # 0x83
'', # 0x84
'', # 0x85
'', # 0x86
'', # 0x87
'', # 0x88
'', # 0x89
'', # 0x8a
'', # 0x8b
'', # 0x8c
'', # 0x8d
'', # 0x8e
'', # 0x8f
'', # 0x90
'', # 0x91
'', # 0x92
'', # 0x93
'', # 0x94
'', # 0x95
'', # 0x96
'', # 0x97
'', # 0x98
'', # 0x99
'', # 0x9a
'', # 0x9b
'', # 0x9c
'', # 0x9d
'', # 0x9e
'', # 0x9f
'', # 0xa0
'', # 0xa1
'', # 0xa2
'', # 0xa3
'', # 0xa4
'', # 0xa5
'', # 0xa6
'', # 0xa7
'', # 0xa8
'', # 0xa9
'', # 0xaa
'', # 0xab
'', # 0xac
'', # 0xad
'', # 0xae
'', # 0xaf
'', # 0xb0
'', # 0xb1
'', # 0xb2
'', # 0xb3
'', # 0xb4
'', # 0xb5
'', # 0xb6
'', # 0xb7
'', # 0xb8
'', # 0xb9
'', # 0xba
'', # 0xbb
'', # 0xbc
'', # 0xbd
'', # 0xbe
'', # 0xbf
'', # 0xc0
'', # 0xc1
'', # 0xc2
'', # 0xc3
'', # 0xc4
'', # 0xc5
'', # 0xc6
'', # 0xc7
'', # 0xc8
'', # 0xc9
'', # 0xca
'', # 0xcb
'', # 0xcc
'', # 0xcd
'', # 0xce
'', # 0xcf
'', # 0xd0
'', # 0xd1
'', # 0xd2
'', # 0xd3
'', # 0xd4
'', # 0xd5
'', # 0xd6
'', # 0xd7
'', # 0xd8
'', # 0xd9
'', # 0xda
'', # 0xdb
'', # 0xdc
'', # 0xdd
'', # 0xde
'', # 0xdf
'', # 0xe0
'', # 0xe1
'', # 0xe2
'', # 0xe3
'', # 0xe4
'', # 0xe5
'', # 0xe6
'', # 0xe7
'', # 0xe8
'', # 0xe9
'', # 0xea
'', # 0xeb
'', # 0xec
'', # 0xed
'', # 0xee
'', # 0xef
'', # 0xf0
'', # 0xf1
'', # 0xf2
'', # 0xf3
'', # 0xf4
'', # 0xf5
'', # 0xf6
'', # 0xf7
'', # 0xf8
'', # 0xf9
'', # 0xfa
'', # 0xfb
'', # 0xfc
'[?]', # 0xfd
'[?]', # 0xfe
'', # 0xff
)
|
KurtDeGreeff/infernal-twin | refs/heads/master | build/pillow/build/lib.linux-i686-2.7/PIL/ImageFile.py | 26 | #
# The Python Imaging Library.
# $Id$
#
# base class for image file handlers
#
# history:
# 1995-09-09 fl Created
# 1996-03-11 fl Fixed load mechanism.
# 1996-04-15 fl Added pcx/xbm decoders.
# 1996-04-30 fl Added encoders.
# 1996-12-14 fl Added load helpers
# 1997-01-11 fl Use encode_to_file where possible
# 1997-08-27 fl Flush output in _save
# 1998-03-05 fl Use memory mapping for some modes
# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
# 1999-05-31 fl Added image parser
# 2000-10-12 fl Set readonly flag on memory-mapped images
# 2002-03-20 fl Use better messages for common decoder errors
# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
# 2003-10-30 fl Added StubImageFile class
# 2004-02-25 fl Made incremental parser more robust
#
# Copyright (c) 1997-2004 by Secret Labs AB
# Copyright (c) 1995-2004 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
from PIL import Image
from PIL._util import isPath
import io
import os
import sys
import traceback
MAXBLOCK = 65536
SAFEBLOCK = 1024*1024
LOAD_TRUNCATED_IMAGES = False
ERRORS = {
-1: "image buffer overrun error",
-2: "decoding error",
-3: "unknown error",
-8: "bad configuration",
-9: "out of memory error"
}
def raise_ioerror(error):
try:
message = Image.core.getcodecstatus(error)
except AttributeError:
message = ERRORS.get(error)
if not message:
message = "decoder error %d" % error
raise IOError(message + " when reading image file")
#
# --------------------------------------------------------------------
# Helpers
def _tilesort(t):
# sort on offset
return t[2]
#
# --------------------------------------------------------------------
# ImageFile base class
class ImageFile(Image.Image):
"Base class for image file format handlers."
def __init__(self, fp=None, filename=None):
Image.Image.__init__(self)
self.tile = None
self.readonly = 1 # until we know better
self.decoderconfig = ()
self.decodermaxblock = MAXBLOCK
if isPath(fp):
# filename
self.fp = open(fp, "rb")
self.filename = fp
else:
# stream
self.fp = fp
self.filename = filename
try:
self._open()
except IndexError as v: # end of data
if Image.DEBUG > 1:
traceback.print_exc()
raise SyntaxError(v)
except TypeError as v: # end of data (ord)
if Image.DEBUG > 1:
traceback.print_exc()
raise SyntaxError(v)
except KeyError as v: # unsupported mode
if Image.DEBUG > 1:
traceback.print_exc()
raise SyntaxError(v)
except EOFError as v: # got header but not the first frame
if Image.DEBUG > 1:
traceback.print_exc()
raise SyntaxError(v)
if not self.mode or self.size[0] <= 0:
raise SyntaxError("not identified by this driver")
def draft(self, mode, size):
"Set draft mode"
pass
def verify(self):
"Check file integrity"
# raise exception if something's wrong. must be called
# directly after open, and closes file when finished.
self.fp = None
def load(self):
"Load image data based on tile list"
pixel = Image.Image.load(self)
if self.tile is None:
raise IOError("cannot load this image")
if not self.tile:
return pixel
self.map = None
use_mmap = self.filename and len(self.tile) == 1
# As of pypy 2.1.0, memory mapping was failing here.
use_mmap = use_mmap and not hasattr(sys, 'pypy_version_info')
readonly = 0
# look for read/seek overrides
try:
read = self.load_read
# don't use mmap if there are custom read/seek functions
use_mmap = False
except AttributeError:
read = self.fp.read
try:
seek = self.load_seek
use_mmap = False
except AttributeError:
seek = self.fp.seek
if use_mmap:
# try memory mapping
d, e, o, a = self.tile[0]
if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES:
try:
if hasattr(Image.core, "map"):
# use built-in mapper
self.map = Image.core.map(self.filename)
self.map.seek(o)
self.im = self.map.readimage(
self.mode, self.size, a[1], a[2]
)
else:
# use mmap, if possible
import mmap
fp = open(self.filename, "r+")
size = os.path.getsize(self.filename)
# FIXME: on Unix, use PROT_READ etc
self.map = mmap.mmap(fp.fileno(), size)
self.im = Image.core.map_buffer(
self.map, self.size, d, e, o, a
)
readonly = 1
except (AttributeError, EnvironmentError, ImportError):
self.map = None
self.load_prepare()
if not self.map:
# sort tiles in file order
self.tile.sort(key=_tilesort)
try:
# FIXME: This is a hack to handle TIFF's JpegTables tag.
prefix = self.tile_prefix
except AttributeError:
prefix = b""
# Buffer length read; assign a default value
t = 0
for d, e, o, a in self.tile:
d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
seek(o)
try:
d.setimage(self.im, e)
except ValueError:
continue
b = prefix
t = len(b)
while True:
try:
s = read(self.decodermaxblock)
except IndexError as ie: # truncated png/gif
if LOAD_TRUNCATED_IMAGES:
break
else:
raise IndexError(ie)
if not s and not d.handles_eof: # truncated jpeg
self.tile = []
# JpegDecode needs to clean things up here either way
# If we don't destroy the decompressor,
# we have a memory leak.
d.cleanup()
if LOAD_TRUNCATED_IMAGES:
break
else:
raise IOError("image file is truncated "
"(%d bytes not processed)" % len(b))
b = b + s
n, e = d.decode(b)
if n < 0:
break
b = b[n:]
t = t + n
# Need to cleanup here to prevent leaks in PyPy
d.cleanup()
self.tile = []
self.readonly = readonly
self.fp = None # might be shared
if not self.map and (not LOAD_TRUNCATED_IMAGES or t == 0) and e < 0:
# still raised if decoder fails to return anything
raise_ioerror(e)
# post processing
if hasattr(self, "tile_post_rotate"):
# FIXME: This is a hack to handle rotated PCD's
self.im = self.im.rotate(self.tile_post_rotate)
self.size = self.im.size
self.load_end()
return Image.Image.load(self)
def load_prepare(self):
# create image memory if necessary
if not self.im or\
self.im.mode != self.mode or self.im.size != self.size:
self.im = Image.core.new(self.mode, self.size)
# create palette (optional)
if self.mode == "P":
Image.Image.load(self)
def load_end(self):
# may be overridden
pass
# may be defined for contained formats
# def load_seek(self, pos):
# pass
# may be defined for blocked formats (e.g. PNG)
# def load_read(self, bytes):
# pass
class StubImageFile(ImageFile):
"""
Base class for stub image loaders.
A stub loader is an image loader that can identify files of a
certain format, but relies on external code to load the file.
"""
def _open(self):
raise NotImplementedError(
"StubImageFile subclass must implement _open"
)
def load(self):
loader = self._load()
if loader is None:
raise IOError("cannot find loader for this %s file" % self.format)
image = loader.load(self)
assert image is not None
# become the other object (!)
self.__class__ = image.__class__
self.__dict__ = image.__dict__
def _load(self):
"(Hook) Find actual image loader."
raise NotImplementedError(
"StubImageFile subclass must implement _load"
)
class Parser(object):
"""
Incremental image parser. This class implements the standard
feed/close consumer interface.
In Python 2.x, this is an old-style class.
"""
incremental = None
image = None
data = None
decoder = None
offset = 0
finished = 0
def reset(self):
"""
(Consumer) Reset the parser. Note that you can only call this
method immediately after you've created a parser; parser
instances cannot be reused.
"""
assert self.data is None, "cannot reuse parsers"
def feed(self, data):
"""
(Consumer) Feed data to the parser.
:param data: A string buffer.
:exception IOError: If the parser failed to parse the image file.
"""
# collect data
if self.finished:
return
if self.data is None:
self.data = data
else:
self.data = self.data + data
# parse what we have
if self.decoder:
if self.offset > 0:
# skip header
skip = min(len(self.data), self.offset)
self.data = self.data[skip:]
self.offset = self.offset - skip
if self.offset > 0 or not self.data:
return
n, e = self.decoder.decode(self.data)
if n < 0:
# end of stream
self.data = None
self.finished = 1
if e < 0:
# decoding error
self.image = None
raise_ioerror(e)
else:
# end of image
return
self.data = self.data[n:]
elif self.image:
# if we end up here with no decoder, this file cannot
# be incrementally parsed. wait until we've gotten all
# available data
pass
else:
# attempt to open this file
try:
try:
fp = io.BytesIO(self.data)
im = Image.open(fp)
finally:
fp.close() # explicitly close the virtual file
except IOError:
# traceback.print_exc()
pass # not enough data
else:
flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
if flag or len(im.tile) != 1:
# custom load code, or multiple tiles
self.decode = None
else:
# initialize decoder
im.load_prepare()
d, e, o, a = im.tile[0]
im.tile = []
self.decoder = Image._getdecoder(
im.mode, d, a, im.decoderconfig
)
self.decoder.setimage(im.im, e)
# calculate decoder offset
self.offset = o
if self.offset <= len(self.data):
self.data = self.data[self.offset:]
self.offset = 0
self.image = im
def close(self):
"""
(Consumer) Close the stream.
:returns: An image object.
:exception IOError: If the parser failed to parse the image file either
because it cannot be identified or cannot be
decoded.
"""
# finish decoding
if self.decoder:
# get rid of what's left in the buffers
self.feed(b"")
self.data = self.decoder = None
if not self.finished:
raise IOError("image was incomplete")
if not self.image:
raise IOError("cannot parse this image")
if self.data:
# incremental parsing not possible; reopen the file
# not that we have all data
try:
fp = io.BytesIO(self.data)
self.image = Image.open(fp)
finally:
self.image.load()
fp.close() # explicitly close the virtual file
return self.image
# --------------------------------------------------------------------
def _save(im, fp, tile, bufsize=0):
"""Helper to save image based on tile list
:param im: Image object.
:param fp: File object.
:param tile: Tile list.
:param bufsize: Optional buffer size
"""
im.load()
if not hasattr(im, "encoderconfig"):
im.encoderconfig = ()
tile.sort(key=_tilesort)
# FIXME: make MAXBLOCK a configuration parameter
# It would be great if we could have the encoder specify what it needs
# But, it would need at least the image size in most cases. RawEncode is
# a tricky case.
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
try:
fh = fp.fileno()
fp.flush()
except (AttributeError, io.UnsupportedOperation):
# compress to Python file-compatible object
for e, b, o, a in tile:
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
if o > 0:
fp.seek(o, 0)
e.setimage(im.im, b)
while True:
l, s, d = e.encode(bufsize)
fp.write(d)
if s:
break
if s < 0:
raise IOError("encoder error %d when writing image file" % s)
e.cleanup()
else:
# slight speedup: compress to real file object
for e, b, o, a in tile:
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
if o > 0:
fp.seek(o, 0)
e.setimage(im.im, b)
s = e.encode_to_file(fh, bufsize)
if s < 0:
raise IOError("encoder error %d when writing image file" % s)
e.cleanup()
try:
fp.flush()
except:
pass
def _safe_read(fp, size):
"""
Reads large blocks in a safe way. Unlike fp.read(n), this function
doesn't trust the user. If the requested size is larger than
SAFEBLOCK, the file is read block by block.
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes to read.
:returns: A string containing up to <i>size</i> bytes of data.
"""
if size <= 0:
return b""
if size <= SAFEBLOCK:
return fp.read(size)
data = []
while size > 0:
block = fp.read(min(size, SAFEBLOCK))
if not block:
break
data.append(block)
size -= len(block)
return b"".join(data)
|
dudw/gfwlist2pac | refs/heads/master | gfwlist2pac/resources/__init__.py | 186 | #!/usr/bin/python
# -*- coding: utf-8 -*-
|
rosenbrockc/dft | refs/heads/master | pydft/solvers/__init__.py | 12133432 | |
rebeling/pattern | refs/heads/master | pattern/web/docx/__init__.py | 12133432 | |
MDI2017/hide_and_seek | refs/heads/master | jugadores/__init__.py | 12133432 | |
octopus-platform/octopus | refs/heads/master | python/octopus-tools/octopus/importer/__init__.py | 12133432 | |
EricCline/CEM_inc | refs/heads/master | env/lib/python2.7/site-packages/django/contrib/localflavor/pt/__init__.py | 12133432 | |
b-me/django | refs/heads/master | django/contrib/staticfiles/templatetags/__init__.py | 12133432 | |
duedil-ltd/pyfilesystem | refs/heads/master | fs/expose/__init__.py | 12133432 | |
bratsche/Neutron-Drive | refs/heads/master | google_appengine/lib/django_1_2/tests/regressiontests/model_inheritance_regress/__init__.py | 12133432 | |
yeming233/horizon | refs/heads/master | openstack_dashboard/dashboards/admin/flavors/__init__.py | 12133432 | |
MySideEffect-Team/MySideEffect | refs/heads/master | MySideEffectMain/MySideEffectApp/__init__.py | 12133432 | |
jyt109/termite-data-server | refs/heads/master | web2py/gluon/contrib/login_methods/oauth10a_account.py | 16 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Written by Michele Comitini <mcm@glisco.it>
License: GPL v3
Adds support for OAuth1.0a authentication to web2py.
Dependencies:
- python-oauth2 (http://github.com/simplegeo/python-oauth2)
"""
import oauth2 as oauth
import cgi
from urllib import urlencode
from gluon import current
class OAuthAccount(object):
"""
Login will be done via OAuth Framework, instead of web2py's
login form.
Include in your model (eg db.py)::
# define the auth_table before call to auth.define_tables()
auth_table = db.define_table(
auth.settings.table_user_name,
Field('first_name', length=128, default=""),
Field('last_name', length=128, default=""),
Field('username', length=128, default="", unique=True),
Field('password', 'password', length=256,
readable=False, label='Password'),
Field('registration_key', length=128, default= "",
writable=False, readable=False))
auth_table.username.requires = IS_NOT_IN_DB(db, auth_table.username)
.
.
.
auth.define_tables()
.
.
.
CLIENT_ID=\"<put your fb application id here>\"
CLIENT_SECRET=\"<put your fb application secret here>\"
AUTH_URL="..."
TOKEN_URL="..."
ACCESS_TOKEN_URL="..."
from gluon.contrib.login_methods.oauth10a_account import OAuthAccount
auth.settings.login_form=OAuthAccount(globals(
),CLIENT_ID,CLIENT_SECRET, AUTH_URL, TOKEN_URL, ACCESS_TOKEN_URL)
"""
def __redirect_uri(self, next=None):
"""Build the uri used by the authenticating server to redirect
the client back to the page originating the auth request.
Appends the _next action to the generated url so the flows continues.
"""
r = self.request
http_host = r.env.http_host
url_scheme = r.env.wsgi_url_scheme
if next:
path_info = next
else:
path_info = r.env.path_info
uri = '%s://%s%s' % (url_scheme, http_host, path_info)
if r.get_vars and not next:
uri += '?' + urlencode(r.get_vars)
return uri
def accessToken(self):
"""Return the access token generated by the authenticating server.
If token is already in the session that one will be used.
Otherwise the token is fetched from the auth server.
"""
if self.session.access_token:
# return the token (TODO: does it expire?)
return self.session.access_token
if self.session.request_token:
# Exchange the request token with an authorization token.
token = self.session.request_token
self.session.request_token = None
# Build an authorized client
# OAuth1.0a put the verifier!
token.set_verifier(self.request.vars.oauth_verifier)
client = oauth.Client(self.consumer, token)
resp, content = client.request(self.access_token_url, "POST")
if str(resp['status']) != '200':
self.session.request_token = None
self.globals['redirect'](self.globals[
'URL'](f='user', args='logout'))
self.session.access_token = oauth.Token.from_string(content)
return self.session.access_token
self.session.access_token = None
return None
def __init__(self, g, client_id, client_secret, auth_url, token_url, access_token_url, socket_timeout=60):
self.globals = g
self.client_id = client_id
self.client_secret = client_secret
self.code = None
self.request = current.request
self.session = current.session
self.auth_url = auth_url
self.token_url = token_url
self.access_token_url = access_token_url
self.socket_timeout = socket_timeout
# consumer init
self.consumer = oauth.Consumer(self.client_id, self.client_secret)
def login_url(self, next="/"):
self.__oauth_login(next)
return next
def logout_url(self, next="/"):
self.session.request_token = None
self.session.access_token = None
return next
def get_user(self):
'''Get user data.
Since OAuth does not specify what a user
is, this function must be implemented for the specific
provider.
'''
raise NotImplementedError("Must override get_user()")
def __oauth_login(self, next):
'''This method redirects the user to the authenticating form
on authentication server if the authentication code
and the authentication token are not available to the
application yet.
Once the authentication code has been received this method is
called to set the access token into the session by calling
accessToken()
'''
if not self.accessToken():
# setup the client
client = oauth.Client(self.consumer, None, timeout=self.socket_timeout)
# Get a request token.
# oauth_callback *is REQUIRED* for OAuth1.0a
# putting it in the body seems to work.
callback_url = self.__redirect_uri(next)
data = urlencode(dict(oauth_callback=callback_url))
resp, content = client.request(self.token_url, "POST", body=data)
if resp['status'] != '200':
self.session.request_token = None
self.globals['redirect'](self.globals[
'URL'](f='user', args='logout'))
# Store the request token in session.
request_token = self.session.request_token = oauth.Token.from_string(content)
# Redirect the user to the authentication URL and pass the callback url.
data = urlencode(dict(oauth_token=request_token.key,
oauth_callback=callback_url))
auth_request_url = self.auth_url + '?' + data
HTTP = self.globals['HTTP']
raise HTTP(302,
"You are not authenticated: you are being redirected to the <a href='" + auth_request_url + "'> authentication server</a>",
Location=auth_request_url)
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.