Exemplo n.º 1
0
    def handleOnlineSongs(self, result):
        self._searchOnlineSongObjsListModel.clear()
        self._searchOnlineAlbumObjsListModel.clear()
        if 'songList' in result:
            songList = result['songList']

            for song in songList:
                song['url'] = ""
                song['title'] = song['songName']
                song['artist'] = song['singerName']
                song['album'] = song['albumName']
                song['songId'] = int(song['songId'])
                song['singerId'] = int(song['singerId'])
                song['albumId'] = int(song['albumId'])
                obj = QmlOnlineSongObject(**song)
                self._searchOnlineSongObjsListModel.append(obj)

        if 'albumList' in result and 'data' in result['albumList']:
            albumList = result['albumList']['data']
            for album in albumList:
                index = albumList.index(album)
                album['artist'] = album['singerName']
                album['album'] = album['albumName']
                if self.isAlbumCoverExisted(album['artist'], album['album']):
                    album['cover'] = self.getAlbumCoverPath(album['artist'],
                                                            album['album'])
                else:
                    d = AlbumCover360Runnable(index, self, album['artist'],
                                              album['album'],
                                              album['albumImage'])
                    QThreadPool.globalInstance().start(d)

                obj = QmlOnlineAlbumObject(**album)
                self._searchOnlineAlbumObjsListModel.append(obj)
Exemplo n.º 2
0
    def handleSuggestPlaylist(self, result):
        if 'lists' in result:
            if self._lists != result['lists']:
                self._lists = result['lists']
                self._suggestPlayListModel.clear()
            else:
                return

            lists = self._lists
            for playlist in lists:
                index = lists.index(playlist)
                _list = {}
                _list['listId'] = playlist['listId']
                _list['listName'] = playlist['listName']
                _list['playAll'] = playlist['playAll']

                if self.isPlaylistCoverExisted(playlist['listName']):
                    _list['cover'] = self.getPlaylistCoverPath(playlist[
                        'listName'])
                else:
                    d = PlaylistCover360Runnable(
                        index, self, playlist['listName'], playlist['image'])
                    QThreadPool.globalInstance().start(d)

                obj = QmlSuggestPlaylistObject(**_list)
                self._suggestPlayListModel.append(obj)
Exemplo n.º 3
0
 def __init__(self):
     super(CoverWorker, self).__init__()
     QThreadPool.globalInstance().setMaxThreadCount(4)
     self.downloadArtistCoverSuccessed.connect(self.cacheArtistCover)
     self.downloadAlbumCoverSuccessed.connect(self.cacheAlbumCover)
     self.artistCovers = {}
     self.albumCovers = {}
Exemplo n.º 4
0
 def downloadOnlineAlbumCover(self, artist, title, url, medias):
     f = self.onlineSongCoverPath(artist, title)
     if os.path.exists(f):
         return
     if url:
         d = AlbumCover360Runnable(self, artist, title, url, medias)
         QThreadPool.globalInstance().start(d)
Exemplo n.º 5
0
    def load_children(self, item: QStandardItemModel = None) -> None:
        if not self.client:
            self.set_loading_cursor(False)
            return

        self.set_loading_cursor(True)
        loader = ContentLoader(self, item)
        QThreadPool.globalInstance().start(loader)
Exemplo n.º 6
0
    def run_worker(self, task, callback):
        """Runs a task in another thread.

        The `task` must be an object that implements a `run()`
        method. Completion is notified to the given `callback` function.

        """
        worker = Worker(task)
        worker.finished.connect(callback)
        QThreadPool.globalInstance().start(worker)
Exemplo n.º 7
0
 def __init__(self, parent=None):
     super(CoverWorker, self).__init__(parent)
     QThreadPool.globalInstance().setMaxThreadCount(50)
     self.albumCoverThreadPool.setMaxThreadCount(50)
     self.artistCovers = {}
     self.albumCovers = {}
     self.onlineSongCovers = {}
     self.taskNumber = 0
     self._artists = set()
     self._albums = set()
     self.initConnect()
Exemplo n.º 8
0
    def addSong(self, media):
        _songDict = self.updateTags(media)
        url = media['url']
        self._songsDict[url] = _songDict
        songObj = QmlOnlineSongObject(**_songDict)
        self._songObjs[url] = songObj

        if not songObj.playlinkUrl:
            d = RequestSongRunnable(self, url)
            QThreadPool.globalInstance().start(d)
        else:
            self.downloadCover(_songDict)
