Exemplo n.º 1
0
 def append_blue_data(self, data):
     """ DOCSTRING """
     self.clear_blue_list.emit()
     i = 1
     for i in data:
         if self.current_lang == "Polski":
             item = QListWidgetItem('Nazwa: ' + str(i) + ' \nMAC: ' +
                                    str(data[i][0].upper()) + ' \nRSSI: ' +
                                    str(data[i][1]) + ' dBm\nProducent: ' +
                                    str(
                                        manu.search_manufacturer_by_mac(
                                            str(data[i][0].upper()))) + '')
         else:
             item = QListWidgetItem('Name: ' + str(i) + ' \nMAC: ' +
                                    str(data[i][0].upper()) + ' \nRSSI: ' +
                                    str(data[i][1]) +
                                    ' dBm\nManufacturer: ' + str(
                                        manu.search_manufacturer_by_mac(
                                            str(data[i][0].upper()))) + '')
         if int(abs(data[i][1])) < 50:
             item.setIcon(QIcon('icons/icons8-no-connection-64-green.png'))
         elif int(abs(data[i][1])) >= 50 and int(abs(data[i][1])) < 70:
             item.setIcon(QIcon('icons/icons8-no-connection-64-blue.png'))
         elif int(abs(data[i][1])) >= 70 and int(abs(data[i][1])) < 80:
             item.setIcon(QIcon('icons/icons8-no-connection-64-orange.png'))
         elif int(abs(data[i][1])) >= 80 and int(abs(data[i][1])) < 90:
             item.setIcon(QIcon('icons/icons8-no-connection-64-red.png'))
         elif int(abs(data[i][1])) >= 90:
             item.setIcon(QIcon('icons/icons8-no-connection-64-black.png'))
         self.append_blue_list_item.emit(item)
         self.loop = QEventLoop()
         QTimer.singleShot(50, self.loop.quit)
         self.loop.exec_()
Exemplo n.º 2
0
 def append_wifi_data(self, data):
     """ Append data to list in WiFi list tab """
     self.clear_wifi_list.emit()
     i = 1
     for i in data:
         if self.current_lang == "Polski":
             item = QListWidgetItem(
                 'BSID: ' + str(i) + ' \nKanał: ' + str(data[i][1]) +
                 ' \nRSSI: ' + str(data[i][0]) + ' dBm \nMAC: ' +
                 str(data[i][3]) + ' (Producent: ' +
                 str(manu.search_manufacturer_by_mac(str(data[i][3]))) +
                 ')')
         else:
             item = QListWidgetItem(
                 'BSID: ' + str(i) + ' \nChannel: ' + str(data[i][1]) +
                 ' \nRSSI: ' + str(data[i][0]) + ' dBm \nMAC: ' +
                 str(data[i][3]) + ' (Manufacturer: ' +
                 str(manu.search_manufacturer_by_mac(str(data[i][3]))) +
                 ')')
         if int(abs(data[i][0])) < 50:
             item.setIcon(QIcon('icons/icons8-no-connection-64-green.png'))
         elif int(abs(data[i][0])) >= 50 and int(abs(data[i][0])) < 70:
             item.setIcon(QIcon('icons/icons8-no-connection-64-blue.png'))
         elif int(abs(data[i][0])) >= 70 and int(abs(data[i][0])) < 80:
             item.setIcon(QIcon('icons/icons8-no-connection-64-orange.png'))
         elif int(abs(data[i][0])) >= 80 and int(abs(data[i][0])) < 90:
             item.setIcon(QIcon('icons/icons8-no-connection-64-red.png'))
         elif int(abs(data[i][0])) >= 90:
             item.setIcon(QIcon('icons/icons8-no-connection-64-black.png'))
         self.append_wifi_list_item.emit(item)
         self.loop = QEventLoop()
         QTimer.singleShot(50, self.loop.quit)
         self.loop.exec_()
