Пример #1
0
class Application(QApplication):
    SELF_HOST, SELF_PORT = 'localhost', 13333
    SERVER_HOST, SERVER_PORT = 'localhost', 13334
    MUSIC_DIR = 'd:\music'

    def __init__(self, argv):
        QApplication.__init__(self, argv)
        log_level = logging.DEBUG if 1 == 1 else logging.INFO
        logging.basicConfig(level=log_level,format='%(name)s: %(message)s')
        self.logger = logging.getLogger('Application')

        port = self.SELF_PORT
        if len(argv) > 1:
            port = int(argv[1])
        self.network = NetworkThread((self.SELF_HOST, port))
        client = False
        if port != self.SERVER_PORT:
            client = True
            self.network.server.connectPeer((self.SERVER_HOST, self.SERVER_PORT))
        self.file_indexer = FileIndexer(self.MUSIC_DIR)
        self.file_indexer.start()

        if client:
            self.database = Database('client_media_db')
        else:
            self.database = Database()

        self.main_window = MainWindow(self.network)
        self.main_window.show()

        self.network.server.musicFound.connect(self.main_window.tracklist_model.setTrackList)
Пример #2
0
    def __init__(self):
        '''
        Constructor
        '''
        qt4.QObject.__init__(self)

        self.view_mode = "R"

        self.cp1 = CircuitProfile(None)
        self.cp2 = CircuitProfile(None)
        self.cpgoal = CircuitProfile(None)

        self.ops = {}
        self.results = {"S1": {}, "S2": {}, "Change": {}, "Goal": {}}

        self.load_operations()
        # create the GUI app
        self.app = qt4.QApplication.instance()
        self.app.processEvents()
        # instantiate the main window
        self.ui = MainWindow(self)
        self.plots_S1 = Plots(self, self.ui, "S1", self.ui.mplS1)
        self.plots_S2 = Plots(self, self.ui, "S2", self.ui.mplS2)
        self.plots_S2.hide()
        # full screen
        self.ui.showMaximized()
        # start the Qt main loop execution, exiting from this script
        # with the same return code of Qt application
        sys.exit(self.app.exec_())

        self.log_file = open("log_file.txt", "w")
Пример #3
0
def main():
    """Creates and runs the PriceChartingTool application."""

    # Parse command-line arguments.
    (options, args) = parseCommandlineArgs()
    
    # Set up the logger.
    
    # Parsing the log config file doesn't work on the current version
    # of cx_Freeze (on Windows and on Mac).  The author of cx_Freeze
    # knows about this bug and hopefully the next release of cx_Freeze
    # addresses this issue.  Until then, only parse the config file if
    # this file is referenced as a .py file.
    if sys.argv[0].split(".")[-1] == "py":
        logging.config.fileConfig(LOG_CONFIG_FILE)
    log = logging.getLogger("main")

    log.info("##########################################");
    log.info("# Starting " + sys.argv[0] + ", version " + APP_VERSION);
    log.info("##########################################");

    # Create the Qt application.
    app = QApplication(sys.argv)
    app.setApplicationName(APP_NAME)
    app.setWindowIcon(QIcon(":/images/rluu/appIcon.png"))

    # Turn off UIEffects so that the application runs faster when doing
    # X11 forwarding.
    app.setEffectEnabled(Qt.UI_AnimateMenu, False)
    app.setEffectEnabled(Qt.UI_FadeMenu, False)
    app.setEffectEnabled(Qt.UI_AnimateCombo, False)
    app.setEffectEnabled(Qt.UI_AnimateTooltip, False)
    app.setEffectEnabled(Qt.UI_FadeTooltip, False)
    app.setEffectEnabled(Qt.UI_AnimateToolBox, False)
    
    # Initialize the Ephemeris.
    Ephemeris.initialize()

    # Set a default location (required).
    Ephemeris.setGeographicPosition(-77.084444, 38.890277)
    
    # Create the main window for the app and show it.
    mainWindow = MainWindow(APP_NAME, 
                            APP_VERSION, 
                            APP_DATE, 
                            APP_AUTHOR, 
                            APP_AUTHOR_EMAIL)
    mainWindow.show()

    # Cleanup and close the application when the last window is closed.
    app.lastWindowClosed.connect(Ephemeris.closeEphemeris)
    app.lastWindowClosed.connect(logging.shutdown)
    app.lastWindowClosed.connect(app.quit)

    return app.exec_()
Пример #4
0
	def __init__(self, *args, **kwargs):
		MainWindowBase.__init__(self, *args, **kwargs)
		
		self.Bind(wx.EVT_CLOSE, self.on_close, self)
		
		self.set_connected(False)
		
		timer_id = 100
		self.update_timer = wx.Timer(self, timer_id)
		wx.EVT_TIMER(self, timer_id, self.on_timer)
		self.update_timer.Start(1000)
Пример #5
0
    def __init__(self):
        super().__init__()
        self.app = QApplication(sys.argv)
        # self.MainWindow = MyQMainWindow()
        self.MainWindow = MainWindow()
        self.MainWindow.show()
        # self.MainWindow.setupUi(self.MainWindow)

        self.MainWindow.actionNew.triggered.connect(self.new_connect)
        self.MainWindow.actionImport.triggered.connect(self.import_connect)
        self.MainWindow.actionExport.triggered.connect(self.export_connect)

        self.new_ui = Ui_Form()
        self.new_QWidget = QWidget()
        self.new_QWidget.setWindowModality(Qt.ApplicationModal)
        self.new_ui.setupUi(self.new_QWidget)

        self.histroy_ui = Ui_history_ui()
        self.history_QWidget = QWidget()
        self.history_QWidget.setWindowModality(Qt.ApplicationModal)
        self.histroy_ui.setupUi(self.history_QWidget)
        self.histroy_ui.clear.clicked.connect(self.histroy_clear)

        self.import_ui_QWidget = QWidget()
        self.import_ui_QWidget.setWindowModality(Qt.ApplicationModal)
        self.import_ui = Import_UI(self.import_ui_QWidget)

        self.create_ui = Create_Ui_Form()
        self.create_QWidget = QWidget()
        self.create_QWidget.setWindowModality(Qt.ApplicationModal)
        self.create_ui.setupUi(self.create_QWidget)

        self.create_database_ui = Ui_create_database()
        self.create_database_QWidget = QWidget()
        self.create_database_QWidget.setWindowModality(Qt.ApplicationModal)
        self.create_database_ui.setupUi(self.create_database_QWidget)

        self.path = os.path.dirname(sys.argv[0])
        self.conn = sqlite3.connect('db/influx.db')
        self.get_server_list()
        self.signal.connect(self.exec_handler)
        self.MainWindow.execAction.triggered.connect(lambda: self.signal.emit())
        self.MainWindow.history_button.triggered.connect(self.show_history)
        self.MainWindow.tabWidget.tabCloseRequested.connect(self.tab_close)

        self.MainWindow.treeView.setContextMenuPolicy(Qt.CustomContextMenu)  # 打开右键菜单的策略
        self.MainWindow.treeView.customContextMenuRequested.connect(self.right_click_menu)  # 绑定事件

        self.influxDbClient = InfluxRegister()
        self.edit_context_menu = QMenu()  # 创建对象
        self.edit_context_flag = False
        self.qt_info = functools.partial(QMessageBox.information, self.MainWindow, '提示信息')
        self.qt_cri = functools.partial(QMessageBox.critical, self.MainWindow, '提示信息')
Пример #6
0
class App:
    class SetupThread(LoadingThread):
        def __init__(self, parent=None):
            super().__init__(parent)
            self.operation = 'Установка языковых пакетов'

        def run(self):
            do_setup()
            self.loadingDone.emit()

    def __init__(self):
        super().__init__()
        self.app = QApplication(sys.argv)
        self.settings = SupremeSettings()
        self.settings.check_settings()
        logging.config.dictConfig(Config.LOGGING_CONFIG)
        self.log = logging.getLogger('root')

        self.tempdir = tempfile.TemporaryDirectory()
        self.log.debug(f'Temporary Directory is {self.tempdir}')
        self.settings['tempdir'] = self.tempdir.name

        self.window = None
        self.login = None
        self.log.debug(f'Main thread {QThread.currentThread()}')

    def start(self):
        if self.settings['setup']:
            self.thread = self.SetupThread()
            self.loading = LoadingWrapper(self.thread)
            self.loading.loadingDone.connect(self.show_login)
            self.loading.start()
        else:
            self.show_login()

        exit_code = self.app.exec_()
        sys.exit(exit_code)

    def show_login(self):
        if self.window:
            self.window.close()
        self.login = LoginWindow()
        self.login.loginSuccesful.connect(self.show_main_window)
        self.login.show()

    def show_main_window(self):
        self.window = MainWindow()
        self.window.actionChangeDB.triggered.connect(self.show_login)
        self.window.show()

    def on_exception_caught(self, type_, value, traceback):
        self.exception = ExceptionDialog(type_, value, traceback)
        self.exception.show()
Пример #7
0
def main():
    """Creates and runs the PriceChartingTool application."""

    # Parse command-line arguments.
    (options, args) = parseCommandlineArgs()

    # Set up the logger.

    # Parsing the log config file doesn't work on the current version
    # of cx_Freeze (on Windows and on Mac).  The author of cx_Freeze
    # knows about this bug and hopefully the next release of cx_Freeze
    # addresses this issue.  Until then, only parse the config file if
    # this file is referenced as a .py file.
    if sys.argv[0].split(".")[-1] == "py":
        logging.config.fileConfig(LOG_CONFIG_FILE)
    log = logging.getLogger("main")

    log.info("##########################################")
    log.info("# Starting " + sys.argv[0] + ", version " + APP_VERSION)
    log.info("##########################################")

    # Create the Qt application.
    app = QApplication(sys.argv)
    app.setApplicationName(APP_NAME)
    app.setWindowIcon(QIcon(":/images/rluu/appIcon.png"))

    # Turn off UIEffects so that the application runs faster when doing
    # X11 forwarding.
    app.setEffectEnabled(Qt.UI_AnimateMenu, False)
    app.setEffectEnabled(Qt.UI_FadeMenu, False)
    app.setEffectEnabled(Qt.UI_AnimateCombo, False)
    app.setEffectEnabled(Qt.UI_AnimateTooltip, False)
    app.setEffectEnabled(Qt.UI_FadeTooltip, False)
    app.setEffectEnabled(Qt.UI_AnimateToolBox, False)

    # Initialize the Ephemeris.
    Ephemeris.initialize()

    # Set a default location (required).
    Ephemeris.setGeographicPosition(-77.084444, 38.890277)

    # Create the main window for the app and show it.
    mainWindow = MainWindow(APP_NAME, APP_VERSION, APP_DATE, APP_AUTHOR,
                            APP_AUTHOR_EMAIL)
    mainWindow.show()

    # Cleanup and close the application when the last window is closed.
    app.lastWindowClosed.connect(Ephemeris.closeEphemeris)
    app.lastWindowClosed.connect(logging.shutdown)
    app.lastWindowClosed.connect(app.quit)

    return app.exec_()
