def test_sip_api_already_set(): """Raise ImportError if sip API v1 was already set""" __import__("PyQt4.QtCore") # Bypass linter warning import sip sip.setapi("QString", 1) assert_raises(ImportError, __import__, "Qt")
def prepare_pyqt4(): # For PySide compatibility, use the new-style string API that automatically # converts QStrings to Unicode Python strings. Also, automatically unpack # QVariants to their underlying objects. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2)
def _setup_pyqt4_internal(api): global QtCore, QtGui, QtWidgets, \ __version__, is_pyqt5, _getSaveFileName # List of incompatible APIs: # http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html _sip_apis = ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"] try: import sip except ImportError: pass else: for _sip_api in _sip_apis: try: sip.setapi(_sip_api, api) except ValueError: pass from PyQt4 import QtCore, QtGui __version__ = QtCore.PYQT_VERSION_STR # PyQt 4.6 introduced getSaveFileNameAndFilter: # https://riverbankcomputing.com/news/pyqt-46 if __version__ < LooseVersion("4.6"): raise ImportError("PyQt<4.6 is not supported") QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot QtCore.Property = QtCore.pyqtProperty _getSaveFileName = QtGui.QFileDialog.getSaveFileNameAndFilter
def importPyQt(): try: import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) from PyQt4 import QtCore, QtGui, QtNetwork, QtWebKit, uic from PyQt4.QtCore import pyqtSignal as Signal, pyqtSlot as Slot, \ pyqtProperty as Property QtUiTools = object() def loadUI(uiFilename, parent=None): newWidget = uic.loadUi(uiFilename) newWidget.setParent(parent) return newWidget logger.info("Successfully initialized PyQt4.") globals().update( QtCore=QtCore, QtGui=QtGui, QtNetwork=QtNetwork, QtWebKit=QtWebKit, QtUiTools=QtUiTools, Signal=Signal, Slot=Slot, Property=Property, loadUI=loadUI, binding="PyQt4", ) return True except ImportError: return False
def import_pyqt4(version=2): """ Import PyQt4 Parameters ---------- version : 1, 2, or None Which QString/QVariant API to use. Set to None to use the system default ImportErrors rasied within this function are non-recoverable """ # The new-style string API (version=2) automatically # converts QStrings to Unicode Python strings. Also, automatically unpacks # QVariants to their underlying objects. import sip if version is not None: sip.setapi('QString', version) sip.setapi('QVariant', version) from PyQt4 import QtGui, QtCore, QtSvg if not check_version(QtCore.PYQT_VERSION_STR, '4.7'): raise ImportError("IPython requires PyQt4 >= 4.7, found %s" % QtCore.PYQT_VERSION_STR) # Alias PyQt-specific functions for PySide compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # query for the API version (in case version == None) version = sip.getapi('QString') api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT return QtCore, QtGui, QtSvg, api
def setup_apiv2(): """ Setup apiv2 when using PyQt4 and Python2. """ # setup PyQt api to version 2 if sys.version_info[0] == 2: import sip if _api_version: default = _api_version apis = [ ("QDate", default), ("QDateTime", default), ("QString", default), ("QTextStream", default), ("QTime", default), ("QUrl", default), ("QVariant", default), ("QFileDialog", default), ] for name, version in apis: try: sip.setapi(name, version) except ValueError: logging.getLogger(__name__).critical("failed to set up sip api to version 2 for PyQt4") raise ImportError('PyQt4') from PyQt4.QtCore import PYQT_VERSION_STR as __version__
def set_sip_api(): import sip api2_classes = [ 'QData', 'QDateTime', 'QString', 'QTextStream', 'QTime', 'QUrl', 'QVariant', ] for cl in api2_classes: sip.setapi(cl, 2)
def setNewPyQtAPI(): try: import sip # We now use the new PyQt API - IPython needs it sip.setapi('QString', 2) sip.setapi('QVariant', 2) except Exception: print "Could not set PyQt API, is PyQt4 installed?"
def load_module(fullname): if fullname in _sys.modules: return _sys.modules[fullname] _, name = fullname.split('.') global qt if qt: # If a Qt implementation was already selected previously # and the selected module is the same as the one being imported, # then return it, otherwise False. if qt.__name__ == name: _sys.modules[fullname] = qt; return qt else: _sys.modules[fullname] = False; return False if name == 'PyQt4' and _sys.version_info[0] == 2: # Select API version 2, this is needed only for PyQt4 on Python 2.x try: import sip for api in ['QDate', 'QDateTime', 'QString', 'QTextStream', 'QTime', 'QUrl', 'QVariant']: try: sip.setapi(api, 2) except Exception: pass except Exception: pass # The selection of Qt implementation is successful only if its QtCore # module can be imported. try: qt = __import__(name + '.QtCore') except ImportError: _sys.modules[fullname] = False; return False core = qt.QtCore # Turn `QtCore.Qt` object into a package, # because `import qt` will actually give this object. core.Qt.__path__ = [] core.Qt.__package__ = 'qt' # Put some additional attributes into `qt`. core.Qt.module = name core.Qt.version_str = core.qVersion() core.Qt.major = int(core.Qt.version_str.split('.', 1)[0]) if name.startswith('PyQt'): core.Qt.module_version_str = core.PYQT_VERSION_STR core.Signal = core.pyqtSignal core.Slot = core.pyqtSlot else: core.Qt.module_version_str = qt.__version__ core.Qt.Signal = core.Signal core.Qt.Slot = core.Slot _sys.modules[fullname] = qt; return qt
def update_apis(apis='QDate QDateTime QString QTextStream QTime QUrl QVariant'.split()): import sys if sys.version_info.major==2: import sip for api in apis: try: sip.setapi(api, 2) except: pass
def _initPyQt4(): """initialize PyQt4 to be compatible with PySide""" if 'PyQt4.QtCore' in sys.modules: # too late to configure API pass else: import sip sip.setapi("QString", 2) sip.setapi("QVariant", 2)
def _checkDependencies(profiler): """Check if 3rdparty software is installed in the system. Notify user, how to install it """ _SEE_SITE_PLAIN = 'See http://enki-editor.org/install-sources.html' _SEE_SITE_HTML = \ 'See <a href="http://enki-editor.org/install-sources.html">' \ 'installation instructions</a>' try: import PyQt5 except ImportError as ex: plain = 'Failed to import Qt4 python bindings:\n{}\n{}'.format(str(ex), _SEE_SITE_PLAIN) _showErrorMessage(False, 'PyQt5 not found', plain, plain) raise ex import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) profiler.stepDone('Import PyQt5') try: import qutepart except ImportError as ex: html = "<html>" + \ "Failed to import qutepart.<br/>" \ "See <a href=\"https://github.com/hlamer/qutepart\">qutepart site</a><br/>" \ "Exception:<br/>" + \ str(ex) + '<br/>' + \ _SEE_SITE_HTML + \ "</html>" plain = "Failed to import qutepart.\n" \ "See https://github.com/hlamer/qutepart\n" + \ str(ex) + '\n' + \ _SEE_SITE_PLAIN _showErrorMessage(True, "Qutepart not found", html, plain) raise ex profiler.stepDone('Import Qutepart') if qutepart.VERSION[0] != enki.core.defines.QUTEPART_SUPPORTED_MAJOR or \ qutepart.VERSION[1] < enki.core.defines.QUTEPART_SUPPORTED_MINOR: text = "Qutepart version not supported\n" + \ "This Enki version requires Qutepart {}.>={}.*\n". \ format(enki.core.defines.QUTEPART_SUPPORTED_MAJOR, enki.core.defines.QUTEPART_SUPPORTED_MINOR) + \ "But {}.{}.{} is detected\n\n".format(*qutepart.VERSION) html = "<html>" + text.replace('\n', '<br/>') + \ _SEE_SITE_HTML + \ "</html>" plain = text + _SEE_SITE_PLAIN _showErrorMessage(True, "Not supported Qutepart version", html, plain) raise ImportError('Not supported Qutepart')
def test_sip_api_1_2(): """sip=1, hint=2 == WARNING""" import sip sip.setapi("QString", 1) os.environ["QT_SIP_API_HINT"] = "2" with captured_output() as out: __import__("Qt") # Bypass linter warning stdout, stderr = out assert stderr.getvalue().startswith("Warning:")
def _initPyQt4(): """initialize PyQt4 to be compatible with PySide""" import sip if 'PyQt4.QtCore' in sys.modules: # too late to configure API, let's check that it was properly parameterized... for api in ('QVariant', 'QString'): if sip.getapi(api) != 2: raise RuntimeError('%s API already set to V%d, but should be 2' % (api, sip.getapi(api))) else: sip.setapi("QString", 2) sip.setapi("QVariant", 2)
def setup_apiv2(): """ Setup apiv2 when using PyQt4 and Python2. """ # setup PyQt api to version 2 if sys.version_info[0] == 2: logging.getLogger(__name__).debug('setting up SIP API to version 2') import sip try: sip.setapi("QString", 2) sip.setapi("QVariant", 2) except ValueError: logging.getLogger(__name__).critical( "failed to set up sip api to version 2 for PyQt4") raise ImportError('PyQt4')
def load_pyqt4(): """Sets up PyQt4 nicely to be PySide-compatible as much as possible.""" # Kill off QString and QVariant to make it act properly like PySide import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) from PyQt4 import QtCore QtCore._QT_ENGINE = 'PyQt4' # Also rename the pyqt things for compatibility. QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot QtCore.Property = QtCore.pyqtProperty global IS_PYQT4 IS_PYQT4 = True
def get_qt(): qtapi = os.environ.get('QT_API', 'pyqt') # Try PyQt4 if qtapi == 'pyqt' or qtapi == 'pyqt4': try: PyQt4 = __import__('PyQt4') imp.find_module('QtCore', PyQt4.__path__) imp.find_module('QtGui', PyQt4.__path__) import sip except ImportError: pass else: api2_classes = [ 'QData', 'QDateTime', 'QString', 'QTextStream', 'QTime', 'QUrl', 'QVariant' ] for cl in api2_classes: try: sip.setapi(cl, 2) except ValueError: pass import PyQt4.QtCore import PyQt4.QtGui os.environ['QT_API'] = 'pyqt' return PyQt4, qtapi # Try PyQt5 if qtapi == 'pyqt5': try: PyQt5 = __import__('PyQt5') imp.find_module('QtCore', PyQt5.__path__) imp.find_module('QtGui', PyQt5.__path__) except ImportError: pass else: import PyQt5.QtCore import PyQt5.QtGui import PyQt5.QtWidgets os.environ['QT_API'] = 'pyqt5' return PyQt5, qtapi # Oh no sys.stderr.write("'file_archive view' requires either PyQt4 or PyQt5\n") if 'QT_API' in os.environ: sys.stderr.write("QT_API is currently set to '%s', which is not " "supported\n" % qtapi) sys.exit(3)
def ets(self, parameter_s=''): """Choose backend for ETS GUI %ets wx|qt """ opts, arg = self.parse_options(parameter_s, '') if arg == "qt": import sip, os sip.setapi('QString', 2) sip.setapi('QVariant', 2) os.environ['ETS_TOOLKIT'] = 'qt4' elif arg == "wx": import os os.environ['ETS_TOOLKIT'] = 'wx' else: from IPython.utils.warn import error error("argument of ets must be wx or qt") self.shell.enable_gui(arg)
def run(self): import unittest import sip sip.setapi("QString", 2) sip.setapi("QVariant", 2) names = [] for filename in glob.glob("test/test_*.py"): name = os.path.splitext(os.path.basename(filename))[0] if not self.tests or name in self.tests: names.append("test." + name) tests = unittest.defaultTestLoader.loadTestsFromNames(names) t = unittest.TextTestRunner(verbosity=self.verbosity) testresult = t.run(tests) if not testresult.wasSuccessful(): sys.exit("At least one test failed.")
def __setPyQt4API(element, api_version=2): try: ver = sip.getapi(element) except ValueError: ver = -1 if ver < 0: try: sip.setapi(element, api_version) log.debug("%s API set to version %d", element, sip.getapi("QString")) except ValueError: log.warning("Error setting %s API to version %s", element, api_version, exc_info=1) return False elif ver < api_version: log.info("%s API set to version %s (advised: version >= %s)", element, ver, api_version) return True
def importPyQt(): try: if "PyQt4" in sys.modules: return True import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) required_modules = ["QtCore", "QtGui", "QtNetwork", "QtWebKit", "uic"] for module_name in required_modules: _named_import('PyQt4.%s' % module_name) from PyQt4.QtCore import pyqtSignal as Signal from PyQt4.QtCore import pyqtSlot as Slot from PyQt4.QtCore import pyqtProperty as Property QtUiTools = object() def loadUi(uifile, parent=None): newWidget = uic.loadUi(uifile, parent) return newWidget si.LogMessage("[PyQtForSoftimage] Successfully initialized PyQt4.", C.siInfo) globals().update( QtCore=QtCore, QtGui=QtGui, QtNetwork=QtNetwork, QtWebKit=QtWebKit, QtUiTools=QtUiTools, Signal=Signal, Slot=Slot, Property=Property, loadUi=loadUi, binding="PyQt4", ) return True except ImportError: return False
def getPyQt4Context( ): "Get a Qt context for using PyQt4 inside of python." import sip as sipModule import PyQt4 as PyQt4Module try: sipModule.setapi('QString', 2) sipModule.setapi('QVariant', 2) except: print( "qt : Cannot force PyQt4 to APIv2 mode, potential data conversion problems with QString and QVariant classes." ) import_module = lambda moduleName : getattr( __import__(PyQt4Module.__name__, globals(), locals(), [moduleName], -1), moduleName) import_module("QtCore") import_module("QtGui") Signal = PyQt4Module.QtCore.pyqtSignal Slot = PyQt4Module.QtCore.pyqtSlot Property = PyQt4Module.QtCore.pyqtProperty return QtContext( PyQt4Module, PyQt4Module.QtCore, PyQt4Module.QtGui, Signal, Slot, Property, import_module, "PyQt4" )
def get_pronunciation(text): """ A set of hacks that are pulled togeher to run awesometts and produce pronunciation for a word. """ import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) sip.setapi('QUrl', 2) from PyQt4.QtGui import QApplication from PyQt4.QtCore import QTimer sound_path = [None] app = QApplication([]) def fake_awesometts(): class FakeAddons(object): def GetAddons(self): return [] GetAddons.__bases__ = [object] import aqt aqt.addons = FakeAddons() sys.path.insert(0, expanduser('~/Documents/Anki/addons')) import awesometts #text = 'furfurfur' # text = 'smear' group = {u'presets': [u'Howjsay (en)', u'Oxford Dictionary (en-US)', u'Collins (en)', u'Google Translate (en-US)', u'Baidu Translate (en)', u'ImTranslator (VW Paul)'], u'mode': u'ordered'} presets = {u'ImTranslator (VW Paul)': {u'voice': u'VW Paul', u'speed': 0, u'service': u'imtranslator'}, u'Linguatec (ko, Sora)': {u'voice': u'Sora', u'service': u'linguatec'}, u'Collins (en)': {u'voice': u'en', u'service': u'collins'}, u'NeoSpeech (ko, Jihun)': {u'voice': u'Jihun', u'service': u'neospeech'}, u'Baidu Translate (en)': {u'voice': u'en', u'service': u'baidu'}, u'Google Translate (en-US)': {u'voice': u'en-US', u'service': u'google'}, u'Acapela Group (ko, Minji)': {u'voice': u'Minji', u'service': u'acapela'}, u'ImTranslator (ko, VW Yumi)': {u'voice': u'VW Yumi', u'speed': 0, u'service': u'imtranslator'}, u'Howjsay (en)': {u'voice': u'en', u'service': u'howjsay'}, u'Oxford Dictionary (en-US)': {u'voice': u'en-US', u'service': u'oxford'}, u'NAVER Translate (ko)': {u'voice': u'ko', u'service': u'naver'}} def on_okay(path): sound_path[0] = path app.quit() def on_fail(path): app.quit() callbacks = { 'okay': on_okay, 'fail': on_fail, } #{'fail': <function fail at 0x7fe53b8aa668>, 'then': <function <lambda> at 0x7fe53b8aa758>, 'done': <function done at 0x7fe55084fed8>, 'okay': <function okay at 0x7fe550afa758>, 'miss': <function miss at 0x7fe53b8aa6e0>} want_human = False note = None # <anki.notes.Note object at 0x7fe550871990> awesometts.router._logger = _logger awesometts.router.group(text, group, presets, callbacks, want_human, note) # fake_awesometts() QTimer.singleShot(1, fake_awesometts) app.exec_() return sound_path[0]
elif 'PyQt5.QtCore' in sys.modules: BINDING = 'PyQt5' elif 'PyQt4.QtCore' in sys.modules: BINDING = 'PyQt4' else: # Then try Qt bindings try: import PyQt5.QtCore # noqa except ImportError: if 'PyQt5' in sys.modules: del sys.modules["PyQt5"] try: import sip sip.setapi("QString", 2) sip.setapi("QVariant", 2) sip.setapi('QDate', 2) sip.setapi('QDateTime', 2) sip.setapi('QTextStream', 2) sip.setapi('QTime', 2) sip.setapi('QUrl', 2) import PyQt4.QtCore # noqa except ImportError: if 'PyQt4' in sys.modules: del sys.modules["sip"] del sys.modules["PyQt4"] try: import PySide2.QtCore # noqa except ImportError: if 'PySide2' in sys.modules:
# Copyright (c) 2016 Detlev Offenbach <*****@*****.**> # # This is the install script for the eric6 debug client. It may be used # to just install the debug clients for remote debugging. # """ Installation script for the eric6 debug clients. """ from __future__ import unicode_literals, print_function try: import cStringIO as io import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) sip.setapi('QTextStream', 2) except (ImportError): import io # __IGNORE_WARNING__ import sys import os import re import compileall import shutil import fnmatch import distutils.sysconfig # Define the globals. progName = None
import os import sys try: from PySide2 import QtCore, QtGui, QtWidgets from PySide2.QtCore import Qt except ImportError: try: from PySide import QtCore, QtGui, QtGui as QtWidgets from PySide.QtCore import Qt except ImportError: import sip for mod in ("QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"): sip.setapi(mod, 2) from PyQt4 import QtCore, QtGui from PyQt4.QtCore import Qt QtCore.Signal = QtCore.pyqtSignal def find_menu_items(menu, _path=None): """Extracts items from a given Nuke menu Returns a list of strings, with the path to each item Ignores divider lines and hidden items (ones like "@;&CopyBranch" for shift+k) >>> found = find_menu_items(nuke.menu("Nodes")) >>> found.sort()
def _pyqt4(): """Initialise PyQt4""" import sip # Validation of envivornment variable. Prevents an error if # the variable is invalid since it's just a hint. try: hint = int(QT_SIP_API_HINT) except TypeError: hint = None # Variable was None, i.e. not set. except ValueError: raise ImportError("QT_SIP_API_HINT=%s must be a 1 or 2") for api in ("QString", "QVariant", "QDate", "QDateTime", "QTextStream", "QTime", "QUrl"): try: sip.setapi(api, hint or 2) except AttributeError: raise ImportError("PyQt4 < 4.6 isn't supported by Qt.py") except ValueError: actual = sip.getapi(api) if not hint: raise ImportError("API version already set to %d" % actual) else: # Having provided a hint indicates a soft constraint, one # that doesn't throw an exception. sys.stderr.write( "Warning: API '%s' has already been set to %d.\n" % (api, actual)) import PyQt4 as module _setup(module, ["uic"]) if hasattr(Qt, "_uic"): Qt.QtCompat.loadUi = _loadUi if hasattr(Qt, "_QtGui"): setattr(Qt, "QtWidgets", _new_module("QtWidgets")) setattr(Qt, "_QtWidgets", Qt._QtGui) Qt.QtCompat.setSectionResizeMode = \ Qt._QtGui.QHeaderView.setResizeMode if hasattr(Qt, "_QtCore"): Qt.QtCore.QAbstractProxyModel = Qt._QtGui.QAbstractProxyModel Qt.QtCore.QSortFilterProxyModel = Qt._QtGui.QSortFilterProxyModel Qt.QtCore.QItemSelection = Qt._QtGui.QItemSelection Qt.QtCore.QStringListModel = Qt._QtGui.QStringListModel Qt.QtCore.QItemSelectionModel = Qt._QtGui.QItemSelectionModel Qt.QtCore.QItemSelectionRange = Qt._QtGui.QItemSelectionRange if hasattr(Qt, "_QtCore"): Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR Qt.QtCore.Property = Qt._QtCore.pyqtProperty Qt.QtCore.Signal = Qt._QtCore.pyqtSignal Qt.QtCore.Slot = Qt._QtCore.pyqtSlot QCoreApplication = Qt._QtCore.QCoreApplication Qt.QtCompat.translate = ( lambda context, sourceText, disambiguation, n: QCoreApplication. translate(context, sourceText, disambiguation, QCoreApplication. CodecForTr, n))
# (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. #------------------------------------------------------------------------------- ''' Created on Dec 1, 2011 @author: thygrrr ''' # CRUCIAL: This must remain on top. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) sip.setapi('QStringList', 2) sip.setapi('QList', 2) sip.setapi('QProcess', 2) import sys from PyQt4 import QtGui #Set up a robust logging system import util util.startLogging() excepthook_original = sys.excepthook
def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2)
def test_sip_api_1_1(): """sip=1, hint=1 == OK""" import sip sip.setapi("QString", 1) os.environ["QT_SIP_API_HINT"] = "1" __import__("Qt") # Bypass linter warning
def set_qt_api(self, api): self.pytest_qt_api = self._get_qt_api_from_env( ) or api or self._guess_qt_api() if not self.pytest_qt_api: # pragma: no cover msg = 'pytest-qt requires either PySide, PySide2, PyQt4 or PyQt5 to be installed' raise RuntimeError(msg) _root_modules = { 'pyside': 'PySide', 'pyside2': 'PySide2', 'pyqt4': 'PyQt4', 'pyqt4v2': 'PyQt4', 'pyqt5': 'PyQt5', } _root_module = _root_modules[self.pytest_qt_api] def _import_module(module_name): m = __import__(_root_module, globals(), locals(), [module_name], 0) return getattr(m, module_name) if self.pytest_qt_api == 'pyqt4v2': # pragma: no cover # the v2 api in PyQt4 # http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html import sip sip.setapi("QDate", 2) sip.setapi("QDateTime", 2) sip.setapi("QString", 2) sip.setapi("QTextStream", 2) sip.setapi("QTime", 2) sip.setapi("QUrl", 2) sip.setapi("QVariant", 2) self.QtCore = QtCore = _import_module('QtCore') self.QtGui = QtGui = _import_module('QtGui') self.QtTest = _import_module('QtTest') self.Qt = QtCore.Qt self.QEvent = QtCore.QEvent self.qDebug = QtCore.qDebug self.qWarning = QtCore.qWarning self.qCritical = QtCore.qCritical self.qFatal = QtCore.qFatal self.QtDebugMsg = QtCore.QtDebugMsg self.QtWarningMsg = QtCore.QtWarningMsg self.QtCriticalMsg = QtCore.QtCriticalMsg self.QtFatalMsg = QtCore.QtFatalMsg # Qt4 and Qt5 have different functions to install a message handler; # the plugin will try to use the one that is not None self.qInstallMsgHandler = None self.qInstallMessageHandler = None if self.pytest_qt_api.startswith('pyside'): self.Signal = QtCore.Signal self.Slot = QtCore.Slot self.Property = QtCore.Property self.QStringListModel = QtGui.QStringListModel self.QStandardItem = QtGui.QStandardItem self.QStandardItemModel = QtGui.QStandardItemModel self.QAbstractListModel = QtCore.QAbstractListModel self.QAbstractTableModel = QtCore.QAbstractTableModel self.QStringListModel = QtGui.QStringListModel if self.pytest_qt_api == 'pyside2': _QtWidgets = _import_module('QtWidgets') self.QApplication = _QtWidgets.QApplication self.QWidget = _QtWidgets.QWidget self.QLineEdit = _QtWidgets.QLineEdit self.qInstallMessageHandler = QtCore.qInstallMessageHandler self.QSortFilterProxyModel = QtCore.QSortFilterProxyModel else: self.QApplication = QtGui.QApplication self.QWidget = QtGui.QWidget self.QLineEdit = QtGui.QLineEdit self.qInstallMsgHandler = QtCore.qInstallMsgHandler self.QSortFilterProxyModel = QtGui.QSortFilterProxyModel def extract_from_variant(variant): """PySide does not expose QVariant API""" return variant def make_variant(value=None): """PySide does not expose QVariant API""" return value self.extract_from_variant = extract_from_variant self.make_variant = make_variant elif self.pytest_qt_api in ('pyqt4', 'pyqt4v2', 'pyqt5'): self.Signal = QtCore.pyqtSignal self.Slot = QtCore.pyqtSlot self.Property = QtCore.pyqtProperty if self.pytest_qt_api == 'pyqt5': _QtWidgets = _import_module('QtWidgets') self.QApplication = _QtWidgets.QApplication self.QWidget = _QtWidgets.QWidget self.qInstallMessageHandler = QtCore.qInstallMessageHandler self.QStringListModel = QtCore.QStringListModel self.QSortFilterProxyModel = QtCore.QSortFilterProxyModel def extract_from_variant(variant): """not needed in PyQt5: Qt API always returns pure python objects""" return variant def make_variant(value=None): """Return a QVariant object from the given Python builtin""" # PyQt4 doesn't allow one to instantiate any QVariant at all: # QVariant represents a mapped type and cannot be instantiated return QtCore.QVariant(value) else: self.QApplication = QtGui.QApplication self.QWidget = QtGui.QWidget self.qInstallMsgHandler = QtCore.qInstallMsgHandler self.QStringListModel = QtGui.QStringListModel self.QSortFilterProxyModel = QtGui.QSortFilterProxyModel def extract_from_variant(variant): """returns python object from the given QVariant""" if isinstance(variant, QtCore.QVariant): return variant.toPyObject() return variant def make_variant(value=None): """Return a QVariant object from the given Python builtin""" # PyQt4 doesn't allow one to instantiate any QVariant at all: # QVariant represents a mapped type and cannot be instantiated return value self.QStandardItem = QtGui.QStandardItem self.QStandardItemModel = QtGui.QStandardItemModel self.QAbstractListModel = QtCore.QAbstractListModel self.QAbstractTableModel = QtCore.QAbstractTableModel self.extract_from_variant = extract_from_variant self.make_variant = make_variant
import sys, os os.environ['PYTHONIOENCODING'] = 'utf-8' srcPath = os.path.abspath(os.path.join("source")) sys.path.append(srcPath) sys.path.append(".") import sip sip.setapi("QString", 2) sip.setapi("QVariant", 2) from domanager import app app.start()
# General Public Licensing requirements will be met: # http://www.trolltech.com/products/qt/opensource.html # # If you are unsure which license is appropriate for your use, please # review the following information: # http://www.trolltech.com/products/qt/licensing.html or contact the # sales department at [email protected]. # # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE # WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # ############################################################################ # This is only needed for Python v2 but is harmless for Python v3. import sip sip.setapi('QString', 2) from PyQt4 import QtCore, QtGui # import dockwidgets_rc class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.textEdit = QtGui.QTextEdit() self.setCentralWidget(self.textEdit) self.createActions() self.createMenus()
from ninja_ide.core import plugin # constants HELPMSG = '''<h3>Ninja Best Practice Checker</h3><i>Go beyond PEP-8!</i><br><br> ''' + ''.join((__doc__, ', v', __version__, __license__, 'by', __author__)) FILE, CLASS, FUNCTION, LINENR, LEVEL = 0, 1, 2, 3, 4 MAXVAL = {'maxAttributesPerClass': 20, 'maxFunctionsPerClass': 20, 'maxFunctionsPerFile': 20, 'maxClassesPerFile': 5, 'maxParametersPerFunction': 5, 'maxLinesPerFunction': 100, 'maxControlStatementsPerFunction': 20, 'maxLinesPerFile': 999, 'maxIndentationLevel': 5, 'maxTabs': 5} # API 2 (setapi(a, 2) for a in ("QDate", "QDateTime", "QString", "QTime", "QUrl", "QTextStream", "QVariant")) ############################################################################### class Main(plugin.Plugin): ' main class for plugin ' def initialize(self, *args, **kwargs): ' class init ' super(Main, self).initialize(*args, **kwargs) self.group0 = QGroupBox() self.group0.setTitle(' Options ') self.group0.setCheckable(True) self.group0.toggled.connect(lambda: self.group0.hide())
NUM_VERSION = (2, 6, 0, "dev") import sip import os import sys curpath = os.path.dirname(__file__) sys.path.append(curpath) try: types = ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"] for qtype in types: sip.setapi(qtype, 2) except ValueError: # API has already been set so we can't set it again. pass def get_git_changeset(): """Returns the SHA of the current HEAD """ import os import subprocess full_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sha = subprocess.check_output(['git', 'rev-parse', '--short','HEAD'], cwd=full_path) return sha.split('\n')[0] def part_string(part, i): """Convert a version number part into a string for concatentation.
and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL. "2019" ''' from __future__ import unicode_literals, print_function #Ensure we use pyqt api 2 and consistency across python 2 and 3 import sip API_NAMES = [ "QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant" ] API_VERSION = 2 for name in API_NAMES: sip.setapi(name, API_VERSION) from opencmiss.zinc.context import Context from opencmiss.zinc.element import Element, Elementbasis from opencmiss.zinc.node import Node #If the mesh is a triangular mesh that face constants are not supported faceValues = False cubicHermite = False class ClothingMeshModel(object): ''' Converts obj file based on manuel bastoni to opencmiss zinc In order to get the part a face belong to export the mesh from blender in obj format In Export select polygroups
# Set up configuration variables __all__ = ['custom_viewer', 'qglue', 'test'] import os try: from sip import setapi except ImportError: pass else: setapi('QString', 2) setapi('QVariant', 2) import sys from ._mpl_backend import MatplotlibBackendSetter sys.meta_path.append(MatplotlibBackendSetter()) import logging from logging import NullHandler logging.getLogger('glue').addHandler(NullHandler()) def custom_viewer(name, **kwargs): """ Create a custom interactive data viewer. To use this, first create a new variable by calling custom_viewer. Then, register one or more viewer functions using decorators.
def _pyqt4(): """Initialise PyQt4""" import sip try: sip.setapi("QString", 2) sip.setapi("QVariant", 2) sip.setapi("QDate", 2) sip.setapi("QDateTime", 2) sip.setapi("QTextStream", 2) sip.setapi("QTime", 2) sip.setapi("QUrl", 2) except AttributeError as e: raise ImportError(str(e)) # PyQt4 < v4.6 except ValueError as e: # API version already set to v1 raise ImportError(str(e)) import PyQt4 as module _setup(module, ["uic"]) if hasattr(Qt, "_uic"): Qt.QtCompat.loadUi = lambda fname: Qt._uic.loadUi(fname) if hasattr(Qt, "_QtGui"): setattr(Qt, "QtWidgets", _new_module("QtWidgets")) setattr(Qt, "_QtWidgets", Qt._QtGui) Qt.QtCompat.setSectionResizeMode = \ Qt._QtGui.QHeaderView.setResizeMode if hasattr(Qt, "_QtCore"): Qt.QtCore.QAbstractProxyModel = Qt._QtGui.QAbstractProxyModel Qt.QtCore.QSortFilterProxyModel = Qt._QtGui.QSortFilterProxyModel Qt.QtCore.QItemSelection = Qt._QtGui.QItemSelection Qt.QtCore.QStringListModel = Qt._QtGui.QStringListModel Qt.QtCore.QItemSelectionModel = Qt._QtGui.QItemSelectionModel if hasattr(Qt, "_QtCore"): Qt.__qt_version__ = Qt._QtCore.QT_VERSION_STR Qt.__binding_version__ = Qt._QtCore.PYQT_VERSION_STR Qt.QtCore.Property = Qt._QtCore.pyqtProperty Qt.QtCore.Signal = Qt._QtCore.pyqtSignal Qt.QtCore.Slot = Qt._QtCore.pyqtSlot QCoreApplication = Qt._QtCore.QCoreApplication Qt.QtCompat.translate = ( lambda context, sourceText, disambiguation, n: QCoreApplication. translate(context, sourceText, disambiguation, QCoreApplication. CodecForTr, n))
def test_sip_api_2_2(): """sip=2, hint=2 == OK""" import sip sip.setapi("QString", 2) os.environ["QT_SIP_API_HINT"] = "2" __import__("Qt") # Bypass linter warning
import os import sys if "PySide" in sys.modules: PYSIDE = True else: PYSIDE = False if PYSIDE: os.environ['QT_API'] = 'pyside' from PySide.QtGui import * else: os.environ['QT_API'] = 'pyqt' if 1: #is this really needed? #If I get rid of it IPython complains import sip sip.setapi("QString", 2) sip.setapi("QVariant", 2) from PyQt4.QtGui import * # Import the console machinery from ipython from IPython.qt.console.rich_ipython_widget import RichIPythonWidget from IPython.qt.inprocess import QtInProcessKernelManager from IPython.lib import guisupport class QIPythonWidget(RichIPythonWidget): """ Convenience class for a live IPython console widget. We can replace the standard banner using the customBanner argument""" def __init__(self, customBanner=None, *args, **kwargs): if customBanner != None: self.banner = customBanner super(QIPythonWidget, self).__init__(*args, **kwargs) self.kernel_manager = kernel_manager = QtInProcessKernelManager() kernel_manager.start_kernel()
def test_sip_api_already_set(): """Raise ImportError with sip was set to 1 with no hint, default""" __import__("PyQt4.QtCore") # Bypass linter warning import sip sip.setapi("QString", 1) assert_raises(ImportError, __import__, "Qt")
# -*- coding: utf-8 -*- # Copyright 2019 Lovac42 # Copyright 2006-2019 Ankitects Pty Ltd and contributors # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html # Support: https://github.com/lovac42/CCBC # imports are all in this file to make moving to pyside easier in the future # fixme: make sure not to optimize imports on this file import sip import os from anki.utils import isWin, isMac sip.setapi('QString', 2) sip.setapi('QVariant', 2) sip.setapi('QUrl', 2) try: sip.setdestroyonexit(False) except: # missing in older versions pass from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4 import QtGui as QtWidgets from PyQt4.QtWebKit import QWebPage, QWebView, QWebSettings from PyQt4.QtNetwork import QLocalServer, QLocalSocket # from anki.lang import _ qtmajor = (QT_VERSION & 0xff0000) >> 16 qtminor = (QT_VERSION & 0x00ff00) >> 8
def setNewPyQtAPI(): import sip # We now use the new PyQt API - IPython needs it sip.setapi('QString', 2) sip.setapi('QVariant', 2)
import sip sip.setapi("QString", 2) sip.setapi('QVariant', 2) from __init__ import * from PyQt5 import QtCore, QtGui def addWidgetWithLayout(child, parent=None, **option): #add a widget to parent along with a new layout direction = option.get('direction', 'vertical') layout = None if direction == 'vertical': layout = QtWidgets.QVBoxLayout() elif direction == 'horizontoal': layout = QtWidgets.QHBoxLayout() if not parent: parent = child.parent() parent.setLayout(layout) layout.addWidget(child) layout.setSpacing(0) layout.setMargin(0) return child class TestWindow(QtWidgets.QWidget): def __init__(self, parent=None): super(TestWindow, self).__init__(parent) self.setMinimumSize(100, 100) self.setWindowTitle('Prop Test')
import sip sip.setapi( 'QString', 2) # strange things happen without this. Must import before PyQt imports # if using ipython: do this on bash before # export QT_API=pyqt from pyspatialite import dbapi2 as db from qgis.core import * from datetime import datetime, timedelta import os import unittest from TimeManager.time_util import datetime_to_str, DEFAULT_FORMAT from test_functionality import TestWithQGISLauncher, RiggedTimeManagerControl import TimeManager.time_util as time_util import TimeManager.timevectorlayer as timevectorlayer from TimeManager.query_builder import STRINGCAST_FORMAT, INT_FORMAT, STRING_FORMAT from mock import Mock STARTTIME = 1420746289 # 8 January 2015 TEST_TABLE = "test_table" DB_FILE = "testdata/test_db.sqlite" DB_FILE_WITH_DATETIMES = "testdata/data_with_datetime.sqlite" INTEGER_TIMESTAMP = "epoch_seconds" STRING_TIMESTAMP = "datetime" NUM_PTS = 100 """Some test cases for Spatialite which do not build on Travis at the moment""" class TestSpatialite(TestWithQGISLauncher):
def prepare_pyqt(): import sip sip.setapi('QDate', 2) sip.setapi('QDateTime', 2) sip.setapi('QString', 2) sip.setapi('QTextStream', 2) sip.setapi('QTime', 2) sip.setapi('QUrl', 2) sip.setapi('QVariant', 2)
# Python2 defaults to PyQt4's API level 1, but Python3 # defaults to level 2, which is what we want. For # compatibility, we have to explicitly ask for level 2. import sip for module in ("QString", "QUrl"): sip.setapi(module, 2) import sys import os import signal import os.path from PyQt4 import QtCore from PyQt4 import QtGui try: from PyQt4.phonon import Phonon has_phonon = True except: # If we don't have phonon, we fall back to QSound. Doesn't work on Linux. has_phonon = False def init(): global _app _app = QtGui.QApplication(sys.argv) # Needs to be set for media below _app.setApplicationName("fbmessenger") # These can't be local variables during play or they'll get GC'd. if has_phonon: global _pling_media, _pling_audio, _pling_source
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'form.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! import sip sip.setapi('QString', 1) from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Dialog(object):
from PyQt5.QtWidgets import QApplication from expert import ExpertMainWindow import sip import sys sip.setapi("QString", 1) if __name__ == "__main__": a = QApplication(sys.argv) a.setStyle("fusion") w = ExpertMainWindow() w.show() a.exec_()
def prepare_pyqt4(): # Set PySide compatible APIs. import sip try: sip.setapi('QDate', 2) sip.setapi('QDateTime', 2) sip.setapi('QString', 2) sip.setapi('QTextStream', 2) sip.setapi('QTime', 2) sip.setapi('QUrl', 2) sip.setapi('QVariant', 2) except ValueError as exc: if sys.version_info[0] <= 2: # most likely caused by something else setting the API version # before us: try to give a better error message to direct the user # how to fix. msg = exc.args[0] msg += (". Pyface expects PyQt API 2 under Python 2. " "Either import Pyface before any other Qt-using packages, " "or explicitly set the API before importing any other " "Qt-using packages.") raise ValueError(msg) else: # don't expect the above on Python 3, so just re-raise raise
* 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__ = 'Nathan Woodrow' __date__ = 'May 2014' __copyright__ = '(C) 2014, Nathan Woodrow' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' try: import sip sip.setapi("QVariant", 2) except: pass import inspect import string from qgis._core import * from PyQt4.QtCore import QCoreApplication def register_function(function, arg_count, group, usesgeometry=False, **kwargs): """
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys try: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * except ImportError: # needed for py3+qt4 # Ref: # http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html # http://stackoverflow.com/questions/21217399/pyqt4-qtcore-qvariant-object-instead-of-a-string if sys.version_info.major >= 3: import sip sip.setapi('QVariant', 2) from PyQt4.QtGui import * from PyQt4.QtCore import * # PyQt5: TypeError: unhashable type: 'QListWidgetItem' class HashableQTreeWidgetItem(QTreeWidgetItem): def __init__(self, *args): super(HashableQTreeWidgetItem, self).__init__(*args) self.setCheckState(0, Qt.Checked) self.setFlags(self.flags() | Qt.ItemIsTristate | Qt.ItemIsUserCheckable) def __hash__(self): # return hash(id(self)) # print(id(self))
import os import matplotlib import sip for api in ['QString', 'QVariant', 'QDate', 'QDateTime', 'QTextStream', 'QTime', 'QUrl']: sip.setapi(api, 2) matplotlib.use('Qt4Agg', warn=False) from matplotlib.backends.qt_compat import QtCore, QtGui if QtCore.__name__.lower().startswith('pyqt4'): os.environ['QT_API'] = 'pyqt' elif QtCore.__name__.lower().startswith('pyside'): os.environ['QT_API'] = 'pyside' def getOpenFileName(*args, **kwargs): fname = QtGui.QFileDialog.getOpenFileName(*args, **kwargs) if isinstance(fname, tuple): fname = fname[0] return fname def getSaveFileName(*args, **kwargs): fname = QtGui.QFileDialog.getSaveFileName(*args, **kwargs) if isinstance(fname, tuple): fname = fname[0] return fname
def prepare_pyqt4(): # Set API version 2 (compatible with both PyQt5 and PySide) import sip sip.setapi('QDate', 2) sip.setapi('QDateTime', 2) sip.setapi('QString', 2) sip.setapi('QTextStream', 2) sip.setapi('QTime', 2) sip.setapi('QUrl', 2) sip.setapi('QVariant', 2)
## 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." ## $QT_END_LICENSE$ ## ############################################################################# # This is only needed for Python v2 but is harmless for Python v3. import sip sip.setapi('QVariant', 2) from PyQt4 import QtCore, QtGui try: import easing_rc3 except ImportError: import easing_rc2 from ui_form import Ui_Form class Animation(QtCore.QPropertyAnimation): LinearPath, CirclePath = range(2) def __init__(self, target, prop):
# (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, see <http://www.gnu.org/licenses/>, # or write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # #ensure we use API 2 from pyqt regardless of python version with python qwt import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) sip.setapi('QDate', 2) sip.setapi('QDateTime', 2) sip.setapi('QTextStream', 2) sip.setapi('QTime', 2) sip.setapi('QUrl', 2) import os os.environ[ 'QT_API'] = 'pyqt' #qt4 not 5 as is installed on most sytems running python 3! debuglevels = {} options = {} import Timba.utils import os
except ImportError: # Try using PySide QT_API = QT_API_PYSIDE cond = ("Could not import sip; falling back on PySide\n" "in place of PyQt4 or PyQt5.\n") verbose.report(cond, 'helpful') if _sip_imported: if QT_API == QT_API_PYQTv2: if QT_API_ENV == 'pyqt': cond = ("Found 'QT_API=pyqt' environment variable. " "Setting PyQt4 API accordingly.\n") else: cond = "PyQt API v2 specified." try: sip.setapi('QString', 2) except: res = 'QString API v2 specification failed. Defaulting to v1.' verbose.report(cond + res, 'helpful') # condition has now been reported, no need to repeat it: cond = "" try: sip.setapi('QVariant', 2) except: res = 'QVariant API v2 specification failed. Defaulting to v1.' verbose.report(cond + res, 'helpful') if QT_API == QT_API_PYQT5: try: from PyQt5 import QtCore, QtGui, QtWidgets _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName except ImportError:
* * *************************************************************************** """ __author__ = 'Matthias Kuhn' __date__ = 'November 2015' __copyright__ = '(C) 2015, Matthias Kuhn' # This will get replaced with a git SHA1 when you do a git archive __revision__ = 'f9842426dccac3b44472f22362191c98bdc34deb' import sip for api in [ "QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant" ]: sip.setapi(api, 2) from PyQt4.QtCore import * from PyQt4.QtGui import QItemSelectionModel, QSortFilterProxyModel # Add a __nonzero__ method onto QPyNullVariant so we can check for null values easier. # >>> value = QPyNullVariant("int") # >>> if value: # >>> print "Not a null value" from types import MethodType from PyQt4.QtCore import QPyNullVariant def __nonzero__(self): return False
import sys import os import cPickle as pickle import sip API_NAMES = ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"] API_VERSION = 2 for api_name in API_NAMES: sip.setapi(api_name, API_VERSION) from PyQt4 import QtGui, QtCore from molecular_view import MolecularView from molecular_scene import MolecularScene from output_dialog import OutputDialog import settings class MainWindow(QtGui.QMainWindow): """The main window of the UI.""" def __init__(self): """Initialise the main window.""" super(MainWindow, self).__init__() self.setGeometry(100, 100, 800, 500) self.setWindowTitle('MolecularUI') file_menu = QtGui.QMenu("File", self) save_action = QtGui.QAction("Save", self) save_action.setShortcut(QtGui.QKeySequence("Ctrl+S")) QtCore.QObject.connect(save_action, QtCore.SIGNAL("triggered()"),
# -*- coding: utf-8 -*- import csv, operator, collections, urllib, itertools, os, json import common, verticals # for using native Python strings import sip sip.setapi('QString', 2) from PyQt4.QtCore import QUrl import parser, scrape, selector, transition # constants for type of parameter PATH, GET, POST, COOKIE = 0, 1, 2, 3 def build(browser, transitions, input_values, prev_transitions=None): """Build a model of these transitions. A recursion via abstract(browser, input_values, examples). Parameters ---------- browser: AjaxBrowser transitions: group of transaction of the same kind (same step in interactive wrapper) to be analyzed input_values: dictionary input keys and values of the interactive wrapper Returns the model or None if failed to abstract transitions. """ diffs = find_differences( transitions ) # differing parameters can potentially be relevant parameters dependent on the input into the original wrapper.