Exemplo n.º 3
0
    def doStep(self, n = 1):
        if self.image.format() != QImage.Format_Grayscale8:
            print("Wrong file format, generate map again.")
            return

        deathLimit = 14
        self._percentage = 0
        for _ in range(n):
            _image = self.image.copy()
            for x in range(self.image.width()):
                self._percentage += 1.0/(self.image.width()*n)
                if x%10 == 0:
                    # Update percentage
                    self.percentageChanged.emit()
                    # processEvent is necessary
                    QEventLoop().processEvents()
                    # Update map
                    self.update()
                for y in range(self.image.height()):
                    if self.countNeighbors(x, y, _image, 2) > deathLimit or \
                        x == 0 or y == 0 or x == _image.width() - 1 or y == _image.height() - 1:
                        self.setPixel(x, y, 0)
                    else:
                        self.setPixel(x, y, 255)
        # Update percentage
        self.update()
        self.oldImage = self.image.copy()
        self.percentageChanged.emit()
        QEventLoop().processEvents()
 def snapshot_await(self):
     self.SnapshotTaken = False
     while self.is_active and not self.SnapshotTaken:
         #self.msg("Waiting for snapshot")
         self.SnapshotEventLoop = QEventLoop()
         QTimer.singleShot(10, self.SnapshotEventLoop.exit)
         self.SnapshotEventLoop.exec_()
     return
Exemplo n.º 5
0
    def take_screenshot_pos(flags):
        loop = QEventLoop()
        screen_shot = Screenshot(flags)
        screen_shot.show()
        screen_shot.widget_closed.connect(loop.quit)

        loop.exec_()
        pos = screen_shot.target_img_pos
        return pos
Exemplo n.º 6
0
    def executejavascript(self, scriptsrc):
        self.loop = QEventLoop()
        self.result = None
        QTimer.singleShot(250, self.loop.quit)

        self.runJavaScript(scriptsrc, self.callbackjs)
        self.loop.exec_()
        self.loop = None
        return self.result
Exemplo n.º 7
0
 def data_request(self, request, bparams):
     connection_loop = QEventLoop()
     QObject.connect(self.managerAccess,
                     SIGNAL("finished( QNetworkReply* )"), connection_loop,
                     SLOT("quit()"))
     reply = self.managerAccess.post(request, bparams)
     connection_loop.exec_()  #sleep
     #reply->bytesAvailable();
     #reply.deleteLater()
     return reply
Exemplo n.º 8
0
 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(2000)
     self.assertEqual(retval, 0)
Exemplo n.º 9
0
 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)
Exemplo n.º 10
0
 def run_leave_animation(self):
     """
     Runs the animation that represents execution leaving this item.
     Blocks until the animation is finished.
     """
     loop = QEventLoop()
     animation = self.make_execution_leave_animation()
     animation.finished.connect(loop.quit)
     animation.start()
     if animation.state() == QParallelAnimationGroup.Running:
         loop.exec_()
Exemplo n.º 11
0
def event_loop(msec):
    """Event loop to show the GUI during a unit test. 
    
    https://www.qtcentre.org/threads/23541-Displaying-GUI-events-with-QtTest
    """
    loop = QEventLoop()
    timer = QTimer()
    timer.timeout.connect(loop.quit)
    timer.setSingleShot(True)
    timer.start(msec)
    loop.exec_()
Exemplo n.º 12
0
 def _run_leave_animation(self, item_name, direction, engine_state):
     """
     Runs the animation that represents execution leaving this item.
     Blocks until the animation is finished.
     """
     if direction == ExecutionDirection.BACKWARD or engine_state != SpineEngineState.RUNNING:
         return
     loop = QEventLoop()
     animation = self._make_execution_leave_animation(item_name)
     animation.finished.connect(loop.quit)
     animation.start()
     if animation.state() == QParallelAnimationGroup.Running:
         loop.exec_()