Пример #8
0
def main():
    app = QtGui.QApplication(sys.argv)

    #scene = BattlefieldScene()
    w = MainWindow()
    w.show()

    sys.exit(app.exec_())

    #   rh = RollHandler("20d6 5+ 4+")
    #   print rh.commandString
    #   rh.Roll()
    return
Пример #9
0
def main():
   app = QtGui.QApplication(sys.argv)

   #scene = BattlefieldScene()
   w = MainWindow()
   w.show()

   sys.exit(app.exec_())
   
#   rh = RollHandler("20d6 5+ 4+")
#   print rh.commandString
#   rh.Roll()
   return
Пример #10
0
def main():
    #============================================================================
    # check if the program is already running
    #============================================================================
    pid = str(os.getpid())
    pidfile = "~firestarter.pid"

    running = False

    if os.path.isfile(pidfile):  # pid file available?
        with open(pidfile, 'r') as pf:
            oldpid = pf.readlines()[0]
            if pidRunning(oldpid):  # process with pid still alive?
                running = True

    if running: sys.exit()
    else:
        with open(pidfile, 'w') as pf:
            pf.write(pid)

    #============================================================================
    # verify directory structure
    #============================================================================
    neededFolders = ("cache", "cache/icons", "cache/steam", "export")
    for folder in neededFolders:
        if not os.path.isdir(folder):
            os.makedirs(folder)

    #============================================================================
    # Start main program
    #============================================================================
    ret = MainWindow.RestartCode
    while ret == MainWindow.RestartCode:
        flushLogfiles(("parser.log", "steamapi.log"), 'utf-8')

        app = QtGui.QApplication(sys.argv)
        # run program
        mainWnd = MainWindow()
        mainWnd.show()

        ret = app.exec_()

        del mainWnd
        del app

    #============================================================================
    # cleanup and exit
    #============================================================================
    os.remove(pidfile)
    sys.exit(ret)
Пример #11
0
def main():
    """"""
    qapp = create_qapp()

    event_engine = EventEngine()

    main_engine = MainEngine(event_engine)

    main_engine.add_gateway(CtpGateway)

    main_window = MainWindow(main_engine, event_engine)
    main_window.showMaximized()

    qapp.exec()
Пример #12
0
def main():
   #============================================================================
   # check if the program is already running
   #============================================================================
   pid = str(os.getpid())
   pidfile = "~firestarter.pid"
   
   running = False
   
   if os.path.isfile(pidfile):         # pid file available?
      with open(pidfile, 'r') as pf:
         oldpid = pf.readlines()[0]
         if pidRunning(oldpid):   # process with pid still alive?
            running = True
   
   if running: sys.exit()
   else:
      with open(pidfile, 'w') as pf: pf.write(pid)
      
   #============================================================================
   # verify directory structure
   #============================================================================
   neededFolders = ("cache", "cache/icons", "cache/steam", "export")
   for folder in neededFolders:
      if not os.path.isdir(folder):
         os.makedirs(folder)

   #============================================================================
   # Start main program
   #============================================================================
   ret = MainWindow.RestartCode
   while ret == MainWindow.RestartCode:
      flushLogfiles(("parser.log","steamapi.log"), 'utf-8')
      
      app = QtGui.QApplication(sys.argv)
      # run program
      mainWnd = MainWindow()
      mainWnd.show()
      
      ret = app.exec_()
      
      del mainWnd
      del app

   #============================================================================
   # cleanup and exit
   #============================================================================
   os.remove(pidfile)
   sys.exit(ret)
Пример #13
0
 def __init__(self):
     '''
     Constructor
     '''
     qt4.QObject.__init__( self )
             
     self.view_mode = "R"        
     
     self.cp1 = CircuitProfile(None)
     self.cp2 = CircuitProfile(None)
     self.cpgoal = CircuitProfile(None)
     
     self.ops = {}
     self.results = {"S1": {}, "S2": {}, "Change": {}, "Goal": {}}
     
     self.load_operations()
     # create the GUI app
     self.app = qt4.QApplication.instance()
     self.app.processEvents()
     # instantiate the main window
     self.ui = MainWindow(self)
     self.plots_S1 = Plots(self, self.ui, "S1", self.ui.mplS1)
     self.plots_S2 = Plots(self, self.ui, "S2", self.ui.mplS2)
     self.plots_S2.hide()
     # full screen
     self.ui.showMaximized()
     # start the Qt main loop execution, exiting from this script
     # with the same return code of Qt application
     sys.exit(self.app.exec_())
     
     self.log_file = open("log_file.txt", "w")
Пример #14
0
Файл: anm.py Проект: yeleman/anm
def main():

    gettext_windows.setup_env()

    locale.setlocale(locale.LC_ALL, '')

    gettext.install('anm', localedir='locale', unicode=True)

    # ensure DB is in place
    fixture_data.initial_setup()

    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    setattr(ANMWindow, 'window', window)
    window.show()
    #window.showMaximized()
    sys.exit(app.exec_())
Пример #15
0
	def __init__(self, *args, **kwargs):
		MainWindowBase.__init__(self, *args, **kwargs)
		
		self.arduino = None
		
		# Load the serial port name
		try:
			serial_port = open("serial_port.conf", "r").read()
		except IOError:
			serial_port = ""
		self.serial_port.ChangeValue(serial_port)
		
		# Connect to the arduino
		try:
			self.connect()
		except:
			pass # Oh well...
		
		self._last_connected = 0
Пример #16
0
    def __init__(self, *args, **kwargs):
        MainWindowBase.__init__(self, *args, **kwargs)

        self.arduino = None

        # Load the serial port name
        try:
            serial_port = open("serial_port.conf", "r").read()
        except IOError:
            serial_port = ""
        self.serial_port.ChangeValue(serial_port)

        # Connect to the arduino
        try:
            self.connect()
        except:
            pass  # Oh well...

        self._last_connected = 0
Пример #17
0
def main(args):
    setup_logging(args)
    commit_hash = get_git_commit_hash()
    LOG.info("Starting the EPIC-narrator" +
             (" ({})".format(commit_hash) if commit_hash is not None else ""))

    if args.query_audio_devices:
        print(Recorder.get_devices())
        exit()

    if args.set_audio_device >= 0:
        LOG.info('Changing default mic device to {}'.format(args.set_audio_device))
        Recorder.set_default_device(args.set_audio_device)

    this_os = get_os()
    single_window = this_os in ['linux', 'windows']

    controller = Controller(this_os)
    main_window = MainWindow(controller, this_os, single_window=single_window)
    main_window.show()

    Gtk.main()
Пример #18
0
def main():
    # Parse command-line arguments.
    (options, args) = parseCommandlineArgs()
    
    # Set up the logger.

    # Parsing the log config file doesn't work on the current version
    # of cx_Freeze (on Windows and on Mac).  The author of cx_Freeze
    # knows about this bug and hopefully the next release of cx_Freeze
    # addresses this issue.  Until then, only parse the config file if
    # this file is referenced as a .py file.
    if sys.argv[0].split(".")[-1] == "py":
        logging.config.fileConfig(LOG_CONFIG_FILE)
    log = logging.getLogger("main")

    log.info("##########################################");
    log.info("# Starting " + sys.argv[0] + ", version " + APP_VERSION);
    log.info("##########################################");

    # Create the Qt application.
    app = QApplication(sys.argv)
    app.setApplicationName(APP_NAME)
    app.setWindowIcon(QIcon(":/images/rluu/appIcon.png"))

    # Create the main window for the app and show it.
    mainWindow = MainWindow(APP_NAME, 
                            APP_VERSION, 
                            APP_DATE, 
                            APP_AUTHOR, 
                            APP_AUTHOR_EMAIL)
    mainWindow.show()

    # Cleanup and close the application when the last window is closed.
    app.lastWindowClosed.connect(logging.shutdown)
    app.lastWindowClosed.connect(app.quit)

    return app.exec_()
Пример #19
0
    def __init__(self):
        # load config
        cfg.init(None)

        # main window
        self._app = QtWidgets.QApplication(sys.argv)
        self._app.setWindowIcon(icon.get_app_icon("me-geomap"))
        self.mainwindow = MainWindow(self)
        cfg.main_window = self.mainwindow

        # set default values
        self._update_document_name()

        # show
        self.mainwindow.show()
Пример #20
0
    def __init__(self):

        QtGui.QMainWindow.__init__(self)
        self.ui = MainWindow.Ui_MainWindow()
        self.ui.setupUi(self)

        self.modified = False
        self.title = self.windowTitle()

        headerLabels = QtCore.QStringList()

        headerLabels.append("Task List")
        headerLabels.append("ID")

        self.ui.treeWidget.setHeaderLabels(headerLabels)
        self.ui.treeWidget.hideColumn(idColumnIndex)
        self.ui.treeWidget.expandAll()

        self.dbHandler = DBHandler()
        self.doConnections()
        self.setActionIcons()

        self.loadDB()
Пример #21
0
import sys

from PyQt5.QtWidgets import *

