#!/usr/bin/python

# ZetCode Advanced PyQt4 tutorial
#
# A simple SELECT query
#
# author: Jan Bodnar
# website: zetcode.com
# last edited: October 2009

from PyQt4 import QtSql, QtCore

app = QtCore.QCoreApplication([])

db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("friends.db")

if not db.open():
    print "cannot establish a database connection"

else:
    query = QtSql.QSqlQuery("SELECT name, age FROM friends")
    while query.next():
        name = query.value(0).toString()
        age = query.value(1).toString()
        print name, age
Exemplo n.º 2
0
    names = dbus_iface.call('ListNames').arguments()[0]

    # Mimic the output from the C++ version.
    sys.stdout.write('QVariant(QStringList, ("%s") )\n' % '", "'.join(names))


def method3():
    sys.stdout.write("Method 3:\n")

    names = QtDBus.QDBusConnection.sessionBus().interface(
    ).registeredServiceNames().value()

    # Mimic the output from the C++ version.
    sys.stdout.write('("%s")\n' % '", "'.join(names))


if __name__ == '__main__':
    app = QtCore.QCoreApplication(sys.argv)

    if not QtDBus.QDBusConnection.sessionBus().isConnected():
        sys.stderr.write("Cannot connect to the D-Bus session bus.\n"
                         "To start it, run:\n"
                         "\teval `dbus-launch --auto-syntax`\n")
        sys.exit(1)

    method1()
    method2()
    method3()

    sys.exit()
Exemplo n.º 3
0
def usingQThread():
    app = QtCore.QCoreApplication([])
    thread = AThread()
    thread.finished.connect(app.exit)
    thread.start()
    sys.exit(app.exec_())
Exemplo n.º 4
0
def usingQRunnable():
    app = QtCore.QCoreApplication([])
    runnable = Runnable()
    QtCore.QThreadPool.globalInstance().start(runnable)
    sys.exit(app.exec_())