Exemplo n.º 13
0
def fix_pyside_exec(namespace):
    if namespace.get("__name__") == "AnyQt.QtWidgets":
        from PySide2.QtWidgets import QApplication, QDialog, QMenu
        if "exec" not in QApplication.__dict__:
            QApplication.exec = lambda self: QApplication.exec_()
        if not hasattr(QDialog, "exec"):
            QDialog.exec = lambda self: QDialog.exec_(self)
        if not hasattr(QMenu, "exec"):
            QMenu.exec = lambda self: QMenu.exec_(self)
    if namespace.get("__name__") == "AnyQt.QtGui":
        from PySide2.QtGui import QGuiApplication, QDrag
        if "exec" not in QGuiApplication.__dict__:
            QGuiApplication.exec = lambda self: QGuiApplication.exec_()
        if not hasattr(QDrag, "exec"):
            QDrag.exec = (lambda self, *args, **kwargs: QDrag.exec_(
                self, *args, **kwargs))
    elif namespace.get("__name__") == "AnyQt.QtCore":
        from PySide2.QtCore import QCoreApplication, QEventLoop, QThread
        if not hasattr(QCoreApplication, "exec"):
            QCoreApplication.exec = lambda self: QCoreApplication.exec_()
        if not hasattr(QEventLoop, "exec"):
            QEventLoop.exec = (lambda self, *args, **kwargs: QEventLoop.exec_(
                self, *args, **kwargs))
        if not hasattr(QThread, "exec"):
            QThread.exec = lambda self: QThread.exec_(self)
    elif namespace.get("__name__") == "AnyQt.QtPrintSupport":
        from PySide2.QtPrintSupport import QPageSetupDialog, QPrintDialog
        if "exec" not in QPageSetupDialog.__dict__:
            QPageSetupDialog.exec = lambda self: QPageSetupDialog.exec_(self)
        if "exec" not in QPrintDialog.__dict__:
            QPrintDialog.exec = lambda self: QPrintDialog.exec_(self)
Exemplo n.º 14
0
class EventLoop:
    def __init__(self, timeout_in_second: float = None):
        self.event = QEventLoop(None)
        self.timeout_in_second = timeout_in_second

    def quit(self):
        self.event.quit()

    def __enter__(self):
        return self

    def __exit__(self, *_):
        if self.timeout_in_second is not None:
            t = Timer()
            t.timeout.connect(self.quit)
            t.start(seconds=self.timeout_in_second)
        self.event.exec_()
Exemplo n.º 15
0
 def append_data_to_wifi_timeline(self, wifi_dict):
     """ DOCSTRING """
     self.default_array = [
         -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
         -100, -100
     ]
     for var_x in wifi_dict:
         self.append_lowest_rssi_to_array(wifi_dict[var_x][1],
                                          wifi_dict[var_x][0])
     self.append_wifi_timeline_data.emit(self.default_array)
     self.default_tupple = tuple(self.default_array)
     self.final_tuple = (datetime.datetime.now().strftime('%H:%M:%S'),
                         *self.default_tupple)
     self.save_wifi_timeline_data.emit(self.final_tuple)
     self.loop = QEventLoop()
     QTimer.singleShot(50, self.loop.quit)
     self.loop.exec_()
Exemplo n.º 16
0
class PlayerMoveSignal(QObject):
    def __init__(self, parent):
        super(PlayerMoveSignal, self).__init__()
        self.game = parent
        self.sig = Signal(str)
        self.eventLoop = QEventLoop(self)
        self.data = None

    @Slot(str)
    def stop_waiting(self, data):
        self.data = data
        self.eventLoop.exit()
        return

    def wait_for_move(self):
        self.eventLoop.exec_()
        return self.data
Exemplo n.º 17
0
 def open(self, url, timeout=60):
     """Wait for download to complete and return result"""
     loop = QEventLoop()
     timer = QTimer()
     timer.setSingleShot(True)
     timer.timeout.connect(loop.quit)
     self.loadFinished.connect(loop.quit)
     self.load(QUrl(url))
     timer.start(timeout * 1000)
     loop.exec_()  # delay here until download finished
     if timer.isActive():
         # downloaded successfully
         timer.stop()
         return self.html()
     else:
         # timed out
         print('Request timed out:', url)