Exemplo n.º 9
0
def qrunnable(fn: Callable,
              *args,
              run=True,
              on_complete=None,
              **kwargs) -> QRunnable:
    class QQRunnable(QRunnable):
        def run(self):
            res = fn(*args, **kwargs)
            if res and on_complete:
                on_complete()

    runner = QQRunnable()
    if run:
        QThreadPool.globalInstance().start(runner)

    return runner
    def run_single_parameter_test(self, metrics_id):
        k_values = range(1, len(self.data.index) + 1)
        metrics = MetricsFactory.get_by_id(metrics_id, self.data)

        distances = PrecalculatedDistance(self.data, self.class_column_name,
                                          metrics)
        classifier = KNNClassifier(self.data, self.class_column_name,
                                   distances)
        tester = LeaveOneOutTester(self.data, self.class_column_name)

        worker = TestingWorker(tester, classifier, k_values)
        worker.signals.progress.connect(self.update_progress)
        worker.signals.status.connect(self.update_status)
        worker.signals.result_set.connect(self.finish_test_session)

        QThreadPool.globalInstance().start(worker)
Exemplo n.º 11
0
 def stage_2_modify(response):
     try:
         if response.status_code == 200:
             j=response.json()
             if 'id' in j.keys():
                 modDepartment=Update(self.auth,dict(id=j.get('id')),"department",self.uid)
                 modDepartment.signals.hasError.connect(lambda x:print(x))
                 modDepartment.signals.hasResponse.connect(stage_2)
                 modDepartment.signals.finished.connect(lambda :print("finished adding department"))
                 QThreadPool.globalInstance().start(modDepartment) 
             else:
                 raise Exception("missing id from response") 
             #modify user with new department id
             #on has response call stage_2
     except Exception as e:
         print(e)
Exemplo n.º 12
0
    def refresh_ip_addr(self):
        if self.isTelnetLogined:
            cmd = RRUCmd.get_ipaddr("ipaddr")

            thread = TelnetWorker(RRUCmd.GET_IP_ADDR, cmd)
            thread.signals.connectionLost.connect(self.health_failure)
            thread.signals.consoleDisplay.connect(self._console_slot)
            thread.signals.result.connect(self.refresh_resp_handler)
            QThreadPool.globalInstance().start(thread)
        else:
            msgBox = QtWidgets.QMessageBox()

            msgBox.setWindowTitle('Warning')
            msgBox.setIcon(QtWidgets.QMessageBox.Warning)
            msgBox.setText('Login before Refreshing the IP Address')

            msgBox.exec()
Exemplo n.º 13
0
    def kinopoisk_poster_parser(self, id):
        self.debug('kinopoisk_poster_parser', id)

        movie = None
        if id in self.movie_data_cache:
            movie = self.movie_data_cache[id]

            if movie[12] is None:
                self.signal_set_loading.emit('poster', True)

                worker = PosterWorker(id)
                worker.signals.result.connect(self.poster_result)
                QThreadPool.globalInstance().start(worker)

            else:
                if self.poster_waiting_id is not None:
                    self.signal_send_movie_to_editdialog.emit(movie)
Exemplo n.º 14
0
 def stage_2(response):
     print(response)
     if response.status_code == 200:
         if self.dialog.newAddress.isChecked():
             NewAddress=NewWorker(self.auth,self.addressModel.item,'address')
             NewAddress.signals.hasError.connect(lambda x:print(x))
             NewAddress.signals.hasResponse.connect(stage_3_modify)
             NewAddress.signals.finished.connect(lambda: print("finished creating new address"))
             QThreadPool.globalInstance().start(NewAddress)
         elif self.dialog.existingAddress.isChecked():
             modAddress=Update(self.auth,self.addressModel.dataToItem(),"address",self.uid)
             modAddress.signals.hasError.connect(lambda x:print(x))
             modAddress.signals.hasResponse.connect(stage_complete)
             modAddress.signals.finished.connect(lambda :print("finished adding address"))
             QThreadPool.globalInstance().start(modAddress)
     else:
         raise Exception("response code for address not 200")