from ui import MainWindow

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

    main_window = MainWindow.MainWindow()
    main_window.setWindowTitle('客户端启动器')
    main_window.setFixedSize(1280, 720)
    main_window.show()

    sys.exit(app.exec_())
    def __init__(self):
        # super()构造器方法返回父级的对象。__init__()方法是构造器的一个方法。
        super().__init__()
        # self.ui = MainUI.Ui_Form()
        self.ui = MainWindowUI.Ui_MainWindow()
        self.ui.setupUi(self)

        # ####################### 相对路径 ######################
        # 初始化label显示的(黑色)背景
        self.bkg_pixmap = QPixmap('./logo_imgs/bkg1.png')
        # 设置主窗口的logo
        self.logo = QIcon('./logo_imgs/fcb_logo.jpg')
        # 设置提示框icon
        self.info_icon = QIcon('./logo_imgs/info_icon.jpg')
        # OpenCV深度学习人脸检测器的路径
        self.detector_path = "./model_face_detection"
        # OpenCV深度学习面部嵌入模型的路径
        self.embedding_model = "./model_facenet/openface_nn4.small2.v1.t7"
        # 训练模型以识别面部的路径
        self.recognizer_path = "./saved_weights/recognizer.pickle"
        # 标签编码器的路径
        self.le_path = "./saved_weights/le.pickle"

        # ###################### 窗口初始化 ######################
        # 设置窗口名称和图标
        self.setWindowTitle('人脸识别考勤系统 v2.0')
        self.setWindowIcon(self.logo)
        # 设置单张图片背景
        self.ui.label_camera.setPixmap(self.bkg_pixmap)
        # label_time显示系统时间
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.show_time_text)
        # 启动时间任务
        self.timer.start()

        # ###################### 摄像头初始化 ######################
        # 初始化摄像头,默认调用第一个摄像头
        # self.url = 0
        # 如果要调用摄像头1,则设置为1,适用于:笔记本外接USB摄像头
        self.url = 1
        self.cap = cv2.VideoCapture()
        # self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 500)
        # self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 400)
        # self.cap.set(cv2.CAP_PROP_FPS, 20)

        # ###################### 按键的槽函数 ######################
        # 设置摄像头按键连接函数
        self.ui.bt_open_camera.clicked.connect(self.open_camera)
        # 设置开始考勤按键的回调函数
        self.ui.bt_start_check.clicked.connect(self.auto_control)
        # 设置活体检测按键的回调函数
        self.ui.bt_blinks.clicked.connect(self.blinks_thread)
        # 设置“退出系统”按键事件, 按下之后退出主界面
        self.ui.bt_exit.clicked.connect(self.quit_window)
        # 设置信息采集按键连接
        self.ui.bt_gathering.clicked.connect(self.open_info_dialog)
        # 设置区分打开摄像头还是人脸识别的标识符
        self.switch_bt = 0

        # ###################### 数据库相关操作 ######################
        # 初始化需要记录的人名
        self.record_name = []
        # 设置更新人脸数据库的按键连接函数
        self.ui.bt_generator.clicked.connect(self.train_model)
        # 设置查询班级人数按键的连接函数
        self.ui.bt_check.clicked.connect(self.check_nums)
        # 设置请假按键的连接函数
        self.ui.bt_leave.clicked.connect(self.leave_button)
        # 设置漏签补签按键的连接函数
        self.ui.bt_supplement.clicked.connect(self.supplyment_button)
        # 设置对输入内容的删除提示
        self.ui.lineEdit_leave.setClearButtonEnabled(True)
        self.ui.lineEdit_supplement.setClearButtonEnabled(True)
        # 设置查看结果(显示未到和迟到)按键的连接函数
        self.ui.bt_view.clicked.connect(self.show_late_absence)
        # 核验本地人脸数据集与数据库中的ID是否一致,即验证是否有未录入数据库的情况,以及是否有未采集人脸的情况。
        self.ui.bt_check_variation.clicked.connect(self.check_variation_db)

        # self.check_time_set, ok = QInputDialog.getText(self, '考勤时间设定', '请输入考勤时间(格式为00:00:00):')
        self.check_time_set = '08:00:00'

        # 设置输入考勤时间的限制
        self.ui.spinBox_time_hour.setRange(0, 23)
        self.ui.spinBox_time_minute.setRange(0, 59)
Пример #23
0
def main():
    app = QApplication(sys.argv)
    app.setApplicationName("Analyze images")
    my_window = MainWindow(950, 750)
    app.setActiveWindow(my_window)
    exit(app.exec_())
Пример #24
0
	def callback_batterystate(self, data):
		try:
			self.main_window.set_battery_state(data.percentage * 100)
		except rospy.ROSInterruptException as e:
			rospy.logerr(e)
			pass

	def listener(self):
		rospy.init_node('listener', anonymous=True, log_level=rospy.DEBUG)
		rospy.Subscriber("/mavros/vfr_hud", VFR_HUD, self.callback_vfr_hud)
		rospy.Subscriber("/mavros/radio_status", RadioStatus, self.callback_radiostatus)
		rospy.Subscriber("/mavros/battery", BatteryState, self.callback_batterystate)
		self.main_window.msg.header.stamp = rospy.Time.now()
		self.main_window.pub.publish(self.main_window.msg)
		rospy.spin()

	def __init__(self, main_window):
		self.initial_altitude = 0
		self.init_set = False
		self.main_window = main_window
		self.listener()

if __name__ == "__main__":
	gui_ready = threading.Event()
	main_window = MainWindow(gui_ready)
	gui_thread = threading.Thread(target=main_window.run_gui_thread)
	gui_thread.start()
	gui_ready.wait()
	fcu = FCU(main_window)
Пример #25
0
import sys
import qdarkstyle
from PyQt4.QtGui import QApplication
from ui import MainWindow

if __name__ == "__main__":

    app = QApplication(sys.argv)
    desktopWidget = QApplication.desktop()
    screenRect = desktopWidget.screenGeometry()
    app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))
    window = MainWindow(screenRect.width(), screenRect.height())
    window.setWindowTitle("model_view")
    window.show()
    sys.exit(app.exec_())
Пример #26
0
import sys
import os

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (
    QApplication, )
from PyQt5.QtCore import Qt

from ui import MainWindow

if __name__ == '__main__':
    # windows task bar icon fix
    if os.name == 'nt':
        import ctypes
        app_id = 'wysockipiotr.strobe'
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id)

    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())
Пример #27
0
import sys
import qdarkstyle
import config
from PyQt4.QtGui import QApplication
from ui import MainWindow
from opt import ConstrainedOpt
from model import DCGANTest

if __name__ == "__main__":
    model = DCGANTest(config.nz, config.nsf, config.nvx, config.batch_size)
    model.restore(config.params_path)
    opt_engine = ConstrainedOpt(model)
    app = QApplication(sys.argv)
    app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))
    window = MainWindow(opt_engine)
    window.setWindowTitle("voxel-dcgan")
    window.show()
    window.viewerWidget.interactor.Initialize()
    sys.exit(app.exec_())
Пример #28
0
class ModelEditor:
    """Model editor main class"""

    def __init__(self):
        # load config
        cfg.init(None)

        # main window
        self._app = QtWidgets.QApplication(sys.argv)
        self._app.setWindowIcon(icon.get_app_icon("me-geomap"))
        self.mainwindow = MainWindow(self)
        cfg.main_window = self.mainwindow

        # set default values
        self._update_document_name()

        # show
        self.mainwindow.show()

    def new_file(self):
        """new file menu action"""
        if not self.save_old_file():
            return
        cfg.new_file()
        self.mainwindow.reload()
        self.mainwindow.update_recent_files(0)
        self._update_document_name()
        self.mainwindow.info.update_from_data({'record_id': cfg.root_input_type['id']})
        self.mainwindow.show_status_message("New file is opened")

    def open_file(self):
        """open file menu action"""
        if not self.save_old_file():
            return
        yaml_file = QtWidgets.QFileDialog.getOpenFileName(
            self.mainwindow, "Choose Yaml Model File",
            cfg.config.last_data_dir, "Yaml Files (*.yaml)")
        if yaml_file[0]:
            cfg.open_file(yaml_file[0])
            self.mainwindow.reload()
            self.mainwindow.update_recent_files()
            self._update_document_name()
            self.mainwindow.show_status_message("File '" + yaml_file[0] + "' is opened")

    def import_file(self):
        """import con file menu action"""
        if not self.save_old_file():
            return
        con_file = QtWidgets.QFileDialog.getOpenFileName(
            self.mainwindow, "Choose Con Model File",
            cfg.config.last_data_dir, "Con Files (*.con)")
        if con_file[0]:
            cfg.import_file(con_file[0])
            self.mainwindow.reload()
            self.mainwindow.update_recent_files()
            self._update_document_name()
            self.mainwindow.show_status_message("File '" + con_file[0] + "' is imported")

    def open_recent(self, action):
        """open recent file menu action"""
        if action.text() == cfg.curr_file:
            return
        if not self.save_old_file():
            return
        cfg.open_recent_file(action.text())
        self.mainwindow.reload()
        self.mainwindow.update_recent_files()
        self._update_document_name()
        self.mainwindow.show_status_message("File '" + action.text() + "' is opened")

    def save_file(self):
        """save file menu action"""
        if cfg.curr_file is None:
            return self.save_as()
        cfg.update_yaml_file(self.mainwindow.editor.text())
        cfg.save_file()
        self.mainwindow.show_status_message("File is saved")

    def save_as(self):
        """save file menu action"""
        cfg.update_yaml_file(self.mainwindow.editor.text())
        if cfg.curr_file is None:
            if cfg.imported_file_name is not None:
                new_file = cfg.imported_file_name
            else:
                new_file = cfg.config.last_data_dir + os.path.sep + "NewFile.yaml"
        else:
            new_file = cfg.curr_file
        dialog = QtWidgets.QFileDialog(self.mainwindow, 'Save as YAML File', new_file,
                                       "YAML Files (*.yaml)")
        dialog.setDefaultSuffix('.yaml')
        dialog.setFileMode(QtWidgets.QFileDialog.AnyFile)
        dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave)
        dialog.setViewMode(QtWidgets.QFileDialog.Detail)
        if dialog.exec_():
            file_name = dialog.selectedFiles()[0]
            cfg.save_as(file_name)
            self.mainwindow.update_recent_files()
            self._update_document_name()
            self.mainwindow.show_status_message("File is saved")
            return True
        return False

    def transform(self, file):
        """Run transformation according rules in set file"""
        cfg.update_yaml_file(self.mainwindow.editor.text())
        cfg.transform(file)
        # synchronize cfg document with editor text
        self.mainwindow.editor.setText(cfg.document, keep_history=True)
        self.mainwindow.reload()

    def edit_transformation_file(self, file):
        """edit transformation rules in file"""
        text = cfg.get_transformation_text(file)
        if text is not None:
            dlg = JsonEditorDlg(cfg.transformation_dir, file,
                                "Transformation rules:", text, self.mainwindow)
            dlg.exec_()

    def select_format(self, filename):
        """Selects format file by filename."""
        if cfg.curr_format_file == filename:
            return
        cfg.curr_format_file = filename
        cfg.update_format()
        self.mainwindow.reload()
        self.mainwindow.show_status_message("Format of file is changed")

    def edit_format(self):
        """Open selected format file in Json Editor"""
        text = cfg.get_curr_format_text()
        if text is not None:
            dlg = JsonEditorDlg(cfg.format_dir, cfg.curr_format_file,
                                "Format", text, self.mainwindow)
            dlg.exec_()

    def _update_document_name(self):
        """Update document title (add file name)"""
        title = "GeoMop Model Editor"
        if cfg.curr_file is None:
            title += " - New File"
        else:
            title += " - " + cfg.curr_file
        self.mainwindow.setWindowTitle(title)

    def save_old_file(self):
        """
        If file not saved, display confirmation dialeg and if is needed, do it

        return: False if action have to be aborted
        """
        cfg.update_yaml_file(self.mainwindow.editor.text())
        if cfg.changed:
            msg_box = QMessageBox()
            msg_box.setWindowTitle("Confirmation")
            msg_box.setIcon(QMessageBox.Question)
            msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No | QMessageBox.Abort)
            msg_box.setDefaultButton(QMessageBox.Abort)
            msg_box.setText("The document has unsaved changes, do you want to save it?")
            reply = msg_box.exec_()

            if reply == QtWidgets.QMessageBox.Abort:
                return False
            if reply == QtWidgets.QMessageBox.Yes:
                if cfg.curr_file is None:
                    return self.save_as()
                else:
                    self.save_file()
        return True

    def main(self):
        """go"""
        self._app.exec_()