Exemplo n.º 18
0
 def execute(self, context):  # eventloop should be here
     self.app = QApplication.instance()
     if not self.app:
         self.app = QApplication(sys.argv)
     self.event_loop = QEventLoop()
     self.widget = ui.EasyKeymapMainWindow()
     self.widget.show()
     # self.app.exec_()  DON'T exec app
     return {'FINISHED'}
Exemplo n.º 19
0
 def open(self, url: str, timeout: int = 10):
     """Wait for download to complete and return result"""
     loop = QEventLoop()
     timer = QTimer()
     timer.setSingleShot(True)
     # noinspection PyUnresolvedReferences
     timer.timeout.connect(loop.quit)
     # noinspection PyUnresolvedReferences
     self.loadFinished.connect(loop.quit)
     self.load(QUrl(url))
     # noinspection PyArgumentList
     timer.start(timeout * 1000)
     loop.exec_()  # delay here until download finished
     if timer.isActive():
         # downloaded successfully
         timer.stop()
     else:
         logger.info('Request timed out: %s' % url)
Exemplo n.º 20
0
def wait_signal(signal, timeout=1):
    """Block loop until signal emitted, or timeout (s) elapses."""
    loop = QEventLoop()
    signal.connect(loop.quit)

    yield

    timed_out = []
    if timeout is not None:

        def quit_with_error():
            timed_out.append(1)
            loop.quit()

        QTimer.singleShot(timeout * 1000, quit_with_error)
    loop.exec_()
    if timed_out:
        assert False, "Timeout while waiting for %s" % signal
Exemplo n.º 21
0
 def _execute_forward(self, resources):
     """See base class."""
     if not self._settings:
         return True
     absolute_paths = _files_from_resources(resources)
     absolute_path_settings = dict()
     for label in self._settings:
         absolute_path = absolute_paths.get(label)
         if absolute_path is not None:
             absolute_path_settings[absolute_path] = self._settings[label]
     source_settings = {
         "GdxConnector": {
             "gams_directory": self._gams_system_directory()
         }
     }
     # Collect arguments for the importer_program
     import_args = [
         list(absolute_paths.values()),
         absolute_path_settings,
         source_settings,
         [
             r.url for r in self._resources_from_downstream
             if r.type_ == "database"
         ],
         self._logs_dir,
         self._cancel_on_error,
     ]
     if not self._prepare_importer_program(import_args):
         self._logger.msg_error.emit(
             f"Executing Importer {self.name} failed.")
         return False
     self._importer_process.start_execution()
     loop = QEventLoop()
     self.importing_finished.connect(loop.quit)
     # Wait for finished right here
     loop.exec_()
     # This should be executed after the import process has finished
     if not self._importer_process_successful:
         self._logger.msg_error.emit(
             f"Executing Importer {self.name} failed.")
     else:
         self._logger.msg_success.emit(
             f"Executing Importer {self.name} finished")
     return self._importer_process_successful
Exemplo n.º 22
0
def wait_signal(signal, timeout=5000):
    """Block loop until signal emitted, or timeout (ms) elapses."""
    loop = QEventLoop()
    signal.connect(loop.quit)

    yield

    if timeout:
        timer = QTimer()
        timer.setInterval(timeout)
        timer.setSingleShot(True)
        timer.timeout.connect(loop.quit)
        timer.start()
    else:
        timer = None
    loop.exec_()
    signal.disconnect(loop.quit)
    if timer and timer.isActive():
        timer.stop()