Exemplo n.º 15
0
    def _add_axi(self):
        addr, okPressed = QtWidgets.QInputDialog.getText(
            self, "Get Addr", "Axi Offset Addr:", QtWidgets.QLineEdit.Normal,
            "")
        match = ValidCheck.filter(ValidCheck.HEX_RE, addr)
        if okPressed and match is not None:
            cmd = RRUCmd.get_axis_reg(self.parentWidget.get_option(),
                                      match.group())

            thread = TelnetWorker(RRUCmd.GET_AXI_REG, cmd)
            thread.signals.connectionLost.connect(
                self.slot_connection_out_signal)
            thread.signals.result.connect(self.get_resp_handler)
            thread.signals.consoleDisplay.connect(self._console_slot)
            QThreadPool.globalInstance().start(thread)
        elif okPressed and match is None:
            self.warning("Invalid Offset Address")
Exemplo n.º 16
0
 def __init__(self,widget):
     super(Login,self).__init__()
     self.widget=widget
     uic.loadUi("app/Login/forms/login.ui",self.widget)
     
     self.widget.username.textChanged.connect(self.saveLogin)
     self.widget.password.textChanged.connect(self.saveLogin)
     self.widget.server_address.textChanged.connect(self.saveLogin)
     self.widget.rememberMe.toggled.connect(self.handleSave)
     self.widget.login.clicked.connect(self.attemptLogin)
     
     self.qtp=QThreadPool.globalInstance() 
     
     self.l=LoadAuth(self.credfile)
     self.l.signals.hasField.connect(self.authLoaded)
     self.l.signals.rememberMe.connect(self.rememberMe)
     QThreadPool.globalInstance().start(self.l)
Exemplo n.º 17
0
    def _on_run_prediction(self):
        """Run prediction."""

        # Instantiate the manager
        predictor_manager = PredictorManager(
            self._learner, self._data_manager.prediction_input_path,
            self._data_manager.prediction_target_path,
            self._data_manager.model_path)

        # Run the training in a separate Qt thread
        predictor_manager.signals.started.connect(self._on_prediction_start)
        predictor_manager.signals.errored.connect(self._on_prediction_error)
        predictor_manager.signals.finished.connect(
            self._on_prediction_completed)
        predictor_manager.signals.returned.connect(
            self._on_prediction_returned)
        QThreadPool.globalInstance().start(predictor_manager)
Exemplo n.º 18
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()

        self.ui.setupUi(self)

        self.info = {}
        self.collected_data = []
        self.progress = 0  #actual img
        self.target = 20  #img to evaluate
        if debug:
            self.target = 20

        #self.ui.img = DicomWidget(self) #lavorare qua per piazzarlo
        self.ui.pushButtonStart.clicked.connect(lambda: self.load_at_start())

        if debug:
            ## Set the imgs
            pix_not = QPixmap(r'ui\img_not_sufficient.png').scaled(50, 50)
            self.ui.labelInsufficientImg.setPixmap(pix_not)

            pix_low = QPixmap(r'ui\img_low.png').scaled(50, 50)
            self.ui.labelLowImg.setPixmap(pix_low)

            pix_med = QPixmap(r'ui\img_medium.png').scaled(50, 50)
            self.ui.labelMediumImg.setPixmap(pix_med)

            pix_ok = QPixmap(r'ui\img_max.png').scaled(50, 50)
            self.ui.labelMaxImg.setPixmap(pix_ok)

        ## Set the imgs
        pix_not = QPixmap(
            r'C:\Users\IEO5572\PycharmProjects\qt_test_image\ui\img_not_sufficient.png'
        ).scaled(50, 50)
        self.ui.labelInsufficientImg.setPixmap(pix_not)

        pix_low = QPixmap(
            r'C:\Users\IEO5572\PycharmProjects\qt_test_image\ui\img_low.png'
        ).scaled(50, 50)
        self.ui.labelLowImg.setPixmap(pix_low)

        pix_med = QPixmap(
            r'C:\Users\IEO5572\PycharmProjects\qt_test_image\ui\img_medium.png'
        ).scaled(50, 50)
        self.ui.labelMediumImg.setPixmap(pix_med)

        pix_ok = QPixmap(
            r'C:\Users\IEO5572\PycharmProjects\qt_test_image\ui\img_max.png'
        ).scaled(50, 50)
        self.ui.labelMaxImg.setPixmap(pix_ok)

        self.ui.pushButtonInsufficient.clicked.connect(lambda: self.vote(0))
        self.ui.pushButtonLow.clicked.connect(lambda: self.vote(1))
        self.ui.pushButtonMedium.clicked.connect(lambda: self.vote(2))
        self.ui.pushButtonMax.clicked.connect(lambda: self.vote(3))

        self.pool = QThreadPool.globalInstance()
        self.pool.setMaxThreadCount(4)  # Use up to 8 threads