Exemplo n.º 5
0
def main():
    import argparse
    import sys

    parser = argparse.ArgumentParser(description='')
    parser.add_argument('-u', dest='user', default='dbuser')
    parser.add_argument('-P', dest='password')
    parser.add_argument('-t', dest='datetime', default=None)
    parser.add_argument('-a', dest='host', default='37.44.41.26')
    parser.add_argument('-p', dest='port', type=int, default='63306')
    parser.add_argument('-d', dest='database', default='iemk')
    parser.add_argument('-D', dest='dir', default=os.getcwd())
    parser.add_argument('-T', dest='type', default='c')
    args = vars(parser.parse_args(sys.argv[1:]))

    if not args['user']:
        print 'Error: you should specify user name'
        sys.exit(-1)
    if not args['password']:
        print 'Error: you should specify password'
        sys.exit(-2)

    app = QtCore.QCoreApplication(sys.argv)
    connectionInfo = {
        'driverName': 'MYSQL',
        'host': args['host'],
        'port': args['port'],
        'database': args['database'],
        'user': args['user'],
        'password': args['password'],
        'connectionName': 'IEMK',
        'compressData': True,
        'afterConnectFunc': None
    }

    db = connectDataBaseByInfo(connectionInfo)
    QtGui.qApp.db = db
    curDateTime = QtCore.QDateTime.currentDateTime()
    dt = args['datetime']
    dt = QDateTime.fromString(
        dt, 'yyyy-MM-ddTHH:mm:ss') if dt else curDateTime.addSecs(-86400)
    typeDatetime = args['type']
    if typeDatetime == 'c':
        strTypeDatetime = u'Client.createDatetime'
        typeFlag = 0
    elif typeDatetime == 'm':
        strTypeDatetime = u'Client.modifyDatetime'
        typeFlag = 1
    else:
        print 'Error: wrong type'
        sys.exit(-4)
    stmt = '''
        SELECT Client.id as clientId,
               Client.lastName,
               Client.firstName,
               Client.patrName,
               rbContactType.code as contactTypeCode,
               ClientContact.contact as contactClient,
               Client.sex,
               Client.birthDate,
               Client.birthTime,
               AddressHouse.KLADRCode,
               AddressHouse.KLADRStreetCode,
               AddressHouse.number as houseNumber,
               AddressHouse.corpus as houseCorpus,
               ClientAddress.freeInput as freeInput,
               Address.flat as flat,
               Client.SNILS,
               ClientPolicy.serial as policySerial,
               ClientPolicy.number as policyNumber,
               ClientPolicy.begDate as policyBegDate,
               Organisation.fullName as insurerName,
               Organisation.obsoleteInfisCode as insurerCode,
               ClientDocument.serial as documentSerial,
               ClientDocument.number as documentNumber,
               ClientDocument.date as documentDate,
               ClientDocument.origin as documentOrg,
               Client.birthPlace,
               Organisation.phone as orgPhone,
               rbDocumentType.federalCode as docTypeCode
        FROM Client
        LEFT JOIN ClientContact ON ClientContact.client_id = Client.id AND ClientContact.deleted = 0
        LEFT JOIN rbContactType ON rbContactType.id = ClientContact.contactType_id
        LEFT JOIN ClientAddress ON ClientAddress.id = getClientRegAddressId(Client.id)
        LEFT JOIN Address ON Address.id = ClientAddress.address_id AND Address.deleted = 0
        LEFT JOIN AddressHouse ON AddressHouse.id = Address.house_id AND AddressHouse.deleted = 0
        LEFT JOIN ClientPolicy ON ClientPolicy.id = getClientPolicyId(Client.id, 1)
        LEFT JOIN Organisation ON Organisation.id = ClientPolicy.insurer_id AND Organisation.deleted = 0
        LEFT JOIN ClientDocument ON ClientDocument.client_id = Client.id AND ClientDocument.deleted = 0
        LEFT JOIN rbDocumentType ON rbDocumentType.id = ClientDocument.documentType_id AND rbDocumentType.code = 1
        WHERE (%s >= TIMESTAMP('%s') OR IFNULL(TIMESTAMP(Client.notes), TIMESTAMP('0000-00-00')) >= TIMESTAMP('%s'))  AND Client.deleted = 0
    ''' % (strTypeDatetime, dt.toString('yyyy-MM-dd hh:mm:ss'),
           dt.toString('yyyy-MM-dd hh:mm:ss'))
    query = db.query(stmt)
    if query.size() > 0:
        if typeFlag == 0:
            fileName = u'RCIEMK_%s.xml' % (
                curDateTime.toString('yyMMddThhmmss.zzz'))
        elif typeFlag == 1:
            fileName = u'RMIEMK_%s.xml' % (
                curDateTime.toString('yyMMddThhmmss.zzz'))
        if not (dt is None or dt.isValid()):
            print 'Error: incorrect base datetime.'
            sys.exit(-4)
        outFile = QtCore.QFile(
            os.path.join(forceStringEx(args['dir']), fileName))
        outFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text)
        clientsOut = CRegistryClientInIEMK(None)
        clientsOut.setCodec(QtCore.QTextCodec.codecForName('cp1251'))
        clientsOut.writeFileHeader(outFile)
        clientsOut.writeRegistryClientInIEMK(query, curDateTime, typeFlag)
        clientsOut.writeFileFooter()
        outFile.close()