Exemplo n.º 23
0
class ReadSerialPortsThread(QThread):
    """ Find connected serial ports and send it to GUI """
    add_serial_port = Signal(str)
    remove_serial_port = Signal(str)

    def __init__(self, parent=None):
        QThread.__init__(self, parent)
        self.current_port = ''
        self.result = []
        self.loop = ""

        if _platform.startswith('linux'):
            self.ports = ['/dev/ttyS%s' % (i + 1) for i in range(256)]
        elif _platform.startswith('win32'):
            self.ports = ['COM%s' % (i + 1) for i in range(256)]
        elif _platform.startswith('darwin'):
            self.ports = ['/dev/cu.serial%s' % (i + 1) for i in range(256)]

    def run(self):
        """ DOCSTRING """
        while True:
            for port in self.ports:
                if port in self.result:
                    try:
                        serial_conn = serial.Serial(port)
                        serial_conn.close()
                    except (OSError, serial.SerialException):
                        if port != self.current_port:
                            self.result.remove(port)
                            self.remove_serial_port.emit(port)
                else:
                    try:
                        serial_conn = serial.Serial(port)
                        serial_conn.close()
                        if port not in self.result:
                            self.result.append(port)
                            self.add_serial_port.emit(port)
                    except (OSError, serial.SerialException):
                        pass
            self.loop = QEventLoop()
            QTimer.singleShot(50, self.loop.quit)
            self.loop.exec_()
Exemplo n.º 24
0
def main():
    app = QApplication([])
    webview = QWebEngineView()
    loop = QEventLoop()
    webview.loadFinished.connect(loop.quit)
    webview.load(QUrl('http://example.webscraping.com/places/default/search'))
    loop.exec_()

    webview.show()
    frame = webview.page().mainFrame()
    frame.findFirstElement('#search_term').setAttribute('value', '.')
    frame.findFirstElement('#page_size option:checked').setPlainText('1000')
    frame.findFirstElement('#search').evaluateJavaScript('this.click()')

    elements = None
    while not elements:
        app.processEvents()
        elements = frame.findAllElements('#results a')
    countries = [e.toPlainText().strip() for e in elements]
    print(countries)
Exemplo n.º 25
0
    def test_sample(self):
        qDebug("KeySequence : %s" % ['k', 'f', 's'])
        self.obj.clear()
        self.obj.keyPressEvent('k')
        self.obj.keyPressEvent('f')
        self.obj.keyPressEvent('s')
        self.obj.keyPressEvent('Return')

        while self.obj.preedit:
            QEventLoop().processEvents(QEventLoop.AllEvents, 1)
        self.assertEqual(self.obj.text, u"간")
Exemplo n.º 26
0
    def __real_test(self, cases):
        for code in cases:
            self.obj.clear()
            key_sequence = cases[code]
            qDebug("KeySequence : %s" % key_sequence)
            for key in key_sequence:
                self.obj.keyPressEvent(key)
            self.obj.keyPressEvent('Return')

            while self.obj.preedit:
                QEventLoop().processEvents(QEventLoop.AllEvents, 1)
            self.assertEqual(self.obj.text, code)
Exemplo n.º 27
0
 def append_data_to_wifi_graph(self, wifi_dict):
     """DOCSTRING"""
     self.clear_wifi_series.emit()
     for var_x in wifi_dict:
         self.line_series = QtCharts.QLineSeries()
         self.line_series.setName(str(var_x))
         self.line_series.append(
             QPoint(2400 + (wifi_dict[var_x][1] * 5 - 4), -100))
         self.line_series.append(
             QPoint(2411 + (wifi_dict[var_x][1] * 5 - 9),
                    int(wifi_dict[var_x][0])))
         self.line_series.append(
             QPoint(2411 + (wifi_dict[var_x][1] * 5 + 1),
                    int(wifi_dict[var_x][0])))
         self.line_series.append(2422 + (wifi_dict[var_x][1] * 5 - 4), -100)
         self.add_wifi_series.emit(self.line_series)
         self.set_axis_x_series.emit(self.line_series)
         self.set_axis_y_series.emit(self.line_series)
         self.loop = QEventLoop()
         QTimer.singleShot(50, self.loop.quit)
         self.loop.exec_()