Пример #29
0
import sys
from PyQt5.QtWidgets import QApplication
from ui import MainWindow
import traceback
import multiprocessing as mp
import logging


def excepthook(excType, excValue, tracebackobj):
    traceback.print_tb(tracebackobj, None, None)
    print(excType, excValue)


sys.excepthook = excepthook

if __name__ == '__main__':
    logging.basicConfig(
        format=
        '[line:%(lineno)d] %(filename)s %(asctime)s %(levelname)s %(message)s',
        level=logging.NOTSET)
    mp.set_start_method('spawn', force=True)
    app = QApplication(sys.argv)
    mainwindow = MainWindow.MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())
Пример #30
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow(app)
    window.show()
    app.exec()
Пример #31
0
#TODO don't have this as a global
mainWindow = None

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='BraidsTag server.')
  args = parser.parse_args()

  gameState = ServerGameState()

  main = ListeningThread(gameState)
  main.start()

  # Create Qt application
  app = QApplication(sys.argv)
  mainWindow = MainWindow(gameState, main)
  mainWindow.show()

  # Enter Qt main loop
  retval = app.exec_()

  for i in gameState.players.values():
    print(i)

  main.stop()
  gameState.terminate()

  #print >> sys.stderr, "\n*** STACKTRACE - START ***\n"
  #code = []
  #for threadId, stack in sys._current_frames().items():
  #    code.append("\n# ThreadID: %s" % threadId)
Пример #32
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.ui = MainWindow.Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.statusbar.hide()

        self.appVersion = "0.1-dev"

        # Setting QTDenter path
        common.set_qtdenter_path()

        # Some variables
        self._hidden = 0
        self.inserted_timeline_dents_ids = []
        self.inserted_mentions_dents_ids = []
        self._new_direct_messages = 0
        self._new_mentions = 0
        self._changed_credentials = False
        self.filters = {}
        # Set default filters
        self._filters_state = ["timeline", "mentions"]

        # Set QTextCodec explicitly. Some disadvantages for rarely used
        # languages, but no problems for others.
        QTextCodec.setCodecForCStrings(QTextCodec.codecForName("UTF-8"))

        # Tray icon
        self.icon = {}
        if not os.path.exists(common.QTDENTER_PATH + "/imgs/qtdenter.png"):
            self.icon["qicon"] = QIcon("/usr/share/pixmaps/qtdenter.png")
            self.icon["path"] = "/usr/share/pixmaps/qtdenter.png"
        else:
            self.icon["qicon"] = QIcon(common.QTDENTER_PATH +
                                       "/imgs/qtdenter.png")
            self.icon["path"] = common.QTDENTER_PATH + "/ui/imgs/qtdenter.png"

        self.trayIcon = QSystemTrayIcon(self.icon["qicon"], self)
        self.trayIcon.setVisible(True)
        self.connect(self.trayIcon,
                     SIGNAL("activated(QSystemTrayIcon::ActivationReason)"),
                     self.check_for_visibility)

        # Tray menu
        menu = QMenu(parent)
        menu.addAction("Show/Hide", self.check_for_visibility)
        menu.addSeparator()
        #menu.addAction("Options", self.show_options)
        #menu.addSeparator()
        menu.addAction("Exit", self.close_from_tray)
        self.trayIcon.setContextMenu(menu)

        # Reading settings and fill settings dict
        self.settings = {}
        if not os.path.exists(os.path.expanduser("~/.config/qtdenter")):
            os.mkdir(os.path.expanduser("~/.config/qtdenter"))
            os.system("touch ~/.config/qtdenter/qsettings.conf")
        if not os.path.exists(
                os.path.expanduser("~/.local/share/qtdenter/avatars/temp")):
            os.makedirs(
                os.path.expanduser("~/.local/share/qtdenter/avatars/temp"))

        if not os.path.exists(cachepath):
            os.mkdir(cachepath)

        try:
            self.qsettings = QSettings("qtdenter", "qsettings")
            self.settings["user"] = self.qsettings.value("user").toString()
            self.settings["password"] = self.qsettings.value(
                "password").toString()
            self.settings["server"] = self.qsettings.value("server").toString()
            self.settings["useSecureConnection"] = self.qsettings.value(
                "useSecureConnection").toString()
            self.settings["isSingle"] = self.qsettings.value(
                "isSingle").toString()
            self.settings["deleteAllFromCacheOnExit"] = self.qsettings.value(
                "deleteAllFromCacheOnExit").toString()
            self.settings["updateInterval"] = self.qsettings.value(
                "updateInterval").toString()
            self.settings["last_dent_id"] = self.qsettings.value(
                "last_dent_id").toString()

        except:
            QMessageBox.critical(self, "denter - No accounts",
                                 "Setup an account in Options!")

        try:
            self.restoreGeometry(
                self.qsettings.value("geometry").toByteArray())
            self.restoreState(self.qsettings.value("state").toByteArray())
        except:
            pass

        try:
            self.settings["remember_last_dent_id"] = self.qsettings.value(
                "remember_last_dent_id").toString()
            self.settings["fetch_on_startup"] = self.qsettings.value(
                "fetch_on_startup").toString()
        except:
            self.settings["remember_last_dent_id"] = "0"
            self.settings["fetch_on_startup"] = "20"

        try:
            self.settings["player"] = self.qsettings.value("player").toString()
            self.settings["player_string"] = self.qsettings.value(
                "player_string").toString()
            self.settings["mpd_port"] = self.qsettings.value(
                "mpd_port").toString()
            self.settings["mpd_host"] = self.qsettings.value(
                "mpd_host").toString()
        except:
            self.settings["player"] = None
            self.settings[
                "player_string"] = "!listening to: $artist - $track #$player"
            self.settings["mpd_port"] = "6600"
            self.settings["mpd_host"] = "localhost"

        try:
            self._filters_state = self.qsettings.value(
                "filters_state").toString()
            self._filters_state = self._filters_state.split(":")
        except:
            print "Failed to restore filters state"

        # Connecting menu actions
        self.ui.action_Options.triggered.connect(self.show_options_dialog)
        self.ui.action_Exit.triggered.connect(self.close_from_menu)
        self.ui.action_About_Denter.triggered.connect(self.show_about)
        self.ui.actionStatistics.triggered.connect(self.show_information)
        self.ui.actionSpam_Music_data.triggered.connect(self.spam_music)
        self.ui.action_Update_all.triggered.connect(self.update_timelines)
        self.ui.action_Mark_all_unread.triggered.connect(self.mark_all_as_read)

        # Connecting some signals
        self.connect(self, SIGNAL("ShowForm()"), self.check_for_visibility)
        self.connect(self, SIGNAL("HideForm()"), self.check_for_visibility)
        self.connect(self, SIGNAL("ShowOptions()"), self.show_options_dialog)
        self.connect(self, SIGNAL("Close()"), self.close_from_tray)

        # New post toolbar icon
        newPostIcon = iconFromTheme("add")
        newPost = QAction(newPostIcon, "New post", self)
        newPost.setShortcut("Ctrl+N")
        newPost.triggered.connect(self.post_status_dialog)

        # New direct message toolbar icon
        new_direct_message_icon = iconFromTheme("no-new-messages")
        new_direct_message = QAction(new_direct_message_icon,
                                     "New direct message", self)
        new_direct_message.setShortcut("Ctrl+D")
        new_direct_message.triggered.connect(self.post_direct_message_dialog)

        # Timelines reload toolbar icon
        reloadTimelinesIcon = iconFromTheme("reload")
        reloadTimelines = QAction(reloadTimelinesIcon, "Reload all timelines",
                                  self)
        reloadTimelines.setShortcut("Ctrl+R")
        reloadTimelines.triggered.connect(self.update_timelines)

        # Mark all read icon
        mark_all_read_icon = iconFromTheme("dialog-ok")
        mark_all_read = QAction(mark_all_read_icon,
                                "Mark all unread dents as read", self)
        mark_all_read.setShortcut("Ctrl+X")
        mark_all_read.triggered.connect(self.mark_all_as_read)

        # Options toolbar icon
        optionsIcon = iconFromTheme("document-properties")
        options = QAction(optionsIcon, "Options", self)
        options.setShortcut("Ctrl+P")
        options.triggered.connect(self.show_options_dialog)

        # Spacer widget, making last updated time label in toolbar to align
        # strictly right
        spacerWidget = QWidget()
        spacerWidget.setSizePolicy(QSizePolicy.Expanding,
                                   QSizePolicy.Preferred)

        # Last updated label
        self.time_updated_action = QLabel()

        # Adding everything to toolbar
        self.ui.toolBar.addAction(newPost)
        self.ui.toolBar.addAction(new_direct_message)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addAction(reloadTimelines)
        self.ui.toolBar.addAction(mark_all_read)
        self.ui.toolBar.addSeparator()
        self.ui.toolBar.addAction(options)
        self.ui.toolBar.addWidget(spacerWidget)
        self.ui.toolBar.addWidget(self.time_updated_action)

        # Setting icons
        self.ui.timeline_btn.setIcon(
            QIcon(common.QTDENTER_PATH + "/imgs/timeline.png"))
        self.ui.mentions_btn.setIcon(
            QIcon(common.QTDENTER_PATH + "/imgs/mentions.png"))
        self.ui.directs_btn.setIcon(
            QIcon(common.QTDENTER_PATH + "/imgs/directs.png"))

        # Adding accounts
        self.ui.no_accounts_btn.hide()

        self.btn = QPushButton()
        self.btn.setIcon(QIcon(common.QTDENTER_PATH + "/imgs/identica.png"))
        self.btn.setText(self.settings["server"])

        self.ui.accounts_layout.addWidget(self.btn)

        if "timeline" in self._filters_state:
            self.ui.timeline_btn.setChecked(True)
        if "mentions" in self._filters_state:
            self.ui.mentions_btn.setChecked(True)
        if "directs" in self._filters_state:
            self.ui.directs_btn.setChecked(True)

        self.ui.timeline_btn.clicked.connect(self.change_filters)
        self.ui.mentions_btn.clicked.connect(self.change_filters)
        self.ui.directs_btn.clicked.connect(self.change_filters)

        # Defining list_handler instance
        self.list_handler = list_handler.List_Handler(
            callback=self.lists_callback)

        # Set some options to timeline list
        self.ui.timeline_list.setSortingEnabled(True)
        self.ui.timeline_list.sortByColumn(2, Qt.DescendingOrder)
        for column in range(2, 6):
            self.ui.timeline_list.setColumnHidden(column, True)
        self.ui.timeline_list.setColumnWidth(0, 65)
        self.ui.timeline_list.itemActivated.connect(self.reply_to_dent)
        self.ui.timeline_list.itemSelectionChanged.connect(
            self.change_item_read_state)

        # Defining list_item instance, that generates items for lists
        self.list_item = list_item.list_item()

        # Init notifications
        try:
            pynotify.init(sys.argv[0])
            print "Notifier loaded"
        except:
            print "Failed to init pynotify"

        self.show()

        # Initialize auther and get timelines for first time
        try:
            self.init_connector()
        except:
            print "No auth data specified"

        try:
            self.initialize_button_mappers()

            opts = {
                "count": str(self.settings["fetch_on_startup"]),
                "name": self.settings["user"]
            }

            if self.settings["remember_last_dent_id"] == "1":
                # Getting last dent ID from server
                temp = self.auth.get_home_timeline(opts)
                # Calculation count of dents we will download on startup
                count = temp[0]["id"] - int(self.settings["last_dent_id"])

                if count == 0:
                    count = 20
                else:
                    pass

                opts = {"count": str(count), "name": self.settings["user"]}
        except:
            print "Can't specify options!"

        try:
            home_timeline = self.auth.get_home_timeline(opts)
            self.list_handler.add_data("home", home_timeline,
                                       self.settings["server"])
        except:
            print "Can't get home timeline. WTF?"

        try:
            mentions = self.auth.get_direct_messages(opts)
            self.list_handler.add_data("direct_messages", mentions,
                                       self.settings["server"])
            if self.settings["remember_last_dent_id"] == "1":
                root = self.ui.timeline_list.invisibleRootItem()
                last_item = root.child(0)
                dent_id = last_item.text(2).split(":")[0]
                self.qsettings.setValue("last_dent_id", dent_id)
            self.qsettings.sync()
        except:
            print "Can't get direct messages. WTF?"

        try:
            # Connect buttons
            self.connect_buttons()
        except:
            print "Failed to connect buttons!"

        # Init timer
        self.start_timer(self.settings["updateInterval"])

        # Init "Now Playing"
        self.np = now_playing.Now_Playing(self.settings)

        # Get max characters count from server
        try:
            server_data = self.auth.get_server_config("config")
            self.settings["messageLength"] = server_data["site"]["textlimit"]
        except:
            self.settings["messageLength"] = "140"