Exemplo n.º 19
0
class HnQTThreadPool():
    thread_list = []

    def __init__(self):
        super().__init__()
        self.threadpool = QThreadPool()
        self.threadpool.globalInstance()
        poolnum = tool.loadJsons(tool.setting_address)[0]['pool_num']
        self.threadpool.setMaxThreadCount(int(poolnum))

    def addThread(self, _thread):
        self.thread_list.append(_thread)

    def Start(self):
        for i in self.thread_list:
            self.threadpool.start(i)
        self.threadpool.waitForDone()
        self.thread_list.clear()
Exemplo n.º 20
0
 def exit(self):
     # Do not start any new threads
     QThreadPool.globalInstance().clear()
     # Wait for any running threads to exit safely
     QThreadPool.globalInstance().waitForDone(5000)  # Kill after 5s
     runners._last_command.clear()
     filelist._paths = []
     filelist._index = 0
     # Needed for cleanup
     QCoreApplication.instance().aboutToQuit.emit()
     api.settings.reset()
     api.mark.mark_clear()
     # Must disconnect these signals ourselves as the automatic disconnection seems
     # to fail with slots assigned using partial
     for name in dir(api.imutils):
         elem = getattr(api.imutils, name)
         if isinstance(elem, pyqtBoundSignal) and name not in dir(QObject):
             elem.disconnect()
Exemplo n.º 21
0
 def downloadArtistCover(self, artist):
     f = self.artistCoverPath(artist)
     if os.path.exists(f):
         return
     if ',' in artist:
         artist = artist.split(',')
         for item in artist:
             if item not in self._artists:
                 self._artists.add(item)
                 self.taskNumber += 1
                 d = CoverRunnable(self, item, qtype="artist")
                 QThreadPool.globalInstance().start(d)
     else:
         if artist not in self._artists:
             self._artists.add(artist)
             self.taskNumber += 1
             d = CoverRunnable(self, artist, qtype="artist")
             QThreadPool.globalInstance().start(d)
Exemplo n.º 22
0
def wait_for_external_command(qtbot):
    """Wait until the external process has completed."""
    max_iterations = 100
    iteration = 0
    while (QThreadPool.globalInstance().activeThreadCount()
           and iteration < max_iterations):
        qtbot.wait(10)
        iteration += 1
    assert iteration != max_iterations, "external command timed out"
Exemplo n.º 23
0
 def downloadArtistCover(self, artist):
     f = self.artistCoverPath(artist)
     if os.path.exists(f):
         return
     if ',' in artist:
         artist = artist.split(',')
         for item in artist:
             if item not in self._artists:
                 self._artists.add(item)
                 self.taskNumber += 1
                 d = CoverRunnable(self, item, qtype="artist")
                 QThreadPool.globalInstance().start(d)
     else:
         if artist not in self._artists:
             self._artists.add(artist)
             self.taskNumber += 1
             d = CoverRunnable(self, artist, qtype="artist")
             QThreadPool.globalInstance().start(d)
Exemplo n.º 24
0
    def cancelTasks(self):
        Task.shutdown_all()
        self.statusBar().showMessage("Waiting for background tasks to terminate...")

        while True:
            qApp.processEvents()
            if QThreadPool.globalInstance().waitForDone(10):
                break

        self.statusBar().showMessage("All background tasks terminated successfully")