Exemplo n.º 28
0
    def _run_importer_program(self, args):
        """Starts and runs the importer program in a separate process.

        Args:
            args (list): List of arguments for the importer program
        """
        self.importer_process = QProcess()
        self.importer_process.readyReadStandardOutput.connect(self._log_importer_process_stdout)
        self.importer_process.readyReadStandardError.connect(self._log_importer_process_stderr)
        self.importer_process.finished.connect(self.importer_process.deleteLater)
        program_path = os.path.abspath(importer_program.__file__)
        self.importer_process.start(sys.executable, [program_path])
        self.importer_process.waitForStarted()
        self.importer_process.write(json.dumps(args).encode("utf-8"))
        self.importer_process.write(b'\n')
        self.importer_process.closeWriteChannel()
        if self.importer_process.state() == QProcess.Running:
            loop = QEventLoop()
            self.importer_process.finished.connect(loop.quit)
            loop.exec_()
        return self.importer_process.exitCode()
Exemplo n.º 29
0
 def _execute_forward(self, resources):
     """See base class."""
     from_urls = self._urls_from_resources(resources)
     to_urls = self._urls_from_resources(self._resources_from_downstream)
     if not from_urls or not to_urls:
         # Moving on...
         return True
     combiner_args = [from_urls, to_urls, self._logs_dir, self._cancel_on_error]
     if not self._prepare_combiner_program(combiner_args):
         self._logger.msg_error.emit(f"Executing Combiner {self.name} failed.")
         return False
     self._combiner_process.start_execution()
     loop = QEventLoop()
     self.recombination_finished.connect(loop.quit)
     # Wait for finished right here
     loop.exec_()
     # This should be executed after the import process has finished
     if not self._combiner_process_successful:
         self._logger.msg_error.emit(f"Executing Combiner {self.name} failed.")
     else:
         self._logger.msg_success.emit(f"Executing Combiner {self.name} finished")
     return self._combiner_process_successful
Exemplo n.º 30
0
 def run(self):
     """ DOCSTRING """
     while True:
         for port in self.ports:
             if port in self.result:
                 try:
                     serial_conn = serial.Serial(port)
                     serial_conn.close()
                 except (OSError, serial.SerialException):
                     if port != self.current_port:
                         self.result.remove(port)
                         self.remove_serial_port.emit(port)
             else:
                 try:
                     serial_conn = serial.Serial(port)
                     serial_conn.close()
                     if port not in self.result:
                         self.result.append(port)
                         self.add_serial_port.emit(port)
                 except (OSError, serial.SerialException):
                     pass
         self.loop = QEventLoop()
         QTimer.singleShot(50, self.loop.quit)
         self.loop.exec_()
Exemplo n.º 31
0
    def initCamera(self,
                   resolution=(640, 480),
                   monochrome=False,
                   framerate=24,
                   effect='none',
                   use_video_port=True):
        # multiple streams are only possible eith the video port!
        self.msg(self.name + "Init: resolution = " + str(resolution))
        self.camera.resolution = resolution
        self.camera.image_effect = effect
        self.camera.image_effect_params = (2, )
        self.camera.iso = 100  # should force unity analog gain
        self.monochrome = monochrome  # spoils edges
        self.camera.framerate = framerate
        if self.monochrome:
            self.rawCapture = PiYArray(self.camera,
                                       size=self.camera.resolution)
            #             self.PreviewArray = PiYArray(self.camera, size=(640,480))
            self.stream = self.camera.capture_continuous(self.rawCapture,
                                                         format='yuv',
                                                         use_video_port=True,
                                                         splitter_port=0)
#             self.previewStream = self.camera.capture_continuous(output=self.PreviewArray, format='yuv', use_video_port=True, splitter_port=1, resize=(640,480))
        else:
            self.rawCapture = PiRGBArray(self.camera,
                                         size=self.camera.resolution)
            #             self.PreviewArray = PiRGBArray(self.camera, size=(640,480))
            self.stream = self.camera.capture_continuous(self.rawCapture,
                                                         format='bgr',
                                                         use_video_port=True,
                                                         splitter_port=0)
#             self.previewStream = self.camera.capture_continuous(output=self.PreviewArray, format='bgr', use_video_port=True, splitter_port=1, resize=(640,480))

        GeneralEventLoop = QEventLoop(self)
        QTimer.singleShot(2, GeneralEventLoop.exit)
        GeneralEventLoop.exec_()