class Settings: def __init__(self): self.values = dict() self.values['mythFileDir'] = '/' self.values['dbHost'] = '' self.values['dbUser'] = '******' self.values['dbPassword'] = '******' self.values['firstRun'] = True self.values['deinterlace'] = True self.values['bufferTime'] = 5 self.values['lengthUpdateInterval'] = 3000 self.values['mplayer'] = 'mplayer' self.values['mpv'] = 'mpv' self.values['backend'] = 'mpv' self.configHandler = ConfigHandler('mythnimal') self.configHandler.loadDict('settings', self.values) def __getitem__(self, key): return self.values[key] def __setitem__(self, key, value): self.values[key] = value def save(self): self.configHandler.saveObject('settings', self.values)
def __init__(self, parent, conf_file='conf.txt', id=-1, title='', pos=wx.Point(0, 0), size=wx.Size(530, 520), style=wx.DEFAULT_DIALOG_STYLE, name='dialogBox'): #pre=wx.PreDialog() self.OnPreCreate() try: self.conf = ConfigHandler(conf_file) except IOError: wx.MessageBox("Could not find the config file, %s" % conf_file) self.__del__() sys.exit(1) board = self.conf.getBoard() wx.Frame.__init__( self, parent, id, title + ' ' + board, pos, size, wx.CAPTION | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.MINIMIZE_BOX, name) self.statusBar = self.CreateStatusBar() font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(10) self.initBefore() self.VwXinit() self.initAfter()
class Test_ConfigHandler(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) self.m_cnfgHdl = [] if not os.path.exists('./tmp'): os.makedirs('./tmp') if os.path.exists('./tmp/config.txt'): os.remove('./tmp/config.txt') with open('./tmp/config.txt', 'w') as f: f.write('[DoorConfig]\nInvertInput = True\nDummyProperty=7') def setUp(self): self.m_cnfgHdl = ConfigHandler('tmp/config.txt') def tearDown(self): pass def test_Option_InvertInput(self): option = self.m_cnfgHdl.getOption('InvertInput') self.assertEqual('True', option) def test_Option_InvertInputBool(self): option = self.m_cnfgHdl.getOptionBool('InvertInput') self.assertEqual(True, option) def test_missingFile(self): cnfgHdl = ConfigHandler('tmp/config_not_exist.txt') self.assertEqual(False, cnfgHdl.optionFileFound()) def test_existingFile(self): cnfgHdl = ConfigHandler('tmp/config.txt') self.assertEqual(True, cnfgHdl.optionFileFound())
def __init__(self, config_file=None, cmdline=False): ''' Designed work as either a command line tool or loaded in as a library. If using the command line mode, be sure to include a config file via the -c option. If loaded in, be sure to point to the correct config file via the config_file keyword argument. ''' if cmdline: self._parse_args() self.configHandler = ConfigHandler(self.args.config_file) else: self.configHandler = ConfigHandler(config_file) # TODO: What else do we need from data_options? any tolerances? # any other relevant options that needs passed in? self.t2form = t2f.Train2Form(handler=self.configHandler) self.formulas, self.dic_formulas = self.t2form.run() self.Simulator = SMCSimulator(self.dic_formulas, handler=self.configHandler) self.MC = ModelChecker(self.formulas) # determine hypothesis parameters alpha = 0.1 alpha = float(alpha)/float(n) prob=0.9 beta=0.1 delta=0.05 # the tester ht = HypothesisTester(prob, alpha, beta, delta)
def __init__(self): super(clHue, self).__init__() name = 'CryptoHue' self.confHandler = ConfigHandler() conf = self.confHandler.load(name) bridgeIP = conf['bridgeIP'] print('Connecting to bridge at ' + bridgeIP) try: self.api = HueInteract(bridgeIP) except ValueError as e: if str(e) == "IP not found on network": print("Currently loaded IP address (" + bridgeIP + ") not found on the network") confirm = input("Would you like to search for a new bridge (y/n)? ") if confirm == 'y': try: self.confHandler.setIP() bridgeIP = conf[name]['bridgeIP'] print('Bridge found at ' + bridgeIP) except ValueError as e: if str(e) == 'No bridge found': print('No bridge found.') bridgeIP = input("Input the address manually: ") self.configHandler.setIP(bridgeIP) else: raise e self.confHandler.writeConfig() self.api = HueInteract(bridgeIP) else: exit() else: raise e self.prompt = self.api.bridgeName() + '> ' self.groupManager = LightGroupManager(self.api)
def __init__(self, dic_formulas, config_file=None, handler=None): self.simulated = False if config_file is not None: # Parse config file here self.configHandler = ConfigHandler(config_file) elif handler is not None: self.configHandler = handler else: print("no way to get config file specified") sys.exit() # use parsed configs self.dic_formulas = dic_formulas self.times = self.get_times_from_formulas(dic_formulas) # TODO: the times are not accurate right now # remove this once it's fixed self.times = np.array(self.times) / 60.0 self.xml_file = self.configHandler.xml_file self.bngl_file = self.configHandler.bngl_file self.name2id = self.backward_associations(self.xml_file, self.bngl_file) # parameters to estimate self.est_parms = self.configHandler.est_parms # set the simulation command using the info from the config file self.configHandler.set_simulate_command(self) # TODO: This is a bit much, we might want to figure out a nicer # way to pull all this out or maybe we want to do this internally # instead of explicitly self.simulator, self.species_index, self.est_parms_index, \ self.obs_index = self.initialize_rr(self.xml_file, \ self.name2id, self.est_parms, self.dic_formulas) if self.configHandler.obs_list is not None: # sel = self.simulator.timeCourseSelections # self.simulator.timeCourseSelections = sel + self.configHandler.obs_list conv_obs_list = [] rev_obs_list = [] flt_names = map(lambda x: "[" + x + "]", self.floating_ids) for elem in self.configHandler.obs_list: rev_obs_list.append(elem) if elem in self.name2id.keys(): conv_obs_list.append("[" + self.name2id[elem] + "]") elif hasattr(self.simulator, elem) or (elem in flt_names) or elem == "time": conv_obs_list.append(elem) else: print( "observable {} is neither in species conversion table nor in roadrunner object" .format(elem)) if "time" not in conv_obs_list: conv_obs_list = ["time"] + conv_obs_list rev_obs_list = ["time"] + rev_obs_list try: self.simulator.timeCourseSelections = conv_obs_list except RuntimeError: print( "an element in the observables list doesn't match with roadrunner simulator. given list after attempting to convert: {}" .format(conv_obs_list)) self.conv_obs_list = conv_obs_list self.rev_obs_list = rev_obs_list
def uploadSkript(): configHandler = ConfigHandler() configHandler.LoadConfigFromFile() config = configHandler.GetConfig() mockModelDeskExporter = ModelDeskExporter() mockModelDeskExporter.DoSomething() mockRestApiHanlder = RestApiHandler() mockRestApiHanlder.DoSomethingElse() print("Ende")
def main(logger): script_dir = os.path.dirname(__file__) conf = ConfigHandler(os.path.join(script_dir, 'config.ini')) try: if os.path.isfile(os.path.join(script_dir, 'config.ini')) is True: parser = conf.get_parser() else: conf.create_config() parser = conf.get_parser() except Exception as e: logger.log_error("Error: %s" % str(e)) raise RuntimeError try: print(parser.get('urls', 'comments_urls')) bot = InstaBot(parser.get('credentials', 'username'), parser.get('credentials', 'password'), parser.get('urls', 'comments_urls')) bot.start() except KeyboardInterrupt: print(comments) raise RuntimeError
def __init__(self): # Reading in data from the config file config_handler = ConfigHandler() self.broker = str(config_handler.get_setting_by_key("mqtt_broker")) self.broker_port = str(config_handler.get_setting_by_key("mqtt_port")) self.log_mode = int( config_handler.get_setting_by_key("default_log_mode")) self.log_mode_topic = str( config_handler.get_setting_by_key("log_mode_topic")) self.robot_info_topic = str( config_handler.get_setting_by_key("robot_info_topic")) self.robot_movement_topic = str( config_handler.get_setting_by_key("robot_movement_topic")) # Initialising Logging file logging.basicConfig(filename='app.log', level=logging.INFO) logging.info("Started Logging in mode %d", self.log_mode)
def __init__(self): self.values = dict() self.values['mythFileDir'] = '/' self.values['dbHost'] = '' self.values['dbUser'] = '******' self.values['dbPassword'] = '******' self.values['firstRun'] = True self.values['deinterlace'] = True self.values['bufferTime'] = 5 self.values['lengthUpdateInterval'] = 3000 self.values['mplayer'] = 'mplayer' self.values['mpv'] = 'mpv' self.values['backend'] = 'mpv' self.configHandler = ConfigHandler('mythnimal') self.configHandler.loadDict('settings', self.values)
def __init__(self,parent,conf_file='conf.txt',id = -1,title = '',pos = wx.Point(0,0),size = wx.Size(530,520),style = wx.DEFAULT_DIALOG_STYLE,name = 'dialogBox'): #pre=wx.PreDialog() self.OnPreCreate() try: self.conf = ConfigHandler(conf_file) except IOError: wx.MessageBox("Could not find the config file, %s" %conf_file) self.__del__() sys.exit(1) board = self.conf.getBoard() wx.Frame.__init__(self, parent, id,title + ' ' + board,pos,size,wx.CAPTION|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CLOSE_BOX|wx.MINIMIZE_BOX,name) self.statusBar = self.CreateStatusBar() font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(10) self.initBefore() self.VwXinit() self.initAfter()
def __init__(self,parent,conf_file='conf.txt',id = -1,title = '',pos = wx.Point(0,0),size = wx.Size(495,550),style = wx.DEFAULT_DIALOG_STYLE,name = 'dialogBox'): #pre=wx.PreDialog() self.OnPreCreate() try: self.conf = ConfigHandler(conf_file) except IOError: wx.MessageBox("Could not find the config file, %s" %conf_file) self.__del__() sys.exit(1) board = self.conf.getBoard() #pre.Create(parent,id,title + ' ' + board,pos,size,wx.CAPTION|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CLOSE_BOX|wx.DIALOG_NO_PARENT|wx.DEFAULT_DIALOG_STYLE|wx.MINIMIZE_BOX,name) wx.Frame.__init__(self, parent, id,title + ' ' + board,pos,size,wx.CAPTION|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CLOSE_BOX|wx.MINIMIZE_BOX,name) self.statusBar = self.CreateStatusBar() #self.PostCreate(pre) self.initBefore() self.VwXinit() self.initAfter()
def __init__(self, parent, cfgFile="Arduino_Duemilanove.cfg"): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition, size=wx.Size(373, 507), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) # This named tuple acts like the group holder for GUI controls # that we need to control self.ctls = namedtuple("ctls", 'availableLstCtl selectedLstCtl') self.ctlDic = {} self.serPort = "" self.cfgFile = cfgFile # Try to open the config file and load the values try: self.cfg = ConfigHandler(self.cfgFile) except: wx.MessageBox(cfgFile + " was not found ") wx.Exit() self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) frameSizer = wx.BoxSizer(wx.VERTICAL) self.mainPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL) mainSizer = wx.BoxSizer(wx.VERTICAL) #mainSizer.Add( gpioBox, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('GPIOs', 'gpio') mainSizer.Add(sizer, 1, wx.EXPAND, 5) sizer = self.addPerBox('DACs', 'dac') mainSizer.Add(sizer, 1, wx.EXPAND, 5) sizer = self.addPerBox('ADCs', 'adc') mainSizer.Add(sizer, 1, wx.EXPAND, 5) # Let's popuate the list box with the pins that are available # first read the pickle file associated with the config file # and populate appropriately try: pick = os.path.splitext(self.cfgFile)[0] + '.pickle' pick = file(pick) self.selectedCtlDic = pickle.load(pick) except: self.selectedCtlDic = {'gpio': [], 'dac': [], 'adc': []} self.selectedCtlDic['gpio'].sort(self.cfg.__cmp__) self.selectedCtlDic['adc'].sort(self.cfg.__cmp__) self.selectedCtlDic['dac'].sort(self.cfg.__cmp__) gpios = self.cfg.getDigiPinNames() gpios = self.__reomove_dups__(gpios, self.selectedCtlDic['gpio']) self.ctlDic['gpio'].availableLstCtl.InsertItems(gpios, 0) self.ctlDic['gpio'].selectedLstCtl.InsertItems( self.selectedCtlDic['gpio'], 0) dacs = self.cfg.getAnaOutPinNames() dacs = self.__reomove_dups__(dacs, self.selectedCtlDic['dac']) self.ctlDic['dac'].availableLstCtl.InsertItems(dacs, 0) self.ctlDic['dac'].selectedLstCtl.InsertItems( self.selectedCtlDic['dac'], 0) adcs = self.cfg.getAnaInPinNames() adcs = self.__reomove_dups__(adcs, self.selectedCtlDic['adc']) self.ctlDic['adc'].availableLstCtl.InsertItems(adcs, 0) self.ctlDic['adc'].selectedLstCtl.InsertItems( self.selectedCtlDic['adc'], 0) self.availbleCtlDic = {'gpio': gpios, 'dac': dacs, 'adc': adcs} self.prts = GetSerPorts() self.ports = self.prts.get_ports() sdbSizer = wx.StdDialogButtonSizer() self.sdbSizerOK = wx.Button(self.mainPanel, wx.ID_OK) self.sdbSizerOK.Bind(wx.EVT_BUTTON, self.onOk) sdbSizer.AddButton(self.sdbSizerOK) self.sdbSizerCancel = wx.Button(self.mainPanel, wx.ID_CANCEL) self.sdbSizerCancel.Bind(wx.EVT_BUTTON, self.onCancel) sdbSizer.AddButton(self.sdbSizerCancel) sdbSizer.Realize() self.stPortName = wx.StaticText(self.mainPanel, -1, " Select the serial port name") self.cmbSerPort = wx.ComboBox(self.mainPanel, -1, "", wx.Point(120, 35), wx.Size(15, 21), self.ports, wx.CB_READONLY) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.stPortName, 1, wx.EXPAND, 10) sizer.Add(self.cmbSerPort, 1, wx.EXPAND, 1) mainSizer.Add((0, 20)) mainSizer.Add(sizer, .9, wx.EXPAND, 5) mainSizer.Add((0, 10)) mainSizer.Add(sdbSizer, .8, wx.EXPAND, 5) mainSizer.Add((0, 20)) self.mainPanel.SetSizer(mainSizer) self.mainPanel.Layout() mainSizer.Fit(self.mainPanel) frameSizer.Add(self.mainPanel, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(frameSizer) # Now that all the GUI controls are laid out, let us now populate the lists self.Layout() self.Centre(wx.BOTH)
def test_existingFile(self): cnfgHdl = ConfigHandler('tmp/config.txt') self.assertEqual(True, cnfgHdl.optionFileFound())
def test_missingFile(self): cnfgHdl = ConfigHandler('tmp/config_not_exist.txt') self.assertEqual(False, cnfgHdl.optionFileFound())
class MainWindow(QMainWindow, Ui_MainWindow): config = None library = None playlist_model = None artist_model = None album_model = None path_to_cfg = os.path.join(os.path.expanduser('~'), '.i2sd', 'conf.ini') config = ConfigHandler(path_to_cfg) def __init__(self, *args, obj=None, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setupUi(self) self.load_config() self.file_handler = FileHandler(config=self.config) self.options = OptionsView(config=self.config) self.loading_message = DialogLoading() self.set_ui() self.set_signals() self.check_lib() def set_ui(self): self.cmbFormat.setCurrentIndex(0) self.cpProgress.setValue(0) self.check_sync() def set_signals(self): self.bSync.clicked.connect(self.sync) self.bDestination.clicked.connect(self.select_dir) self.cbExtended.stateChanged.connect(self.save_config) self.cbOnlyPlaylist.stateChanged.connect(self.save_config) self.cmbFormat.currentIndexChanged.connect(self.save_config) self.bMoreOptions.clicked.connect(lambda x: self.options.setVisible(not self.options.isVisible())) self.options.load.connect(self.check_lib) self.options.reload.connect(self.reload_library) self.iDestination.textChanged.connect(self.check_sync) self.file_handler.progress.connect(lambda progress, file: self.cpProgress.setValue(progress)) self.file_handler.finished.connect(lambda: self.bSync.setEnabled(True)) def reload_library(self): print("Main.py: reload_library") self.loading_message.show() self.library.reload_library() def check_lib(self): print("check") if self.config.has_option("library", "path") and self.config.get("library", "path") != "": if os.path.isfile(self.config.get("library", "path")): self.loading_message.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.loading_message.show() self.library = Library(path_to_xml=self.config.get("library", "path")) self.library.loaded.connect(self.set_up_lib) self.library.check_for_library() self.lNoLib.setVisible(False) return self.lNoLib.setText("XML File not valid.") self.lNoLib.setVisible(True) return self.lNoLib.setText("No library defined. Please provide XML file.") self.lNoLib.setVisible(True) def set_up_lib(self): total_playlists = len(self.library.get_playlists()) total_songs = len(self.library.get_songs()) total_albums = len(self.library.get_albums()) total_artists = len(self.library.get_artists()) date = datetime.now().strftime("%d/%m/%Y %H:%M:%S") self.options.set_statistics(total_playlists, total_songs, total_albums, total_artists, date) print("Library set up") self.playlist_model = PlaylistModel(library=self.library) self.artist_model = ArtistModel(library=self.library) self.album_model = AlbumModel(library=self.library) self.lPlaylistCount.setText(f'{len(self.library.get_playlists())}') self.lArtistCount.setText(f'{len(self.library.get_artists())}') self.lAlbumCount.setText(f'{len(self.library.get_albums())}') self.vPlaylists.setModel(self.playlist_model) self.vArtists.setModel(self.artist_model) self.vAlbums.setModel(self.album_model) self.loading_message.close() self.show() def load_config(self): if not self.config.has_section("main"): self.config.add_section("main") self.cbExtended.setChecked(self.config.getboolean("main", "extended", fallback=False)) self.cbOnlyPlaylist.setChecked(self.config.getboolean("main", "plonly", fallback=False)) self.cmbFormat.setCurrentText(self.config.get("main", "format", fallback="m3u")) if self.config.has_option("main", "destination"): self.iDestination.setText(self.config.get("main", "destination")) def save_config(self): if not self.config.has_section("main"): self.config.add_section("main") self.config.set("main", "extended", str(self.cbExtended.isChecked())) self.config.set("main", "plonly", str(self.cbOnlyPlaylist.isChecked())) self.config.set("main", "format", self.cmbFormat.currentText()) self.config.set("main", "destination", self.iDestination.text()) self.config.save() def select_dir(self): destination = str(QFileDialog.getExistingDirectory(self, "Select Target Directory")) if destination: self.iDestination.setText(destination) self.save_config() def check_sync(self): condition = self.iDestination.text() != "" self.bSync.setEnabled(condition) def sync(self): self.cpProgress.setValue(0) self.bSync.setEnabled(False) playlists = self.playlist_model.get_selected_playlists() artists = self.artist_model.get_selected_artists() albums = self.album_model.get_selected_albums() self.file_handler.create_files(playlists=playlists, artists=artists, albums=albums)
from pynput.keyboard import Key, Controller, KeyCode import pynput._util.win32_vks as VK from ConfigHandler import ConfigHandler keyboard = Controller() SELLING = dict() INVENTORY = dict() once = True dropKey = 'q' money = 0 zahlvorgang = False zwischenliste = list() config = ConfigHandler() config.loadFile("configuration.conf") def output(out): print(out) print() a = open('./logfile.txt', 'a+') a.write(str(out)) a.close() def push(key): keyboard.press(key) keyboard.release(key)
def main(): # Instance of tkinter to do GUI stuff tkRoot = Tk() tkRoot.title("WarpWar") tkRoot.hCon = None tkRoot.plid = None tkRoot.hPlayerAi = None tkRoot.hexMap = None tkRoot.game = None tkRoot.configureDelay = None #get the user's profile. tkRoot.cfg = ConfigHandler("warpwar.ini") tkRoot.battleOrders = {} tkRoot.bind("<<updateWWMenu>>", lambda event: updateWWMenu(event, tkRoot)) tkRoot.bind("<<sendReady>>", lambda event: sendReady(event, tkRoot)) tkRoot.bind("<<sendStart>>", lambda event: sendStart(event, tkRoot)) # menu bar addMenus(tkRoot) # Create A "PanedWindow" on top of a frame to fit everything into # # +------------------------------------+ # | PANED WINDOW | # | | # | | # +------------------------------------+ # | button frame | # +------------------------------------+ tkRoot.topPane = PanedWindow(tkRoot, orient='horizontal', bg='blue') tkRoot.buttonFrame = Frame(tkRoot) tkRoot.buttonFrame.pack(side="bottom") # It is important to pack the topPane LAST (but at the top) so that # the buttons don't disappear when shrinking the whole window tkRoot.topPane.pack(side="top", expand=YES, fill=BOTH) # Create add a map to the top paned window on the left # and add another paned window on the right # +------------------------------------+ # | | | # | map window | info pane | # | | | # +------------------------------------+ tkRoot.hexMap = hexMap(tkRoot.topPane, tkRoot, 10, 10) tkRoot.infoPane = PanedWindow(tkRoot, orient='vertical') tkRoot.topPane.add(tkRoot.hexMap, stretch='always') tkRoot.topPane.add(tkRoot.infoPane, stretch='always') # Call back for when the map grows/shrinks tkRoot.hexMap.bind("<Configure>", lambda event, tkRoot=tkRoot: Configure(event, tkRoot)) # Create another Pane in the right PanedWindow(infoPane) # for displaying history. There is, history, info and server, # and playerai ... we can add others # +--------------------+ # | | # | Future pane1 | # +------------------- + # | Future pane2 | # +------------------- + # | | # | history pane | # +--------------------+ tkRoot.hexInfoFrame = hexpane.hexpane(tkRoot.infoPane, borderwidth=1, relief="sunken") tkRoot.infoPane.add(tkRoot.hexInfoFrame, stretch='always') tkRoot.histFrame = histpane.history(tkRoot.infoPane, borderwidth=1, relief="sunken") tkRoot.infoPane.add(tkRoot.histFrame, stretch='always') # Put buttons into the button frame tkRoot.quitButton = Button(tkRoot.buttonFrame, text="Quit", command=lambda: exitProgram(tkRoot)) tkRoot.quitButton.grid(row=0, column=0, padx=15) tkRoot.playersButton = Button(tkRoot.buttonFrame, text="Players", command=lambda: popupPlayers(tkRoot)) tkRoot.playersButton.grid(row=0, column=1, padx=15) # Display default game info on the map tkRoot.hexMap.updateMap(tkRoot.game) tkRoot.tooltipX = 0 tkRoot.tooltipY = 0 tkRoot.tooltipCount = 0 tkRoot.tooltip = None tkRoot.after(1000, lambda: tooltip(tkRoot)) # at the moment this does nothing valuable #foo = GameInfo(tkRoot.hexMap.grid_width, #tkRoot.hexMap.grid_height, #tkRoot.game['playerList']) # Let tkinter main loop run forever and handle input events tkRoot.mainloop() # it is better to wait for child threads here (after GUI ends) # rather than in the GUI code. That created deadlocks. if (tkRoot.hCon): tkRoot.hCon.join() tkRoot.hCon = None if (tkRoot.hPlayerAi): tkRoot.hPlayerAi.join() tkRoot.hPlayerAi = None
class MainWindow(QMainWindow, Ui_MainWindow): browser = None meta = {} pdfcreator = PDFCreator() config = ConfigHandler() def __init__(self, *args, obj=None, **kwargs): super().__init__(*args, **kwargs) self.browser = Browser() self.setupUi(self) self.load_config() self.set_ui() self.set_signals() def load_config(self): if not self.config.has_section("main"): self.config.add_section("main") self.i_link.setText(self.config.get("main", "link", fallback="")) self.i_destination.setText( self.config.get("main", "destination", fallback="")) self.chk_create_pdf.setChecked( bool(self.config.get("main", "createPDF", fallback="False"))) if not self.i_link.text() is "" and not self.i_destination.text() is "": self.update_info() def set_ui(self): self.pb_download.setValue(0) def set_signals(self): self.i_link.textChanged.connect(self.update_info) self.b_destination.clicked.connect(self.set_dest) self.b_download.clicked.connect(self.start_download) self.chk_create_pdf.clicked.connect(lambda x: self.config.set( "main", "createPDF", str(self.chk_create_pdf.isChecked()))) def set_dest(self): dialog = QFileDialog() dialog.setDirectory(self.i_destination.text() or "/") destination = str( QFileDialog.getExistingDirectory(self, "Select Target Directory")) if destination: self.i_destination.setText(destination) self.config.set("main", "destination", destination) self.check_if_download_possible() def check_if_download_possible(self): if "http://rawmangaupdate.com" in self.i_link.text( ) and os.path.exists(self.i_destination.text()): self.b_download.setEnabled(True) def update_info(self): print("Info Updated") if "http://rawmangaupdate.com" in self.i_link.text(): self.meta = self.browser.get_info(self.i_link.text()) manga_chapter_names = self.meta["manga_chapter_names"] manga_chapter_links = self.meta["manga_chapter_links"] self.i_name.setText(self.meta["manga_title"]) self.i_chapters.setText(f'{len(manga_chapter_links)}') self.cb_start.clear() self.cb_start.addItems(manga_chapter_names) self.cb_start.setCurrentIndex(0) self.cb_end.clear() self.cb_end.addItems(manga_chapter_names) self.cb_end.setCurrentIndex(len(manga_chapter_names) - 1) self.check_if_download_possible() self.config.set("main", "link", self.i_link.text()) def start_download(self): self.browser.download_chapters(self.i_destination.text(), self.meta, self.cb_start.currentIndex(), self.cb_end.currentIndex()) if self.chk_create_pdf.isChecked(): self.pdfcreator.createPDF( os.path.join(self.i_destination.text(), self.meta["manga_title"]))
def __init__( self, parent, cfgFile="Arduino_Duemilanove.cfg" ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 373,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) # This named tuple acts like the group holder for GUI controls # that we need to control self.ctls = namedtuple("ctls", 'availableLstCtl selectedLstCtl') self.ctlDic = {} self.serPort = "" self.cfgFile = cfgFile # Try to open the config file and load the values try: self.cfg = ConfigHandler(self.cfgFile) except: wx.MessageBox(cfgFile + " was not found ") wx.Exit() self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) frameSizer = wx.BoxSizer( wx.VERTICAL ) self.mainPanel = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL ) mainSizer = wx.BoxSizer( wx.VERTICAL ) #mainSizer.Add( gpioBox, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('GPIOs', 'gpio') mainSizer.Add( sizer, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('DACs', 'dac') mainSizer.Add( sizer, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('ADCs', 'adc') mainSizer.Add( sizer, 1, wx.EXPAND, 5 ) # Let's popuate the list box with the pins that are available # first read the pickle file associated with the config file # and populate appropriately try: pick = os.path.splitext(self.cfgFile)[0]+'.pickle' pick = file(pick) self.selectedCtlDic = pickle.load(pick) except: self.selectedCtlDic = {'gpio':[], 'dac':[], 'adc':[]} self.selectedCtlDic['gpio'].sort(self.cfg.__cmp__) self.selectedCtlDic['adc'].sort(self.cfg.__cmp__) self.selectedCtlDic['dac'].sort(self.cfg.__cmp__) gpios = self.cfg.getDigiPinNames() gpios = self.__reomove_dups__(gpios, self.selectedCtlDic['gpio']) self.ctlDic['gpio'].availableLstCtl.InsertItems(gpios, 0) self.ctlDic['gpio'].selectedLstCtl.InsertItems(self.selectedCtlDic['gpio'], 0) dacs = self.cfg.getAnaOutPinNames() dacs = self.__reomove_dups__(dacs, self.selectedCtlDic['dac']) self.ctlDic['dac'].availableLstCtl.InsertItems(dacs, 0) self.ctlDic['dac'].selectedLstCtl.InsertItems(self.selectedCtlDic['dac'], 0) adcs = self.cfg.getAnaInPinNames() adcs = self.__reomove_dups__(adcs, self.selectedCtlDic['adc']) self.ctlDic['adc'].availableLstCtl.InsertItems(adcs, 0) self.ctlDic['adc'].selectedLstCtl.InsertItems(self.selectedCtlDic['adc'], 0) self.availbleCtlDic = {'gpio':gpios, 'dac':dacs, 'adc':adcs} self.prts = GetSerPorts() self.ports = self.prts.get_ports(); sdbSizer = wx.StdDialogButtonSizer() self.sdbSizerOK = wx.Button( self.mainPanel, wx.ID_OK ) self.sdbSizerOK.Bind( wx.EVT_BUTTON, self.onOk ) sdbSizer.AddButton( self.sdbSizerOK ) self.sdbSizerCancel = wx.Button( self.mainPanel, wx.ID_CANCEL ) self.sdbSizerCancel.Bind( wx.EVT_BUTTON, self.onCancel ) sdbSizer.AddButton( self.sdbSizerCancel ) sdbSizer.Realize(); self.stPortName = wx.StaticText(self.mainPanel, -1, " Select the serial port name") self.cmbSerPort = wx.ComboBox(self.mainPanel,-1,"",wx.Point(120,35),wx.Size(15,21), self.ports,wx.CB_READONLY) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.stPortName, 1, wx.EXPAND, 10) sizer.Add(self.cmbSerPort, 1, wx.EXPAND, 1) mainSizer.Add((0, 20)) mainSizer.Add(sizer, .9, wx.EXPAND, 5 ) mainSizer.Add((0, 10)) mainSizer.Add( sdbSizer, .8, wx.EXPAND, 5 ) mainSizer.Add((0, 20)) self.mainPanel.SetSizer( mainSizer ) self.mainPanel.Layout() mainSizer.Fit( self.mainPanel ) frameSizer.Add( self.mainPanel, 1, wx.EXPAND |wx.ALL, 5 ) self.SetSizer( frameSizer ) # Now that all the GUI controls are laid out, let us now populate the lists self.Layout() self.Centre( wx.BOTH )
class ControllerFrame(wx.Frame): def __init__(self, parent, conf_file='conf.txt', id=-1, title='', pos=wx.Point(0, 0), size=wx.Size(530, 520), style=wx.DEFAULT_DIALOG_STYLE, name='dialogBox'): #pre=wx.PreDialog() self.OnPreCreate() try: self.conf = ConfigHandler(conf_file) except IOError: wx.MessageBox("Could not find the config file, %s" % conf_file) self.__del__() sys.exit(1) board = self.conf.getBoard() wx.Frame.__init__( self, parent, id, title + ' ' + board, pos, size, wx.CAPTION | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CLOSE_BOX | wx.MINIMIZE_BOX, name) self.statusBar = self.CreateStatusBar() font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(10) self.initBefore() self.VwXinit() self.initAfter() def __del__(self): self.Ddel() wx.Exit() return def VwXinit(self): self.main_pannel = wx.Panel(self, -1, wx.Point(-5, 0), wx.Size(609, 493)) self.DigiOpPin = wx.StaticBox(self.main_pannel, -1, "", wx.Point(10, 100), wx.Size(500, 70)) self.DigiOpPin.SetLabel('Digital output pins') digi_pins = self.conf.getDigiPinNames() self.cmbDigiOpPins = wx.ComboBox(self.main_pannel, -1, "", wx.Point(160, 125), wx.Size(80, 25), digi_pins, wx.CB_READONLY) self.cmbDigiOpPins.SetLabel("Select Pin") self.stDigitalOut = wx.StaticText(self.main_pannel, -1, "", wx.Point(25, 125), wx.Size(125, 20), wx.ST_NO_AUTORESIZE) self.stDigitalOut.SetLabel("Select a Digital Pin") self.btDigiOutSet = wx.Button(self.main_pannel, -1, "", wx.Point(420, 120), wx.Size(85, 30)) self.btDigiOutSet.SetLabel("Set") self.Bind(wx.EVT_BUTTON, self.OnDigiSet, self.btDigiOutSet) self.stDigiOpSelState = wx.StaticText(self.main_pannel, -1, "", wx.Point(250, 125), wx.Size(80, 20), wx.ST_NO_AUTORESIZE) self.stDigiOpSelState.SetLabel("Select State") self.cmbHighLow = wx.ComboBox(self.main_pannel, -1, "", wx.Point(340, 125), wx.Size(65, 25), [r'High', r'Low'], wx.CB_READONLY) self.cmbHighLow.SetLabel("State") self.sbDigigInpPins = wx.StaticBox(self.main_pannel, -1, "", wx.Point(10, 190), wx.Size(500, 76)) self.sbDigigInpPins.SetLabel('Digital Input Pins') self.stDigiOutPin = wx.StaticText(self.main_pannel, -1, "", wx.Point(25, 215), wx.Size(125, 20), wx.ST_NO_AUTORESIZE) self.stDigiOutPin.SetLabel("Select a Digital Pin") self.cmbSerPort = wx.ComboBox(self.main_pannel, -1, "", wx.Point(160, 35), wx.Size(120, 25), [], wx.CB_READONLY) self.cmbSerPort.SetLabel("Select Pin") self.btOpenPrt = wx.Button(self.main_pannel, -1, "", wx.Point(285, 30), wx.Size(85, 30)) self.btOpenPrt.SetLabel("Open") self.Bind(wx.EVT_BUTTON, self.OnOpenPrt, self.btOpenPrt) self.ledPinState = wx.gizmos.LEDNumberCtrl(self.main_pannel, -1, wx.Point(350, 215), wx.Size(70, 40)) self.sbAnalogOut = wx.StaticBox(self.main_pannel, -1, "", wx.Point(10, 285), wx.Size(500, 70)) self.sbAnalogOut.SetLabel('Analog Out') self.stAnIn = wx.StaticText(self.main_pannel, -1, "", wx.Point(20, 400), wx.Size(140, 20), wx.ST_NO_AUTORESIZE) self.stAnIn.SetLabel("Select an Analog pin") self.cmbAnalogOut = wx.ComboBox(self.main_pannel, -1, "", wx.Point(160, 310), wx.Size(80, 25), self.conf.getAnaOutPinNames(), wx.CB_READONLY) self.cmbAnalogOut.SetLabel("Select pin") self.txAnalogOut = wx.TextCtrl(self.main_pannel, -1, "", wx.Point(345, 310), wx.Size(60, 25)) self.stAnoutVal = wx.StaticText(self.main_pannel, -1, "", wx.Point(250, 310), wx.Size(100, 20), wx.ST_NO_AUTORESIZE) self.stAnoutVal.SetLabel("Enter a value") self.btAnalogOut = wx.Button(self.main_pannel, -1, "", wx.Point(420, 310), wx.Size(85, 30)) self.btAnalogOut.SetLabel("Set") self.Bind(wx.EVT_BUTTON, self.OnAnaSet, self.btAnalogOut) self.sbAnalogIn = wx.StaticBox(self.main_pannel, -1, "", wx.Point(10, 375), wx.Size(500, 80)) self.sbAnalogIn.SetLabel('Analog In') self.stSelAnOut = wx.StaticText(self.main_pannel, -1, "", wx.Point(20, 310), wx.Size(140, 20), wx.ST_NO_AUTORESIZE) self.stSelAnOut.SetLabel("Select an Analog pin") self.cmbAnalogIn = wx.ComboBox(self.main_pannel, -1, "", wx.Point(160, 400), wx.Size(80, 25), self.conf.getAnaInPinNames(), wx.CB_READONLY) self.cmbAnalogIn.SetLabel("Select pin") self.btAnalogRead = wx.Button(self.main_pannel, -1, "", wx.Point(250, 400), wx.Size(85, 30)) self.btAnalogRead.SetLabel("Read") self.Bind(wx.EVT_BUTTON, self.OnAnaRead, self.btAnalogRead) self.ledAnalogRead = wx.gizmos.LEDNumberCtrl(self.main_pannel, -1, wx.Point(350, 400), wx.Size(75, 40)) self.SerPort = wx.StaticBox(self.main_pannel, -1, "", wx.Point(10, 10), wx.Size(500, 71)) self.SerPort.SetLabel('Serial port selection') self.stSelPort = wx.StaticText(self.main_pannel, -1, "", wx.Point(20, 35), wx.Size(140, 20), wx.ST_NO_AUTORESIZE) self.stSelPort.SetLabel("Select a serial port") self.cmbDigiRead = wx.ComboBox(self.main_pannel, -1, "", wx.Point(160, 215), wx.Size(80, 25), digi_pins, wx.CB_READONLY) self.cmbDigiRead.SetLabel("Select Pin") self.btClosePrt = wx.Button(self.main_pannel, -1, "", wx.Point(385, 30), wx.Size(85, 30)) self.btClosePrt.SetLabel("Close") self.Bind(wx.EVT_BUTTON, self.OnClosePrt, self.btClosePrt) self.btDigiRead = wx.Button(self.main_pannel, -1, "", wx.Point(250, 215), wx.Size(85, 30)) self.btDigiRead.SetLabel("Read") self.Bind(wx.EVT_BUTTON, self.OnDigiRead, self.btDigiRead) self.Refresh() return def VwXDelComp(self): return #[win]add your code here def OnOpenPrt(self, event): #init function #[51e]Code event VwX...Don't modify[51e]# #add your code here ser_prt = self.cmbSerPort.GetValue().encode('ASCII') if (ser_prt == ""): return # lets try and create a TransLayer object try: self.ArdCtrl = TransLayer(ser_prt, self.conf.getVref(), self.conf.getRes()) print self.conf.getVref() self.btOpenPrt.Enable(False) self.btClosePrt.Enable(True) self.btDigiOutSet.Enable(True) self.btDigiRead.Enable(True) self.btAnalogOut.Enable(True) self.btAnalogRead.Enable(True) except IOError, error: err = str(error) wx.MessageBox(err + "\n Application exiting...") sys.exit(1) return #end function
""" import time, os, re, datetime from pynput.keyboard import Key, Controller, KeyCode import pynput._util.win32_vks as VK from ConfigHandler import ConfigHandler keyboard = Controller() SELLING = dict() INVENTORY = dict() once = True dropKey = 'q' config = ConfigHandler() config.loadFile("configuration.conf") def output(out): print(out) print() a = open('./logfile.txt', 'a+') a.write(str(out)) a.close() def push(key): keyboard.press(key) keyboard.release(key) def quickSay(message): output(message)
return frac = float(ana_val) / 100 ana_val = int(frac * maxAout) if ana_val == 0: return try: self.BoardComm.SetAnalogVal(ana_pin, ana_val) self.SetStatusText("Set analog pin " + pinName + " to " + str(ana_val)) except Exception, e: self.HandleException(e) def __del__(self): try: self.BoardComm.Close() except: pass wx.Exit() return if __name__ == '__main__': app = wx.PySimpleApp() from ConfigHandler import ConfigHandler import os cfgFile = os.path.join('cfg', 'Arduino_Duemilanove.cfg') cfg = ConfigHandler(cfgFile) QuickCtl('COM5', cfg, ['p0', 'p1', 'p13'], ['p0', 'p3'], ['p3', 'p6']).Show() app.MainLoop()
class QuickCtlConfig(wx.Frame): def __init__(self, parent, cfgFile="Arduino_Duemilanove.cfg"): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=wx.EmptyString, pos=wx.DefaultPosition, size=wx.Size(373, 507), style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL) # This named tuple acts like the group holder for GUI controls # that we need to control self.ctls = namedtuple("ctls", 'availableLstCtl selectedLstCtl') self.ctlDic = {} self.serPort = "" self.cfgFile = cfgFile # Try to open the config file and load the values try: self.cfg = ConfigHandler(self.cfgFile) except: wx.MessageBox(cfgFile + " was not found ") wx.Exit() self.SetSizeHintsSz(wx.DefaultSize, wx.DefaultSize) frameSizer = wx.BoxSizer(wx.VERTICAL) self.mainPanel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL) mainSizer = wx.BoxSizer(wx.VERTICAL) #mainSizer.Add( gpioBox, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('GPIOs', 'gpio') mainSizer.Add(sizer, 1, wx.EXPAND, 5) sizer = self.addPerBox('DACs', 'dac') mainSizer.Add(sizer, 1, wx.EXPAND, 5) sizer = self.addPerBox('ADCs', 'adc') mainSizer.Add(sizer, 1, wx.EXPAND, 5) # Let's popuate the list box with the pins that are available # first read the pickle file associated with the config file # and populate appropriately try: pick = os.path.splitext(self.cfgFile)[0] + '.pickle' pick = file(pick) self.selectedCtlDic = pickle.load(pick) except: self.selectedCtlDic = {'gpio': [], 'dac': [], 'adc': []} self.selectedCtlDic['gpio'].sort(self.cfg.__cmp__) self.selectedCtlDic['adc'].sort(self.cfg.__cmp__) self.selectedCtlDic['dac'].sort(self.cfg.__cmp__) gpios = self.cfg.getDigiPinNames() gpios = self.__reomove_dups__(gpios, self.selectedCtlDic['gpio']) self.ctlDic['gpio'].availableLstCtl.InsertItems(gpios, 0) self.ctlDic['gpio'].selectedLstCtl.InsertItems( self.selectedCtlDic['gpio'], 0) dacs = self.cfg.getAnaOutPinNames() dacs = self.__reomove_dups__(dacs, self.selectedCtlDic['dac']) self.ctlDic['dac'].availableLstCtl.InsertItems(dacs, 0) self.ctlDic['dac'].selectedLstCtl.InsertItems( self.selectedCtlDic['dac'], 0) adcs = self.cfg.getAnaInPinNames() adcs = self.__reomove_dups__(adcs, self.selectedCtlDic['adc']) self.ctlDic['adc'].availableLstCtl.InsertItems(adcs, 0) self.ctlDic['adc'].selectedLstCtl.InsertItems( self.selectedCtlDic['adc'], 0) self.availbleCtlDic = {'gpio': gpios, 'dac': dacs, 'adc': adcs} self.prts = GetSerPorts() self.ports = self.prts.get_ports() sdbSizer = wx.StdDialogButtonSizer() self.sdbSizerOK = wx.Button(self.mainPanel, wx.ID_OK) self.sdbSizerOK.Bind(wx.EVT_BUTTON, self.onOk) sdbSizer.AddButton(self.sdbSizerOK) self.sdbSizerCancel = wx.Button(self.mainPanel, wx.ID_CANCEL) self.sdbSizerCancel.Bind(wx.EVT_BUTTON, self.onCancel) sdbSizer.AddButton(self.sdbSizerCancel) sdbSizer.Realize() self.stPortName = wx.StaticText(self.mainPanel, -1, " Select the serial port name") self.cmbSerPort = wx.ComboBox(self.mainPanel, -1, "", wx.Point(120, 35), wx.Size(15, 21), self.ports, wx.CB_READONLY) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.stPortName, 1, wx.EXPAND, 10) sizer.Add(self.cmbSerPort, 1, wx.EXPAND, 1) mainSizer.Add((0, 20)) mainSizer.Add(sizer, .9, wx.EXPAND, 5) mainSizer.Add((0, 10)) mainSizer.Add(sdbSizer, .8, wx.EXPAND, 5) mainSizer.Add((0, 20)) self.mainPanel.SetSizer(mainSizer) self.mainPanel.Layout() mainSizer.Fit(self.mainPanel) frameSizer.Add(self.mainPanel, 1, wx.EXPAND | wx.ALL, 5) self.SetSizer(frameSizer) # Now that all the GUI controls are laid out, let us now populate the lists self.Layout() self.Centre(wx.BOTH) def __reomove_dups__(self, origList, copyList): """ Removes entries from origList that are present in origList """ if len(origList) == 0: return for cp in copyList: if cp in origList: origList.remove(cp) return origList def onL2r(self, event): button = event.GetEventObject() btnId = event.GetId() btnById = self.FindWindowById(btnId) name = btnById.GetName().replace('l2r', '') selection = self.ctlDic[name].availableLstCtl.GetStringSelection() if selection == '': return self.ctlDic[name].selectedLstCtl.Append(selection) self.selectedCtlDic[name].append(selection) n = self.ctlDic[name].availableLstCtl.FindString(selection) self.ctlDic[name].availableLstCtl.Delete(n) #print self.selectedCtlDic[name] def onR2l(self, event): button = event.GetEventObject() btnId = event.GetId() btnById = self.FindWindowById(btnId) name = btnById.GetName().replace('r2l', '') selection = self.ctlDic[name].selectedLstCtl.GetStringSelection() if selection == '': return self.ctlDic[name].availableLstCtl.Append(selection) self.selectedCtlDic[name].remove(selection) n = self.ctlDic[name].selectedLstCtl.FindString(selection) self.ctlDic[name].selectedLstCtl.Delete(n) #print self.selectedCtlDic[name] def onOk(self, event): # Let us store the user selections cfgFile = os.path.splitext(self.cfgFile)[0] # serialize pick = file(cfgFile + '.pickle', 'w') self.selectedCtlDic['gpio'].sort(self.cfg.__cmp__) self.selectedCtlDic['adc'].sort(self.cfg.__cmp__) self.selectedCtlDic['dac'].sort(self.cfg.__cmp__) pickle.dump(self.selectedCtlDic, pick) serPort = self.cmbSerPort.GetValue().encode('ASCII') try: quickCtlFrame = QuickCtl(serPort, self.cfg, self.selectedCtlDic['gpio'], self.selectedCtlDic['adc'], self.selectedCtlDic['dac']) self.Show(False) except: wx.MessageBox("Oops, there was a problem", style=wx.ICON_EXCLAMATION) wx.Exit() quickCtlFrame.Show(True) def onCancel(self, event): self.Close() def addPerBox(self, title='GPIOs', name='gpio'): # We will use a dictionary to hold all the info required to # control the list item boxSizer = wx.StaticBoxSizer( wx.StaticBox(self.mainPanel, wx.ID_ANY, title), wx.VERTICAL) vSizer = wx.BoxSizer(wx.HORIZONTAL) leftVSizer = wx.BoxSizer(wx.VERTICAL) self.stAvailablePorts = wx.StaticText(self.mainPanel, wx.ID_ANY, u"Available port(s)", wx.DefaultPosition, wx.DefaultSize, 0) self.stAvailablePorts.Wrap(-1) leftVSizer.Add(self.stAvailablePorts, 0, wx.ALL, 5) self.lstAvailablePorts = wx.ListBox(self.mainPanel, wx.ID_ANY, wx.DefaultPosition, (100, 75), style=wx.LB_SORT) leftVSizer.Add(self.lstAvailablePorts, 0, wx.ALL, 5) vSizer.Add(leftVSizer, 1, wx.EXPAND, 5) midVSizer = wx.BoxSizer(wx.VERTICAL) midVSizer.Add((0, 30)) self.btnLeftToRight = wx.Button(self.mainPanel, wx.ID_ANY, u">>", wx.DefaultPosition, wx.DefaultSize, 0, name=name + 'l2r') self.btnLeftToRight.Bind(wx.EVT_BUTTON, self.onL2r) midVSizer.Add(self.btnLeftToRight, 0, wx.ALIGN_CENTER | wx.ALL, 5) self.btnRightToLeft = wx.Button(self.mainPanel, wx.ID_ANY, u"<<", wx.DefaultPosition, wx.DefaultSize, 0, name=name + 'r2l') self.btnRightToLeft.Bind(wx.EVT_BUTTON, self.onR2l) midVSizer.Add(self.btnRightToLeft, 0, wx.ALIGN_CENTER | wx.ALL, 5) vSizer.Add(midVSizer, 1, wx.EXPAND, 10) rightVSizer = wx.BoxSizer(wx.VERTICAL) self.stSelectedPorts = wx.StaticText(self.mainPanel, wx.ID_ANY, u"Selected port(s)", wx.DefaultPosition, wx.DefaultSize, 0) self.stSelectedPorts.Wrap(-1) rightVSizer.Add(self.stSelectedPorts, 0, wx.ALL, 5) self.lstSelectedPorts = wx.ListBox(self.mainPanel, wx.ID_ANY, wx.DefaultPosition, (100, 75), style=wx.LB_SORT) rightVSizer.Add(self.lstSelectedPorts, 0, wx.ALL, 5) temp = self.ctls(self.lstAvailablePorts, self.lstSelectedPorts) vSizer.Add(rightVSizer, 1, wx.EXPAND, 5) boxSizer.Add(vSizer, 1, wx.ALIGN_CENTER | wx.EXPAND, 5) self.ctlDic[name] = temp return boxSizer def __del__(self): wx.Exit() return
def DoSomething(self): config = ConfigHandler().GetConfig() print("Hier wird die bereits bestehende Config geladen")
class clHue(cmd.Cmd): """ A command-line interface for interacting with a Philips Hue bridge. """ intro = 'Welcome to clHue!\n' def __init__(self): super(clHue, self).__init__() name = 'CryptoHue' self.confHandler = ConfigHandler() conf = self.confHandler.load(name) bridgeIP = conf['bridgeIP'] print('Connecting to bridge at ' + bridgeIP) try: self.api = HueInteract(bridgeIP) except ValueError as e: if str(e) == "IP not found on network": print("Currently loaded IP address (" + bridgeIP + ") not found on the network") confirm = input("Would you like to search for a new bridge (y/n)? ") if confirm == 'y': try: self.confHandler.setIP() bridgeIP = conf[name]['bridgeIP'] print('Bridge found at ' + bridgeIP) except ValueError as e: if str(e) == 'No bridge found': print('No bridge found.') bridgeIP = input("Input the address manually: ") self.configHandler.setIP(bridgeIP) else: raise e self.confHandler.writeConfig() self.api = HueInteract(bridgeIP) else: exit() else: raise e self.prompt = self.api.bridgeName() + '> ' self.groupManager = LightGroupManager(self.api) def do_exit(self, arg): """ Exit the program. """ print("Bye!") exit() def do_get(self, arg): """ Get an object from the bridge. Doesn't return anything. Parameters: arg -- a string in the form of <lights/groups> <id> """ pprint(self.api.get(arg)) def do_toggle(self, arg): """ Toggle the power of an object. Doesn't return anything. Parameters: arg -- a string in the form of <lights/groups> <id> """ pprint(self.api.toggle(arg)) def do_on(self, arg): """ Power an object on. Doesn't return anything. Parameters: arg -- a string in the form of <lights/groups> <id> """ pprint(self.api.power(arg, True)) def do_off(self, arg): """ Power an object off. Doesn't return anything. Parameters: arg -- a string in the form of <lights/groups> <id> """ pprint(self.api.power(arg, False)) def do_changestate(self, arg): """ Change the state information of an object. Doesn't return anything. Parameters: arg -- a string in the form of <lights/groups> <id> """ newStateStr = input("Enter the new state: ") newState = dict() # Is there a way to just throw newStateStr into a dict without converting types? for i in newStateStr.split(','): state = i.split('=') stateParam = state[0].strip() stateValue = state[1].strip() if stateValue.isnumeric(): stateValue = int(stateValue) elif stateValue == 'True': stateValue = True # bool(state[1]) always returns True, so we need to do this instead elif stateValue == 'False': stateValue = False # bool(state[1]) always returns True newState[stateParam] = stateValue pprint(self.api.putState(arg, newState)) def do_rainbow(self, arg): """ Cycles the object (arg) through all hues. Doesn't return anything. Parameters: arg -- a string in the form of <lights/groups> <id> """ argParser = self.subparsers.add_parser('rainbow', help = 'help rainbow') pprint(self.api.rainbow(arg)) def do_test(self, arg): """ Lets us test commands in HueInteract """ allLights = self.groupManager['all'] livingRoom = self.groupManager.add([3, 5]) pprint(allLights.toggle()) def do_save(self, arg): print("Currently loaded configuration (" + self.confHandler.name + ")") print(self.confHandler.conf) confirm = input("Save currently loaded configuration (y/n)? ") if confirm == 'y': self.confHandler.writeConfig() print("Saved configuration to clConfig.conf")
def logMultiLineText(self, userId, text): print( str(datetime.datetime.now()) + ' : ' + str(userId) + ' >>>\n' + text + '\n<<<\n') # ------------------------------------------------------------------------------ # Main program createDirectory('log') createDirectory('cnfg') m_debugLogger = DebugLogger() m_doorStats = [] m_cnfgHdl = ConfigHandler('cnfg/config.txt', m_debugLogger) if False == m_cnfgHdl.optionFileFound(): m_debugLogger.logText('Config file not found (cnfg/config.txt)') else: m_telegramId = readTelegramId() m_userAccessList = UserListHandler(m_debugLogger) m_userAccessList.initialize('./cnfg/registeredIds.txt') m_userAccessList.loadList() #m_userAccessList.printList() m_userNotificationList = UserListHandler(m_debugLogger) m_userNotificationList.initialize('./cnfg/notificationIds.txt') m_userNotificationList.loadList() #m_userNotificationList.printList()
class SMCSimulator: def __init__(self, dic_formulas, config_file=None, handler=None): self.simulated = False if config_file is not None: # Parse config file here self.configHandler = ConfigHandler(config_file) elif handler is not None: self.configHandler = handler else: print("no way to get config file specified") sys.exit() # use parsed configs self.dic_formulas = dic_formulas self.times = self.get_times_from_formulas(dic_formulas) # TODO: the times are not accurate right now # remove this once it's fixed self.times = np.array(self.times) / 60.0 self.xml_file = self.configHandler.xml_file self.bngl_file = self.configHandler.bngl_file self.name2id = self.backward_associations(self.xml_file, self.bngl_file) # parameters to estimate self.est_parms = self.configHandler.est_parms # set the simulation command using the info from the config file self.configHandler.set_simulate_command(self) # TODO: This is a bit much, we might want to figure out a nicer # way to pull all this out or maybe we want to do this internally # instead of explicitly self.simulator, self.species_index, self.est_parms_index, \ self.obs_index = self.initialize_rr(self.xml_file, \ self.name2id, self.est_parms, self.dic_formulas) if self.configHandler.obs_list is not None: # sel = self.simulator.timeCourseSelections # self.simulator.timeCourseSelections = sel + self.configHandler.obs_list conv_obs_list = [] rev_obs_list = [] flt_names = map(lambda x: "[" + x + "]", self.floating_ids) for elem in self.configHandler.obs_list: rev_obs_list.append(elem) if elem in self.name2id.keys(): conv_obs_list.append("[" + self.name2id[elem] + "]") elif hasattr(self.simulator, elem) or (elem in flt_names) or elem == "time": conv_obs_list.append(elem) else: print( "observable {} is neither in species conversion table nor in roadrunner object" .format(elem)) if "time" not in conv_obs_list: conv_obs_list = ["time"] + conv_obs_list rev_obs_list = ["time"] + rev_obs_list try: self.simulator.timeCourseSelections = conv_obs_list except RuntimeError: print( "an element in the observables list doesn't match with roadrunner simulator. given list after attempting to convert: {}" .format(conv_obs_list)) self.conv_obs_list = conv_obs_list self.rev_obs_list = rev_obs_list def get_times_from_formulas(self, formulas): all_times = [] for key in formulas: formula = formulas[key] formula_times = list(map(lambda x: x[1], formula)) all_times += formula_times times = sorted(list(set(all_times))) return times def extract_basic_species_names(self, bngl_file): """get the species mentioned in the bngl model Parameters ---------- bngl_file: txt file Contains the bngl model. Returns ------- set_N : list The list of species names but where the name is broken down into its set of components. This is needed for matching the species names in the sbml file where the components of a name are often arranged in a different order. """ with open(bngl_file, 'rt') as myfile: L = [] for myline in myfile: L.append(myline) borders = [i for i in range(len(L)) if 'species' in L[i]] L_species = L[borders[0] + 1:borders[1]] L_species = [tuple(l.split()) for l in L_species] N = [ L_species[i][0] for i in range(len(L_species)) if len(L_species[i]) > 0 ] set_N = [] for n in N: n = n.replace("(", ",") n = n.replace(")", "") X = set(n.split(",")) set_N.append(X) return (set_N) def backward_associations(self, xml_file, bngl_file): """Establishes a link between the species names in the bngl file and the corresponding ids in the sbml file. Parameters ---------- xml_file : The xml file corresponding to the bngl model. here it is generated by the bngl tool. bngl_file : text file As before. Returns ------- name2index : dictionary Each species name in the bngl model is assigned its corresponding id in the sbml file. name2conc : dictionary Each name """ doc = readSBMLFromFile("comp31_sbml.xml") model = doc.getModel() S = model.species set_N = self.extract_basic_species_names(bngl_file) name2index = {} for s in S: n = s.getName() m = n.replace("(", ",") m = m.replace(")", "") N = set(m.split(",")) if N in set_N: name2index[n] = s.getId() return (name2index) def initialize_rr(self, xml_file, name2index, est_parms, dic_formulas): """Extract from the sbml file the indices of the species, parameters and observables. For each simulation run we will be supplying new initial sampled initial concentrations of the species. We will also be supplying sampled values for the parameters to be estimated. Finally we will want to extract the reported values of the observables from the results of the simulation. Parameters ---------- xml_file : text file As before name2index : dictionary As before est_parms : list The list of parameters to be estimated. This is the tricky one. Here I have hard-wired it just in order to be able to run everything. dic_formulas: dictionary The dictionary which assigns to each observable a list of future formulas; one for each time point at which there is data for the observable. Used merely to extract the observables. Returns ------- I : list The list of floating species Ids extracted from the sbml model. This is probably not necessary. Will prune later. parms: list This is the list of all parameters extracted from the sbml model. species_index : dictionary Assigns the index of the id in the sbml model to the species name in the bngl model. species_conc : dictionary Assigns to a species its the initial concentration. params_index : dictionary Assigns to each parameter to be estimated its index in the list of all the parameters in the sbml model. obs_index : dictionary Assigns to each observable its in the in the list all parmeters in the sbml model. """ rr = roadrunner.RoadRunner(xml_file) m = rr.model I = m.getFloatingSpeciesIds() # setting this here self.floating_ids = I C = m.getFloatingSpeciesConcentrations() species_index = {} species = name2index.keys() species_conc = {} for s in species: species_index[s] = I.index(name2index[s]) species_conc[s] = C[species_index[s]] # self.spec_conc = species_conc # P = m.getGlobalParameterIds() # setting this here self.param_ids = P parms_index = {} for p in est_parms: parms_index[p] = P.index(p) obs = dic_formulas.keys() obs_index = {} for o in obs: obs_index[o] = P.index(o) self.init_ids = [] for init_id in rr.getFloatingSpeciesInitialConcentrationIds(): iid = init_id.replace("init([", "") iid = iid.replace("])", "") self.init_ids.append((iid, init_id)) return (rr, species_index, parms_index, obs_index) def simulate(self): res = self._simulate() if hasattr(self, "conv_obs_list"): if len(res.dtype.names) == len(self.conv_obs_list): new_dtype = [(i, "float64") for i in self.rev_obs_list] res = np.array(res, dtype=new_dtype) # res.colnames = self.rev_obs_list return res def sample_vals(self, per): # let's get the initial values +- %5 new_vals = {} for fid, init_id in self.init_ids: init_val = self.simulator[init_id] delta = init_val * per # 5% of the initial value val_sample = np.random.uniform(init_val - delta, high=init_val + delta) new_vals[fid] = val_sample # adding new value to dictionary # parameter values for param in self.est_parms: pval = self.simulator[param] delta = pval * 0.05 # 5% of the current parameter value val_sample = np.random.uniform(pval - delta, high=pval + delta) new_vals[param] = val_sample return new_vals def set_values(self, values): for name in values: self.simulator[name] = values[name] def reset_simulator(self, values=None): if values is None: self.simulator.resetAll() else: # TODO: Only reset values here raise NotImplemented def get_new_trajectory(self): if self.simulated: # we first reset to the initial state self.reset_simulator() # sample new values per = 0.05 # %5 new_vals = self.sample_vals(per) # set the values self.set_values(values=new_vals) getting_results = True ctr = 0 while getting_results: try: res = self.simulate() getting_results = False except: ctr += 1 if ctr == 10: print( "tried resampling 10 times and the simulator doesn't work" ) else: res = self.simulate() self.simulated = True return res
class MyDlg(wx.Frame): def __init__(self,parent,conf_file='conf.txt',id = -1,title = '',pos = wx.Point(0,0),size = wx.Size(495,550),style = wx.DEFAULT_DIALOG_STYLE,name = 'dialogBox'): #pre=wx.PreDialog() self.OnPreCreate() try: self.conf = ConfigHandler(conf_file) except IOError: wx.MessageBox("Could not find the config file, %s" %conf_file) self.__del__() sys.exit(1) board = self.conf.getBoard() #pre.Create(parent,id,title + ' ' + board,pos,size,wx.CAPTION|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CLOSE_BOX|wx.DIALOG_NO_PARENT|wx.DEFAULT_DIALOG_STYLE|wx.MINIMIZE_BOX,name) wx.Frame.__init__(self, parent, id,title + ' ' + board,pos,size,wx.CAPTION|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.CLOSE_BOX|wx.MINIMIZE_BOX,name) self.statusBar = self.CreateStatusBar() #self.PostCreate(pre) self.initBefore() self.VwXinit() self.initAfter() def __del__(self): self.Ddel() return def VwXinit(self): self.main_pannel = wx.Panel(self,-1,wx.Point(-5,0),wx.Size(609,493)) self.DigiOpPin = wx.StaticBox(self.main_pannel,-1,"",wx.Point(10,100),wx.Size(468,71)) self.DigiOpPin.SetLabel('Digital output pins') digi_pins = self.conf.getDigiPinNames() self.cmbDigiOpPins = wx.ComboBox(self.main_pannel,-1,"",wx.Point(125,125),wx.Size(80,21),digi_pins,wx.CB_READONLY) self.cmbDigiOpPins.SetLabel("Select Pin") self.stDigitalOut = wx.StaticText(self.main_pannel,-1,"",wx.Point(25,125),wx.Size(99,13),wx.ST_NO_AUTORESIZE) self.stDigitalOut.SetLabel("Select a Digital Pin") self.btDigiOutSet = wx.Button(self.main_pannel,-1,"",wx.Point(380,120),wx.Size(85,30)) self.btDigiOutSet.SetLabel("Set") self.Bind(wx.EVT_BUTTON,self.OnDigiSet,self.btDigiOutSet) self.stDigiOpSelState = wx.StaticText(self.main_pannel,-1,"",wx.Point(220,125),wx.Size(69,13),wx.ST_NO_AUTORESIZE) self.stDigiOpSelState.SetLabel("Select State") self.cmbHighLow = wx.ComboBox(self.main_pannel,-1,"",wx.Point(290,125),wx.Size(65,21),[r'High',r'Low'],wx.CB_READONLY) self.cmbHighLow.SetLabel("State") self.sbDigigInpPins = wx.StaticBox(self.main_pannel,-1,"",wx.Point(10,190),wx.Size(463,76)) self.sbDigigInpPins.SetLabel('Digital Input Pins') self.stDigiOutPin = wx.StaticText(self.main_pannel,-1,"",wx.Point(25,225),wx.Size(94,13),wx.ST_NO_AUTORESIZE) self.stDigiOutPin.SetLabel("Select a Digital Pin") self.cmbSerPort = wx.ComboBox(self.main_pannel,-1,"",wx.Point(120,35),wx.Size(145,21),[],wx.CB_READONLY) self.cmbSerPort.SetLabel("Select Pin") self.btOpenPrt = wx.Button(self.main_pannel,-1,"",wx.Point(285,30),wx.Size(85,30)) self.btOpenPrt.SetLabel("Open") self.Bind(wx.EVT_BUTTON,self.OnOpenPrt,self.btOpenPrt) self.ledPinState = wx.gizmos.LEDNumberCtrl(self.main_pannel,-1,wx.Point(350,220),wx.Size(70,40)) self.sbAnalogOut = wx.StaticBox(self.main_pannel,-1,"",wx.Point(10,290),wx.Size(463,86)) self.sbAnalogOut.SetLabel('Analog Out') self.stAnIn = wx.StaticText(self.main_pannel,-1,"",wx.Point(20,420),wx.Size(104,13),wx.ST_NO_AUTORESIZE) self.stAnIn.SetLabel("Select an Analog pin") self.cmbAnalogOut = wx.ComboBox(self.main_pannel,-1,"",wx.Point(125,325),wx.Size(80,21),self.conf.getAnaOutPinNames(),wx.CB_READONLY) self.cmbAnalogOut.SetLabel("Select pin") self.txAnalogOut = wx.TextCtrl(self.main_pannel,-1,"",wx.Point(300,320),wx.Size(60,21)) self.stAnoutVal = wx.StaticText(self.main_pannel,-1,"",wx.Point(225,325),wx.Size(69,13),wx.ST_NO_AUTORESIZE) self.stAnoutVal.SetLabel("Enter a value") self.btAnalogOut = wx.Button(self.main_pannel,-1,"",wx.Point(370,315),wx.Size(85,30)) self.btAnalogOut.SetLabel("Set") self.Bind(wx.EVT_BUTTON,self.OnAnaSet,self.btAnalogOut) self.sbAnalogIn = wx.StaticBox(self.main_pannel,-1,"",wx.Point(10,390),wx.Size(463,81)) self.sbAnalogIn.SetLabel('Analog In') self.stSelAnOut = wx.StaticText(self.main_pannel,-1,"",wx.Point(20,325),wx.Size(104,13),wx.ST_NO_AUTORESIZE) self.stSelAnOut.SetLabel("Select an Analog pin") self.cmbAnalogIn = wx.ComboBox(self.main_pannel,-1,"",wx.Point(125,420),wx.Size(80,21),self.conf.getAnaInPinNames(),wx.CB_READONLY) self.cmbAnalogIn.SetLabel("Select pin") self.btAnalogRead = wx.Button(self.main_pannel,-1,"",wx.Point(225,415),wx.Size(85,30)) self.btAnalogRead.SetLabel("Read") self.Bind(wx.EVT_BUTTON,self.OnAnaRead,self.btAnalogRead) self.ledAnalogRead = wx.gizmos.LEDNumberCtrl(self.main_pannel,-1,wx.Point(350,415),wx.Size(75,40)) self.SerPort = wx.StaticBox(self.main_pannel,-1,"",wx.Point(10,10),wx.Size(468,71)) self.SerPort.SetLabel('Serial port selection') self.stSelPort = wx.StaticText(self.main_pannel,-1,"",wx.Point(20,35),wx.Size(100,13),wx.ST_NO_AUTORESIZE) self.stSelPort.SetLabel("Select a serial port") self.cmbDigiRead = wx.ComboBox(self.main_pannel,-1,"",wx.Point(125,225),wx.Size(80,21),digi_pins,wx.CB_READONLY) self.cmbDigiRead.SetLabel("Select Pin") self.btClosePrt = wx.Button(self.main_pannel,-1,"",wx.Point(385,30),wx.Size(85,30)) self.btClosePrt.SetLabel("Close") self.Bind(wx.EVT_BUTTON,self.OnClosePrt,self.btClosePrt) self.btDigiRead = wx.Button(self.main_pannel,-1,"",wx.Point(225,220),wx.Size(85,30)) self.btDigiRead.SetLabel("Read") self.Bind(wx.EVT_BUTTON,self.OnDigiRead,self.btDigiRead) self.Refresh() return def VwXDelComp(self): return #[win]add your code here def OnOpenPrt(self,event): #init function #[51e]Code event VwX...Don't modify[51e]# #add your code here ser_prt = self.cmbSerPort.GetValue().encode('ASCII') if (ser_prt == ""): return # lets try and create a TransLayer object try: self.ArdCtrl = TransLayer(ser_prt, self.conf.getVref(), self.conf.getRes()) self.btOpenPrt.Enable(False) self.btClosePrt.Enable(True) self.btDigiOutSet.Enable(True) self.btDigiRead.Enable(True) self.btAnalogOut.Enable(True) self.btAnalogRead.Enable(True) except IOError, error: err = str(error) wx.MessageBox(err+"\n Application exiting...") sys.exit(1) return #end function
class QuickCtlConfig ( wx.Frame ): def __init__( self, parent, cfgFile="Arduino_Duemilanove.cfg" ): wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = wx.EmptyString, pos = wx.DefaultPosition, size = wx.Size( 373,507 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL ) # This named tuple acts like the group holder for GUI controls # that we need to control self.ctls = namedtuple("ctls", 'availableLstCtl selectedLstCtl') self.ctlDic = {} self.serPort = "" self.cfgFile = cfgFile # Try to open the config file and load the values try: self.cfg = ConfigHandler(self.cfgFile) except: wx.MessageBox(cfgFile + " was not found ") wx.Exit() self.SetSizeHintsSz( wx.DefaultSize, wx.DefaultSize ) frameSizer = wx.BoxSizer( wx.VERTICAL ) self.mainPanel = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL ) mainSizer = wx.BoxSizer( wx.VERTICAL ) #mainSizer.Add( gpioBox, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('GPIOs', 'gpio') mainSizer.Add( sizer, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('DACs', 'dac') mainSizer.Add( sizer, 1, wx.EXPAND, 5 ) sizer = self.addPerBox('ADCs', 'adc') mainSizer.Add( sizer, 1, wx.EXPAND, 5 ) # Let's popuate the list box with the pins that are available # first read the pickle file associated with the config file # and populate appropriately try: pick = os.path.splitext(self.cfgFile)[0]+'.pickle' pick = file(pick) self.selectedCtlDic = pickle.load(pick) except: self.selectedCtlDic = {'gpio':[], 'dac':[], 'adc':[]} self.selectedCtlDic['gpio'].sort(self.cfg.__cmp__) self.selectedCtlDic['adc'].sort(self.cfg.__cmp__) self.selectedCtlDic['dac'].sort(self.cfg.__cmp__) gpios = self.cfg.getDigiPinNames() gpios = self.__reomove_dups__(gpios, self.selectedCtlDic['gpio']) self.ctlDic['gpio'].availableLstCtl.InsertItems(gpios, 0) self.ctlDic['gpio'].selectedLstCtl.InsertItems(self.selectedCtlDic['gpio'], 0) dacs = self.cfg.getAnaOutPinNames() dacs = self.__reomove_dups__(dacs, self.selectedCtlDic['dac']) self.ctlDic['dac'].availableLstCtl.InsertItems(dacs, 0) self.ctlDic['dac'].selectedLstCtl.InsertItems(self.selectedCtlDic['dac'], 0) adcs = self.cfg.getAnaInPinNames() adcs = self.__reomove_dups__(adcs, self.selectedCtlDic['adc']) self.ctlDic['adc'].availableLstCtl.InsertItems(adcs, 0) self.ctlDic['adc'].selectedLstCtl.InsertItems(self.selectedCtlDic['adc'], 0) self.availbleCtlDic = {'gpio':gpios, 'dac':dacs, 'adc':adcs} self.prts = GetSerPorts() self.ports = self.prts.get_ports(); sdbSizer = wx.StdDialogButtonSizer() self.sdbSizerOK = wx.Button( self.mainPanel, wx.ID_OK ) self.sdbSizerOK.Bind( wx.EVT_BUTTON, self.onOk ) sdbSizer.AddButton( self.sdbSizerOK ) self.sdbSizerCancel = wx.Button( self.mainPanel, wx.ID_CANCEL ) self.sdbSizerCancel.Bind( wx.EVT_BUTTON, self.onCancel ) sdbSizer.AddButton( self.sdbSizerCancel ) sdbSizer.Realize(); self.stPortName = wx.StaticText(self.mainPanel, -1, " Select the serial port name") self.cmbSerPort = wx.ComboBox(self.mainPanel,-1,"",wx.Point(120,35),wx.Size(15,21), self.ports,wx.CB_READONLY) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.stPortName, 1, wx.EXPAND, 10) sizer.Add(self.cmbSerPort, 1, wx.EXPAND, 1) mainSizer.Add((0, 20)) mainSizer.Add(sizer, .9, wx.EXPAND, 5 ) mainSizer.Add((0, 10)) mainSizer.Add( sdbSizer, .8, wx.EXPAND, 5 ) mainSizer.Add((0, 20)) self.mainPanel.SetSizer( mainSizer ) self.mainPanel.Layout() mainSizer.Fit( self.mainPanel ) frameSizer.Add( self.mainPanel, 1, wx.EXPAND |wx.ALL, 5 ) self.SetSizer( frameSizer ) # Now that all the GUI controls are laid out, let us now populate the lists self.Layout() self.Centre( wx.BOTH ) def __reomove_dups__(self, origList, copyList): """ Removes entries from origList that are present in origList """ if len(origList) == 0:return for cp in copyList: if cp in origList: origList.remove(cp) return origList def onL2r(self, event): button = event.GetEventObject() btnId = event.GetId() btnById = self.FindWindowById(btnId) name = btnById.GetName().replace('l2r', '') selection = self.ctlDic[name].availableLstCtl.GetStringSelection() if selection == '': return self.ctlDic[name].selectedLstCtl.Append(selection) self.selectedCtlDic[name].append(selection) n = self.ctlDic[name].availableLstCtl.FindString(selection) self.ctlDic[name].availableLstCtl.Delete(n) #print self.selectedCtlDic[name] def onR2l(self, event): button = event.GetEventObject() btnId = event.GetId() btnById = self.FindWindowById(btnId) name = btnById.GetName().replace('r2l', '') selection = self.ctlDic[name].selectedLstCtl.GetStringSelection() if selection == '': return self.ctlDic[name].availableLstCtl.Append(selection) self.selectedCtlDic[name].remove(selection) n = self.ctlDic[name].selectedLstCtl.FindString(selection) self.ctlDic[name].selectedLstCtl.Delete(n) #print self.selectedCtlDic[name] def onOk(self, event): # Let us store the user selections cfgFile = os.path.splitext(self.cfgFile)[0] # serialize pick = file(cfgFile + '.pickle', 'w') self.selectedCtlDic['gpio'].sort(self.cfg.__cmp__) self.selectedCtlDic['adc'].sort(self.cfg.__cmp__) self.selectedCtlDic['dac'].sort(self.cfg.__cmp__) pickle.dump(self.selectedCtlDic, pick) serPort = self.cmbSerPort.GetValue().encode('ASCII') try: quickCtlFrame = QuickCtl(serPort, self.cfg, self.selectedCtlDic['gpio'], self.selectedCtlDic['adc'], self.selectedCtlDic['dac']) self.Show(False) except: wx.MessageBox("Oops, there was a problem", style=wx.ICON_EXCLAMATION) wx.Exit() quickCtlFrame.Show(True) def onCancel(self, event): self.Close() def addPerBox(self, title='GPIOs', name='gpio'): # We will use a dictionary to hold all the info required to # control the list item boxSizer = wx.StaticBoxSizer( wx.StaticBox( self.mainPanel, wx.ID_ANY, title), wx.VERTICAL ) vSizer = wx.BoxSizer( wx.HORIZONTAL ) leftVSizer = wx.BoxSizer( wx.VERTICAL ) self.stAvailablePorts = wx.StaticText( self.mainPanel, wx.ID_ANY, u"Available port(s)", wx.DefaultPosition, wx.DefaultSize, 0 ) self.stAvailablePorts.Wrap( -1 ) leftVSizer.Add( self.stAvailablePorts, 0, wx.ALL, 5 ) self.lstAvailablePorts = wx.ListBox( self.mainPanel, wx.ID_ANY, wx.DefaultPosition, (100, 75), style = wx.LB_SORT) leftVSizer.Add( self.lstAvailablePorts, 0, wx.ALL, 5 ) vSizer.Add( leftVSizer, 1, wx.EXPAND, 5 ) midVSizer = wx.BoxSizer( wx.VERTICAL ) midVSizer.Add((0, 30)) self.btnLeftToRight = wx.Button( self.mainPanel, wx.ID_ANY, u">>", wx.DefaultPosition, wx.DefaultSize, 0, name = name+'l2r' ) self.btnLeftToRight.Bind( wx.EVT_BUTTON, self.onL2r ) midVSizer.Add( self.btnLeftToRight, 0, wx.ALIGN_CENTER|wx.ALL, 5 ) self.btnRightToLeft = wx.Button( self.mainPanel, wx.ID_ANY, u"<<", wx.DefaultPosition, wx.DefaultSize, 0, name = name+'r2l' ) self.btnRightToLeft.Bind( wx.EVT_BUTTON, self.onR2l ) midVSizer.Add( self.btnRightToLeft, 0, wx.ALIGN_CENTER|wx.ALL, 5 ) vSizer.Add( midVSizer, 1, wx.EXPAND, 10 ) rightVSizer = wx.BoxSizer( wx.VERTICAL ) self.stSelectedPorts = wx.StaticText( self.mainPanel, wx.ID_ANY, u"Selected port(s)", wx.DefaultPosition, wx.DefaultSize, 0 ) self.stSelectedPorts.Wrap( -1 ) rightVSizer.Add( self.stSelectedPorts, 0, wx.ALL, 5 ) self.lstSelectedPorts = wx.ListBox( self.mainPanel, wx.ID_ANY, wx.DefaultPosition, (100, 75), style = wx.LB_SORT) rightVSizer.Add( self.lstSelectedPorts, 0, wx.ALL, 5 ) temp = self.ctls(self.lstAvailablePorts, self.lstSelectedPorts) vSizer.Add( rightVSizer, 1, wx.EXPAND, 5 ) boxSizer.Add( vSizer, 1, wx.ALIGN_CENTER|wx.EXPAND, 5 ) self.ctlDic[name] = temp return boxSizer def __del__( self ): wx.Exit() return
def DoSomethingElse(self): configHandler = ConfigHandler() config = configHandler.GetConfig() print( "auch hier wird die config des handler verwendet, ohne sie vorherh übergeben zu müssen" )
def setUp(self): self.m_cnfgHdl = ConfigHandler('tmp/config.txt')