Exemplo n.º 25
0
    def save_(self, state):
        #get product row data
        base_item_data = self.model.dataToItem()

        #get relationship data
        manufacturerID = regexThisShit2(self.tab.manufacturers.currentText())
        vendorID = regexThisShit2(self.tab.vendors.currentText())
        brandID = regexThisShit2(self.tab.brands.currentText())
        departmentID = regexThisShit2(self.tab.departments.currentText())

        combos_data = dict(manufacturer=manufacturerID,
                           vendor=vendorID,
                           brand=brandID,
                           department=departmentID)

        productImage = dict()
        product_image = self.tab.product_image.pixmap()
        self.product_image = product_image
        product_image_name = self.displayedImages.get("product_image")
        print(self.displayedImages)
        if product_image_name != "":
            product_image_bio = pixmapToBytesIO(product_image)
            productImage['image'] = product_image_bio
            productImage['name'] = product_image_name
            #upload new image

        upcImage = dict()
        upc_image = self.tab.upc_image.pixmap()
        self.upc_image = upc_image
        upc_image_name = self.displayedImages.get("upc_image")
        if upc_image_name != "":
            upc_image_bio = pixmapToBytesIO(upc_image)
            upcImage['image'] = upc_image_bio
            upcImage['name'] = upc_image_name
            #upload new image

        update = UpdateP(self.auth, base_item_data, combos_data, "product",
                         upcImage, productImage, self.old)
        update.signals.hasError.connect(lambda e: print(e))
        update.signals.hasResponse.connect(self.hasResponse)
        update.signals.finished.connect(lambda: print("finished"))
        update.signals.disabledGrid.connect(self.tab.setEnabled)
        QThreadPool.globalInstance().start(update)
    def edit_address(self):
        wn=self.name
        def preSwitch(item):
            address=item
            if type(item) == type(list()):
                address=item[0]
            self.wantsToSwitch.emit(address)
            print(address)
            #self.parent.stackedWidgets

        address_data=regexThisShit2(self.tab.addresses.currentText())
        addrID=address_data.get('ID')
        searchL=SearchWorker(self.auth,dict(id=addrID,page=0,limit=sys.maxsize),'address',fields('address'))
        searchL.signals.hasError.connect(lambda x:print(x))
        searchL.signals.hasItem.connect(preSwitch)
        searchL.signals.hasItems.connect(preSwitch)

        QThreadPool.globalInstance().start(searchL)
        print(address_data)
Exemplo n.º 27
0
 def __init__(self, *args, **kwargs):
     super(MainWindow, self).__init__(*args, **kwargs)
     self.setupUi(self)
     QTimer.singleShot(
         1, self.load_settings)  # Initialize settings after ui setup
     self.threadpool = QThreadPool.globalInstance()
     self.update_text.connect(self.append_text)
     self.use_client_box.currentIndexChanged.connect(
         self.on_client_change, self.use_client_box.currentIndex())
     self.did_they_save = False
Exemplo n.º 28
0
    def __init__(self, config_path: Path, parent):
        super(ServerSettings, self).__init__()
        self.config_path = config_path
        self.parent = parent
        self.dialog = QDialog(parent)
        uic.loadUi("Client/MainWindow/forms/server_settings.ui", self.dialog)
        self.dialog.setWindowTitle("Server Settings")

        self.conf_reader = readServerConfig(server_config())
        self.conf_reader.signals.finished.connect(
            lambda: print("finished reading server config"))
        self.conf_reader.signals.hasError.connect(
            lambda x: QErrorMessage(self.paret).showMessage(str(x) + __name__))

        @pyqtSlot(dict)
        def load(data):
            print(data)
            self.model.load_data(data, re=True)
            self.setDelegates()

        self.conf_reader.signals.hasConfig.connect(load)
        QThreadPool.globalInstance().start(self.conf_reader)

        self.model = TableModel(item=dict())
        self.dialog.editor.setModel(self.model)
        prep_table(self.dialog.editor)

        def userAcceptsChanges():
            saver = saveServerConfig(self.dialog, server_config(),
                                     self.model.item)
            saver.signals.finished.connect(lambda: print(
                "finished saving server... you need to restart the server"))
            #need a serverNeedsRestart signal
            saver.signals.hasError.connect(lambda x: QErrorMessage(self.parent)
                                           .showMessage(str(x) + __name__))
            QThreadPool.globalInstance().start(saver)

            print(self.model.item)

        self.dialog.confirm.accepted.connect(userAcceptsChanges)

        self.dialog.show()