Exemplo n.º 6
0
def main():
    global log
    log = logging.getLogger()
    logHandler = logging.StreamHandler()
    log.addHandler(logHandler)
    logHandler.setFormatter(logging.Formatter("%(message)s"))

    parser = argparse.ArgumentParser(description="Switch between laptop and tablet mode for ThinkPad Yoga 12")
    parser.add_argument("-v", "--version",
                        help="Print out the version number",
                        action="store_true")
    parser.add_argument("-d", "--daemon",
                        help="Run in the background as a daemon",
                        action="store_true")
    parser.add_argument("-m", "--mode",
                        help="Toggle between Tablet and Laptop mode",
                        action="store_true")
    parser.add_argument("-r", "--rotatelock",
                        help="Toggle screen rotation locking",
                        action="store_true")
    parser.add_argument("-t", "--toggletouch",
                        help="Toggle touch screen on and off",
                        action="store_true")
    parser.add_argument("-c", "--calibrate",
                        help="Calibrate the Wacom pen for the current screen orientation",
                        action="store_true")
    parser.add_argument("-x", "--reset",
                        help="Reset the Wacom pen calibration for the current screen orientation",
                        action="store_true")
    parser.add_argument("-l", "--loglevel",
                        help="Log level (1=debug, 2=info, 3=warning, 4=error, 5=critical)",
                        type=int,
                        default=4)
    args = parser.parse_args()

    log.level = args.loglevel * 10
    if args.version:
        # TODO! Have version update
        print(version)
    elif args.daemon:
        log.info("Starting Yoga Spin background daemon")
        app = QtCore.QCoreApplication(sys.argv)
        daemon = Daemon()
        sys.exit(app.exec_())
    elif args.mode:
        log.info("Toggle between tablet and laptop mode")
        send_command("toggle")
    elif args.rotatelock:
        log.info("Toggle the rotation lock on/off")
        send_command("togglelock")
    elif args.toggletouch:
        log.info("Togge touch screen on/off")
        send_command("toggletouch")
    elif args.calibrate:
        log.info("Calibrating the Wacom pen")
        cal = Calibration('Wacom ISDv4 EC Pen stylus')
        cal.calibrate()
    elif args.reset:
        log.info("Resetting the Wacom pen calibration")
        cal = Calibration('Wacom ISDv4 EC Pen stylus')
        cal.reset_calibration()
    else:
        log.info("No arguments passed. Doing nothing.")
