class DamTerm(QObject): #Main Class def __init__(self, addr): super(self.__class__, self).__init__() self.start() @pyqtSlot(str) def take_info(self, _str): print("TAKE::INFO:: %s" % _str) with open("test", "w") as f: f.write("Test") self.info.write(_str) def test(self): print("TESTETT!") def start(self): print("Start!") self.GenUids = GenerateUids(self) self.th = QThread(self) self.th.setObjectName("GenerateUids") self.GenUids.moveToThread(self.th) self.GenUids.pasInfo.connect(self.take_info) self.th.started.connect(self.GenUids.run) self.th.start() while not self.th.isFinished(): time.sleep(1) print("while") print("Koniec startu")
def __init__(self, main_window, exp_number, scan_tuple_list, mask_det, mask_name, norm_type, num_pt_bg_left, num_pt_bg_right, scale_factor=1.000): """ :param main_window: :param exp_number: :param scan_tuple_list: list of tuples for scan as (scan number, pt number list, state as merged) :param mask_det: :param mask_name: :param norm_type: type of normalization :param num_pt_bg_left: number of Pt in the left :param num_pt_bg_right: number of Pt for background in the right """ # start thread QThread.__init__(self) # check assert main_window is not None, 'Main window cannot be None' assert isinstance(exp_number, int), 'Experiment number must be an integer.' assert isinstance(scan_tuple_list, list), 'Scan (info) tuple list must be a list but not %s.' \ '' % str(type(scan_tuple_list)) assert isinstance(mask_det, bool), 'Parameter mask_det must be a boolean but not %s.' \ '' % str(type(mask_det)) assert isinstance(mask_name, str), 'Name of mask must be a string but not %s.' % str(type(mask_name)) assert isinstance(norm_type, str), 'Normalization type must be a string but not %s.' \ '' % str(type(norm_type)) assert isinstance(num_pt_bg_left, int) and num_pt_bg_left >= 0,\ 'Number of Pt at left for background {0} must be non-negative integers but not of type {1}.' \ ''.format(num_pt_bg_left, type(num_pt_bg_left)) assert isinstance(num_pt_bg_right, int) and num_pt_bg_right >= 0,\ 'Number of Pt at right for background {0} must be non-negative integers but not of type {1}.' \ ''.format(num_pt_bg_right, type(num_pt_bg_right)) # set values self._mainWindow = main_window self._expNumber = exp_number self._scanTupleList = scan_tuple_list[:] self._maskDetector = mask_det self._normalizeType = norm_type self._selectedMaskName = mask_name self._numBgPtLeft = num_pt_bg_left self._numBgPtRight = num_pt_bg_right self._scaleFactor = scale_factor # other about preprocessed options self._checkPreprocessedScans = True # link signals self.peakMergeSignal.connect(self._mainWindow.update_merge_value) self.mergeMsgSignal.connect(self._mainWindow.update_merge_message) return
def shutdown(self): """Shutdown kernel""" self.shutdown_called = True self.spyder_kernel_comm.close() self.spyder_kernel_comm.shutdown_comm_channel() self.kernel_manager.stop_restarter() self.shutdown_thread = QThread() self.shutdown_thread.run = self.kernel_manager.shutdown_kernel if self.kernel_client is not None: self.shutdown_thread.finished.connect( self.kernel_client.stop_channels) self.shutdown_thread.start() super(ShellWidget, self).shutdown()
def shutdown(self): """Shutdown kernel""" if self.get_kernel() is not None and not self.slave: self.shellwidget.spyder_kernel_comm.close() self.shellwidget.spyder_kernel_comm.shutdown_comm_channel() try: self.shellwidget._pdb_history_file.save_thread.stop() except AttributeError: pass self.shellwidget.kernel_manager.stop_restarter() self.shutdown_thread = QThread() self.shutdown_thread.run = self.finalize_shutdown self.shutdown_thread.finished.connect(self.stop_kernel_channels) self.shutdown_thread.start()
def restart_kernel(self): """ Restart the associated kernel. Took this code from the qtconsole project Licensed under the BSD license """ sw = self.shellwidget if not running_under_pytest() and self.ask_before_restart: message = _('Are you sure you want to restart the kernel?') buttons = QMessageBox.Yes | QMessageBox.No result = QMessageBox.question(self, _('Restart kernel?'), message, buttons) else: result = None if (result == QMessageBox.Yes or running_under_pytest() or not self.ask_before_restart): if sw.kernel_manager: if self.infowidget.isVisible(): self.infowidget.hide() if self._abort_kernel_restart(): sw.spyder_kernel_comm.close() return self._show_loading_page() # Close comm sw.spyder_kernel_comm.close() # Stop autorestart mechanism sw.kernel_manager.stop_restarter() sw.kernel_manager.autorestart = False # Create and run restarting thread self.restart_thread = QThread() self.restart_thread.run = self._restart_thread_main self.restart_thread.error = None self.restart_thread.finished.connect( lambda: self._finalise_restart(True)) self.restart_thread.start() else: sw._append_plain_text( _('Cannot restart a kernel not started by Spyder\n'), before_prompt=True) self._hide_loading_page()
def grab_data(self, Naverage=1, **kwargs): """ """ coeff = self.settings.child(('width_coeff')).value() fun_type = self.settings.child(('fun_type')).value() self.datas = np.zeros((self.Ny, self.Nx)) self.stop_flag = False if self.scan_parameters is not None: for ind in range(self.scan_parameters.Nsteps): if self.stop_flag: break positions = (self.x_axis[self.scan_parameters.axes_indexes[ind, 0]], self.y_axis[self.scan_parameters.axes_indexes[ind, 1]]) if fun_type == 'Gaussians': self.datas[self.scan_parameters.axes_indexes[ind, 1], self.scan_parameters.axes_indexes[ ind, 0]] = random_hypergaussians2D_signal( positions, coeff) else: self.datas[self.scan_parameters.axes_indexes[ind, 1], self.scan_parameters.axes_indexes[ ind, 0]] = diverging2D_signal(positions, coeff) if ind % 100 == 0: # refresh plot every 100 grabed points self.data_grabed_signal_temp.emit([ utils.DataFromPlugins( name='MockScanner', data=[self.datas], dim='Data2D', x_axis=utils.Axis(data=self.x_axis), y_axis=utils.Axis(data=self.y_axis)) ]) QtWidgets.QApplication.processEvents() QThread.msleep(100) self.data_grabed_signal.emit([ utils.DataFromPlugins(name='MockScanner', data=[self.datas], dim='Data2D', x_axis=utils.Axis(data=self.x_axis), y_axis=utils.Axis(data=self.y_axis)) ]) self.ind_data += 1
def ini_PID(self): if self.ini_PID_action.isChecked(): output_limits = [None, None] if self.settings.child('main_settings', 'pid_controls', 'output_limits', 'output_limit_min_enabled').value(): output_limits[0] = self.settings.child('main_settings', 'pid_controls', 'output_limits', 'output_limit_min').value() if self.settings.child('main_settings', 'pid_controls', 'output_limits', 'output_limit_max_enabled').value(): output_limits[1] = self.settings.child('main_settings', 'pid_controls', 'output_limits', 'output_limit_max').value() self.PIDThread = QThread() pid_runner = PIDRunner(self.model_class, self.modules_manager, setpoints=self.setpoints, params=dict(Kp=self.settings.child('main_settings', 'pid_controls', 'pid_constants', 'kp').value(), Ki=self.settings.child('main_settings', 'pid_controls', 'pid_constants', 'ki').value(), Kd=self.settings.child('main_settings', 'pid_controls', 'pid_constants', 'kd').value(), sample_time=self.settings.child('main_settings', 'pid_controls', 'sample_time').value() / 1000, output_limits=output_limits, auto_mode=False), ) self.PIDThread.pid_runner = pid_runner pid_runner.pid_output_signal.connect(self.process_output) pid_runner.status_sig.connect(self.thread_status) self.command_pid.connect(pid_runner.queue_command) pid_runner.moveToThread(self.PIDThread) self.PIDThread.start() self.pid_led.set_as_true() self.enable_controls_pid_run(True) else: if hasattr(self, 'PIDThread'): if self.PIDThread.isRunning(): try: self.PIDThread.quit() except Exception: pass self.pid_led.set_as_false() self.enable_controls_pid_run(False) self.Initialized_state = True
def __init__(self, parent, enable_code_snippets=True): QObject.__init__(self, parent) self.endpoint = None self.requests = {} self.languages = [] self.mutex = QMutex() self.opened_files = {} self.opened_files_status = {} self.thread_started = False self.enable_code_snippets = enable_code_snippets self.thread = QThread() self.moveToThread(self.thread) self.thread.started.connect(self.started) self.sig_perform_request.connect(self.perform_request) self.sig_perform_status_request.connect(self.get_status)
def check_updates(self, startup=False): """Check for spyder updates on github releases using a QThread.""" # Disable check_updates_action while the thread is working self.check_updates_action.setDisabled(True) if self.thread_updates is not None: self.thread_updates.terminate() self.thread_updates = QThread(self) self.worker_updates = WorkerUpdates(self, startup=startup) self.worker_updates.sig_ready.connect(self._check_updates_ready) self.worker_updates.sig_ready.connect(self.thread_updates.quit) self.worker_updates.moveToThread(self.thread_updates) self.thread_updates.started.connect(self.worker_updates.start) self.thread_updates.start()
def run(self): while(self.is_processing): value = self.buffer.get() if value: self.do_zoom.emit() self.is_zooming = True # wait for zoom to finish. while(self.is_zooming): QThread.msleep(10) # one more, to prevent hiccups. QThread.msleep(10)
def show_notification(cls, notification: Notification): from ...utils.settings import get_settings settings = get_settings() # after https://github.com/napari/napari/issues/2370, # the os.getenv can be removed (and NAPARI_CATCH_ERRORS retired) if ( os.getenv("NAPARI_CATCH_ERRORS") not in ('0', 'False') and notification.severity >= settings.application.gui_notification_level ): application_instance = QApplication.instance() if application_instance: # Check if this is running from a thread if application_instance.thread() != QThread.currentThread(): dispatcher = getattr( application_instance, "_dispatcher", None ) if dispatcher: dispatcher.sig_notified.emit(notification) return cls.from_notification(notification).show()
def __init__(self, serialport, callback): super().__init__() self.signal.connect(callback) self.serialport = serialport self.thread = QThread() #self.timer = QTimer() #self.timer.setSingleShot(True) self.timerStopped = True self.thread.started.connect(self.run) self.moveToThread(self.thread) self.msg1 = [] self.msg2 = [] self.flagGlitch = False self.flagCatch = False self.flagModbus = False
def start(self): """Start server and create socket workers.""" self.__logger = logging.getLogger(self.__class__.__name__) # noqa self.workers = [] # noqa self.threads = [] # noqa if not self.cores: self.cores = QThread.idealThreadCount() self.close_signal.connect(self.close, Qt.BlockingQueuedConnection) self.write.connect(self._write) self.write_all.connect(self._write_all) self.kick.connect(self._kick) self.__logger.debug("Allocating {} worker threads...".format(self.cores)) try: for i in range(self.cores): self.create_worker() self.__logger.info("Started worker threads!") self.__logger.debug("Active socket workers: {}".format(sum([1 for x in self.threads if x.isRunning()]))) self.started.emit() except Exception as e: self.__logger.error("Failed to start socket handler: {}".format(e)) self.close()
def launch_youtubedl(self, query: str) -> None: """ Starts a YoutubeDL thread that will call either self.on_youtubedl_success or self.on_youtubedl_fail once it's done. """ logging.info("Starting the youtube-dl thread") self.youtubedl = YouTubeDLWorker( query, self.config.debug, self.config.width, self.config.height) self.yt_thread = QThread() self.youtubedl.moveToThread(self.yt_thread) self.yt_thread.started.connect(self.youtubedl.get_url) self.youtubedl.success.connect(self.on_yt_success) self.youtubedl.fail.connect(self.on_youtubedl_fail) self.youtubedl.finish.connect(self.yt_thread.exit) self.yt_thread.start()
def setAcquisitionMode(self, mode): """ Set the acquisition mode. The acquisition mode is modified only if it corresponds to the current used instrument. If success, the parameters controller is also setup. Args: mode (str): aquisition mode name """ if ((self.instrument is None) or (mode not in RundexSettings.ACQUISITION_MODES[self.instrument])): return self.rundexFile = None self.samples = list() self.acquisitionMode = mode self.columns = RundexSettings.COLUMNS[self.acquisitionMode] self.algorithm = RundexSettings.ALGORITHM[self.acquisitionMode] if self.acquisitionMode in RundexSettings.THREADS_NUMBER: nThreads = RundexSettings.THREADS_NUMBER[self.acquisitionMode] else: nThreads = QThread.idealThreadCount() self.tasksPool.setMaxThreadCount(nThreads) self.settings = dict() self.settings.update(RundexSettings.SETTINGS[self.acquisitionMode]) self._initController()
def setAcquisitionMode(self, mode): """ Set the acquisition mode. The acquisition mode is modified only if it corresponds to the current used instrument. If success, the parameters controller is also setup. Args: mode (str): aquisition mode name """ if ((self.instrument is None) or (mode not in RundexSettings.ACQUISITION_MODES[self.instrument])): return self._samples = list() self._sampleGroups = dict() self.visualSettings = dict() if mode in RundexSettings.VISUAL_SETTINGS: self.visualSettings = RundexSettings.VISUAL_SETTINGS[mode] self.acquisitionMode = mode self.algorithm = RundexSettings.ALGORITHM[self.acquisitionMode] if self.acquisitionMode in RundexSettings.THREADS_NUMBER: nThreads = RundexSettings.THREADS_NUMBER[self.acquisitionMode] else: nThreads = QThread.idealThreadCount() self.tasksPool.setMaxThreadCount(nThreads) self.exportModel = DrillExportModel(self.acquisitionMode) self._initController() self._initProcessingParameters()
def startSimulation(self): self._run_model.reset() self._snapshot_model.reset() self._tab_widget.clear() evaluator_server_config = EvaluatorServerConfig() def run(): asyncio.set_event_loop(asyncio.new_event_loop()) self._run_model.startSimulations( evaluator_server_config=evaluator_server_config, ) simulation_thread = Thread(name="ert_gui_simulation_thread") simulation_thread.setDaemon(True) simulation_thread.run = run simulation_thread.start() self._ticker.start(1000) tracker = EvaluatorTracker( self._run_model, ee_con_info=evaluator_server_config.get_connection_info(), ) worker = TrackerWorker(tracker) worker_thread = QThread() worker.done.connect(worker_thread.quit) worker.consumed_event.connect(self._on_tracker_event) worker.moveToThread(worker_thread) self.simulation_done.connect(worker.stop) self._worker = worker self._worker_thread = worker_thread worker_thread.started.connect(worker.consume_and_emit) self._worker_thread.start()
def startSimulation(self): self._run_model.reset() self._snapshot_model.reset() self._tab_widget.clear() def run(): asyncio.set_event_loop(asyncio.new_event_loop()) self._run_model.startSimulations(self._simulations_argments) simulation_thread = Thread(name="ert_gui_simulation_thread") simulation_thread.setDaemon(True) simulation_thread.run = run simulation_thread.start() self._ticker.start(1000) tracker = create_tracker( self._run_model, num_realizations=self._simulations_argments["active_realizations"]. count(), ee_config=self._simulations_argments.get("ee_config", None), ) worker = TrackerWorker(tracker) worker_thread = QThread() worker.done.connect(worker_thread.quit) worker.consumed_event.connect(self._on_tracker_event) worker.moveToThread(worker_thread) self.simulation_done.connect(worker.stop) self._worker = worker self._worker_thread = worker_thread worker_thread.started.connect(worker.consume_and_emit) self._worker_thread.start()
def my_excepthook(type_, value, trace_back): """ Custom excepthook. base on base on :py:data:`state_store.show_error_dialog` decide if shown error dialog. """ # log the exception here if state_store.show_error_dialog and not isinstance(value, KeyboardInterrupt): if state_store.report_errors and parsed_version.is_devrelease: with sentry_sdk.push_scope() as scope: scope.set_tag("auto_report", "true") sentry_sdk.capture_exception(value) try: # noinspection PyUnresolvedReferences from qtpy.QtWidgets import QApplication if QApplication.instance(): from qtpy.QtCore import QMetaObject, Qt, QThread QApplication.instance().error = value if QThread.currentThread() != QApplication.instance().thread(): QMetaObject.invokeMethod(QApplication.instance(), "show_error", Qt.QueuedConnection) else: QApplication.instance().show_error() except ImportError: sys.__excepthook__(type_, value, trace_back) elif isinstance(value, KeyboardInterrupt): print("KeyboardInterrupt close", file=sys.stderr) sys.exit(1) else: # then call the default handler sys.__excepthook__(type_, value, trace_back)
def run(self): logger = logging.getLogger("SSTF") incomming = collections.deque(copy.deepcopy(self.que)) queue = collections.deque() completed = collections.deque() current_pos = self.start_pos time = incomming[0].arrive_time self.setHeadPos(current_pos) while True: for request in list(incomming): if request.arrive_time <= time: queue.append(request) incomming.remove(request) self.addRequest(request.cylinder) if len(queue) != 0: nearest: Request = min( queue, key=lambda req: abs(current_pos - req.cylinder)) queue.remove(nearest) completed.append(nearest) QThread.msleep(100) self.removeRequest(nearest.cylinder) # calculate delta of head position and add it to time delta = abs(current_pos - nearest.cylinder) current_pos = nearest.cylinder time = time + delta QThread.msleep(100) self.setHeadPos(current_pos) for other in list(queue): other.add_wait_time(delta) if len(incomming) == 0 and len(queue) == 0: break longest_waiting = max(completed, key=operator.attrgetter("wait_time")) logger.info("================= SSTF =================") logger.info("High starvation rate for requests on \"edges\" of disk.") logger.info("Average waiting time: {}".format( round(sum(req.wait_time for req in completed) / len(completed), 2))) logger.info( "Request with longest waiting time ID: {}, Time: {}, Cylinder: {}, Arrived: {}" .format(longest_waiting.request_id, longest_waiting.wait_time, longest_waiting.cylinder, longest_waiting.arrive_time))
def __init__(self, main_window, exp_number, scan_number_list, md_file_list): """Initialization :param main_window: :param exp_number: :param scan_number_list: list of tuples for scan as (scan number, pt number list, state as merged) :param md_file_list: """ # check assert main_window is not None, 'Main window cannot be None' assert isinstance(exp_number, int), 'Experiment number must be an integer.' assert isinstance(scan_number_list, list), 'Scan (info) tuple list {0} must be a list but not {1}.' \ ''.format(scan_number_list, type(scan_number_list)) assert isinstance(md_file_list, list) or md_file_list is None, 'Output MDWorkspace file name list {0} ' \ 'must be either a list or None but not {1}.' \ ''.format(md_file_list, type(md_file_list)) if md_file_list is not None and len(scan_number_list) != len( md_file_list): raise RuntimeError( 'If MD file list is not None, then it must have the same size ({0}) as the ' 'scans ({1}) to merge.'.format(len(md_file_list), len(scan_number_list))) # start thread QThread.__init__(self) # set values self._mainWindow = main_window self._expNumber = exp_number self._scanNumberList = scan_number_list[:] self._outputMDFileList = None if md_file_list is not None: self._outputMDFileList = md_file_list[:] # other about preprocessed options self._checkPreprocessedScans = False self._preProcessedDir = None self._redoMerge = True # link signals self.mergeMsgSignal.connect(self._mainWindow.update_merge_value) self.saveMsgSignal.connect(self._mainWindow.update_file_name) return
def setup_docks(self): ''' subclass method from CustomApp ''' logger.debug('setting docks') self.dock_settings = Dock('Settings', size=(350, 350)) self.dockarea.addDock(self.dock_settings, 'left') self.dock_settings.addWidget(self.settings_tree, 10) self.dock_logger = Dock("Logger") self.logger_list = QtWidgets.QListWidget() self.logger_list.setMinimumWidth(300) self.dock_logger.addWidget(self.logger_list) self.dockarea.addDock(self.dock_logger, 'bottom', self.dock_settings) # create a dock containing a viewer object, could be 0D, 1D or 2D depending what kind of data one want to plot here a 0D dock_Viewer0D = Dock('Viewer dock', size=(350, 350)) self.dockarea.addDock(dock_Viewer0D, 'right', self.dock_logger) target_widget = QtWidgets.QWidget() self.target_viewer = Viewer0D(target_widget) dock_Viewer0D.addWidget(target_widget) # create 2 docks to display the DAQ_Viewer (one for its settings, one for its viewer) self.dock_detector_settings = Dock("Detector Settings", size=(350, 350)) self.dockarea.addDock(self.dock_detector_settings, 'right', self.dock_settings) self.dock_detector = Dock("Detector Viewer", size=(350, 350)) self.dockarea.addDock(self.dock_detector, 'right', self.dock_detector_settings) # init one daq_viewer object named detector self.detector = DAQ_Viewer(self.dockarea, dock_settings=self.dock_detector_settings, dock_viewer=self.dock_detector, title="A detector", DAQ_type='DAQ0D') # set its type to 'Mock' self.detector.daq_type = 'Mock' # init the detector and wait 1000ms for the completion self.detector.init_det() self.detector.settings.child('main_settings', 'wait_time').setValue(100) QtWidgets.QApplication.processEvents() QThread.msleep(1000) logger.debug('docks are set')
def ini_stage_fun(self): """ Init : * a DAQ_move_stage instance if not exists * a linked thread connected by signal to the DAQ_move_main instance See Also -------- set_enabled_move_buttons, DAQ_utils.ThreadCommand, DAQ_Move_stage, DAQ_Move_stage.queue_command, thread_status, DAQ_Move_stage.update_settings, update_status """ try: if not self.ui.IniStage_pb.isChecked(): try: self.set_enabled_move_buttons(enable=False) self.ui.Stage_type_combo.setEnabled(True) self.ui.Ini_state_LED.set_as_false() self.command_stage.emit(ThreadCommand(command="close")) except Exception as e: self.logger.exception(str(e)) else: self.stage_name = self.ui.Stage_type_combo.currentText() stage = DAQ_Move_stage(self.stage_name, self.current_position, self.title) self.stage_thread = QThread() stage.moveToThread(self.stage_thread) self.command_stage[ThreadCommand].connect(stage.queue_command) stage.status_sig[ThreadCommand].connect(self.thread_status) self.update_settings_signal[edict].connect( stage.update_settings) self.stage_thread.stage = stage self.stage_thread.start() self.ui.Stage_type_combo.setEnabled(False) self.command_stage.emit( ThreadCommand(command="ini_stage", attributes=[ self.settings.child( ('move_settings')).saveState(), self.controller ])) except Exception as e: self.logger.exception(str(e)) self.set_enabled_move_buttons(enable=False)
def __init__(self, parent): QThread.__init__(self, parent) self.mutex = QMutex() self.stopped = None self.results = None self.pathlist = None self.nb = None self.error_flag = None self.rootpath = None self.python_path = None self.hg_manifest = None self.include = None self.exclude = None self.texts = None self.text_re = None self.completed = None self.get_pythonpath_callback = None
def create_thread(target, *args, dispose=False, parent=None, **kwargs): thread_ = QThread(parent) worker = ThreadWorker(target, *args, **kwargs) worker.moveToThread(thread_) thread_.started.connect(worker.run) worker.finished.connect(thread_.quit) if dispose: worker.finished.connect(worker.deleteLater) thread_.finished.connect(thread_.deleteLater) # Make the worker an attribute of the thread to stop Python from garbage collecting it. # https://stackoverflow.com/a/63274024/2512078 thread_.worker = worker return thread_
def grab_data(self, Naverage=1, **kwargs): """ """ self.status_timer.stop() data_tot = [] selected_channels = self.settings.child(('channels')).value()['selected'] for channel in selected_channels: data, diag = self.controller.get_diag_from_name(channel) data = int.from_bytes(data, 'big') / diag['divider'] self.settings.child('diagnostics', f'diag_{diag["id"]}').setValue(data) data_tot.append(np.array([data])) QThread.msleep(200) self.data_grabed_signal.emit( [DataFromPlugins(name='AmplitudeSystems', data=data_tot, dim='Data0D', labels=selected_channels)]) self.status_timer.start(1000)
def __init__(self, parent): QThread.__init__(self, parent) self.mutex = QMutex() self.stopped = None self.results = None self.pathlist = None self.total_matches = None self.error_flag = None self.rootpath = None self.exclude = None self.texts = None self.text_re = None self.completed = None self.case_sensitive = True self.results = {} self.total_matches = 0 self.is_file = False
def run(self): """ 运行代码 """ call_id_list = self.scene.topo_sort() self.scene.call_id_list = call_id_list thread = QThread() for node in self.scene.nodes: node.reset() node.content.moveToThread(thread) worker = self.scene.find_node(call_id_list[0]).content worker.moveToThread(thread) thread.started.connect(worker._process) thread.start() self.worker = worker self.thread = thread
def create_worker(self): """Creates new socket worker in thread.""" thread = QThread() worker = _SocketWorker() worker.moveToThread(thread) worker.connected.connect(self.connected.emit) # noqa worker.message.connect(self.message.emit) # noqa worker.disconnected.connect(self.disconnected.emit) # noqa worker.error.connect(self.error.emit) # noqa thread.started.connect(worker.start) # noqa worker.closed.connect(thread.quit) # noqa worker.closed.connect(thread.wait) # noqa self.workers.append(worker) self.threads.append(thread) thread.start()
def addAlgorithm(self, algorithm): algorithm_thread = QThread() algorithm.setDiskSize(self.disk_size) algorithm.moveToThread(algorithm_thread) algorithm_thread.started.connect(algorithm.run) self.algorithms.append(algorithm) self.threads.append(algorithm_thread) self.update()
def grab_data(self, Naverage=1, **kwargs): #for rapid block mode """ | Start a new acquisition. | | grab the current values with Picoscope 5000A profile procedure. =============== ======== =============================================== **Parameters** **Type** **Description** *Naverage* int Number of spectrum to average =============== ======== =============================================== Returns ------- string list the updated status. See Also -------- daq_utils.ThreadCommand """ try: self.Naverage = Naverage N_pre_trigger = int(self.Nsample_available * self.settings.child( 'main_settings', 'trigger', 'trig_pretrigger').value() / 100) N_post_trigger = self.Nsample_available - N_pre_trigger status = self.pico.setNoOfCapture( self.settings.child('main_settings', 'Nsegments').value()) if status != "PICO_OK": self.emit_status( ThreadCommand("Update_Status", [status, 'log'])) status = self.pico.run_block(N_pre_trigger, N_post_trigger, ind_segment=0) if status[0] == "PICO_OK": if type(status[1]) == int: QThread.msleep(status[1]) return status except Exception as e: self.emit_status( ThreadCommand("Update_Status", [getLineInfo() + str(e), 'log']))
def start_process(self): if not self.is_running(): self.out_thread = QThread(self) self.monitor_thread = ProcessMonitorThread() self.monitor_thread.args = self.args self.monitor_thread.moveToThread(self.out_thread) self.out_thread.started.connect(self.monitor_thread.run) self.out_thread.start() self.monitor_thread.on_out.connect(self.on_stdout) self.monitor_thread.on_err.connect(self.on_stderr) self.signal_stop_qthread.connect(self.monitor_thread.stop) self.out_thread.finished.connect(self.out_thread.deleteLater) self.out_thread.finished.connect(self.monitor_thread.deleteLater) self.monitor_thread.on_finished.connect(self.terminate_process)
def __init__(self, main_window, exp_number, scan_number_list, md_file_list): """Initialization :param main_window: :param exp_number: :param scan_number_list: list of tuples for scan as (scan number, pt number list, state as merged) :param md_file_list: """ # check assert main_window is not None, 'Main window cannot be None' assert isinstance(exp_number, int), 'Experiment number must be an integer.' assert isinstance(scan_number_list, list), 'Scan (info) tuple list {0} must be a list but not {1}.' \ ''.format(scan_number_list, type(scan_number_list)) assert isinstance(md_file_list, list) or md_file_list is None, 'Output MDWorkspace file name list {0} ' \ 'must be either a list or None but not {1}.' \ ''.format(md_file_list, type(md_file_list)) if md_file_list is not None and len(scan_number_list) != len(md_file_list): raise RuntimeError('If MD file list is not None, then it must have the same size ({0}) as the ' 'scans ({1}) to merge.'.format(len(md_file_list), len(scan_number_list))) # start thread QThread.__init__(self) # set values self._mainWindow = main_window self._expNumber = exp_number self._scanNumberList = scan_number_list[:] self._outputMDFileList = None if md_file_list is not None: self._outputMDFileList = md_file_list[:] # other about preprocessed options self._checkPreprocessedScans = False self._preProcessedDir = None self._redoMerge = True # link signals self.mergeMsgSignal.connect(self._mainWindow.update_merge_value) self.saveMsgSignal.connect(self._mainWindow.update_file_name) return
def __init__(self, parent): QThread.__init__(self, parent) self.mutex = QMutex() self.stopped = None self.results = None self.pathlist = None self.total_matches = None self.error_flag = None self.rootpath = None self.python_path = None self.hg_manifest = None self.exclude = None self.texts = None self.text_re = None self.completed = None self.case_sensitive = True self.get_pythonpath_callback = None self.results = {} self.total_matches = 0 self.is_file = False
def _start(self, worker=None): """Start threads and check for inactive workers.""" if worker: self._queue_workers.append(worker) if self._queue_workers and self._running_threads < self._max_threads: #print('Queue: {0} Running: {1} Workers: {2} ' # 'Threads: {3}'.format(len(self._queue_workers), # self._running_threads, # len(self._workers), # len(self._threads))) self._running_threads += 1 worker = self._queue_workers.popleft() thread = QThread() if isinstance(worker, PythonWorker): worker.moveToThread(thread) worker.sig_finished.connect(thread.quit) thread.started.connect(worker._start) thread.start() elif isinstance(worker, ProcessWorker): thread.quit() worker._start() self._threads.append(thread) else: self._timer.start() if self._workers: for w in self._workers: if w.is_finished(): self._bag_collector.append(w) self._workers.remove(w) if self._threads: for t in self._threads: if t.isFinished(): self._threads.remove(t) self._running_threads -= 1 if len(self._threads) == 0 and len(self._workers) == 0: self._timer.stop() self._timer_worker_delete.start()
def revert(self): """ Takes the data stored in the models and displays them in the widgets. """ # make sure it is called from main thread if (not QThread.currentThread() == QCoreApplication.instance( ).thread()): QTimer.singleShot(0, self.revert) return for key in self._mappings: self._on_model_notification(key)
def start(self): print("Start!") self.GenUids = GenerateUids(self) self.th = QThread(self) self.th.setObjectName("GenerateUids") self.GenUids.moveToThread(self.th) self.GenUids.pasInfo.connect(self.take_info) self.th.started.connect(self.GenUids.run) self.th.start() while not self.th.isFinished(): time.sleep(1) print("while") print("Koniec startu")
def setup_packages(self): """ """ pip_packages = self._conda_process.pip_list(prefix=self._prefix) self._thread.terminate() self._thread = QThread(self) self._worker = PackagesWorker(self, self._repo_files, self._prefix, self._root_prefix, pip_packages) self._worker.sig_status_updated.connect(self._update_status) self._worker.sig_ready.connect(self._worker_ready) self._worker.sig_ready.connect(self._thread.quit) self._worker.moveToThread(self._thread) self._thread.started.connect(self._worker._prepare_model) self._thread.start()
def __call__(self, *args, **kwargs): """ If the current thread is the qApp thread then this performs a straight call to the wrapped callable_obj. Otherwise it invokes the do_call method as a slot via a BlockingQueuedConnection. """ if QThread.currentThread() == self.qApp.thread(): return self.callee(*args, **kwargs) else: self._store_function_args(*args, **kwargs) QMetaObject.invokeMethod(self, "on_call", Qt.BlockingQueuedConnection) if self._exc_info is not None: reraise(*self._exc_info) return self._result
def submit(self): """ Submits the current values stored in the widgets to the models. """ # make sure it is called from main thread if (not QThread.currentThread() == QCoreApplication.instance( ).thread()): QTimer.singleShot(0, self.submit) return submit_policy = self._submit_policy self.submit_policy = SUBMIT_POLICY_AUTO try: for key in self._mappings: self._on_widget_property_notification(key) finally: self.submit_policy = submit_policy
def setup_packages(self): """ """ if self._selected_env is None: self._selected_env = const.ROOT self._thread.terminate() self._thread = QThread(self) self._worker = PackagesWorker(self, self._repo_files, self._selected_env, self._prefix) self._worker.sig_status_updated.connect(self._update_status) self._worker.sig_ready.connect(self._worker_ready) self._worker.sig_ready.connect(self._thread.quit) self._worker.moveToThread(self._thread) self._thread.started.connect(self._worker._prepare_model) self._thread.start()
def accept(self): """Called when the user clicks the "Okay" button of the dialog.""" # Show the progress bar and abort button self.progress_bar.setEnabled(True) self.abort_button.setEnabled(True) self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) self.button_box.button(QDialogButtonBox.Cancel).setEnabled(False) if self._func_proxy is not None: op_func = lambda *args, **kwargs: self._func_proxy(self._function, *args, **kwargs) else: op_func = self._function self._op_thread = QThread() self._op_worker = OperationWorker(self._compose_cube(), op_func) self._op_worker.moveToThread(self._op_thread) self._op_worker.result.connect(self.on_finished) self._op_worker.status.connect(self.on_status_updated) self._op_thread.started.connect(self._op_worker.run) self._op_thread.start()
class SpectralOperationHandler(QDialog): """ Widget to handle user interactions with operations that are communicated from the SpecViz viewer. This is built to work with :func:`~spectral_cube.SpectralCube.apply_function` method by passing in a callable :class:`specviz.analysis.operations.FunctionalOperation` object. Parameters ---------- data : :class:`~glue.core.data.Data` Glue data object on which the spectral operation will be performed. function : :class:`specviz.analysis.operations.FunctionalOperation` Python class instance whose `call` function will be performed on the :class:`~spectral_cube.SpectralCube` object. """ def __init__(self, data, component_id, layout, function=None, func_proxy=None, stack=None, operation_name=None, ui_settings=None, *args, **kwargs): super(SpectralOperationHandler, self).__init__(*args, **kwargs) self._data = data self._stack = stack self._func_proxy = func_proxy self._function = function or (stack[0] if stack is not None else None) self._operation_name = operation_name or (self._function.function.__name__ if self._function is not None else "None") self._component_id = component_id self._operation_thread = None self._layout = layout self._ui_settings = ui_settings self._op_thread = None self.setup_ui() self.setup_connections() def setup_ui(self): """Setup the PyQt UI for this dialog.""" # Load the ui dialog loadUi(os.path.join(os.path.dirname(__file__), "operation_dialog.ui"), self) if self._ui_settings is not None: self.setWindowTitle(self._ui_settings.get("title")) self.operation_group_box.setTitle(self._ui_settings.get("group_box_title")) self.description_label.setText(self._ui_settings.get("description")) component_ids = [str(i) for i in self._data.component_ids()] cur_ind = self._data.component_ids().index(self._component_id) if self._stack is not None: operation_stack = [] for oper in self._stack: func_params = [] for arg in oper.args: func_params.append("{}".format(arg)) for k, v in oper.kwargs.items(): func_params.append("{}={}".format(k, str(v)[:10] + "... " + str( v)[-5:] if len( str(v)) > 15 else str( v))) operation_stack.append("{}({})".format(oper.function.__name__, ", ".join(func_params))) self.operation_combo_box.addItems(operation_stack) else: self.operation_combo_box.addItem(self._operation_name) # Populate combo box self.data_component_combo_box.addItems(component_ids) self.data_component_combo_box.setCurrentIndex(cur_ind) # Disable the button box if there are no available operations if self._function is None: self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) def setup_connections(self): """Setup signal/slot connections for this dialog.""" # When an operation is selected, update the function reference self.operation_combo_box.currentIndexChanged.connect( self.on_operation_index_changed) # When a data component is selected, update the data object reference self.data_component_combo_box.currentIndexChanged.connect( self.on_data_component_index_changed) # If the abort button is clicked, attempted to stop execution self.abort_button.clicked.connect(self.on_aborted) def _compose_cube(self): """ Create a :class:`~spectral_cube.SpectralCube` from a Glue data component. """ if issubclass(self._data.__class__, Subset): wcs = self._data.data.coords.wcs data = self._data.data mask = self._data.to_mask() else: wcs = self._data.coords.wcs data = self._data mask = np.ones(self._data.shape).astype(bool) mask = BooleanArrayMask(mask=mask, wcs=wcs) return SpectralCube(data[self._component_id], wcs=wcs, mask=mask, meta={'unit':self._data.get_component(self._component_id).units}) def on_operation_index_changed(self, index): """Called when the index of the operation combo box has changed.""" self._function = self._stack[index] def on_data_component_index_changed(self, index): """Called when the index of the component combo box has changed.""" self._component_id = self._data.component_ids()[index] def accept(self): """Called when the user clicks the "Okay" button of the dialog.""" # Show the progress bar and abort button self.progress_bar.setEnabled(True) self.abort_button.setEnabled(True) self.button_box.button(QDialogButtonBox.Ok).setEnabled(False) self.button_box.button(QDialogButtonBox.Cancel).setEnabled(False) if self._func_proxy is not None: op_func = lambda *args, **kwargs: self._func_proxy(self._function, *args, **kwargs) else: op_func = self._function self._op_thread = QThread() self._op_worker = OperationWorker(self._compose_cube(), op_func) self._op_worker.moveToThread(self._op_thread) self._op_worker.result.connect(self.on_finished) self._op_worker.status.connect(self.on_status_updated) self._op_thread.started.connect(self._op_worker.run) self._op_thread.start() # data, unit = op_func(self._compose_cube(), None) # self.on_finished(data, unit) def on_aborted(self): """Called when the user aborts the operation.""" self._op_thread.terminate() self.progress_bar.reset() # Hide the progress bar and abort button self.abort_button.setEnabled(False) self.button_box.button(QDialogButtonBox.Ok).setEnabled(True) self.button_box.button(QDialogButtonBox.Cancel).setEnabled(True) def on_status_updated(self, value): """ Called when the status of the operation has been updated. This can be optionally be passed a value to use as the new progress bar value. Parameters ---------- value : float The value passed to the :class:`~qtpy.QtWidgets.QProgressBar` instance. """ self.progress_bar.setValue(value * 100) def on_finished(self, data, unit=None): """ Called when the `QThread` has finished performing the operation on the `SpectralCube` object. Parameters ---------- data : ndarray The result of the operation performed on the `SpectralCube` object. """ component_name = "{} {}".format(self._component_id, self._operation_name) comp_count = len([x for x in self._data.component_ids() if component_name in str(x)]) if comp_count > 0: component_name = "{} {}".format(component_name, comp_count) if data.ndim == 2: coords = WCSCoordinates(wcs=self._data.coords.wcs.celestial) self._data.container_2d = Data(label=self._data.label + " [2d]", coords=coords) self._data.container_2d.add_component(data, component_name) # self._layout.session.data_collection.append(self._data.container_2d) self._layout.add_overlay(data, component_name, display_now=True) else: component = Component(data, units=unit) self._data.add_component(component, component_name) self._op_thread.exit() super(SpectralOperationHandler, self).accept()
def __init__(self, duration): QThread.__init__(self) self.duration = duration
def __init__(self): QThread.__init__(self)
def __init__(self, parent, name=None, prefix=None, channels=[]): super(CondaPackagesWidget, self).__init__(parent) self._parent = parent self._status = '' # Statusbar message self._conda_process = conda_api_q.CondaProcess(self) self._root_prefix = self._conda_process.ROOT_PREFIX self._prefix = None self._temporal_action_dic = {} self._download_manager = DownloadManager(self, self._on_download_finished, self._on_download_progress, self.CONDA_CONF_PATH) self._thread = QThread(self) self._worker = None self._db_metadata = cp.ConfigParser() self._db_file = CondaPackagesWidget.DATABASE_FILE self._db_metadata.readfp(open(osp.join(self.DATA_PATH, self._db_file))) self._packages_names = None self._row_data = None self._hide_widgets = False # TODO: Hardcoded channels for the moment self._default_channels = [ ['_free_', 'http://repo.continuum.io/pkgs/free'], #['_pro_', 'http://repo.continuum.io/pkgs/pro'] ] self._extra_channels = channels # pyqt not working with ssl some bug here on the anaconda compilation # [['binstar_goanpeca_', 'https://conda.binstar.org/goanpeca']] self._repo_name = None # linux-64, win-32, etc... self._channels = None # [['filename', 'channel url'], ...] self._repo_files = None # [filepath, filepath, ...] self._packages = {} self._download_error = None self._error = None # Widgets self.combobox_filter = QComboBox(self) self.button_update = QPushButton(_('Update package index')) self.textbox_search = SearchLineEdit(self) self.table = CondaPackagesTable(self) self.status_bar = QLabel(self) self.progress_bar = QProgressBar(self) self.button_ok = QPushButton(_('Ok')) self.bbox = QDialogButtonBox(Qt.Horizontal) self.bbox.addButton(self.button_ok, QDialogButtonBox.ActionRole) self.widgets = [self.button_update, self.combobox_filter, self.textbox_search, self.table, self.button_ok] # Widgets setup self.combobox_filter.addItems([k for k in const.COMBOBOX_VALUES_ORDERED]) self.combobox_filter.setMinimumWidth(120) self.button_ok.setDefault(True) self.button_ok.setAutoDefault(True) self.button_ok.setVisible(False) self.progress_bar.setVisible(False) self.progress_bar.setTextVisible(False) self.progress_bar.setMaximumHeight(16) self.progress_bar.setMaximumWidth(130) self.setWindowTitle(_("Conda Package Manager")) self.setMinimumSize(QSize(480, 300)) # Signals and slots self.combobox_filter.currentIndexChanged.connect(self.filter_package) self.button_update.clicked.connect(self.update_package_index) self.textbox_search.textChanged.connect(self.search_package) self._conda_process.sig_partial.connect(self._on_conda_process_partial) self._conda_process.sig_finished.connect(self._on_conda_process_ready) # NOTE: do not try to save the QSpacerItems in a variable for reuse # it will crash python on exit if you do! # Layout self._spacer_w = 250 self._spacer_h = 5 self._top_layout = QHBoxLayout() self._top_layout.addWidget(self.combobox_filter) self._top_layout.addWidget(self.button_update) self._top_layout.addWidget(self.textbox_search) self._middle_layout = QVBoxLayout() self._middle_layout.addWidget(self.table) self._bottom_layout = QHBoxLayout() self._bottom_layout.addWidget(self.status_bar, Qt.AlignLeft) self._bottom_layout.addWidget(self.progress_bar, Qt.AlignRight) self._layout = QVBoxLayout(self) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self._layout.addLayout(self._top_layout) self._layout.addLayout(self._middle_layout) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self._layout.addLayout(self._bottom_layout) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self._layout.addWidget(self.bbox) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self.setLayout(self._layout) # Setup self.set_environment(name=name, prefix=prefix, update=False) if self._supports_architecture(): self.update_package_index() else: status = _('no packages supported for this architecture!') self._update_status(progress=[0, 0], hide=True, status=status)
class CondaPackagesWidget(QWidget): """Conda Packages Widget.""" # Location of updated repo.json files from continuum/binstar CONDA_CONF_PATH = get_conf_path('repo') # Location of continuum/anaconda default repos shipped with conda-manager DATA_PATH = get_module_data_path() # file inside DATA_PATH with metadata for conda packages DATABASE_FILE = 'packages.ini' sig_worker_ready = Signal() sig_packages_ready = Signal() sig_environment_created = Signal() def __init__(self, parent, name=None, prefix=None, channels=[]): super(CondaPackagesWidget, self).__init__(parent) self._parent = parent self._status = '' # Statusbar message self._conda_process = conda_api_q.CondaProcess(self) self._root_prefix = self._conda_process.ROOT_PREFIX self._prefix = None self._temporal_action_dic = {} self._download_manager = DownloadManager(self, self._on_download_finished, self._on_download_progress, self.CONDA_CONF_PATH) self._thread = QThread(self) self._worker = None self._db_metadata = cp.ConfigParser() self._db_file = CondaPackagesWidget.DATABASE_FILE self._db_metadata.readfp(open(osp.join(self.DATA_PATH, self._db_file))) self._packages_names = None self._row_data = None self._hide_widgets = False # TODO: Hardcoded channels for the moment self._default_channels = [ ['_free_', 'http://repo.continuum.io/pkgs/free'], #['_pro_', 'http://repo.continuum.io/pkgs/pro'] ] self._extra_channels = channels # pyqt not working with ssl some bug here on the anaconda compilation # [['binstar_goanpeca_', 'https://conda.binstar.org/goanpeca']] self._repo_name = None # linux-64, win-32, etc... self._channels = None # [['filename', 'channel url'], ...] self._repo_files = None # [filepath, filepath, ...] self._packages = {} self._download_error = None self._error = None # Widgets self.combobox_filter = QComboBox(self) self.button_update = QPushButton(_('Update package index')) self.textbox_search = SearchLineEdit(self) self.table = CondaPackagesTable(self) self.status_bar = QLabel(self) self.progress_bar = QProgressBar(self) self.button_ok = QPushButton(_('Ok')) self.bbox = QDialogButtonBox(Qt.Horizontal) self.bbox.addButton(self.button_ok, QDialogButtonBox.ActionRole) self.widgets = [self.button_update, self.combobox_filter, self.textbox_search, self.table, self.button_ok] # Widgets setup self.combobox_filter.addItems([k for k in const.COMBOBOX_VALUES_ORDERED]) self.combobox_filter.setMinimumWidth(120) self.button_ok.setDefault(True) self.button_ok.setAutoDefault(True) self.button_ok.setVisible(False) self.progress_bar.setVisible(False) self.progress_bar.setTextVisible(False) self.progress_bar.setMaximumHeight(16) self.progress_bar.setMaximumWidth(130) self.setWindowTitle(_("Conda Package Manager")) self.setMinimumSize(QSize(480, 300)) # Signals and slots self.combobox_filter.currentIndexChanged.connect(self.filter_package) self.button_update.clicked.connect(self.update_package_index) self.textbox_search.textChanged.connect(self.search_package) self._conda_process.sig_partial.connect(self._on_conda_process_partial) self._conda_process.sig_finished.connect(self._on_conda_process_ready) # NOTE: do not try to save the QSpacerItems in a variable for reuse # it will crash python on exit if you do! # Layout self._spacer_w = 250 self._spacer_h = 5 self._top_layout = QHBoxLayout() self._top_layout.addWidget(self.combobox_filter) self._top_layout.addWidget(self.button_update) self._top_layout.addWidget(self.textbox_search) self._middle_layout = QVBoxLayout() self._middle_layout.addWidget(self.table) self._bottom_layout = QHBoxLayout() self._bottom_layout.addWidget(self.status_bar, Qt.AlignLeft) self._bottom_layout.addWidget(self.progress_bar, Qt.AlignRight) self._layout = QVBoxLayout(self) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self._layout.addLayout(self._top_layout) self._layout.addLayout(self._middle_layout) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self._layout.addLayout(self._bottom_layout) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self._layout.addWidget(self.bbox) self._layout.addItem(QSpacerItem(self._spacer_w, self._spacer_h)) self.setLayout(self._layout) # Setup self.set_environment(name=name, prefix=prefix, update=False) if self._supports_architecture(): self.update_package_index() else: status = _('no packages supported for this architecture!') self._update_status(progress=[0, 0], hide=True, status=status) def _supports_architecture(self): """ """ self._set_repo_name() if self._repo_name is None: return False else: return True def _set_repo_name(self): """Get python system and bitness, and return default repo name""" system = sys.platform.lower() bitness = 64 if sys.maxsize > 2**32 else 32 machine = platform.machine() fname = [None, None] if 'win' in system: fname[0] = 'win' elif 'lin' in system: fname[0] = 'linux' elif 'osx' in system or 'darwin' in system: # TODO: is this correct? fname[0] = 'osx' else: return None if bitness == 32: fname[1] = '32' elif bitness == 64: fname[1] = '64' else: return None # armv6l if machine.startswith('armv6'): fname[1] = 'armv6l' if None in fname: self._repo_name = None else: self._repo_name = '-'.join(fname) def _set_channels(self): """ """ default = self._default_channels extra = self._extra_channels body = self._repo_name tail = '/repodata.json' channels = [] files = [] for channel in default + extra: prefix = channel[0] url = '{0}/{1}{2}'.format(channel[1], body, tail) name = '{0}{1}.json'.format(prefix, body) channels.append([name, url]) files.append(osp.join(self.CONDA_CONF_PATH, name)) self._repo_files = files self._channels = channels def _download_repodata(self): """download the latest version available of the repo(s)""" status = _('Updating package index...') self._update_status(hide=True, progress=[0, 0], status=status) self._download_manager.set_queue(self._channels) self._download_manager.start_download() # --- Callback download manager # ------------------------------------------------------------------------ def _on_download_progress(self, progress): """function called by download manager when receiving data progress : [int, int] A two item list of integers with relating [downloaded, total] """ self._update_status(hide=True, progress=progress, status=None) def _on_download_finished(self): """function called by download manager when finished all downloads this will be called even if errors were encountered, so error handling is done here as well """ error = self._download_manager.get_errors() if error is not None: self._update_status(hide=False) if not osp.isdir(self.CONDA_CONF_PATH): os.mkdir(self.CONDA_CONF_PATH) for repo_file in self._repo_files: # if a file does not exists, look for one in DATA_PATH if not osp.isfile(repo_file): filename = osp.basename(repo_file) bck_repo_file = osp.join(self.DATA_PATH, filename) # if available copy to CONDA_CONF_PATH if osp.isfile(bck_repo_file): shutil.copy(bck_repo_file, repo_file) # otherwise remove from the repo_files list else: self._repo_files.remove(repo_file) self._error = None self.setup_packages() # ------------------------------------------------------------------------ def setup_packages(self): """ """ pip_packages = self._conda_process.pip_list(prefix=self._prefix) self._thread.terminate() self._thread = QThread(self) self._worker = PackagesWorker(self, self._repo_files, self._prefix, self._root_prefix, pip_packages) self._worker.sig_status_updated.connect(self._update_status) self._worker.sig_ready.connect(self._worker_ready) self._worker.sig_ready.connect(self._thread.quit) self._worker.moveToThread(self._thread) self._thread.started.connect(self._worker._prepare_model) self._thread.start() def _worker_ready(self): """ """ self._packages_names = self._worker.packages_names self._packages_versions = self._worker.packages_versions self._row_data = self._worker.row_data # depending on the size of table this might lock the gui for a moment self.table.setup_model(self._packages_names, self._packages_versions, self._row_data) self.table.filter_changed() self._update_status(hide=False) self.filter_package(const.INSTALLED) self.sig_worker_ready.emit() self.sig_packages_ready.emit() def _update_status(self, status=None, hide=True, progress=None, env=False): """Update status bar, progress bar display and widget visibility status : str TODO: hide : bool TODO: progress : [int, int] TODO: """ self.busy = hide for widget in self.widgets: widget.setDisabled(hide) self.progress_bar.setVisible(hide) if status is not None: self._status = status if self._prefix == self._root_prefix: short_env = 'root' elif self._conda_process.environment_exists(prefix=self._prefix): short_env = osp.basename(self._prefix) else: short_env = self._prefix if env: self._status = '{0} (<b>{1}</b>)'.format(self._status, short_env) self.status_bar.setText(self._status) if progress is not None: self.progress_bar.setMinimum(0) self.progress_bar.setMaximum(progress[1]) self.progress_bar.setValue(progress[0]) def _run_action(self, package_name, action, version, versions): """ """ prefix = self._prefix dlg = CondaPackageActionDialog(self, prefix, package_name, action, version, versions) if dlg.exec_(): dic = {} self.status = 'Processing' self._update_status(hide=True) self.repaint() ver1 = dlg.label_version.text() ver2 = dlg.combobox_version.currentText() pkg = u'{0}={1}{2}'.format(package_name, ver1, ver2) dep = dlg.checkbox.checkState() state = dlg.checkbox.isEnabled() dlg.close() dic['pkg'] = pkg dic['dep'] = not (dep == 0 and state) dic['action'] = None self._run_conda_process(action, dic) def _run_conda_process(self, action, dic): """ """ cp = self._conda_process prefix = self._prefix if prefix == self._root_prefix: name = 'root' elif self._conda_process.environment_exists(prefix=prefix): name = osp.basename(prefix) else: name = prefix if 'pkg' in dic and 'dep' in dic: pkgs = dic['pkg'] if not isinstance(pkgs, list): pkgs = [pkgs] dep = dic['dep'] if action == const.INSTALL or action == const.UPGRADE or \ action == const.DOWNGRADE: status = _('Installing <b>') + dic['pkg'] + '</b>' status = status + _(' into <i>') + name + '</i>' cp.install(prefix=prefix, pkgs=pkgs, dep=dep) elif action == const.REMOVE: status = (_('moving <b>') + dic['pkg'] + '</b>' + _(' from <i>') + name + '</i>') cp.remove(pkgs[0], prefix=prefix) # --- Actions to be implemented in case of environment needs elif action == const.CREATE: status = _('Creating environment <b>') + name + '</b>' cp.create(prefix=prefix, pkgs=pkgs) elif action == const.CLONE: status = (_('Cloning ') + '<i>' + dic['cloned from'] + _('</i> into <b>') + name + '</b>') elif action == const.REMOVE_ENV: status = _('Removing environment <b>') + name + '</b>' self._update_status(hide=True, status=status, progress=[0, 0]) self._temporal_action_dic = dic def _on_conda_process_ready(self): """ """ error = self._conda_process.error if error is None: status = _('there was an error') self._update_status(hide=False, status=status) else: self._update_status(hide=True) dic = self._temporal_action_dic if dic['action'] == const.CREATE: self.sig_environment_created.emit() self.setup_packages() def _on_conda_process_partial(self): """ """ try: partial = self._conda_process.partial.split('\n')[0] partial = json.loads(partial) except: partial = {'progress': 0, 'maxval': 0} progress = partial['progress'] maxval = partial['maxval'] if 'fetch' in partial: status = _('Downloading <b>') + partial['fetch'] + '</b>' elif 'name' in partial: status = _('Installing and linking <b>') + partial['name'] + '</b>' else: progress = 0 maxval = 0 status = None self._update_status(status=status, progress=[progress, maxval]) # Public api # ---------- def get_package_metadata(self, name): """ """ db = self._db_metadata metadata = dict(description='', url='', pypi='', home='', docs='', dev='') for key in metadata: name_lower = name.lower() for name_key in (name_lower, name_lower.split('-')[0]): try: metadata[key] = db.get(name_key, key) break except (cp.NoSectionError, cp.NoOptionError): pass return metadata def update_package_index(self): """ """ self._set_channels() self._download_repodata() def search_package(self, text): """ """ self.table.search_string_changed(text) def filter_package(self, value): """ """ self.table.filter_status_changed(value) def set_environment(self, name=None, prefix=None, update=True): """ """ if name and prefix: raise Exception('#TODO:') if name and self._conda_process.environment_exists(name=name): self._prefix = self.get_prefix_envname(name) elif prefix and self._conda_process.environment_exists(prefix=prefix): self._prefix = prefix else: self._prefix = self._root_prefix # Reset environent to reflect this environment in the package model if update: self.setup_packages() def get_environment_prefix(self): """Returns the active environment prefix.""" return self._prefix def get_environment_name(self): """ Returns the active environment name if it is located in the default conda environments directory, otherwise it returns the prefix. """ name = osp.basename(self._prefix) if not (name and self._conda_process.environment_exists(name=name)): name = self._prefix return name def get_environments(self): """ Get a list of conda environments located in the default conda environments directory. """ return self._conda_process.get_envs() def get_prefix_envname(self, name): """Returns the prefix for a given environment by name.""" return self._conda_process.get_prefix_envname(name) def get_package_versions(self, name): """ """ return self.table.source_model.get_package_versions(name) def create_environment(self, name=None, prefix=None, packages=['python']): """ """ # If environment exists already? GUI should take care of this # BUT the api call should simply set that env as the env dic = {} dic['name'] = name dic['pkg'] = packages dic['dep'] = True # Not really needed but for the moment! dic['action'] = const.CREATE self._run_conda_process(const.CREATE, dic) def enable_widgets(self): """ """ self.table.hide_columns() def disable_widgets(self): """ """ self.table.hide_action_columns()
def __init__(self, port=7464): QThread.__init__(self) self.port = port self.server = None self.complete = False
def __init__(self): QThread.__init__(self) self.notify_socket = None
def __init__(self, image_view): QThread.__init__(self) self.image_view = image_view
def __init__(self): QThread.__init__(self) self.map_lock = QMutex() self.widget_map = dict()