Пример #33
0
#!/usr/bin/python 
# -*- coding: utf-8 -*-

import os, sys, locale, os.path
from PyQt4 import QtGui, QtCore
from ui import MainWindow
from Functions import InitConfigValue, createStructure

locale.setlocale(locale.LC_ALL, 'C')
createStructure()
app = QtGui.QApplication(sys.argv)
os.chdir(os.path.split(sys.argv[0])[0])
pixmap = QtGui.QPixmap ('..' + os.sep + 'icons' + os.sep + 'tux_partizan.png')
splash = QtGui.QSplashScreen (pixmap, QtCore.Qt.WindowStaysOnTopHint)
splash.show()
app.processEvents()
main = MainWindow()
if InitConfigValue(main.Settings, 'RunInTray', 'False') == 'True' :
	main.hide()
else :
	main.show()
#splash.showMessage(" 00001\n", QtCore.Qt.AlignCenter, QtCore.Qt.yellow)
#app.processEvents()
splash.finish(main)
sys.exit(app.exec_())
Пример #34
0
class Model(qt4.QObject):
    '''
    
    Main work horse. Model of the data.
    '''  
    
    #*************************************__init__()************************************* 
    def __init__(self):
        '''
        Constructor
        '''
        qt4.QObject.__init__( self )
                
        self.view_mode = "R"        
        
        self.cp1 = CircuitProfile(None)
        self.cp2 = CircuitProfile(None)
        self.cpgoal = CircuitProfile(None)
        
        self.ops = {}
        self.results = {"S1": {}, "S2": {}, "Change": {}, "Goal": {}}
        
        self.load_operations()
        # create the GUI app
        self.app = qt4.QApplication.instance()
        self.app.processEvents()
        # instantiate the main window
        self.ui = MainWindow(self)
        self.plots_S1 = Plots(self, self.ui, "S1", self.ui.mplS1)
        self.plots_S2 = Plots(self, self.ui, "S2", self.ui.mplS2)
        self.plots_S2.hide()
        # full screen
        self.ui.showMaximized()
        # start the Qt main loop execution, exiting from this script
        # with the same return code of Qt application
        sys.exit(self.app.exec_())
        
        self.log_file = open("log_file.txt", "w")

    #*************************************load_circuit_profile()************************************* 
    def load_circuit_profile(self, identifier, fname):
        '''
        
        Args: 
        Returns:
        Raises:
        '''  
        if identifier == "S1":
            cp = self.cp1
        elif identifier == "S2":
            cp = self.cp2
            self.plots_S2.unhide()
            if len(cp.results) == 0:
                self.plots_S1.hide()
        elif identifier == "Goal":
            cp = self.cpgoal
        else:
            print "Unknown circuit profile identifier"
            sys.exit()
        
        cp.open_file(fname)
        results = self.compute_operations(cp)
        cp.set_results(results)
        self.results[identifier] = results
        
        if identifier == "S1":
            self.plots_S1.update_plots(cp)
        elif identifier == "S2":
            self.plots_S2.update_plots(cp)
                    
        self.check_change()
        self.emit(qt4.SIGNAL("sigModified"))
        
        
    #***************************check_change()***************************
    def check_change(self):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        rS1 = self.results["S1"]
        rS2 = self.results["S2"]
        
        if len(rS1) > 0 and len(rS2) > 0:
            self.results["Change"] = self.cp2 - self.cp1
            self.plots_S1.unhide()
            self.plots_S2.unhide()
        
    #***************************load_operations()***************************
    def load_operations(self):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        self.ops = Operations(self)
        self.vert_headers = ["S1", "S2", "Change", "Goal"]
        self.horiz_headers = self.ops.get_ops("table").keys()
        self.horiz_headers.sort()
        
    #***************************compute_operations()***************************
    def compute_operations(self, cp):
        '''
        
        Args: 
        Returns:
        Raises:
        '''  
        return self.ops.compute(cp)
    
    #***************************change_view()***************************
    def change_view(self, view):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        self.view_mode = view
        
        temp = []
        temp_plots = []

        if self.view_mode == "R":
            temp = self.ops.get_ops("table").keys()
            temp_plots = self.ops.get_ops("plot").keys()
        
        if self.view_mode == "T":
            for opname, op in self.ops.get_ops("table").items():
                if op.therapist is True or op.patient is True:
                    temp.append(opname)
            
            for opname, op in self.ops.get_ops("plot").items():
                if op.therapist is True or op.patient is True:
                    temp_plots.append(opname)
        
        if self.view_mode == "P":
            for opname, op in self.ops.get_ops("table").items():
                if op.patient is True:
                    temp.append(opname)
                    
            for opname, op in self.ops.get_ops("plot").items():
                if op.patient is True:
                    temp_plots.append(opname)
                    
        self.plots_S1.change_view(temp_plots)
        self.plots_S2.change_view(temp_plots)
        
        temp.sort()
        self.horiz_headers = temp
            
        self.emit(qt4.SIGNAL("sigModified"))
        
    #***************************get_result_at()***************************
    def get_result_at(self, row, col):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        cpname = self.vert_headers[col]
        cp_results = self.results[cpname]
        
        if len(cp_results) == 0:
            return None
        
        opname = self.horiz_headers[row]
        
        if self.view_mode == "R":
            return cp_results[opname]
        
        if self.view_mode == "T":
            op = self.ops.ops[opname]
            if op.therapist is True or op.patient is True:
                return cp_results[opname]
        
        if self.view_mode == "P":
            op = self.ops.ops[opname]
            if op.patient is True:
                return cp_results[opname]
            
    #***************************get_description_at()***************************
    def get_description_at(self, row, col):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        cpname = self.vert_headers[col]
        opname = self.horiz_headers[row]
        
        return self.ops.get_description(opname)

    #***************************get_vert_headers()***************************
    def get_vert_headers(self):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        return self.vert_headers
        
    #***************************get_horiz_headers()***************************
    def get_horiz_headers(self):
        '''
        
        Args: 
        Returns:
        Raises:
        '''
        return self.horiz_headers
        
Пример #35
0
    def __init__(self):
        super(Main, self).__init__()
        self.ui = MainWindow.Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton.clicked.connect(self.helloWorld)
Пример #36
0
# -*- coding: utf-8 -*-

# PyCollisionSim  - A graphical collision simulator wirtten in python
# Copyright (C) 2009 Gregory Haynes <*****@*****.**>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import sys
from PyQt4 import QtGui
from ui import MainWindow

if __name__ == "__main__":
	app = QtGui.QApplication(sys.argv)
	window = MainWindow()
	window.show()
	sys.exit(app.exec_())
Пример #37
0
import sys
import qdarkstyle
from PyQt4.QtGui import QApplication
from ui import MainWindow
from opt import ConstrainedOpt
from model import sgan

if __name__ == "__main__":
    model = sgan.Model("params/sgan_model.ckpt")
    opt_engine = ConstrainedOpt(model)

    # initialize application
    app = QApplication(sys.argv)
    app.setStyleSheet(qdarkstyle.load_stylesheet(pyside=False))
    window = MainWindow(opt_engine)
    window.setWindowTitle("pix2vox")
    window.show()
    window.viewerWidget.interactor.Initialize()
    sys.exit(app.exec_())
Пример #38
0
 def __init__(self):
     super().__init__()
     self.ui = MainWindow()
     self.ui.setupUi(self)
     self.show()  