Exemplo n.º 7
0
def freezeApp():
    # Necesito esta línea para que se carguen correctamente los paths de qt hacia los plugins, traducciones, etc.
    app = QtCore.QCoreApplication(sys.argv)

    options = {}

    includes = ["PyQt4", "PyQt4.QtCore", "PyQt4.QtGui"]
    packages = ["lxml"]
    excludes = [
        "PyQt4.QtSvg", "PyQt4.QtNetwork", "PyQt4.QtOpenGL", "PyQt4.QtScript",
        "PyQt4.QtSql", "PyQt4.Qsci", "PyQt4.QtXml", "PyQt4.QtTest", "PyQt4.uic"
    ]
    include_files = [("epubcreator/epubbase/files", "files")]

    qtSpanishTranslation = config.getQtSpanishTranslation()

    if not os.path.exists(qtSpanishTranslation):
        raise Exception("No se encontró el archivo de traducciones.")

    include_files.append(
        (qtSpanishTranslation,
         "translations/{0}".format(os.path.split(qtSpanishTranslation)[1])))

    options["icon"] = "epubcreator/gui/resources/icons/app_icon.ico"
    options["build_exe"] = "build/epubcreator"

    if config.IS_RUNNING_ON_LINUX:
        libsPath = "/usr/lib/i386-linux-gnu"
        if sys.maxsize > 2**32:
            libsPath = "/usr/lib/x86_64-linux-gnu"
        include_files.append((os.path.join(libsPath,
                                           "libxml2.so.2"), "libxml2.so.2"))
        include_files.append((os.path.join(libsPath,
                                           "libxslt.so.1"), "libxslt.so.1"))
        include_files.append((os.path.join(libsPath, "libz.so"), "libz.so"))
    else:
        imageFormatsPath = os.path.join(
            QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.PluginsPath),
            "imageformats")

        if config.IS_RUNNING_ON_MAC:
            include_files.append((os.path.join(imageFormatsPath,
                                               "libqjpeg.dylib"),
                                  "plugins/imageformats/libqjpeg.dylib"))
            include_files.append(
                ("/opt/local/lib/libjpeg.9.dylib", "libjpeg.9.dylib"))

            # Elimino el archivo ".ico": en mac el ícono es un archivo ".icns", que luego
            # me encargo de copiar manualmente.
            del (options["icon"])

            # En mac, al utilizar bdist_mac para crear el bundle, intenta leer los archivos desde el
            # directorio: "exe.macos-i386..." (algo así), independientemente de que yo especifique otro
            # directorio de destino... por eso no puedo modificarlo, y debo dejar el que crea por defecto.
            del (options["build_exe"])

    options["packages"] = packages
    options["includes"] = includes
    options["excludes"] = excludes
    options["include_files"] = include_files
    options["include_msvcr"] = True

    if os.path.isdir("build"):
        shutil.rmtree("build", ignore_errors=True)

    setup(name=version.APP_NAME,
          version=version.VERSION,
          description=version.DESCRIPTION,
          options={"build_exe": options},
          executables=[
              Executable("epubcreator/gui/main.py",
                         base="Win32GUI" if config.IS_RUNNING_ON_WIN else None,
                         targetName="{0}{1}".format(
                             version.APP_NAME,
                             ".exe" if config.IS_RUNNING_ON_WIN else ""))
          ])

    if config.IS_RUNNING_ON_WIN:
        # Necesito el archivo qt.conf vacío. Si está vacío, Qt carga todos los paths por defecto, que
        # en el caso de los plugins es el directorio "plugins".
        with open(os.path.join("build", "epubcreator", "qt.conf"),
                  "w",
                  encoding="utf-8"):
            pass
    elif config.IS_RUNNING_ON_MAC:
        # El bundle ".app" creado por defecto tiene el nombre de esta forma: name-version.app.
        bundlePath = "build/{0}-{1}.app".format(version.APP_NAME,
                                                version.VERSION)
        bundleMacOsDir = os.path.join(bundlePath, "Contents", "MacOS")
        bundleResourcesDir = os.path.join(bundlePath, "Contents", "Resources")

        with open(os.path.join(bundleResourcesDir, "qt.conf"),
                  "w",
                  encoding="utf-8") as file:
            # Deben ser comillas dobles en el path, con las simples no funciona...
            file.write('[Paths]\nPlugins = "MacOS/plugins"\n')
            file.write('[Paths]\nTranslations = "MacOS/translations"\n')

        # Necesito saber todas las librerías que se incluyen en el bundle.
        shippedFiles = os.listdir(bundleMacOsDir)

        # cx_freeze modifica los paths de las librerías que él mismo copia al bundle, pero no hace
        # lo mismo con las librerías que yo manualmente incluyo. Por eso necesito modificar sus
        # paths para que se haga referencia al bundle, y no a las librerías del sistema.
        libsToModify = [
            os.path.join(bundleMacOsDir, "plugins/imageformats", imgLib)
            for imgLib in os.listdir(
                os.path.join(bundleMacOsDir, "plugins/imageformats"))
        ]
        libsToModify.append(os.path.join(bundleMacOsDir, "libjpeg.9.dylib"))

        for lib in libsToModify:
            # Primero modifico el nombre de la librería.
            subprocess.call(
                ("install_name_tool", "-id",
                 "@executable_path/{0}".format(os.path.basename(lib)), lib))

            # Acá leo cuáles son las otras librerías referencias por la librería actual que estoy procesando.
            # El comando "otool" en mac es similar al "ldd" de linux.
            otool = subprocess.Popen(("otool", "-L", lib),
                                     stdout=subprocess.PIPE)
            referencedLibs = otool.stdout.readlines()

            for referencedLib in referencedLibs:
                # Ahora, por cada librería referenciada, necesito saber si es una de las
                # librerías que se incluyen en el bundle, y en dicho caso modificar el path
                # para que apunte al path del ejecutable.
                referencedLib = referencedLib.decode()
                filename, _, _ = referencedLib.strip().partition(" ")
                prefix, name = os.path.split(filename)
                if name in shippedFiles:
                    newfilename = "@executable_path/{0}".format(name)
                    subprocess.call(("install_name_tool", "-change", filename,
                                     newfilename, lib))

        # Copio el ícono.
        shutil.copy(
            "epubcreator/gui/resources/icons/app_icon.icns",
            "build/{0}-{1}.app/Contents/Resources".format(
                version.APP_NAME, version.VERSION))

        # Renombro el bundle, porque no quiero que el nombre incluya la versión.
        os.rename(bundlePath, "build/EpubCreator.app")
    elif config.IS_RUNNING_ON_LINUX:
        # No distribuyo Qt en linux, por lo que no necesito estos directorios.
        shutil.rmtree("build/epubcreator/imageformats", ignore_errors=True)
        shutil.rmtree("build/epubcreator/plugins", ignore_errors=True)