Exemplo n.º 29
0
    def __init__(self,parent:QWidget,address:str,auth:tuple):
        super(DeleteDialog,self).__init__()

        self.auth=auth
        self.address=address
        self.w=parent
        self.dialog=QDialog(parent)
        uic.loadUi("app/DeleteDialog/forms/DeleteDialog.ui",self.dialog)

        self.qtp=QThreadPool.globalInstance()
        updaterSelector=UpdateSelector(self.w,self.dialog.selector)
        updaterSelector.signals.ready.connect(self.selector_ud)

        self.qtp.start(updaterSelector)        
        self.dialog.selector.activated.connect(self.stack_changer)
        
        #widget
        self.adr=EntityStack(self.w,self.dialog.address,self.dialog,self.address,self.auth,"address")
        self.adr.done_del.connect(self.progress_statement) 
        #for first displayable widget that user will see so selector is populated
        self.adr.worker.signals.waitResult=False
        self.enabledWidgetsChanger.append(self.adrCH)


        self.brand=EntityStack(self.w,self.dialog.brand,self.dialog,self.address,self.auth,"brand")
        self.brand.done_del.connect(self.progress_statement)
        self.enabledWidgetsChanger.append(self.brandCH)

        self.vendor=EntityStack(self.w,self.dialog.vendor,self.dialog,self.address,self.auth,"vendor")
        self.vendor.done_del.connect(self.progress_statement)               
        self.enabledWidgetsChanger.append(self.vendorCH)

        self.manufacturer=EntityStack(self.w,self.dialog.manufacturer,self.dialog,self.address,self.auth,"manufacturer")
        self.manufacturer.done_del.connect(self.progress_statement)               
        self.enabledWidgetsChanger.append(self.manufacturerCH)

        self.department=EntityStack(self.w,self.dialog.department,self.dialog,self.address,self.auth,"department")
        self.department.done_del.connect(self.progress_statement)               
        self.enabledWidgetsChanger.append(self.departmentCH)

        self.priceUnit=EntityStack(self.w,self.dialog.priceUnit,self.dialog,self.address,self.auth,"priceUnit")
        self.priceUnit.done_del.connect(self.progress_statement)               
        self.enabledWidgetsChanger.append(self.priceUnitCH)

        self.weightUnit=EntityStack(self.w,self.dialog.weightUnit,self.dialog,self.address,self.auth,"weightUnit")
        self.weightUnit.done_del.connect(self.progress_statement)               
        self.enabledWidgetsChanger.append(self.weightUnitCH)

        self.product=EntityStack(self.w,self.dialog.product,self.dialog,self.address,self.auth,"product")
        self.product.done_del.connect(self.progress_statement)               
        self.enabledWidgetsChanger.append(self.productCH)

        #first time using QThreadPool, ping me if you have any ideas, questions or comments
        self.dialog.show() 
Exemplo n.º 30
0
    def get(*, globalinstance: bool = True) -> QThreadPool:
        """Return a thread pool to work with.

        Args:
            globalinstance: Return the Qt application thread pool instead of a new one.
        """
        if globalinstance:
            return QThreadPool.globalInstance()
        threadpool = QThreadPool()
        Pool._threadpools.append(threadpool)
        return threadpool
Exemplo n.º 31
0
 def init_config(self):
     """
     初始化全局配置
     :return:
     """
     try:
         initConfigTask = InitConfigTask(self)
         pool = QThreadPool.globalInstance()
         pool.start(initConfigTask)
     except Exception as e:
         self.print_log(str(e))
     pass
Exemplo n.º 32
0
 def update(self):
     conn = connection.get()
     self.model.set_connection(conn)
     try:
         mapped = self.model.mapped(update_required=True)
     except Exception as e:
         msg = Message(self.ui, Message.ERROR, self.messages[4], str(e))
         msg.show()
     else:
         if mapped:
             pd = Progress(self.ui, self.messages[9], 0, len(mapped))
             pd.show()
             worker = Worker(self.updater, mapped)
             worker.signals.progress.connect(pd.setValue)
             worker.signals.error.connect(pd.close)
             worker.signals.error.connect(self.update_error)
             worker.signals.done.connect(self.update_done)
             QThreadPool.globalInstance().start(worker)
             self.tab.btnUpdate.setDisabled(True)
     finally:
         conn.close()
Exemplo n.º 33
0
    def loadPhoto(self, size, onLoadFun):
        # there already is a pixmap smaller or equal to requested
        if self.pixmap is not None and _sizeFits(size, self.pixmap.size()):
            onLoadFun(self.pixmap)
        else:
            doMetrics = self.metrics is None
            loaderTask = ImageLoaderThread(self.fileName,
                                           [self.PHOTOITEM_PIXMAP_SIZE, size],
                                           calculateMetrics=doMetrics)

            loaderTask.signals.pixmapReady.connect(onLoadFun,
                                                   Qt.QueuedConnection)

            if doMetrics:
                loaderTask.signals.metricsReady.connect(
                    self._calculatedMetrics, Qt.QueuedConnection)

            if self.pixmap is None:
                loaderTask.signals.pixmapReady.connect(self._loadedPhoto,
                                                       Qt.QueuedConnection)

            QThreadPool.globalInstance().start(loaderTask)
