def main(): parser = OptionParser(description='A chat client/server') parser.add_option('-s', '--server', help='Start a server. If not ' 'given, a client will be started', action='store_true') opts, args = parser.parse_args() if opts.server: from PySide.QtCore import QCoreApplication app = QCoreApplication(sys.argv) # spawn a server server = ChatServer() listening = server.listen(HOST_ADDRESS, PORT) if not listening: # a server error print('Server start failed: {}'.format(server.errorString()), file=sys.stderr) server.serverShutdown.connect(app.quit) # print everything received by the server to standard output server.textReceived.connect(partial(print, '>>')) else: app = QApplication(sys.argv) chat_window = ChatWindow() chat_window.show() app.exec_()
def generate_classifier(mpec_data,mainWindow): for i in range(0,len(mpec_data)): mainWindow.ReadProgressBar.setValue(75+25*i/len(mpec_data)) tmp_out = open("classifier.csv","w+") str_out = "" vector = [] for j in range(1,5): key = "w"+str(j)+"mpro" str_out += str(mpec_data[i][key])+"," vector.append(float(mpec_data[i][key])) for j in range(1,5): key = "w"+str(j)+"sigmpro" str_out +=str(mpec_data[i][key]) if j!=4: str_out+="," vector.append(float(mpec_data[i][key])) mainWindow.NetworkView.getData(vector) time.sleep(1) mainWindow.NetworkView.update() tmp_out.write(str_out) tmp_out.close() command = "java -jar ../out/artifacts/NASAProject_jar/NASAProject.jar ../Data/Model.NN classifier.csv" sub_proc = subprocess.Popen(command,stdout=subprocess.PIPE, stderr=subprocess.PIPE) (output, error) = sub_proc.communicate() output = output.split() mpec_data[i]['class'] = output[-1] if mpec_data[i]['class'] =="": mpec_data[i]['class'] = "0" mpec_tmp = mpec_data mainWindow.AsteroidBrowser.setHtml(format_mpec_table(mpec_tmp)) mainWindow.Map.drawPlot(mpec_data) QCoreApplication.processEvents() return mpec_data
class ProducerConsumer(unittest.TestCase): '''Basic test case for producer-consumer QThread''' def setUp(self): #Create fixtures self.app = QCoreApplication([]) def tearDown(self): #Destroy fixtures del self.app def finishCb(self): #Quits the application self.app.exit(0) def testProdCon(self): #QThread producer-consumer example bucket = Bucket() prod = Producer(bucket) cons = Consumer(bucket) prod.start() cons.start() QObject.connect(prod, SIGNAL('finished()'), self.finishCb) QObject.connect(cons, SIGNAL('finished()'), self.finishCb) self.app.exec_() prod.wait() cons.wait() self.assertEqual(prod.production_list, cons.consumption_list)
class SkDesktopProxy(QObject): def __init__(self, parent=None): super(SkDesktopProxy, self).__init__(parent) d = QCoreApplication.instance().desktop() d.resized.connect(self.refresh) def refresh(self): self.xChanged.emit(self.x) self.yChanged.emit(self.y) self.widthChanged.emit(self.width) self.heightChanged.emit(self.height) dprint("pass") def __property(type, method): """ @param type type @param method method """ sig = Signal(type) prop = Property(type, method, notify=sig) return prop, sig x, xChanged = __property(int, lambda _: QCoreApplication.instance().desktop().x()) y, yChanged = __property(int, lambda _: QCoreApplication.instance().desktop().y()) width, widthChanged = __property(int, lambda _: QCoreApplication.instance().desktop().width()) height, heightChanged = __property(int, lambda _: QCoreApplication.instance().desktop().height())
def read(self, fileName): self.state = PluginState.Invalid self.hasError = False self.dependencies = [] specFile = QFile(fileName) if not specFile.exists(): msg = QCoreApplication.translate(None, "File does not exist: {name}") return self.__reportError(msg.format(name=specFile.fileName())) if not specFile.open(QIODevice.ReadOnly): msg = QCoreApplication.translate(None, "Could not open file for read: {name}") return self.__reportError(msg.format(name=specFile.fileName())) fileInfo = QFileInfo(specFile) self.location = fileInfo.absolutePath() self.filePath = fileInfo.absoluteFilePath() reader = QXmlStreamReader(specFile) while not reader.atEnd(): reader.readNext() tokenType = reader.tokenType() if tokenType is QXmlStreamReader.StartElement: self.__readPluginSpec(reader) else: pass if reader.hasError(): msg = QCoreApplication.translate(None, "Error parsing file {0}: {1}, at line {2}, column {3}") return self.__reportError(msg.format(specFile.fileName(), reader.errorString(), reader.lineNumber(), reader.columnNumber())) self.state = PluginState.Read return True
def readDatas(self): if self.socket is not None: if self.socket.isValid(): ins = QDataStream(self.socket) ins.setVersion(QDataStream.Qt_4_2) loop = 0 while not ins.atEnd(): QCoreApplication.processEvents() loop += 1 if loop > 1000: break if self.socket is not None: if self.socket.isValid(): if self.blockSize == 0: if self.socket.isValid(): if self.socket.bytesAvailable() < 4: return self.blockSize = ins.readUInt32() else: return if self.socket.isValid(): if self.socket.bytesAvailable() < self.blockSize: bytesReceived = str(self.socket.bytesAvailable()) return bytesReceived = str(self.socket.bytesAvailable()) else: return action = ins.readQString() self.handleAction(action, ins) self.blockSize = 0 else: return else: return return
def generate_classifier(mpec_data, mainWindow): for i in range(0, len(mpec_data)): mainWindow.ReadProgressBar.setValue(75 + 25 * i / len(mpec_data)) tmp_out = open("classifier.csv", "w+") str_out = "" vector = [] for j in range(1, 5): key = "w" + str(j) + "mpro" str_out += str(mpec_data[i][key]) + "," vector.append(float(mpec_data[i][key])) for j in range(1, 5): key = "w" + str(j) + "sigmpro" str_out += str(mpec_data[i][key]) if j != 4: str_out += "," vector.append(float(mpec_data[i][key])) mainWindow.NetworkView.getData(vector) time.sleep(1) mainWindow.NetworkView.update() tmp_out.write(str_out) tmp_out.close() command = "java -jar ../out/artifacts/NASAProject_jar/NASAProject.jar ../Data/Model.NN classifier.csv" sub_proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (output, error) = sub_proc.communicate() output = output.split() mpec_data[i]['class'] = output[-1] if mpec_data[i]['class'] == "": mpec_data[i]['class'] = "0" mpec_tmp = mpec_data mainWindow.AsteroidBrowser.setHtml(format_mpec_table(mpec_tmp)) mainWindow.Map.drawPlot(mpec_data) QCoreApplication.processEvents() return mpec_data
def resolveDependencies(self, specs): if self.hasError: return False if self.state is PluginState.Resolved: # Go back, so we just re-resolve the dependencies. self.state = PluginState.Read if self.state is not PluginState.Read: self.errorString = QCoreApplication.translate(None, "Resolving dependencies failed because state != Read") self.hasError = True return False resolvedDependencies = [] for dependency in self.dependencies: found = None for spec in specs: if spec.provides(dependency.name, dependency.version): found = spec spec.private.addProvidesForPlugin(self.pluginSpec) break if not found: self.hasError = True if self.errorString: self.errorString += "\n" msg = QCoreApplication.translate(None, "Could not resolve dependency {0}({1})") self.errorString += msg.format(dependency.name, dependency.version) continue resolvedDependencies.append(found) if self.hasError: return False self.dependencySpecs = resolvedDependencies self.state = PluginState.Resolved return True
def install(app=None, timeout=0.02, engine=None): """ Creates a :class:`~PySide.QtCore.QTimer` instance that will be triggered continuously to call :func:`Engine.poll() <pants.engine.Engine.poll>`, ensuring that Pants remains responsive. ========= ======== ============ Argument Default Description ========= ======== ============ app None *Optional.* The :class:`~PySide.QtCore.QCoreApplication` to attach to. If no application is provided, it will attempt to find an existing application in memory, or, failing that, create a new application instance. timeout ``0.02`` *Optional.* The maximum time to wait, in seconds, before running :func:`Engine.poll() <pants.engine.Engine.poll>`. engine *Optional.* The :class:`pants.engine.Engine` instance to use. ========= ======== ============ """ global timer global _timeout global _engine _engine = engine or Engine.instance() _engine._install_poller(_Qt()) if app is None: app = QCoreApplication.instance() if app is None: app = QCoreApplication([]) _timeout = timeout * 1000 timer = QTimer(app) timer.timeout.connect(do_poll) timer.start(_timeout)
def __init__(self, parent = None): super(UserList, self).__init__(parent = parent) query = grizzle.User.query(keys_only = False) query.add_sort("email") self.setQueryAndColumns(query, "email", "display_name", "status") #self.setMinimumSize(400, 600) QCoreApplication.instance().refresh.connect(self.refresh)
def run(self): ser = pc.start_serial() # wait for reply for trial, bitpat, target_time in self.entries: if self.do_stop: self.do_stop = False break sys.stdout.write(bin(bitpat) + ' ') bitpat = pc.fix_bitpat(bitpat) sys.stdout.write("|") sys.stdout.write(' ' + bin(bitpat) + '\n') pc.send_command(bitpat, target_time, ser) sys.stdout.flush() while ser.inWaiting() == 0: QCoreApplication.processEvents() time.sleep(0.01) # pause for 10 ms rcvd = ser.read(2) if rcvd == 's5': sys.stdout.write("*") sys.stdout.flush() self.progressBar.setValue(trial) time.sleep(0.02) # clear the last timeout warning # this should leave an 's0' waiting for next time ser.read(2) ser.close()
def readDatas(self): if self.socket != None : if self.socket.isValid() : ins = QDataStream(self.socket) ins.setVersion(QDataStream.Qt_4_2) loop = 0 while ins.atEnd() == False : QCoreApplication.processEvents() loop = loop + 1 if self.socket != None : if self.socket.isValid() : if self.blockSize == 0: if self.socket.isValid() : if self.socket.bytesAvailable() < 4: return self.blockSize = ins.readUInt32() else : return if self.socket.isValid() : if self.socket.bytesAvailable() < self.blockSize: bytesReceived = str(self.socket.bytesAvailable()) return bytesReceived = str(self.socket.bytesAvailable()) else : return action = ins.readQString() self.handleAction(action, ins) self.blockSize = 0 else : return else : return return
def main(): parser = OptionParser( description='A chat client/server') parser.add_option('-s', '--server', help='Start a server. If not ' 'given, a client will be started', action='store_true') opts, args = parser.parse_args() if opts.server: from PySide.QtCore import QCoreApplication app = QCoreApplication(sys.argv) # spawn a server server = ChatServer() listening = server.listen(HOST_ADDRESS, PORT) if not listening: # a server error print('Server start failed: {}'.format(server.errorString()), file=sys.stderr) server.serverShutdown.connect(app.quit) # print everything received by the server to standard output server.textReceived.connect(partial(print, '>>')) else: app = QApplication(sys.argv) chat_window = ChatWindow() chat_window.show() app.exec_()
def __init__(self): dbus_main_loop = dbus.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus(dbus_main_loop) bus_name = dbus.service.BusName("com.mikeasoft.statusnet", bus=session_bus) dbus.service.Object.__init__(self, object_path="/synchronize", bus_name=bus_name) self.app = QCoreApplication(sys.argv) signal.signal(signal.SIGINT, signal.SIG_DFL) self.client = gconf.client_get_default() self.api_path = self.client.get_string( '/apps/ControlPanel/Statusnet/api_path') self.latest = self.client.get_int( '/apps/ControlPanel/Statusnet/latest') self.eventService = EventFeedService('statusnet', 'StatusNet') self.eventService.local_name = "com.mikeasoft.statusnet.eventcallback" self.eventService.DEFAULT_INTF = "com.mikeasoft.statusnet.eventcallback" if not self.api_path: return self.cacheDir = QDesktopServices.storageLocation( QDesktopServices.CacheLocation) if not os.path.exists(self.cacheDir): os.mkdir(self.cacheDir) sys.exit(self.app.exec_())
def table_size_to_contents(table_widget): """ To make things look prettier... """ table_widget.resizeColumnsToContents() QCoreApplication.processEvents() # sum all the new column widths and account for the verticalScrollBar and verticalHeader table_width = 0 table_width += table_widget.verticalHeader().size().width() for col in range(table_widget.columnCount()): table_width += table_widget.columnWidth(col) table_width += table_widget.verticalScrollBar().width() table_width += 4 # set the table width # not sure why we have to add 4 below, but we do..maybe something with # the border of the table table_widget.setFixedWidth(table_width) for row in range(table_widget.rowCount()): table_widget.resizeRowToContents(row) # sum all the new row heights table_height = 0 # for row_num in range(table_widget.rowCount()): for row_num in range(TABLE_HEIGHT_IN_ROWS): table_height += table_widget.rowHeight(row_num) table_height += table_widget.horizontalHeader().size().height() table_height += 4 table_widget.setFixedHeight(table_height) return
def start(self, startMainLoop=False): if startMainLoop: from PySide.QtCore import QCoreApplication self.qtApplication = QCoreApplication(sys.argv) # we import QGeoPositionInfoSource after the Qt Application is # created to get rid of the: # " # QDBusConnection: system D-Bus connection created before QCoreApplication. Application may misbehave. # QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave. # " # warnings from QtMobility.Location import QGeoPositionInfoSource self.source = QGeoPositionInfoSource.createDefaultSource(None) if self.source is not None: self.source.positionUpdated.connect(self._positionUpdateCB) log.info("position source created") # TODO: custom interval setting self.source.setUpdateInterval(1000) self.source.startUpdates() log.info("started") # only start the mainloop if the source was created successfully, # otherwise it would never end as the signal provided by the source, # that stops the main loop, would never be triggered if startMainLoop: log.info("starting headless mainloop") self.qtApplication.exec_() else: log.error("source creation failed")
def __init__(self): super(STMainWindow, self).__init__() self.createActions() self.createMenus() layout = QVBoxLayout() self.tabs = QTabWidget() self.tabs.setTabPosition(QTabWidget.West) self.tabs.currentChanged[int].connect(self.tabChanged) self.sessiontab = sweattrails.qt.sessiontab.SessionTab(self) self.tabs.addTab(self.sessiontab, "Sessions") self.tabs.addTab(sweattrails.qt.fitnesstab.FitnessTab(self), "Fitness") self.tabs.addTab(sweattrails.qt.profiletab.ProfileTab(self), "Profile") self.usertab = sweattrails.qt.usertab.UserTab(self) self.tabs.addTab(self.usertab, "Users") self.usertab.hide() layout.addWidget(self.tabs) w = QWidget(self) w.setLayout(layout) self.setCentralWidget(w) self.statusmessage = QLabel() self.statusmessage.setMinimumWidth(200) self.statusBar().addPermanentWidget(self.statusmessage) self.progressbar = QProgressBar() self.progressbar.setMinimumWidth(100) self.progressbar.setMinimum(0) self.progressbar.setMaximum(100) self.statusBar().addPermanentWidget(self.progressbar) self.setWindowTitle("SweatTrails") self.setWindowIconText("SweatTrails") icon = QPixmap("image/sweatdrops.png") self.setWindowIcon(QIcon(icon)) QCoreApplication.instance().refresh.connect(self.userSet)
def file_import(self): (fileNames, _) = QFileDialog.getOpenFileNames(self, "Open Activity File", "", "Activity Files (*.tcx *.fit *.csv)") if fileNames: QCoreApplication.instance().import_files(*fileNames)
def move(self, i, j): tiles = self.tile.map.tiles self.tile.removeUnit(self) tiles[i][j].addUnit(self) self.tile.setChosenByDist(-1) self.tile.ensureVisible() QCoreApplication.instance().processEvents()
def setUpClass(cls): if not QCoreApplication.instance(): cls.app = QApplication(sys.argv) else: cls.app = QCoreApplication.instance() cls.window = mainwidget.MainWindow() cls.form = cls.window.ui
def setUp(self): #Acquire resources self.called = False self.app = QCoreApplication([]) self.socket = QUdpSocket() self.server = QUdpSocket() self.server.bind(QHostAddress(QHostAddress.LocalHost), 45454)
def __init__(self,audio=True,vibra=True): _d = NotifierDebug(); self._d = _d.d; self.manager = MNotificationManager('wazappnotify','WazappNotify'); self.vibra = vibra self.personalRingtone = WAConstants.DEFAULT_SOUND_NOTIFICATION; self.personalVibrate = True; self.groupRingtone = WAConstants.DEFAULT_SOUND_NOTIFICATION; self.groupVibrate = True; QCoreApplication.setApplicationName("Wazapp"); self.audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, None) self.mediaObject = Phonon.MediaObject(None) Phonon.createPath(self.mediaObject, self.audioOutput) self.profileChanged(0, 0, self.getCurrentProfile(), 0) bus = dbus.SessionBus() mybus = bus.get_object('com.nokia.profiled', '/com/nokia/profiled') self.nface = dbus.Interface(mybus, 'com.nokia.profiled') self.nface.connect_to_signal("profile_changed", self.profileChanged) #prof = self.getCurrentProfile() #reply = self.nface.get_value(prof,"ringing.alert.volume"); #self.currentProfile = prof #self.currentVolume = "1.0" if reply=="100" else "0." + reply #self._d("Checking current profile: " + prof + " - Volume: " + self.currentVolume) #self.audioOutput.setVolume(float(self.currentVolume)) #self.newMessageSound = WAConstants.DEFAULT_SOUND_NOTIFICATION #fetch from settings self.devInfo = QSystemDeviceInfo(); #self.devInfo.currentProfileChanged.connect(self.profileChanged); self.audio = True '''if audio: self.audio = QMediaPlayer(None,QMediaPlayer.LowLatency); self.audio.setVolume(100); else: self.audio = False''' self.enabled = True self.notifications = {} # vibration comes too early here, now handled by ui.py when the message is already added in QML # well, the truth is that sound comes too late... :D #>> Any notification should be handler by the notifier, not UI :P I don't feel it's too early though, # but if necessary connect to a signal and vibrate from here. if self.vibra: self.vibra = QFeedbackHapticsEffect(); self.vibra.setIntensity(1.0); self.vibra.setDuration(200);
def run_app(): app = create_app() create_db(app) appg = QApplication(sys.argv) if os.name != 'nt': # !!! it did not work creates no back-end available error !!! # !!! strange bug , do not remove !!! if listp(): pass window = NewWindow(app) # switching the language with template folder path @app.route('/lang_switch/<lang>') def lang_switch(lang): session['lang'] = lang if current_user.is_authenticated: return redirect(str(request.referrer)) return redirect(url_for('core.root')) @app.before_first_request def defLanguage(): if session.get('lang') not in ['en', 'ar', 'fr', 'it', 'es']: session['lang'] = 'en' # Adding error handlers on main app instance @app.errorhandler(404) @app.errorhandler(500) @app.errorhandler(413) def page_not_found(error): if error == 413: flash(get_lang(55), "danger") if current_user.is_authenticated: return redirect(url_for('cust_app.multimedia', nn=1)) return redirect(url_for('core.root')) flash(get_lang(56), "danger") return redirect(url_for('core.root')) # Injecting default variables to all templates @app.context_processor def inject_vars(): # adding language support var ar = False if session.get('lang') == 'AR': ar = True # modifing side bar spacing for specific paths path = request.path adml = ['/users', '/user_a', '/admin_u', '/user_u', '/csvd', '/settings'] adme = False if path in adml or path[:7] in adml or path[:5] in adml: adme = True return dict(path=path, adme=adme, brp=Markup("<br>"), ar=ar, version=version, str=str, defLang=session.get('lang')) QCoreApplication.processEvents() appg.exec_()
def gui_thread_schedule_async(callable, args=None): if is_gui_thread(): if args is None: callable() else: callable(*args) return event = ExecuteCodeEvent(callable, args) QCoreApplication.postEvent(GlobalInfo.main_window, event)
def testBlockingSignal(self): app = QCoreApplication.instance() or QCoreApplication([]) eventloop = QEventLoop() emitter = Emitter() receiver = Receiver(eventloop) emitter.connect(emitter, SIGNAL("signal(int)"), receiver.receive, Qt.BlockingQueuedConnection) emitter.start() retval = eventloop.exec_() emitter.wait() self.assertEqual(retval, 0)
def __init__(self, interval, parent = None): super(IntervalPage, self).__init__(parent, grumble.qt.bridge.FormButtons.AllButtons if interval.basekind() == "session" else grumble.qt.bridge.FormButtons.EditButtons) with gripe.db.Tx.begin(): interval = interval() self.interval = interval if isinstance(interval, sweattrails.session.Session): self.addProperty(sweattrails.session.Session, "sessiontype", 0, 0, readonly = True, has_label = False, rowspan = 3, bridge = grumble.qt.bridge.Image, height = 64, displayconverter = sweattrails.qt.view.SessionTypeIcon()) self.addProperty(sweattrails.session.Session, "start_time", 0, 1, readonly = True) self.addProperty(sweattrails.session.Session, "description", 1, 1, colspan = 3) col = 1 row = 2 else: self.addProperty(sweattrails.session.Interval, "timestamp", 0, 0, colspan = 3, readonly = True) col = 0 row = 1 self.addProperty(sweattrails.session.Interval, "elapsed_time", row, col, readonly = True) self.addProperty(sweattrails.session.Interval, "duration", row, col + 2, readonly = True) row += 1 self.addProperty(sweattrails.session.Interval, "distance", row, col, readonly = True, displayconverter = sweattrails.qt.view.Distance()) row += 1 self.addProperty(sweattrails.session.Interval, "average_speed", row, col, readonly = True, displayconverter = sweattrails.qt.view.PaceSpeed("Average")) self.addProperty(sweattrails.session.Interval, "max_speed", row, col + 2, readonly = True, displayconverter = sweattrails.qt.view.PaceSpeed({"Pace": "Best", "Speed": "Maximum"})) row += 1 self.setInstance(interval) intervals = sweattrails.session.Interval.query(parent = interval).fetchall() if len(intervals) > 1: page = IntervalListPage(self) self.addTab(page, "Intervals") page.list.objectSelected.connect(parent.addInterval) self.partSpecificContent(interval) self.addTab(GraphPage(self, interval), "Graphs") self.addTab(MapPage(self, interval), "Map") self.addTab(MiscDataPage(self, interval), "Other Data") if interval.basekind() == "session": self.addTab(RawDataPage(self), "Raw Data") self.statusMessage.connect(QCoreApplication.instance().status_message) self.exception.connect(QCoreApplication.instance().status_message) self.instanceSaved.connect(QCoreApplication.instance().status_message) self.instanceDeleted.connect(QCoreApplication.instance().status_message) self.setInstance(interval)
def play(self, do_loop=False, real_time=True): time = 0.0 # seconds timer = QElapsedTimer() timer.restart() dtime = 1.0 / self.frames_per_second key_frame_number = 0 frame_number = 0 for kf in self._key_frames: self.current_key_frame_index = key_frame_number key_frame_time = 0.0 while key_frame_time < kf.time_to_next_frame: # Drop frames if we are going too slow # if real_time and (timer.elapsed() - 200) > time*1000.0: # continue tf = key_frame_time / kf.time_to_next_frame interpolation_parameter = tf + key_frame_number camera_state = camera.State() focus_x = self.spline.interpolate_sequence( self._focusx, interpolation_parameter, do_loop) focus_y = self.spline.interpolate_sequence( self._focusy, interpolation_parameter, do_loop) focus_z = self.spline.interpolate_sequence( self._focusz, interpolation_parameter, do_loop) camera_state.focus= Vec3([focus_x, focus_y, focus_z]) camera_state.zFocus_vheight = self.spline.interpolate_sequence( self._zfv, interpolation_parameter, do_loop) quat = self.spline.interpolate_quaternion_sequence( self._quat, interpolation_parameter, do_loop) camera_state.rotation = quat.to_rotation() if real_time: while timer.elapsed() < time*1000.0: # TODO - use threading instead QCoreApplication.processEvents() frame = KeyFrame(camera_state) frame.frame_number = frame_number + 1 frame.key_frame_number = key_frame_number + 1 yield frame key_frame_time += dtime time += dtime frame_number += 1 if (not do_loop) and (key_frame_number == len(self._key_frames) - 1): return # Don't go past final frame key_frame_number += 1
def on_action_update_triggered(self): """Sequentially updates all series in the database. .. todo:: Update should also recognize/announce updated episodes. """ series_factory = SeriesFactory() for series in db_get_series(): logger.info("Updating series '{}'".format(series.series_name)) tvdb_show = tvdb.get_series(series.id, "en", cache=False) tvdb_show.update() tvdb_show.load_banners() series_factory.new_series(tvdb_show, update=series) db_commit() series_index = self.model.index_of(series) for removed_season in series_factory.removed: season_index = self.model.index_of(removed_season, series_index) season_row = self.model.node_at(season_index).child_index() self.model.removeRow(season_row, series_index) logger.info(" Removed season {} from series '{}'".format( removed_season.season_number, series.series_name)) for added_season in series_factory.added: self.model.add_item(added_season, series_index) logger.info( " Added season {}".format(added_season.season_number)) for updated_season in series_factory.updated: season, added_episodes, removed_episodes = updated_season logger.info( " Updated season {} (Episodes added: {}, removed: {})".format( season.season_number, len(added_episodes), len(removed_episodes))) season_index = self.model.index_of(season, series_index) for removed_episode in removed_episodes: episode_index = self.model.index_of(removed_episode, season_index) episode_row = self.model.node_at( episode_index).child_index() self.model.removeRow(episode_row, season_index) for added_episode in added_episodes: self.model.add_item(added_episode, season_index) series_factory.reset() QCoreApplication.processEvents()
def main(): app = QCoreApplication(sys.argv) context = Context() monitor = Monitor.from_netlink(context) monitor.filter_by(subsystem='input') observer = QUDevMonitorObserver(monitor) observer.deviceAdded.connect( partial(print_mouse_status, status_message="added")) observer.deviceRemoved.connect( partial(print_mouse_status, status_message="removed")) monitor.start() app.exec_()
def __init__(self, user = None, parent = None): super(SessionList, self).__init__(parent = parent) if not user: user = QCoreApplication.instance().user query = sweattrails.session.Session.query(keys_only = False) query.add_filter("athlete", "=", user) query.add_sort("start_time") self.setQueryAndColumns(query, grumble.qt.model.TableColumn("start_time", format = "%A %B %d", header = "Date"), grumble.qt.model.TableColumn("start_time", format = "%H:%M", header = "Time"), DescriptionColumn()) QCoreApplication.instance().refresh.connect(self.refresh)
def createActions(self): self.switchUserAct = QAction("&Switch User", self, shortcut = "Ctrl+U", statusTip = "Switch User", triggered = self.switch_user) self.importFileAct = QAction("&Import", self, shortcut = "Ctrl+I", statusTip = "Import Session", triggered = self.file_import) self.downloadAct = QAction("&Download", self, shortcut = "Ctrl+D", statusTip = "Download activities from device", triggered = QCoreApplication.instance().download) self.downloadAct = QAction("&Withings", self, statusTip = "Download Withings data", triggered = QCoreApplication.instance().withings) self.exitAct = QAction("E&xit", self, shortcut = "Ctrl+Q", statusTip = "Exit SweatTrails", triggered = self.close) self.aboutAct = QAction("&About", self, triggered = self.about) self.aboutQtAct = QAction("About &Qt", self, triggered = QApplication.aboutQt)
def readline ( self ): """ Emulate a file object. """ self._reading = True self._clear_line() self.moveCursor( QTextCursor.EndOfLine ) while self._reading: QCoreApplication.processEvents() if self._line.length(): return str( self._line ) return '\n'
def changeFormatting(self, formats): """ TOWRITE """ attributes = [] # QList<QInputMethodEvent::Attribute> for range_ in formats: type_ = QInputMethodEvent.TextFormat start = range_.start - self.cursorPosition() length = range_.length value = range_.format attributes.append(QInputMethodEvent.Attribute(type_, start, length, value)) event = QInputMethodEvent("", attributes) QCoreApplication.sendEvent(self, event)
def __init__(self): self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) self.qApp = QCoreApplication.instance() self._ownApp = False if self.qApp is None: self.qApp = QCoreApplication([]) self._ownApp = True self._blockApp = None posixbase.PosixReactorBase.__init__(self)
def gui_thread_schedule(callable, args=None): if is_gui_thread(): if args is None: return callable() else: callable(*args) event = ExecuteCodeEvent(callable, args) QCoreApplication.postEvent(GlobalInfo.main_window, event) event.event.wait() if event.exception is not None: raise event.exception[0], event.exception[1], event.exception[2] return event.result
def init_config(self, args): save = False self.user = self.user_id = None if "qtapp" not in gripe.Config: gripe.Config.qtapp = {} self.config = gripe.Config.qtapp if "settings" not in self.config: self.config["settings"] = {} save = True if save: self.config = gripe.Config.set("qtapp", self.config) save = False if args.user and args.password: if QCoreApplication.instance().has_users(): self.authenticate(args.user, args.password, args.savecreds) else: self.add_user(args.user, args.password, args.user, args.savecreds) else: if "user" in self.config.settings: user_settings = self.config.settings.user uid = user_settings.user_id if "user_id" in user_settings else None password = user_settings.password if "password" in user_settings else None logger.debug("Auto-login uid %s", uid) if not uid or not self.authenticate(uid, password, False): del self.config.settings["user"] save = True if save: self.config = gripe.Config.set("qtapp", self.config)
def __init__(self, user, parent = None): super(UserDetails, self).__init__(parent) self.addProperty(grizzle.User, "email", 0, 0, readonly = True) self.addProperty(grizzle.User, "display_name", 1, 0) self.addProperty(grizzle.User, "status", 2, 0) self.addProperty(grizzle.User, "has_roles", 3 , 0) self.statusMessage.connect(QCoreApplication.instance().status_message)
def app_version(): """ Detect and return the application version for the running application. The following locations are searched, in this order, for a version string: 1. ``siding.plugins.version`` 2. :func:`PySide.QtCore.QCoreApplication.applicationVersion` 3. ``__main__.version`` 4. ``__main__.__version__`` If the version is not found in one of those locations, a :class:`RuntimeError` will be raised. """ if version: return version ver = QCoreApplication.instance().applicationVersion() if ver: return ver import __main__ if hasattr(__main__, 'version'): return __main__.version elif hasattr(__main__, '__version__'): return __main__.__version__ raise RuntimeError("Application version not set.")
def __init__(self, parent = None): super(SettingsPage, self).__init__(parent) self.setMinimumSize(800, 600) self.addProperty(grizzle.User, "email", 0, 0) self.addProperty(grizzle.User, "display_name", 1, 0) self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.dob", 2, 0) self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.gender", 3, 0, style = "radio") self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.height", 4, 0, min = 100, max = 240, suffix = "cm") self.addProperty(sweattrails.userprofile.UserProfile, "_userprofile.units", 5, 0, style = "radio") withingsB = QGroupBox("Withings Support", self) withingsL = QGridLayout(withingsB) self.enableWithings = QCheckBox("Enable Withings", withingsB) self.enableWithings.toggled.connect(self.toggleWithings) withingsL.addWidget(self.enableWithings, 0, 0) withingsL.addWidget(QLabel("Withings User ID"), 1, 0) self.withingsUserID = QLineEdit(withingsB) withingsL.addWidget(self.withingsUserID, 1, 1) withingsL.addWidget(QLabel("Withings Key"), 2, 0) self.withingsKey = QLineEdit(withingsB) withingsL.addWidget(self.withingsKey, 2, 1) self.addWidget(withingsB, self.form.rowCount(), 0, 1, 2) self.addStretch() self.statusMessage.connect(QCoreApplication.instance().status_message)
def create(self): password = self.pwd.text() if password != self.pwd_again.text(): QMessageBox.critical(self, "Passwords don't match", "The passwords entered are different") self.reject() try: QCoreApplication.instance().add_user(self.email.text(), password, self.display_name.text(), self.savecreds.isChecked()) self.accept() except Exception as e: logger.exception("Exception creating user") QMessageBox.critical(self, "Error", str(e)) self.reject()
def formatUptime(time): s = '' loc = QLocale() if time.days > 0: d = QCoreApplication.translate('ifmon', 'days') if time.days > 1 \ else QCoreApplication.translate('ifmon', 'day') s = '%s %s, ' % (loc.toString(time.days), d) mm, ss = divmod(time.seconds, 60) hh, mm = divmod(mm, 60) def padded(d): if d < 10: return loc.toString(0) + loc.toString(d) else: return loc.toString(d) s += '%s:%s:%s' % (padded(hh), padded(mm), padded(ss)) return s
def quit(self): if self.hasQuit: return self.hasQuit = True import curtheme curtheme.unload() for w in self.widgets: if w.isVisible(): w.hide() # wait for for done or kill all threads from PySide.QtCore import QThreadPool if QThreadPool.globalInstance().activeThreadCount(): dwarn("warning: wait for active threads") QThreadPool.globalInstance().waitForDone(config.QT_THREAD_TIMEOUT) dprint("leave qthread pool") dprint("send quit signal to qApp") qApp = QCoreApplication.instance() # Make sure settings.sync is the last signal conneced with aboutToQuit #qApp.aboutToQuit.connect(self.settings.sync) skevents.runlater(qApp.quit)
def start(self, startMainLoop=False): if startMainLoop: from PySide.QtCore import QCoreApplication self.qtApplication = QCoreApplication(sys.argv) # we import QGeoPositionInfoSource after the Qt Application is # created to get rid of the: # " # QDBusConnection: system D-Bus connection created before QCoreApplication. Application may misbehave. # QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave. # " # warnings from QtMobility.Location import QGeoPositionInfoSource self.source = QGeoPositionInfoSource.createDefaultSource(None) if self.source is not None: self.source.positionUpdated.connect(self._positionUpdateCB) print("location Qt Mobility: position source created") # TODO: custom interval setting self.source.setUpdateInterval(1000) self.source.startUpdates() print("location qt mobility: started") # only start the mainloop if the source was created successfully, # otherwise it would never end as the signal provided by the source, # that stops the main lopp, would never be triggered if startMainLoop: print("location qt mobility: starting headless mainloop") self.qtApplication.exec_() else: print("location Qt Mobility: source creation failed")
def __init__(self): _assert(in_main_thread()) self._reads = {} self._writes = {} self._notifiers = {} self._timer = QTimer() self._timer.setSingleShot(True) QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate) self.qApp = QCoreApplication.instance() self._ownApp=False if self.qApp is None: self.qApp=QCoreApplication([]) self._ownApp=True self._blockApp = None posixbase.PosixReactorBase.__init__(self)
def install(app=None, timeout=0.02): """ Creates a :class:`~PySide.QtCore.QTimer` instance that will be triggered continuously to call :func:`Engine.poll() <pants.engine.Engine.poll>`, ensuring that Pants remains responsive. ========= ======== ============ Argument Default Description ========= ======== ============ app None *Optional.* The :class:`~PySide.QtCore.QCoreApplication` to attach to. If no application is provided, it will attempt to find an existing application in memory, or, failing that, create a new application instance. timeout ``0.02`` *Optional.* The maximum time to wait, in seconds, before running :func:`Engine.poll() <pants.engine.Engine.poll>`. ========= ======== ============ """ global timer global _timeout Engine.instance()._install_poller(_Qt()) if app is None: app = QCoreApplication.instance() if app is None: app = QCoreApplication([]) _timeout = timeout * 1000 timer = QTimer(app) timer.timeout.connect(do_poll) timer.start(_timeout)
def quit(self): if self.hasQuit: return self.hasQuit = True dprint("schedule to kill all python instances in a few seconds") skevents.runlater(lambda: os.system("tskill pythonw & tskill python"), config.QT_QUIT_TIMEOUT + config.QT_THREAD_TIMEOUT) # wait for for done or kill all threads from PySide.QtCore import QThreadPool if QThreadPool.globalInstance().activeThreadCount(): dwarn("warning: wait for active threads") QThreadPool.globalInstance().waitForDone(config.QT_THREAD_TIMEOUT) dprint("leave qthread pool") dprint("send quit signal to qApp") qApp = QCoreApplication.instance() # Make sure settings.sync is the last signal conneced with aboutToQuit #qApp.aboutToQuit.connect(self.settings.sync) skevents.runlater(qApp.quit)
def testTypes(self): o = MyBaseObject() o.app = QCoreApplication(sys.argv) o.app.exec_() for e in o.events: self.assertTrue(isinstance(e, MyEvent)) o.app = None
def doit(): try: app = QApplication([]) except RuntimeError: app = QCoreApplication.instance() main_window = main_window_factory() main_window.show() app.exec_()
def __init__(self, parent=None): super(TrayIcon, self).__init__(parent) self.setIcon(rc.icon('logo-reader')) self.setToolTip(QCoreApplication.instance().applicationName()) self.activated.connect(self.onActivated) self.__d = _TrayIcon(self) TrayIcon.instance = self
def setUp(self): '''Set up resources''' global _core_instance if _core_instance is None: _core_instance = QCoreApplication([]) self.app = _core_instance
def __init__(self, parent=None, f=0): super(_Window, self).__init__(parent, f) self.__canClose = False self.setWindowIcon(rc.icon('logo-reader')) self.setWindowTitle(QCoreApplication.instance().applicationName()) self.showNothing() self.setStyleSheet(''.join(imap(rc.qss, config.QT_STYLESHEETS)))
def downloader(self): from dl import Downloader ret = Downloader(self.q, self.networkAccessManager) ret.finished.connect(self._continue, Qt.QueuedConnection) ret.aborted.connect(self._retry) qApp = QCoreApplication.instance() qApp.aboutToQuit.connect(ret.abort) return ret
def __init__(self): self.__d = _SubtitleEditorManager() from PySide.QtCore import QCoreApplication qApp = QCoreApplication.instance() qApp.aboutToQuit.connect(self.hide) import dataman dataman.manager().loginChanged.connect(lambda name: name or self.hide())
def confirmQuit(): """ @return bool """ from PySide.QtCore import QCoreApplication appName = QCoreApplication.instance().applicationName() return Yes == QMessageBox.question(_parent(), appName, my.tr("Quit {0}?").format(appName), Yes | No, No)
def testScriptQProperty(self): qapp = QCoreApplication([]) myEngine = QScriptEngine() obj = MyObject() scriptObj = myEngine.newQObject(obj) myEngine.globalObject().setProperty("obj", scriptObj) myEngine.evaluate("obj.x = 42") self.assertEqual(scriptObj.property("x").toInt32(), 42) self.assertEqual(obj.property("x"), 42)