def main():

    supported_data_types = [
        'OS Mastermap Topography (v7)', 'OS Mastermap Topography (v9)'
    ]

    parser = argparse.ArgumentParser(
        description='Import OS products into PostGIS from the command-line.\n\n'
        +
        'Please note that this script needs a PGPASSFILE to function - see \n'
        + 'https://www.postgresql.org/docs/9.5/static/libpq-pgpass.html')
    parser.add_argument(
        '--osmm-data-type',
        required=True,
        help='OS MasterMap data type, e.g. "OS Mastermap Topography (v7)"')
    parser.add_argument(
        '--input-path',
        required=True,
        help='Path under which to search of .gml.gz or .gml files')
    parser.add_argument(
        '--host',
        default='localhost',
        help='Hostname of PostgreSQL server (default=localhost)')
    parser.add_argument('--database',
                        required=True,
                        help='Destination database for import')
    parser.add_argument('--port',
                        default=5432,
                        help='Port of PostgreSQL server (default=5432)')
    parser.add_argument('--user',
                        default='postgres',
                        help='Username to connect as (default=postgres)')
    parser.add_argument('--schema',
                        required=True,
                        help='Destination schema for import')
    parser.add_argument(
        '--num-processes',
        default=2,
        help='Number of concurrent import processes (default=2)')
    parser.add_argument(
        '--ignore-fid',
        default=False,
        action='store_true',
        help=
        'allow to import features for boundary tiles (use GML_EXPOSE_FID NO in ogr2ogr command)'
    )

    args = parser.parse_args()
    if args.osmm_data_type not in supported_data_types:
        print '%s is not a supported data type.'
        print 'Supported data types are:'
        for sup in supported_data_types:
            print '  %s' % sup
        sys.exit(1)

    if not os.path.isdir(args.input_path):
        print '%s doesn\'t appear to be a folder'
        sys.exit(1)

    app = QtCore.QCoreApplication(sys.argv)
    o = OSTranslatorCli(input_path=args.input_path,
                        osmm_data_type=args.osmm_data_type,
                        host=args.host,
                        database=args.database,
                        port=args.port,
                        user=args.user,
                        schema=args.schema,
                        num_processes=args.num_processes,
                        ignore_fid=args.ignore_fid)

    o.finished.connect(app.exit)

    QtCore.QTimer.singleShot(10, o.run)
    sys.exit(app.exec_(
    ))  # FIXME: For some reason the app returns -1 instead of 0 as expected
Exemplo n.º 9
0
def testtd():
    import sys
    from PyQt4 import QtCore
    app = QtCore.QCoreApplication(sys.argv)

    def print_log(event):
        log = event.dict_['data']
        print ':'.join([log.logTime, log.logContent])

    eventEngine = EventEngine2()
    eventEngine.register(EVENT_LOG, print_log)
    eventEngine.start()

    gateway = Shzd2Gateway(eventEngine)
    gateway.connect()

    # sleep(1)
    # req = VtOrderReq()
    # req.direction = DIRECTION_LONG
    # req.exchange = 'CME'
    # req.symbol = 'GC1712'
    # req.volume = 1
    # req.price = 1275.0
    # req.priceType = PRICETYPE_LIMITPRICE
    # vtOrderID = gateway.sendOrder(req)

    # sleep(1)
    # import pprint
    # pprint.pprint(gateway.tdApi.OrderID_OrderSysID_Map)
    # cancelreq = VtCancelOrderReq()
    # cancelreq.orderID = vtOrderID
    # gateway.cancelOrder(cancelreq)
    sys.exit(app.exec_())


# def testmd():
#     import sys
#     from PyQt4 import QtCore
#     app = QtCore.QCoreApplication(sys.argv)

#     def print_log(event):
#         log = event.dict_['data']
#         print ':'.join([log.logTime, log.logContent])

#     eventEngine = EventEngine2()
#     eventEngine.register(EVENT_LOG, print_log)
#     eventEngine.start()

#     gateway = Shzd2Gateway(eventEngine)
#     gateway.connect()
#     subreq1 = VtSubscribeReq()
#     subreq1.symbol = 'GC1712'
#     subreq1.exchange = 'CME'

#     subreq2 = VtSubscribeReq()
#     subreq2.symbol = 'CL1712'
#     subreq2.exchange = 'CME'
#     gateway.subscribe(subreq1)
#     gateway.subscribe(subreq2)

#     sys.exit(app.exec_())