Exemplo n.º 34
0
def thread_pool():
    """Return a QThreadPool instance that can `start()` Worker instances for multithreading.

    Example
    -------

    ```python
    w = Worker(print, "hello world")
    thread_pool().start(w)
    ```

    """
    return QThreadPool.globalInstance()
Exemplo n.º 35
0
    def updateDataFiles(self):
        """Calls coingecko's API and writes btcfiat.json, coinlist.json, coinprices.json"""
        self.updatingdata_mssg = QDialog(self)
        updatingdata_lyt = QVBoxLayout()
        text = QLabel(self.tr("Updating data. Please wait..."))
        updatingdata_lyt.addWidget(text)
        self.updatingdata_mssg.setLayout(updatingdata_lyt)
        self.updatingdata_mssg.show()

        # Run update on separate thread
        update_data_process = UpdateData(self)
        threadpool = QThreadPool.globalInstance()
        threadpool.start(update_data_process)
Exemplo n.º 36
0
 def stage_1(response):
     try:
         #print(response.json())
         if response.status_code == 200 and response.json().get("status") != 'old':
             self.uid=response.json().get("id")
             if self.dialog.newDepartment.isChecked():
                 NewDepartment=NewWorker(self.auth,self.departmentModel.item,"department")
                 NewDepartment.signals.hasError.connect(lambda x:print(x))
                 NewDepartment.signals.hasResponse.connect(stage_2_modify)
                 NewDepartment.signals.finished.connect(lambda:print("finished creating new department"))
                 QThreadPool.globalInstance().start(NewDepartment)
             elif self.dialog.existingDepartment.isChecked():
                 modDepartment=Update(self.auth,self.departmentModel.dataToItem(),"department",self.uid)
                 modDepartment.signals.hasError.connect(lambda x:print(x))
                 modDepartment.signals.hasResponse.connect(stage_2)
                 modDepartment.signals.finished.connect(lambda :print("finished adding department"))
                 QThreadPool.globalInstance().start(modDepartment)
             #modify department
         else:
             raise Exception("response for department was not 200")
     except Exception as e:
         print(e)
Exemplo n.º 37
0
    def cachedUser(self):
        try:
            def hasUser(user):
                self.auth['username']=user.get("uname")
                self.auth['password']=user.get("password")
                self.auth['host']=user.get("host")
                self.parent.username.setText(user.get("uname"))
                self.parent.password.setText(user.get("password"))
                self.parent.host.setText(user.get("host"))
                self.cmdline_options()
                self.parent.rememberMe.setChecked(user.get("rememberMe"))

                self.signals.hasUser.emit(user)
                
            self.cached=Remember(self.parent,Path.home()/Path(".cache")/Path("User.json"))
            self.cached.signals.finished.connect(lambda :print("finished loading user from cache"))
            #not this one
            self.cached.signals.hasError.connect(lambda x:QErrorMessage(self.parent).showMessage(str(x)+__name__))
            self.cached.signals.hasUser.connect(hasUser)
            QThreadPool.globalInstance().start(self.cached)
        except Exception as e:
            print(e)
Exemplo n.º 38
0
 def print_log(self, message):
     """
     异度打印日志
     :param message: 日志信息
     :return:
     """
     try:
         logTask = LogTask(self, message)
         pool = QThreadPool.globalInstance()
         pool.start(logTask)
     except Exception as msg:
         print(msg)
     pass
Exemplo n.º 39
0
    def set_ip_addr(self):
        if self.isTelnetLogined:
            ipaddr2set = ValidCheck.filter(ValidCheck.IPADDR_RE,
                                           self.ipaddrEdit.text().strip())
            if ipaddr2set is not None:
                cmd = RRUCmd.config_ipaddr("ipaddr", ipaddr2set.group())

                thread = TelnetWorker(RRUCmd.SET_IP_ADDR, cmd)
                thread.signals.connectionLost.connect(self.health_failure)
                thread.signals.consoleDisplay.connect(self._console_slot)
                thread.signals.result.connect(self.set_handler)
                QThreadPool.globalInstance().start(thread)
            else:
                self.ipaddrEdit.setStyleSheet(NonQSSStyle.warningStyle)
        else:
            msgBox = QtWidgets.QMessageBox()

            msgBox.setWindowTitle('Warning')
            msgBox.setIcon(QtWidgets.QMessageBox.Warning)
            msgBox.setText('Login before Setting the IP Address')

            msgBox.exec()