Пример #39
0
class InfluxManage(QObject):
    signal = pyqtSignal()

    def __init__(self):
        super().__init__()
        self.app = QApplication(sys.argv)
        # self.MainWindow = MyQMainWindow()
        self.MainWindow = MainWindow()
        self.MainWindow.show()
        # self.MainWindow.setupUi(self.MainWindow)

        self.MainWindow.actionNew.triggered.connect(self.new_connect)
        self.MainWindow.actionImport.triggered.connect(self.import_connect)
        self.MainWindow.actionExport.triggered.connect(self.export_connect)

        self.new_ui = Ui_Form()
        self.new_QWidget = QWidget()
        self.new_QWidget.setWindowModality(Qt.ApplicationModal)
        self.new_ui.setupUi(self.new_QWidget)

        self.histroy_ui = Ui_history_ui()
        self.history_QWidget = QWidget()
        self.history_QWidget.setWindowModality(Qt.ApplicationModal)
        self.histroy_ui.setupUi(self.history_QWidget)
        self.histroy_ui.clear.clicked.connect(self.histroy_clear)

        self.import_ui_QWidget = QWidget()
        self.import_ui_QWidget.setWindowModality(Qt.ApplicationModal)
        self.import_ui = Import_UI(self.import_ui_QWidget)

        self.create_ui = Create_Ui_Form()
        self.create_QWidget = QWidget()
        self.create_QWidget.setWindowModality(Qt.ApplicationModal)
        self.create_ui.setupUi(self.create_QWidget)

        self.create_database_ui = Ui_create_database()
        self.create_database_QWidget = QWidget()
        self.create_database_QWidget.setWindowModality(Qt.ApplicationModal)
        self.create_database_ui.setupUi(self.create_database_QWidget)

        self.path = os.path.dirname(sys.argv[0])
        self.conn = sqlite3.connect('db/influx.db')
        self.get_server_list()
        self.signal.connect(self.exec_handler)
        self.MainWindow.execAction.triggered.connect(lambda: self.signal.emit())
        self.MainWindow.history_button.triggered.connect(self.show_history)
        self.MainWindow.tabWidget.tabCloseRequested.connect(self.tab_close)

        self.MainWindow.treeView.setContextMenuPolicy(Qt.CustomContextMenu)  # 打开右键菜单的策略
        self.MainWindow.treeView.customContextMenuRequested.connect(self.right_click_menu)  # 绑定事件

        self.influxDbClient = InfluxRegister()
        self.edit_context_menu = QMenu()  # 创建对象
        self.edit_context_flag = False
        self.qt_info = functools.partial(QMessageBox.information, self.MainWindow, '提示信息')
        self.qt_cri = functools.partial(QMessageBox.critical, self.MainWindow, '提示信息')

    def histroy_clear(self):
        try:
            c = self.conn.cursor()
            c.execute("delete from history")
            c.execute("update sqlite_sequence SET seq = 0 where name ='history'")
            self.conn.commit()
            c.close()
            self.show_history()
        except Exception as e:
            with open("error.log", "w") as f:
                f.write(str(e))
            print(e)

    def save_history(self, text):
        save_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        c = self.conn.cursor()
        cursor = c.execute("select * from history")
        if text != "":
            if len(cursor.fetchall()) >= 100:
                c.execute("delete from history where time IN (SELECT time from history limit 1)")  # 删除最老的一条
            text = text.replace("'", "''")
            sql = """INSERT INTO history (time , sql) VALUES ('{}','{}')""".format(save_time, text)  # 插入新的
            c.execute(sql)
            self.conn.commit()
        c.close()

    def show_history(self):
        self.history_QWidget.show()
        c = self.conn.cursor()
        cursor = c.execute("SELECT * from history order by time DESC ")
        data = cursor.fetchall()
        self.histroy_ui.tableWidget.setRowCount(len(data))  # 设置行
        self.histroy_ui.tableWidget.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)  # 添加滚动条
        for index, i in enumerate(data):
            for _index, j in enumerate(i):
                newItem = QTableWidgetItem(str(j))
                newItem.setTextAlignment(Qt.AlignCenter)
                self.histroy_ui.tableWidget.setItem(index, _index, newItem)

    def new_connect(self):
        """新建窗口,添加服务器"""
        self.new_QWidget.show()
        self.new_ui.pushButton.disconnect()  # 重新绑定时需要先释放绑定
        self.new_ui.pushButton_2.disconnect()  # 重新绑定时需要先释放绑定
        self.new_ui.pushButton.clicked.connect(self.save_connect)
        self.new_ui.pushButton_2.clicked.connect(self.test_connect)

    def import_handler(self):
        conn = sqlite3.connect('db/influx.db')
        src = self.import_ui.browse_edit.text()
        try:
            df = pandas.read_excel(src)
            print(df)
            data = df.to_dict(orient='split')
            c = conn.cursor()
            for server_data in data["data"]:
                sql = """INSERT INTO ServerList (name, address, port, user, password, ssl_switch) VALUES ('{}','{}',{}
                ,'{}','{}',{})""".format(*server_data)
                c.execute(sql)
            conn.commit()
            self.qt_info("保存成功")
        except sqlite3.IntegrityError as e:
            self.qt_cri("name or ip existing")
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)
        except FileNotFoundError:
            self.qt_cri("No such file or directory")
        except Exception as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)
        finally:
            conn.close()
            self.MainWindow.treeView.clear()
            self.get_server_list()

    def import_connect(self):
        self.import_ui_QWidget.show()
        self.import_ui.import_button.disconnect()
        self.import_ui.import_button.clicked.connect(self.import_handler)

    def export_connect(self):
        c = self.conn.cursor()
        sql = "SELECT name, address, port, user, password, ssl_switch from ServerList"
        cursor = c.execute(sql)
        df = pandas.DataFrame(cursor, columns=["name", "ip", "port", "account", "password", "ssl(2=open,0=close)"])
        filename = QFileDialog.getSaveFileName(self.MainWindow, 'save file', './template.xls')
        if not all(filename):
            return
        try:
            df.to_excel(filename[0], index=False)
            self.qt_info("导出成功!已导出到当前目录下的template.xls文件中")
        except Exception as e:
            self.qt_cri(str(e))

    def test_connect(self):
        address = self.new_ui.address.text()
        port = self.new_ui.port.text()
        user = self.new_ui.user.text()
        password = self.new_ui.password.text()
        ssl = self.new_ui.checkBox.checkState()
        ssl_switch = True if ssl == 2 else False
        client = InfluxDBClient(host=address, port=port, username=user, password=password,
                                verify_ssl=ssl_switch)
        try:
            client.get_list_database()
            self.qt_info("连接成功")
        except Exception as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def save_connect(self, types):
        """ 如果类型为True则编辑服务器"""
        name = self.new_ui.name.text()
        address = self.new_ui.address.text()
        port = self.new_ui.port.text()
        user = self.new_ui.user.text()
        password = self.new_ui.password.text()
        ssl = self.new_ui.checkBox.checkState()
        c = self.conn.cursor()
        if not user:
            user = "******"
        if not password:
            password = "******"

        if not all([name, address, port]):  # 当这三个中不管哪一个为空都不能继续往下执行
            self.qt_cri("名称、地址、端口不可以为空")
            return
        sql = """INSERT INTO ServerList (name, address, user, port, password, ssl_switch) VALUES ('{}','{}','{}',{},'{}',{})""".format(
            name, address, user, port, password, ssl)
        if types == 1:
            old_name = self.MainWindow.treeView.currentItem().text(0)  # 取当前节点的value值
            self.influxDbClient.create_client(old_name)
            clients = self.influxDbClient.clients.get(old_name)
            data = clients.get("data")
            ID = data[-1]
            sql = """UPDATE ServerList SET name="{}", address="{}", user="******", port="{}", password="******", ssl_switch="{}" where ID={}""".format(
                name, address, user, port, password, ssl, ID)
        try:
            c.execute(sql)
            self.conn.commit()
            if types:  # 点击编辑时,则删除当前服务器节点,并重新添加节点后高亮
                self.action_handler_1(2)
                rootIndex = self.MainWindow.treeView.indexOfTopLevelItem(self.MainWindow.treeView.currentItem())
                self.MainWindow.treeView.takeTopLevelItem(rootIndex)  # 删除当前服务器节点
                self.get_server_list(True, ID, rootIndex)
            else:  # 否则在保存以后刷新界面,先获取插入的最后一条数据的ID
                sql = """select ID from ServerList where rowid = last_insert_rowid() ;"""
                result = c.execute(sql)
                ID = result.fetchone()[0]
                rootIndex = self.MainWindow.treeView.topLevelItemCount()
                self.get_server_list(True, ID, rootIndex)
            self.qt_info("保存成功")
            self.new_QWidget.close()

        except sqlite3.IntegrityError as e:
            self.qt_cri("名称不能重复")
        except ValueError as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def get_server_list(self, types=False, ID=None, rootIndex=None):
        """ ssl_switch : 开启ssl2 未开启ssl, 0"""
        c = self.conn.cursor()
        sql = "SELECT name, address, port, user, password, ssl_switch from ServerList"
        if types:
            sql = "SELECT name, address, port, user, password, ssl_switch from ServerList WHERE ID={}".format(ID)
        cursor = c.execute(sql)
        for x in cursor:
            if types:
                root = QTreeWidgetItem()
            else:
                root = QTreeWidgetItem(self.MainWindow.treeView)
            root.setText(0, x[0])
            root.setText(1, json.dumps(x))

            icon = QIcon()
            icon.addPixmap(QPixmap("images/server_open.ico"), QIcon.Normal, QIcon.On)
            icon.addPixmap(QPixmap("images/server_close.ico"), QIcon.Normal, QIcon.Off)
            root.setIcon(0, icon)
            if types:
                self.MainWindow.treeView.insertTopLevelItem(rootIndex, root)
                self.MainWindow.treeView.setCurrentItem(root)

        self.MainWindow.treeView.doubleClicked.disconnect()
        self.MainWindow.treeView.doubleClicked.connect(self.double_handler)

    def tab_close(self, index):
        self.MainWindow.tabWidget.removeTab(index)

    def create_table(self, text, name, database, tables_name=None):
        tab = QWidget()
        tab.setObjectName("tab")
        MyTextEdit.constant = sql_constant
        if tables_name:
            MyTextEdit.constant.extend(tables_name)
        self.MainWindow.textEdit = MyTextEdit(tab)
        self.MainWindow.textEdit.setGeometry(QtCore.QRect(0, 0, self.MainWindow.width() - 312, 181))
        self.MainWindow.textEdit.setObjectName("textEdit")
        self.MainWindow.textEdit.setPlainText(text)

        self.MainWindow.tableWidget = QTableWidget(tab)
        self.MainWindow.tableWidget.setGeometry(
            QtCore.QRect(0, 211, self.MainWindow.width() - 315, self.MainWindow.height() - 335))
        self.MainWindow.tableWidget.setObjectName("tableWidget")

        self.MainWindow.QComboBox = QComboBox(tab)
        self.MainWindow.QComboBox.setGeometry(QtCore.QRect(self.MainWindow.width() - 430, 184, 120, 25))
        self.MainWindow.QComboBox.setObjectName("QComboBox")

        self.MainWindow.tabWidget.addTab(tab, "{}.{}".format(name, database))
        current_index = self.MainWindow.tabWidget.count()  # 获取tab数量
        self.MainWindow.tabWidget.setCurrentIndex(current_index - 1)  # 激活最后一个创建的tab

    def group_select(self, series):
        current_text = self.MainWindow.QComboBox.currentText()
        currentTableWidget = self.MainWindow.tabWidget.currentWidget().findChild(QTableWidget, "tableWidget")
        for x in series:
            tags = x.get('tags')
            columns = x.get('columns')
            values = x.get('values')
            for z in tags:
                if tags[z] == current_text:
                    currentTableWidget.setColumnCount(len(columns))  # 设置列
                    currentTableWidget.setRowCount(len(values))  # 设置行
                    currentTableWidget.setHorizontalHeaderLabels(columns)  # 设置标题
                    # currentTableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 关闭双击编辑
                    currentTableWidget.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)  # 添加滚动条
                    for index, i in enumerate(values):
                        for _index, j in enumerate(i):
                            newItem = QTableWidgetItem(str(j))
                            newItem.setTextAlignment(Qt.AlignCenter)
                            currentTableWidget.setItem(index, _index, newItem)
                    return

    def show_table(self, tables):
        """传入influx数据,table显示数据"""
        currentTableWidget = self.MainWindow.tabWidget.currentWidget().findChild(QTableWidget, "tableWidget")
        flag = True
        try:
            series = tables.get("series")
            # print(series)
            if not series:
                currentTableWidget.setColumnCount(1)  # 设置列
                currentTableWidget.setRowCount(1)  # 设置行
                currentTableWidget.setHorizontalHeaderLabels(["返回结果"])  # 设置标题
                currentTableWidget.setItem(0, 0, QTableWidgetItem(""))
                return
            for x in series:
                table_name = x.get('name')
                columns = x.get('columns')
                values = x.get('values')
                tags = x.get('tags')
                if tags:
                    if flag:
                        self.MainWindow.QComboBox.currentIndexChanged.connect(lambda: self.group_select(series))
                        flag = False
                    for n in tags:
                        self.MainWindow.QComboBox.addItem(tags[n])
                currentTableWidget.setColumnCount(len(columns))  # 设置列
                currentTableWidget.setRowCount(len(values))  # 设置行
                currentTableWidget.setHorizontalHeaderLabels(columns)  # 设置标题
                # currentTableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 关闭双击编辑
                currentTableWidget.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)  # 添加滚动条
                for index, i in enumerate(values):
                    for _index, data_time in enumerate(i):
                        if _index == 0:
                            obj = re.match(
                                "^[1-2][0-9][0-9][0-9]-[0-1]{0,1}[0-9]-[0-3]{0,1}[0-9]T([0-1]?[0-9]|2[0-3]):([0-5]"
                                "[0-9]):([0-5][0-9]).+$",
                                data_time)
                            if obj:
                                data_time = str(data_time).replace("T", " ")
                                data_time = data_time.split(".")[0]
                        newItem = QTableWidgetItem(str(data_time))
                        newItem.setTextAlignment(Qt.AlignCenter)
                        currentTableWidget.setItem(index, _index, newItem)
        except Exception as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def double_handler(self):
        """双击服务器节点事件"""
        # treeView层级处理
        index_row = -1
        item = self.MainWindow.treeView.currentItem()
        parent = item.parent()
        if parent is None:
            index_top = self.MainWindow.treeView.indexOfTopLevelItem(item)
        else:
            index_top = self.MainWindow.treeView.indexOfTopLevelItem(parent)
            index_row = parent.indexOfChild(item)
        level = (index_top, index_row)
        # print(level)

        # 每个层级的逻辑处理
        if level == (-1, index_row):  # 当双击表的时候操作的事件
            client, server_name, database_name, table_name = self.table_conn_client()
            text = """SELECT * FROM "{}" WHERE time > now() - 5m""".format(table_name)
            childCount = self.MainWindow.treeView.currentItem().parent().childCount()
            tables_name = set()
            for x in range(childCount):
                name = self.MainWindow.treeView.currentItem().parent().child(x).text(0)
                tables_name.add(name)
            sql = 'SHOW TAG KEYS FROM "{}"'.format(table_name)
            keys_data = client.query(sql)
            sql = 'SHOW FIELD KEYS FROM "{}"'.format(table_name)
            field_data = client.query(sql)
            key_data = [x for x in keys_data]
            field_data = [x for x in field_data]
            new_data = key_data[0]
            new_data.extend(field_data[0])

            f = map(lambda x: {x.get('tagKey'), x.get('fieldKey')}, new_data)  # 同时取tagkey和fieldKey
            var = functools.reduce(lambda x, y: x | y, f)  # 循环获取列表中的集合,并且对之前的集合与后面的集合进行合并。reduce的功能
            tables_name.update(var)  # 更新到主集合中

            self.create_table(text, server_name, database_name, tables_name)

        elif level == (index_top, -1):  # 当双击服务器的时候显示数据库
            childCount = self.MainWindow.treeView.currentItem().childCount()
            if childCount == 0:
                icon = QIcon()
                icon.addPixmap(QPixmap("images/database_open.ico"), QIcon.Normal, QIcon.On)  # 设置打开时的图片样式
                icon.addPixmap(QPixmap("images/database_close.ico"), QIcon.Normal,
                               QIcon.Off)  # 设置关闭的时候图片样式
                try:
                    # 通过value中保存的服务器信息连接服务器并获得client
                    name = self.MainWindow.treeView.currentItem().text(0)  # 取当前节点的value值
                    self.influxDbClient.create_client(name)
                    clients = self.influxDbClient.clients.get(name)
                    client = clients.get("client")
                    database_list = client.get_list_database()
                    for x in database_list:
                        database_name = x.get("name")
                        child = QTreeWidgetItem()
                        child.setText(0, database_name)  # 插入根节点
                        child.setIcon(0, icon)
                        self.MainWindow.treeView.currentItem().addChild(child)
                except Exception as e:
                    self.qt_cri(str(e))
                    print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

        elif level == (index_top, index_row):  # 当双击数据库的时候显示表
            childCount = self.MainWindow.treeView.currentItem().childCount()
            if childCount == 0:
                name = self.MainWindow.treeView.currentItem().parent().text(0)  # 取服务器名
                database = self.MainWindow.treeView.currentItem().text(0)  # 取数据库名
                self.influxDbClient.create_client(name, database=database)
                clients = self.influxDbClient.clients.get(name)
                client = clients.get("client")
                tables = client.query('show measurements;')
                Children = []
                for x in tables:
                    for i in x:
                        child = QTreeWidgetItem()
                        child.setText(0, i.get("name"))
                        child.setIcon(0, QIcon('images/form.ico'))
                        Children.append(child)
                self.MainWindow.treeView.currentItem().addChildren(Children)

    def status_bar_signal(self, text):
        self.MainWindow.statusBar.showMessage(text)

    def run(self):
        try:
            text_obj = self.MainWindow.tabWidget.currentWidget().findChild(QPlainTextEdit, "textEdit")
            old_time = time.time() * 1000
            tab_name = self.MainWindow.tabWidget.tabText(self.MainWindow.tabWidget.currentIndex())
            data = tab_name.rsplit(sep='.', maxsplit=1)
            name = data[0]
            database = data[1]
            self.influxDbClient.create_client(name, database=database)
            clients = self.influxDbClient.clients.get(name)
            client = clients.get("client")
            tables = client.query(text_obj.toPlainText())
            now_time = time.time() * 1000
            self.show_table(tables.raw)  # 将查询结果传到show_table,并显示数据到前端
            self.MainWindow.statusBar.showMessage("执行完毕,耗时:{}毫秒".format(int(now_time - old_time)))
            self.MainWindow.statusBar.setStyleSheet("color:green")
            self.save_history(text=text_obj.toPlainText())
        except AttributeError:
            self.MainWindow.statusBar.setStyleSheet("color:red")
            self.MainWindow.statusBar.showMessage("没有选择数据库,请先选择数据库")
        except Exception as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def exec_handler(self):
        self.MainWindow.statusBar.showMessage("执行中...")
        self.MainWindow.statusBar.setStyleSheet("color:red")
        self.run_thread = Runthread()  # 步骤2. 主线程连接子线,同时传递一个值给子线程
        self.run_thread.signal.connect(self.run)  # 自定义信号连接
        self.run_thread.start()  # 步骤3 子线程开始执行run函数

    def table_conn_client(self):
        server_name = self.MainWindow.treeView.currentItem().parent().parent().text(0)
        database_name = self.MainWindow.treeView.currentItem().parent().text(0)
        table_name = self.MainWindow.treeView.currentItem().text(0)

        self.influxDbClient.create_client(server_name, database=database_name)
        clients = self.influxDbClient.clients.get(server_name)
        client = clients.get("client")
        return client, server_name, database_name, table_name

    def select(self, i):
        client, name, database, db = self.table_conn_client()
        sql = 'SHOW TAG VALUES FROM "{}" WITH KEY = "{}"'.format(db, i)
        new_tables = client.query(sql)
        self.show_table(new_tables.raw)

    def create_form(self, client):
        """创建表的点击事件"""
        json_body = self.create_ui.textEdit.toPlainText()
        try:
            json_body = json.loads(json_body)
            client.write_points(json_body)
            self.qt_info("创建成功")
            self.action_handler_2(0)
        except Exception as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def create_database(self, client):
        database = self.create_database_ui.lineEdit.text()
        try:
            client.create_database(database)  # 创建数据库
            QMessageBox.information(self.MainWindow, 'Message', "创建成功")
            self.action_handler_1(2)
            self.double_handler()

        except Exception as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def action_handler_1(self, types):
        """服务器层操作:
            1.创建数据库
            2.关闭连接
            3.编辑服务器
            4.删除服务器
          """
        name = self.MainWindow.treeView.currentItem().text(0)
        self.influxDbClient.create_client(name)
        clients = self.influxDbClient.clients.get(name)
        client = clients.get("client")
        if types == 1:
            self.create_database_QWidget.show()
            self.create_database_ui.pushButton.disconnect()
            self.create_database_ui.pushButton.clicked.connect(lambda: self.create_database(client))

        if types == 2:
            client.close()
            del self.influxDbClient.clients[name]
            child = self.MainWindow.treeView.currentItem().childCount()
            while child:
                now_child = self.MainWindow.treeView.currentItem().child(0)
                self.MainWindow.treeView.currentItem().removeChild(now_child)
                child -= 1
            self.MainWindow.treeView.currentItem().setIcon(0, QIcon('images/server_close.ico'))

        if types == 3:
            data = clients.get("data")
            self.new_QWidget.show()
            self.new_QWidget.setWindowTitle("编辑连接")
            self.new_ui.name.setText(data[0])
            self.new_ui.address.setText(data[1])
            self.new_ui.port.setValue(data[2])
            self.new_ui.user.setText(data[3])
            self.new_ui.password.setText(data[4])
            ssl_switch = True if data[5] == 2 else False
            self.new_ui.checkBox.setChecked(ssl_switch)
            self.new_ui.pushButton.disconnect()  # 重新绑定时需要先释放绑定
            self.new_ui.pushButton_2.disconnect()  # 重新绑定时需要先释放绑定
            self.new_ui.pushButton.clicked.connect(lambda: self.save_connect(True))
            self.new_ui.pushButton_2.clicked.connect(self.test_connect)

        if types == 4:
            # 删除数据库中的信息
            data = clients.get("data")
            sql = 'delete from ServerList where id={}'.format(data[-1])
            reply = QMessageBox.question(self.MainWindow, 'Message', "确定要删除?",
                                         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                try:
                    c = self.conn.cursor()
                    c.execute(sql)
                    self.conn.commit()
                    self.qt_info("删除成功")
                    self.action_handler_1(2)
                    rootIndex = self.MainWindow.treeView.indexOfTopLevelItem(self.MainWindow.treeView.currentItem())
                    self.MainWindow.treeView.takeTopLevelItem(rootIndex)  # 删除当前服务器节点
                except Exception as e:
                    self.qt_cri(str(e))
                    print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def action_handler_2(self, types):
        """
            数据库层操作
            types : 0 刷新窗口, 1 新建表, 2 删除数据库
        """
        name = self.MainWindow.treeView.currentItem().parent().text(0)
        database = self.MainWindow.treeView.currentItem().text(0)
        self.influxDbClient.create_client(name, database=database)
        clients = self.influxDbClient.clients.get(name)
        client = clients.get("client")
        if types == 0:
            child = self.MainWindow.treeView.currentItem().childCount()
            while child:
                now_child = self.MainWindow.treeView.currentItem().child(0)
                self.MainWindow.treeView.currentItem().removeChild(now_child)
                child -= 1
            tables = client.query('show measurements;')
            for x in tables:
                for i in x:
                    child = QTreeWidgetItem()
                    child.setText(0, i.get("name"))
                    child.setIcon(0, QIcon('images/form.ico'))
                    self.MainWindow.treeView.currentItem().addChild(child)
        if types == 1:
            self.create_QWidget.show()
            self.create_ui.pushButton.disconnect()
            self.create_ui.pushButton.clicked.connect(lambda: self.create_form(client))
        if types == 2:
            reply = QMessageBox.question(self.MainWindow, 'Message', "确定要删除数据库: {}".format(database),
                                         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                try:
                    client.drop_database(database)  # 删除数据库
                    self.qt_info("删除成功")
                    current_item = self.MainWindow.treeView.currentItem()  # 获取当前节点
                    self.MainWindow.treeView.currentItem().parent().removeChild(current_item)  # 删除父目录下当前节点
                except Exception as e:
                    self.qt_cri(str(e))
                    print(e, '错误所在的行号:', e.__traceback__.tb_lineno)

    def action_handler_3(self, types):
        """表单层操作"""
        client, name, database, db = self.table_conn_client()
        self.influxDbClient.create_client(name, database=database)
        clients = self.influxDbClient.clients.get(name)
        client = clients.get("client")

        if types == 0:
            sql = 'SHOW TAG KEYS FROM "{}"'.format(db)
            tables = client.query(sql)
            self.create_table(sql, name, database)
            self.show_table(tables.raw)
        elif types == 1:
            tables = client.query('SHOW TAG KEYS FROM "{}"'.format(db))
            self.create_table("", name, database)
            switch = True
            for x in tables:
                for i in x:
                    for z in i:
                        if switch:
                            sql = 'SHOW TAG VALUES FROM "{}" WITH KEY = "{}"'.format(db, i[z])
                            new_tables = client.query(sql)
                            self.show_table(new_tables.raw)
                            switch = False
                        self.MainWindow.QComboBox.addItem(str(i[z]))
            self.MainWindow.QComboBox.currentIndexChanged[str].connect(self.select)
        elif types == 2:
            text = 'SHOW FIELD KEYS FROM "{}"'.format(db)
            tables = client.query(text)
            self.create_table(text, name, database)
            self.show_table(tables.raw)
        elif types == 3:
            client, name, database, db = self.table_conn_client()
            reply = QMessageBox.question(self.MainWindow, 'Message', "确定要删除?",
                                         QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                try:
                    client.query('drop measurement {}'.format(db))
                    self.qt_cri("删除成功")
                    current_item = self.MainWindow.treeView.currentItem()
                    self.MainWindow.treeView.currentItem().parent().removeChild(current_item)
                except Exception as e:
                    self.qt_cri(str(e))
                    print('错误所在的行号:', e.__traceback__.tb_lineno)
        else:
            raise ValueError

    def right_click_menu(self, pos):
        index_row = -1
        item = self.MainWindow.treeView.currentItem()
        if not item:
            contextMenu = QMenu()  # 创建对象
            new_conn = contextMenu.addAction(u'新建连接')  # 添加动作
            new_conn.triggered.connect(self.new_connect)
            contextMenu.exec_(self.MainWindow.treeView.mapToGlobal(pos))  # 随指针的位置显示菜单
            contextMenu.show()  # 显示
            return
        try:
            parent = item.parent()
        except Exception as e:
            self.qt_cri(str(e))
            print(e, '错误所在的行号:', e.__traceback__.tb_lineno)
            return
        if parent is None:
            index_top = self.MainWindow.treeView.indexOfTopLevelItem(item)
        else:
            index_top = self.MainWindow.treeView.indexOfTopLevelItem(parent)
            index_row = parent.indexOfChild(item)
        level = (index_top, index_row)
        if level == (-1, index_row):  # 当右击表的时候
            try:
                contextMenu = QMenu()  # 创建对象
                actionA = contextMenu.addAction(u'显示标签键')  # 添加动作
                actionB = contextMenu.addAction(u'显示标签值')
                actionC = contextMenu.addAction(u'显示字段键')
                actionD = contextMenu.addAction(u'删除表')
                actionA.triggered.connect(lambda: self.action_handler_3(0))
                actionB.triggered.connect(lambda: self.action_handler_3(1))
                actionC.triggered.connect(lambda: self.action_handler_3(2))
                actionD.triggered.connect(lambda: self.action_handler_3(3))
                contextMenu.exec_(self.MainWindow.treeView.mapToGlobal(pos))  # 随指针的位置显示菜单
                contextMenu.show()  # 显示
            except Exception as e:
                print(e, '错误所在的行号:', e.__traceback__.tb_lineno)
        elif level == (index_top, -1):  # 当右击服务器的时候
            contextMenu = QMenu()  # 创建对象
            actionA = contextMenu.addAction(u'创建数据库')  # 添加动作
            actionB = contextMenu.addAction(u'关闭连接')

            actionC = contextMenu.addAction(u'编辑服务器')  # 添加动作
            actionD = contextMenu.addAction(u'删除服务器')  # 添加动作

            actionA.triggered.connect(lambda: self.action_handler_1(1))
            actionB.triggered.connect(lambda: self.action_handler_1(2))
            actionC.triggered.connect(lambda: self.action_handler_1(3))
            actionD.triggered.connect(lambda: self.action_handler_1(4))

            contextMenu.exec_(self.MainWindow.treeView.mapToGlobal(pos))  # 随指针的位置显示菜单
            contextMenu.show()  # 显示
        elif level == (index_top, index_row):  # 当右击数据库的时候
            contextMenu = QMenu()  # 创建对象
            actionA = contextMenu.addAction(u'刷新')  # 添加动作
            actionB = contextMenu.addAction(u'创建表')  # 添加动作
            actionC = contextMenu.addAction(u'删除数据库')
            actionA.triggered.connect(lambda: self.action_handler_2(0))
            actionB.triggered.connect(lambda: self.action_handler_2(1))
            actionC.triggered.connect(lambda: self.action_handler_2(2))
            contextMenu.exec_(self.MainWindow.treeView.mapToGlobal(pos))  # 随指针的位置显示菜单
            contextMenu.show()  # 显示
Пример #40
0
            nargs='+',
            action=required_length(1, 2),
            help=
            "transforms the input using the specified script (optional arguments)"
        )

        args = parser.parse_args()
        if args.help:
            parser.print_help()
            sys.exit(0)

        if not args.encode and not args.decode and not args.script and not args.hash and not args.interactive:
            # Start GUI when no other parameters were used.
            try:
                app = QApplication(sys.argv)
                ex = MainWindow(context)
                sys.exit(app.exec_())
            except Exception as e:
                context.logger().error("Unexpected Exception: {}".format(e))
                sys.exit(1)

        if args.interactive:
            setup_syntax_completion()
            from ptpython.repl import embed
            print("{app_name} {app_version}".format(
                app_name=context.config().getName(),
                app_version=context.config().getVersion()))
            embed(globals=globals(), locals=locals())
            sys.exit(0)

        if not args.encode and not args.decode and not args.script and not args.hash:
Пример #41
0
    reload_lessons()


def action_clear_button():
    tasks.neural.clear()
    reload_lessons()


def action_teach_button():
    tasks.refresh()
    reload_lessons()


if __name__ == '__main__':
    app = QApplication(argv)
    window = MainWindow()
    contents = window.centralWidget()
    status_bar = window.statusBar()
    data = contents.head_widget

    window.menuBar().action_queue_clear.triggered.connect(remove_lessons)
    window.menuBar().action_clear.triggered.connect(action_clear_button)
    window.menuBar().action_teach.triggered.connect(action_teach_button)
    data.add_button.clicked.connect(add_button_click)

    status_bar.showMessage('Загрузка...', msecs=STATUS_BAR_TIMEOUT)
    load_tasks()
    window.show()
    status_bar.showMessage('Готово', msecs=STATUS_BAR_TIMEOUT)

    exit_code = app.exec()
Пример #42
0
def run():
    w = MainWindow()
    w.show(dockable=True, floating=False, area='left')
Пример #43
0
'''
Created on Jun 18, 2018

@author: rameshpr
'''
from PyQt4 import QtGui
import sys
from ui import MainWindow

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    form = MainWindow()
    form.show()
    app.exec_()
Пример #44
0
 tft = TFT()
 chess = tft.get_chess()  # 获取所有的棋子数据 返回一个列表
 equip = tft.get_equip()  # 获取所有的装备数据 返回一个列表
 job = tft.get_job()  # 获取所有的职业数据 返回一个列表
 race = tft.get_race()  # 获取所有的羁绊数据 返回一个列表
 downSJ()  # 下载所有数据
 tft.get_linelist()
 strategyS = []
 #-------------------界面----------------------------------------------------
 # 创建一个QApplication类的实例 可以看做是屏幕 要有屏幕对象,才能开始画窗口
 app=QApplication(sys.argv)
 #自适应DPI缩放
 QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
 #----------mainwindow主窗口------------------
 mainWindow=QMainWindow()#创建一个界面
 ui= MainWindow.Ui_MainWindow()#实例化ui界面对象
 ui.setupUi(mainWindow)#运行里面的代码
 mainWindowInitialize() #初始化赋值
 mainWindow.show() #显示
 # ----------strategyForm攻略选项面板------------------
 straForm = QDialog()  # 创建一个界面
 straFormUI = Form_strategy.Ui_strategyForm()  # 实例化ui界面对象
 straFormUI.setupUi(straForm)  # 运行里面的代码
 straFormInitialize()  # 初始化赋值
 straForm.show()  # 显示
 # ----------hero英雄面板------------------
 heroForm = QDialog()  # 创建一个界面
 heroFormUI = Form_hero.Ui_Form_hero()  # 实例化ui界面对象
 heroFormUI.setupUi(heroForm)  # 运行里面的代码
 heroFormInitialize()  # 初始化赋值
 heroForm.show()  # 显示
Пример #45
0
def main():
    app = QApplication(argv)
    window = MainWindow()
    window.show()
    exit(app.exec_())