Exemplo n.º 40
0
    def __init__(self,
      # A number *n* to create a pool of *n* simple threads, where each thread
      # lacks an event loop, so that it can emit but not receive signals.
      # This means that g_ may **not** be run in a thread of this pool,
      # without manually adding a event loop. If *n* < 1, the global thread
      # pool is used.
      maxThreadCount,

      # See parent_.
      parent=None):

        super().__init__(parent)
        if maxThreadCount < 1:
            self.threadPool = QThreadPool.globalInstance()
        else:
            self.threadPool = QThreadPool(self)
            self.threadPool.setMaxThreadCount(maxThreadCount)
Exemplo n.º 41
0
 def deffer_to_thread(self, cb, *args, **kwargs):
     args = (self, ) + args
     thread = Thread(self, cb, *args, **kwargs)
     QThreadPool.globalInstance().start(thread)
Exemplo n.º 42
0
    def run(self):
        engine = NetEaseEngine()
        if self.qtype == "artist":
            url = engine.searchCoverByArtistName(self.name)
        elif self.qtype == "album":
            url = engine.searchCoverByAlbumName(self.name)

        coverWorker.receiveCover.emit(self.qtype, self.name, url)


if __name__ == "__main__":
    app = QGuiApplication(sys.argv)

    artists = []
    for artist in db.get_cursor().execute("Select name from artist").fetchall():
        artists.append(artist)

    albums = []
    for album in db.get_cursor().execute("Select name from album").fetchall():
        albums.append(album)

    for artist in artists:
        d = DRunnable(artist, qtype="artist")
        QThreadPool.globalInstance().start(d)
    for album in albums:
        d = DRunnable(album, qtype="album")
        QThreadPool.globalInstance().start(d)

    exitCode = app.exec_()
    sys.exit(exitCode)
Exemplo n.º 43
0
class SomeObjectToDoComplicatedStuff(QRunnable):
    def __init__(self, name):
        QRunnable.__init__(self)
        self.name = name

    def run(self):
        print('running', self.name)
        a = 10
        b = 30
        c = 0
        for i in range(5000000):
            c += a**b
        print('done', self.name)


pool = QThreadPool.globalInstance()
pool.setMaxThreadCount(10)

batch_size = 100

workers = [None] * batch_size

for i in range(batch_size):
    worker = SomeObjectToDoComplicatedStuff('object ' + str(i))
    workers[i] = worker
    pool.start(worker)

print('All cued')
pool.waitForDone()

# processing the results back
Exemplo n.º 44
0
 def restoreSongs(self, songs):
     d = RestoreDBRunnable(self, songs)
     QThreadPool.globalInstance().start(d)
Exemplo n.º 45
0
    def cacheAlbumCover(self, artist, album, url):
        # print artist, album, url
        self.albumCovers[album] = url

    def downloadArtistCover(self, artist):
        d = CoverRunnable(self, artist, qtype="artist")
        QThreadPool.globalInstance().start(d)

    def downloadAlbumCover(self, artist, album):
        d = CoverRunnable(self, artist, album, qtype="artist")
        QThreadPool.globalInstance().start(d)


if __name__ == '__main__':
    app = QGuiApplication(sys.argv)
    QThreadPool.globalInstance().setMaxThreadCount(10)
    from peewee import *
    MusicDBFile = '/home/djf/.config/DeepinMusic3/music.db'
    db = SqliteDatabase(MusicDBFile, threadlocals=True)
    db.connect()

    coverWorker = CoverWorker()
    artists = []
    for artist in db.get_cursor().execute('Select name from artist').fetchall():
        artists.append(artist[0])
    for artist in artists:
        coverWorker.downloadArtistCover(artist)

    albums = []
    for artist, album in db.get_cursor().execute(
            'Select artist, name from album').fetchall():
Exemplo n.º 46
0
 def start(self, action, data=None):
     QThreadPool.globalInstance().start(
         PugdebugAsyncTask(self, action, data)
     )
Exemplo n.º 47
0
 def close(self):
     QThreadPool.globalInstance().clear()
     mediaPlayer.stop()
     configWorker.save()
     playlistWorker.savePlaylists()
Exemplo n.º 48
0
 def downloadAlbumCover(self, artist, album):
     d = CoverRunnable(self, artist, album, qtype="artist")
     QThreadPool.globalInstance().start(d)
Exemplo n.º 49
0
 def addSongs(self, songs):
     d = DBRunnable(self, songs)
     QThreadPool.globalInstance().start(d)