def update_NET_DESKTOP_GEOMETRY(force=False): global properties, xinerama old_geom = properties["_NET_DESKTOP_GEOMETRY"] old_xinerama = xinerama time.sleep(1) properties["_NET_DESKTOP_GEOMETRY"] = ptxcb.XROOT.get_desktop_geometry() xinerama = ptxcb.connection.xinerama_get_screens() if old_xinerama != xinerama or force: if not force and len(old_xinerama) == len(xinerama): for mon in Workspace.iter_all_monitors(): mid = mon.id mon.refresh_bounds( xinerama[mid]["x"], xinerama[mid]["y"], xinerama[mid]["width"], xinerama[mid]["height"] ) mon.calculate_workarea() else: for mon in Workspace.iter_all_monitors(): for tiler in mon.tilers: tiler.destroy() for wid in Window.WINDOWS.keys(): Window.remove(wid) for wsid in Workspace.WORKSPACES.keys(): Monitor.remove(wsid) Workspace.remove(wsid) reset_properties() load_properties()
class DiskPartitioner(object): def __init__(self, maxy, maxx): self.menu_items = [] self.maxx = maxx self.maxy = maxy self.win_width = 70 self.win_height = 17 self.win_starty = (self.maxy - self.win_height) / 2 self.win_startx = (self.maxx - self.win_width) / 2 self.menu_starty = self.win_starty + 10 # initialize the devices self.devices = Device.refresh_devices() self.items = [ ('Auto-partitioning - use entire disk', self.guided_partitions, None), ('Manual - not implemented!', self.manual_partitions, None), ] self.menu = Menu(self.menu_starty, self.maxx, self.items) self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx, 'Welcome to the Photon installer', True, self.menu) self.window.addstr(0, 0, 'First, we will setup your disks. \n\nYou can: \n\na) use auto-partitioning or\nb) you can do it manually.') def guided_partitions(self, params): return ActionResult(True, {'guided': True, 'devices': self.devices}) def manual_partitions(self, params): raise NameError('Manual partitioning not implemented') def display(self, params): return self.window.do_action()
def __init__(self, maxy, maxx, install_config): self.install_config = install_config self.menu_items = [] self.maxx = maxx self.maxy = maxy self.win_width = 70 self.win_height = 16 self.win_starty = (self.maxy - self.win_height) / 2 self.win_startx = (self.maxx - self.win_width) / 2 self.menu_starty = self.win_starty + 6 self.menu_height = 5 self.progress_padding = 5 self.progress_width = self.win_width - self.progress_padding self.progress_bar = ProgressBar(self.win_starty + 6, self.win_startx + self.progress_padding / 2, self.progress_width, new_win=True) self.disk_buttom_items = [] self.disk_buttom_items.append(('<Custom>', self.custom_function, False)) self.disk_buttom_items.append(('<Auto>', self.auto_function, False)) self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx, 'Select a disk', True, items = self.disk_buttom_items, menu_helper = self.save_index, position = 2, tab_enabled=False) self.partition_window = Window(self.win_height, self.win_width, self.maxy, self.maxx, 'Partition', True) self.devices = Device.refresh_devices()
def __init__(self, slider_files, pointer_files, button_files, show_button=True, finish_callback=None, slide_delay=8000, ): ''' Initialize Wizard class. @param slider_files: The slider image files. @param pointer_files: The pointer image files. @param button_files: The button image files. @param show_button: if True will at last page show start button. @param finish_callback: The callback call when slider finish, this callback don't need input argument, default is None. @param slide_delay: The delay between slider images, default is 8000ms. ''' Window.__init__(self) self.finish_callback = finish_callback self.set_position(gtk.WIN_POS_CENTER) self.set_resizable(False) self.wizard_box = WizardBox(slider_files, pointer_files, button_files, show_button, slide_delay) self.wizard_box.connect("close", lambda widget: self.destroy()) self.connect("destroy", self.destroy_wizard) self.window_frame.add(self.wizard_box) self.add_move_event(self.wizard_box)
def __init__(self): Window.__init__(self, 'main.glade') self._create_canvas() self._create_status_bar() self._create_history() self.view.main.set_size_request(450, 300) self.view.main.show()
def cross_validation(X, y, metric, k, kernel='optimal', cv_fold=5.): scores = [] # performing random permutation on data perm = np.random.permutation(X.shape[0]) X = X[perm] y = y[perm] # dividing into chunks chunks = [] y_chunks = [] start = 0 chunk_size = X.shape[0]/cv_fold end = chunk_size while end < X.shape[0]: chunks.append(X[start:end]) y_chunks.append(y[start:end]) start = end end += chunk_size if (start < X.shape[0]): chunks.append(X[start:]) y_chunks.append(y[start:]) # calculating accuracy for each chunk for i in range(len(chunks)): # for knn cross-validation # knn = MatrixBasedKNN(num_loops=0) # knn = knn.fit(np.concatenate(chunks[:i]+chunks[i+1:],axis=0), # np.concatenate(y_chunks[:i]+y_chunks[i+1:],axis=0), metric) # y_pred = knn.predict(chunks[i],k) # for window cross-validation window = Window() window = window.fit(chunks[i], np.concatenate(chunks[:i]+chunks[i+1:], axis=0), np.concatenate(y_chunks[:i]+y_chunks[i+1:], axis=0), k, metric, kernel) y_pred = window.predict() scores.append(accuracy(y_chunks[i], y_pred)) return np.mean(scores)
def __init__(self): global MAPGENERATOR_ACTIVE if MAPGENERATOR_ACTIVE: raise Exception("Can't run more than one MapGenerator instance at a time") else: #this is the only instance MAPGENERATOR_ACTIVE = True try: Window.__init__(self) #create Tkinter Variables self.name = StringVar(self, value=IMAGEMAP_NAME) self.size = (DoubleVar(self, value=IMAGEMAP_SIZE[0]), DoubleVar(self, value=IMAGEMAP_SIZE[1])) self.destination = StringVar(self, value=IMAGEMAP_DESTINATION) self.codeType = StringVar(self, value=IMAGEMAP_CODETYPE) #create controls imageControls = self.ImageControls(self, self.name, self.size) codeControls = self.CodeControls(self, self.destination, self.codeType) buttons = self.MapButtons(self) buttons.closeButton.config(command=self.destroy) buttons.generateButton.config(command=self.generate) imageControls.pack(pady=2, side=TOP) codeControls.pack(pady=2, side=TOP) buttons.pack(side=BOTTOM, padx=2, pady=2) #tweak window self.title("Create Map") self.geometry(MAPGENERATOR_GEOMETRY) self.resizable(False, False) # display everything self.update_idletasks() self.focus_force() self.mainloop() except: raise finally: MAPGENERATOR_ACTIVE = False
def setup_and_run(): import gtk from window import Window window = Window() window._do_gui() gtk.main()
def execute_cb(self, widget, event, data=None): window = Window(self) self.windows.append(window) localcaps = list(self.caps) for i in range(len(localcaps)): window.acceptCap(heapq.heappop(localcaps))
def __init__(self, x, y, width, height ): Window.__init__(self, x, y, width, height ) Visettings.BoardX = (width-2)/2 Visettings.BoardY = (height-2)/2 self.setupPieces()
def __init__(self, size, caption=None, win=None): Window.__init__(self, size, caption, win) self.background = GameData.image(GET_NAME_BGD_IMG) button_image = GameData.image(BUTTON_IMG) self.ok_button = Button(GN_OK_BTN_POS, button_image, self.buttons) self.return_data = "NO NAME"
def __init__(self, main, x, y, width, height=0): Window.__init__(self, main, x, y, width, height) self.grid_size = 10 self.grid_visible = True self.selected_point = None self.snap_to_grid = False self.shape = Shape()
def on_window_create(event, window: Window): if window.name in ["dzen title", "XOSD", "panel"]: window.sticky = True window.can_focus = False window.above_all = True # log.critical("PANEL!") if window.type in ["dropdown", "menu", "notification", "tooltip"]: window.can_focus = False
def calculate_windows(self, save): window = Window(self.stock) windows = window.get_opportune_moments() train_data, test_data = self._split_shuffle_data(windows) train_file = self.make_trainer_file(train_data, DATA_TRAIN_FILE, save) test_file = self.make_trainer_file(test_data, DATA_TEST_FILE, save) return train_file, test_file
class MyGame(Game): """Implements a Game that interfaces with the user.""" def __init__(self): """Initialize the game.""" Game.__init__(self) self.window = Window(800, 600) self.window.set_title("Olá, sou o PyGame.")
def __init__(self, parent, title, top_left, w, h): #assert(parent is not None) #assert(isinstance(parent, (AppWindow))) #assert(isinstance(top_left, Point)) if parent is None or not isinstance(parent, Container): raise BadArgumentError("Expecting a valid parent window") Window.__init__(self, parent, title, top_left, w, h)
def main(): w = Window() start = time.time() while True: print "search game area" w.getScreenShot() w.current_screen.save("test.png") gameWin = findGameArea(w) if gameWin is not None: print "found area" break gameWin.getScreenShot() gameWin.current_screen.save("whack1.png", "png") whack = Whack(gameWin) area = whack.getArea() area.getScreenShot() area.current_screen.save("whack2.png", "png") i=0 while True: if whack.hasArea(): break time.sleep(0.3) ignoreUntilNextClick = (9999,9999) resetIgnore = 0 while True: if resetIgnore < time.time(): print "reset",resetIgnore, time.time() resetIgnore = time.time() + 100 ignoreUntilNextClick = (9999,9999) i+=1 print i print "search button" coords = whack.findClicks(i) if len(coords) < 1: continue if len(coords) > 7: return c=0 last = (9999, 9999) for coord in coords: c+=1 y,x = coord print "coord",coord if y > ignoreUntilNextClick[0] - 90 and y < ignoreUntilNextClick[0] + 90 and x == ignoreUntilNextClick[1]: print "ignore", ignoreUntilNextClick continue #tmp = SubWindow(area, x-10, y-10, 30, 30) #tmp.getScreenShot() #tmp.current_screen.save("click"+str(i)+str(c)+".png") area.mouseMove(x, y) area.mouseClick() gameWin.mouseMove(10, 10) last = coord if last[0] != 9999: print "last",last ignoreUntilNextClick = last resetIgnore = time.time() + 0.6 print time.time()-start
def __init__(self, title, default_width=None, default_height=None, mask_type=None, close_callback=None, modal=True, window_hint=gtk.gdk.WINDOW_TYPE_HINT_DIALOG, window_pos=None, skip_taskbar_hint=True, resizable=False): '''Dialog box.''' Window.__init__(self, resizable) self.default_width = default_width self.default_height = default_height self.mask_type = mask_type if window_pos: self.set_position(window_pos) self.set_modal(modal) # grab focus to avoid build too many skin window if window_hint: self.set_type_hint(window_hint) self.set_skip_taskbar_hint(skip_taskbar_hint) # skip taskbar if self.default_width != None and self.default_height != None: self.set_default_size(self.default_width, self.default_height) if not resizable: self.set_geometry_hints(None, self.default_width, self.default_height, -1, -1, -1, -1, -1, -1, -1, -1) self.padding_left = 2 self.padding_right = 2 self.titlebar = Titlebar( ["close"], None, title) self.add_move_event(self.titlebar) self.body_box = gtk.VBox() self.body_align = gtk.Alignment() self.body_align.set(0.5, 0.5, 1, 1) self.body_align.set_padding(0, 0, self.padding_left, self.padding_right) self.body_align.add(self.body_box) self.button_box = gtk.HBox() self.left_button_box = DialogLeftButtonBox() self.right_button_box = DialogRightButtonBox() self.button_box.pack_start(self.left_button_box, True, True) self.button_box.pack_start(self.right_button_box, True, True) self.window_frame.pack_start(self.titlebar, False, False) self.window_frame.pack_start(self.body_align, True, True) self.window_frame.pack_start(self.button_box, False, False) if close_callback: self.titlebar.close_button.connect("clicked", lambda w: close_callback()) self.connect("destroy", lambda w: close_callback()) else: self.titlebar.close_button.connect("clicked", lambda w: self.destroy()) self.connect("destroy", lambda w: self.destroy()) self.draw_mask = self.get_mask_func(self, 1, 1, 0, 1)
def runApp(): if config.DEBUG: sys.argv.append("--remote-debugging-port=" + str(config.DEBUG_PORT)) app = QApplication(sys.argv) app.setApplicationName(config.APP_NAME) QApplication.setQuitOnLastWindowClosed(False) window = Window() window.showMaximized() app.exec_()
def __init__(self, hero, monster): Window.__init__(self, pygame.Rect((200, 200), (400, 300))) close_bt = gui.Button(pygame.Rect(360, 10, 30, 30), pygame.Color('red')) close_bt.click = lambda a, b: self.close() self.add(close_bt) self.add(gui.Label((100, 50), 'Round 1: Fight!', pygame.Color('green'))) self.add(gui.Label((50, 100), hero.character_class, pygame.Color('azure'))) self.add(gui.Label((250, 100), monster.type, pygame.Color('red')))
def __init__(self, classes, selected_classes): """ Params: `classes`: list of strings with all class names. `selected_classes`: list of strings with selected classes. """ Window.__init__(self, 'classlist.glade') self._create_list() self._populate_model(classes, selected_classes) self.view.classlist.set_default_size(300, 300)
class SimplyUbuntuApplication(Gtk.Application): def __init__(self): Gtk.Application.__init__(self) def do_startup(self): Gtk.Application.do_startup(self) def do_activate(self): self._win = Window(self) self._win.present()
def __init__(self, parent, maze, moves, width): Window.__init__(self, parent) Frame.__init__(self, parent, background = "white") self.maze = maze self.canvas = Canvas(self) self.queue = moves self.delay = DELAY self.size = get_size(self.maze, width) #self.photo = PhotoImage(file = "mouse.gif") self.init_ui()
class LinuxSelector(object): def __init__(self, maxy, maxx, install_config): self.install_config = install_config self.maxx = maxx self.maxy = maxy self.win_width = 60 self.win_height = 13 self.win_starty = (self.maxy - self.win_height) / 2 self.win_startx = (self.maxx - self.win_width) / 2 self.menu_starty = self.win_starty + 6 self.menu_items = [] self.menu_items.append(("1. Hypervisor optimized", self.set_linux_esx_installation, True)) self.menu_items.append(("2. Generic", self.set_linux_esx_installation, False)) self.host_menu = Menu(self.menu_starty, self.maxx, self.menu_items, default_selected=0, tab_enable=False) self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx, 'Select Linux kernel to install', True, items=[], tab_enabled=False, position=1, can_go_next=True) self.window.set_action_panel(self.host_menu) def set_linux_esx_installation(self, is_linux_esx): self.install_config['install_linux_esx'] = is_linux_esx return ActionResult(True, None) def display(self, params): self.window.addstr(0, 0, 'The installer has detected that you are installing') self.window.addstr(1, 0, 'Photon OS on a VMware hypervisor.') self.window.addstr(2, 0, 'Which type of Linux kernel would you like to install?') return self.window.do_action()
def __init__(self, model, classes): Window.__init__(self, 'class.glade') self.model = model self.classes = classes self._populate_ui() self._change_selection_mode() self._create_superclass_list(classes) self._select_model_superclass() self.load_attributes()
def __init__(self, main, x, y, width, height=0): Window.__init__(self, main, x, y, width, height) self.grid_size = 10 self.grid_visible = True self.selected_stamp = None self.snap_to_grid = False self.keep_current_ratio = False self.keep_original_ratio = False self.layout = Layout(self.main.shape_window.shape) self.colors = [pygame.Color('white')] * 10
def __init__(self, main, x, y, width, height=0): Window.__init__(self, main, x, y, width, height) self.shape = self.main.shape_window.shape self.layout = self.main.layout_window.layout self.check_point = None # This is the maximum number of milliseconds that this window has # to draw during each frame. If the time is exceeded it remembers # where it was and resumes in the next frame. self.time_limit = 50 self.end_time = 0 self.min_line_size = 0.05 self.colors = self.main.layout_window.colors
def __init__(self, parent=None): Window.__init__(self, parent) # Important must be empty this is a reference self.files = [] self.projects = None self.recent = None self.dirty = None self.isFull = False self.adb = Adb(self) self.parser = Parser(self) self.command = Command(self) self.init()
class Boot: def __init__(self): self.__threads = 0 self.__lock = Lock() def start(self): self.__window = Window(self) self.__window.build() self.__window.mainloop() ### # Run when copying thread has encountered an error ### def onCopyError(self, error): print(traceback.format_exc(error)) self.__window.showError(error) ### # Run when copying thread has ended ### def onCopyEnd(self): with self.__lock: self.__threads -= 1 if self.__threads is 0: # No more thread, copying engine has ended self.__window.showSuccess() ### # Called when user has launched system ### def onRun(self, srcDir, targetDir, method): # First: build file trees originalTree = FileTree(srcDir) targetTree = FileTree(targetDir) originalTree.build() targetTree.build() # Now, launch copying engine if method is '0': copyEngine = CopyEngine(self, lambda x, y: True) else: copyEngine = CopyEngine(self, lambda x,y: x.getLatestEdition() > y.getLatestEdition()) outcome = copyEngine.run(srcDir, originalTree, targetDir, targetTree) with self.__lock: self.__threads += outcome if self.__threads is 0: # Copy engine has ended after copying threads, process is over self.__window.showSuccess()
def destroy(self, event=None): global MAPGENERATOR_GEOMETRY global IMAGEMAP_NAME global IMAGEMAP_SIZE global IMAGEMAP_DESTINATION global IMAGEMAP_CODETYPE MAPGENERATOR_GEOMETRY = self.geometry() IMAGEMAP_NAME = self.name.get() IMAGEMAP_SIZE = ( self.size[0].get(), self.size[1].get() ) IMAGEMAP_DESTINATION = self.destination.get() IMAGEMAP_CODETYPE = self.codeType.get() Window.destroy(self)
def main(): # Create an instance of window app = Window()
class Installer(object): def __init__(self, install_config, maxy=0, maxx=0, iso_installer=False, rpm_path="../stage/RPMS", log_path="../stage/LOGS"): self.install_config = install_config self.iso_installer = iso_installer self.rpm_path = rpm_path self.log_path = log_path self.mount_command = "./mk-mount-disk.sh" self.prepare_command = "./mk-prepare-system.sh" self.finalize_command = "./mk-finalize-system.sh" self.chroot_command = "./mk-run-chroot.sh" self.setup_grub_command = "./mk-setup-grub.sh" self.unmount_disk_command = "./mk-unmount-disk.sh" if 'working_directory' in self.install_config: self.working_directory = self.install_config['working_directory'] else: self.working_directory = "/mnt/photon-root" self.photon_root = self.working_directory + "/photon-chroot" self.restart_command = "shutdown" if self.iso_installer: self.output = open(os.devnull, 'w') else: self.output = None if self.iso_installer: #initializing windows self.maxy = maxy self.maxx = maxx self.height = 10 self.width = 75 self.progress_padding = 5 self.progress_width = self.width - self.progress_padding self.starty = (self.maxy - self.height) // 2 self.startx = (self.maxx - self.width) // 2 self.window = Window(self.height, self.width, self.maxy, self.maxx, 'Installing Photon', False, items=[]) self.progress_bar = ProgressBar( self.starty + 3, self.startx + self.progress_padding // 2, self.progress_width) signal.signal(signal.SIGINT, self.exit_gracefully) # This will be called if the installer interrupted by Ctrl+C or exception def exit_gracefully(self, signal, frame): if self.iso_installer: self.progress_bar.hide() self.window.addstr( 0, 0, 'Oops, Installer got interrupted.\n\nPress any key to get to the bash...' ) self.window.content_window().getch() modules.commons.dump(modules.commons.LOG_FILE_NAME) sys.exit(1) def install(self, params): try: return self.unsafe_install(params) except Exception as inst: if self.iso_installer: modules.commons.log(modules.commons.LOG_ERROR, repr(inst)) self.exit_gracefully(None, None) else: raise def unsafe_install(self, params): if self.iso_installer: self.window.show_window() self.progress_bar.initialize('Initializing installation...') self.progress_bar.show() #self.rpm_path = "https://dl.bintray.com/vmware/photon_release_1.0_TP2_x86_64" if self.rpm_path.startswith( "https://") or self.rpm_path.startswith("http://"): cmdoption = 's/baseurl.*/baseurl={}/g'.format( self.rpm_path.replace('/', '\/')) process = subprocess.Popen([ 'sed', '-i', cmdoption, '/etc/yum.repos.d/photon-iso.repo' ]) retval = process.wait() if retval != 0: modules.commons.log(modules.commons.LOG_INFO, "Failed to reset repo") self.exit_gracefully(None, None) cmdoption = 's/cachedir=\/var/cachedir={}/g'.format( self.photon_root.replace('/', '\/')) process = subprocess.Popen( ['sed', '-i', cmdoption, '/etc/tdnf/tdnf.conf']) retval = process.wait() if retval != 0: modules.commons.log(modules.commons.LOG_INFO, "Failed to reset tdnf cachedir") self.exit_gracefully(None, None) self.execute_modules(modules.commons.PRE_INSTALL) self.initialize_system() if self.iso_installer: self.adjust_packages_for_vmware_virt() selected_packages = self.install_config['packages'] state = 0 packages_to_install = {} total_size = 0 with open(modules.commons.TDNF_CMDLINE_FILE_NAME, "w") as tdnf_cmdline_file: tdnf_cmdline_file.write( "tdnf install --installroot {0} --nogpgcheck {1}".format( self.photon_root, " ".join(selected_packages))) with open(modules.commons.TDNF_LOG_FILE_NAME, "w") as tdnf_errlog: process = subprocess.Popen( ['tdnf', 'install'] + selected_packages + [ '--installroot', self.photon_root, '--nogpgcheck', '--assumeyes' ], stdout=subprocess.PIPE, stderr=tdnf_errlog) while True: output = process.stdout.readline() if output == '': retval = process.poll() if retval is not None: break if state == 0: if output == 'Installing:\n': state = 1 elif state == 1: #N A EVR Size(readable) Size(in bytes) if output == '\n': state = 2 self.progress_bar.update_num_items(total_size) else: info = output.split() package = '{0}-{1}.{2}'.format( info[0], info[2], info[1]) packages_to_install[package] = int(info[5]) total_size += int(info[5]) elif state == 2: if output == 'Downloading:\n': self.progress_bar.update_message('Preparing ...') state = 3 elif state == 3: self.progress_bar.update_message(output) if output == 'Running transaction\n': state = 4 else: modules.commons.log(modules.commons.LOG_INFO, "[tdnf] {0}".format(output)) prefix = 'Installing/Updating: ' if output.startswith(prefix): package = output[len(prefix):].rstrip('\n') self.progress_bar.increment( packages_to_install[package]) self.progress_bar.update_message(output) # 0 : succeed; 137 : package already installed; 65 : package not found in repo. if retval != 0 and retval != 137: modules.commons.log( modules.commons.LOG_ERROR, "Failed to install some packages, refer to {0}".format( modules.commons.TDNF_LOG_FILE_NAME)) self.exit_gracefully(None, None) else: #install packages rpms = [] for rpm in self.rpms_tobeinstalled: # We already installed the filesystem in the preparation if rpm['package'] == 'filesystem': continue rpms.append(rpm['filename']) return_value = self.install_package(rpms) if return_value != 0: self.exit_gracefully(None, None) if self.iso_installer: self.progress_bar.show_loading('Finalizing installation') if os.path.exists("/etc/resolv.conf"): shutil.copy("/etc/resolv.conf", self.photon_root + '/etc/.') self.finalize_system() if not self.install_config['iso_system']: # Execute post installation modules self.execute_modules(modules.commons.POST_INSTALL) if os.path.exists(modules.commons.KS_POST_INSTALL_LOG_FILE_NAME): shutil.copy(modules.commons.KS_POST_INSTALL_LOG_FILE_NAME, self.photon_root + '/var/log/') if self.iso_installer and os.path.isdir("/sys/firmware/efi"): self.install_config['boot'] = 'efi' # install grub if 'boot_partition_number' not in self.install_config['disk']: self.install_config['disk']['boot_partition_number'] = 1 try: if self.install_config['boot'] == 'bios': process = subprocess.Popen([ self.setup_grub_command, '-w', self.photon_root, "bios", self.install_config['disk']['disk'], self.install_config['disk']['root'], self.install_config['disk']['boot'], self.install_config['disk']['bootdirectory'], str(self.install_config['disk'] ['boot_partition_number']) ], stdout=self.output) elif self.install_config['boot'] == 'efi': process = subprocess.Popen([ self.setup_grub_command, '-w', self.photon_root, "efi", self.install_config['disk']['disk'], self.install_config['disk']['root'], self.install_config['disk']['boot'], self.install_config['disk']['bootdirectory'], str(self.install_config['disk'] ['boot_partition_number']) ], stdout=self.output) except: #install bios if variable is not set. process = subprocess.Popen([ self.setup_grub_command, '-w', self.photon_root, "bios", self.install_config['disk']['disk'], self.install_config['disk']['root'], self.install_config['disk']['boot'], self.install_config['disk']['bootdirectory'], str(self.install_config['disk']['boot_partition_number']) ], stdout=self.output) retval = process.wait() self.update_fstab() if os.path.exists(self.photon_root + '/etc/resolv.conf'): os.remove(self.photon_root + '/etc/resolv.conf') command = [self.unmount_disk_command, '-w', self.photon_root] if not self.install_config['iso_system']: command.extend(self.generate_partitions_param(reverse=True)) process = subprocess.Popen(command, stdout=self.output) retval = process.wait() if self.iso_installer: self.progress_bar.hide() self.window.addstr( 0, 0, 'Congratulations, Photon has been installed in {0} secs.\n\nPress any key to continue to boot...' .format(self.progress_bar.time_elapsed)) eject_cdrom = True if 'ui_install' in self.install_config: self.window.content_window().getch() if 'eject_cdrom' in self.install_config and not self.install_config[ 'eject_cdrom']: eject_cdrom = False if eject_cdrom: process = subprocess.Popen(['eject', '-r'], stdout=self.output) process.wait() return ActionResult(True, None) def copy_rpms(self): # prepare the RPMs list json_pkg_to_rpm_map = JsonWrapper( self.install_config["pkg_to_rpm_map_file"]) pkg_to_rpm_map = json_pkg_to_rpm_map.read() self.rpms_tobeinstalled = [] selected_packages = self.install_config['packages'] for pkg in selected_packages: if pkg in pkg_to_rpm_map: if not pkg_to_rpm_map[pkg]['rpm'] is None: name = pkg_to_rpm_map[pkg]['rpm'] basename = os.path.basename(name) self.rpms_tobeinstalled.append({ 'filename': basename, 'path': name, 'package': pkg }) # Copy the rpms for rpm in self.rpms_tobeinstalled: shutil.copy(rpm['path'], self.photon_root + '/RPMS/') def copy_files(self): # Make the photon_root directory if not exits process = subprocess.Popen(['mkdir', '-p', self.photon_root], stdout=self.output) retval = process.wait() # Copy the installer files process = subprocess.Popen( ['cp', '-r', "../installer", self.photon_root], stdout=self.output) retval = process.wait() # Create the rpms directory process = subprocess.Popen(['mkdir', '-p', self.photon_root + '/RPMS'], stdout=self.output) retval = process.wait() self.copy_rpms() def bind_installer(self): # Make the photon_root/installer directory if not exits process = subprocess.Popen( ['mkdir', '-p', os.path.join(self.photon_root, "installer")], stdout=self.output) retval = process.wait() # The function finalize_system will access the file /installer/mk-finalize-system.sh after chroot to photon_root. # Bind the /installer folder to self.photon_root/installer, so that after chroot to photon_root, # the file can still be accessed as /installer/mk-finalize-system.sh. process = subprocess.Popen([ 'mount', '--bind', '/installer', os.path.join(self.photon_root, "installer") ], stdout=self.output) retval = process.wait() def bind_repo_dir(self): rpm_cache_dir = self.photon_root + '/cache/tdnf/photon-iso/rpms' if self.rpm_path.startswith("https://") or self.rpm_path.startswith( "http://"): return if subprocess.call( ['mkdir', '-p', rpm_cache_dir]) != 0 or subprocess.call( ['mount', '--bind', self.rpm_path, rpm_cache_dir]) != 0: modules.commons.log(modules.commons.LOG_ERROR, "Fail to bind cache rpms") self.exit_gracefully(None, None) def unbind_repo_dir(self): rpm_cache_dir = self.photon_root + '/cache/tdnf/photon-iso/rpms' if self.rpm_path.startswith("https://") or self.rpm_path.startswith( "http://"): return if subprocess.call(['umount', rpm_cache_dir]) != 0 or subprocess.call( ['rm', '-rf', rpm_cache_dir]) != 0: modules.commons.log(modules.commons.LOG_ERROR, "Fail to unbind cache rpms") self.exit_gracefully(None, None) def update_fstab(self): with open(os.path.join(self.photon_root, "etc/fstab"), "w") as fstab_file: fstab_file.write("#system\tmnt-pt\ttype\toptions\tdump\tfsck\n") for partition in self.install_config['disk']['partitions']: options = 'defaults' dump = 1 fsck = 2 if 'mountpoint' in partition and partition['mountpoint'] == '/': options = options + ',barrier,noatime,noacl,data=ordered' fsck = 1 if partition['filesystem'] == 'swap': mountpoint = 'swap' dump = 0 fsck = 0 else: mountpoint = partition['mountpoint'] fstab_file.write("{}\t{}\t{}\t{}\t{}\t{}\n".format( partition['path'], mountpoint, partition['filesystem'], options, dump, fsck)) # Add the cdrom entry fstab_file.write( "/dev/cdrom\t/mnt/cdrom\tiso9660\tro,noauto\t0\t0\n") def generate_partitions_param(self, reverse=False): if reverse: step = -1 else: step = 1 params = [] for partition in self.install_config['disk']['partitions'][::step]: if partition["filesystem"] == "swap": continue params.extend([ '--partitionmountpoint', partition["path"], partition["mountpoint"] ]) return params def initialize_system(self): #Setup the disk if (not self.install_config['iso_system']): command = [self.mount_command, '-w', self.photon_root] command.extend(self.generate_partitions_param()) process = subprocess.Popen(command, stdout=self.output) retval = process.wait() if self.iso_installer: self.bind_installer() self.bind_repo_dir() process = subprocess.Popen( [self.prepare_command, '-w', self.photon_root, 'install'], stdout=self.output) retval = process.wait() else: self.copy_files() #Setup the filesystem basics process = subprocess.Popen( [self.prepare_command, '-w', self.photon_root], stdout=self.output) retval = process.wait() def finalize_system(self): #Setup the disk process = subprocess.Popen([ self.chroot_command, '-w', self.photon_root, self.finalize_command, '-w', self.photon_root ], stdout=self.output) retval = process.wait() if self.iso_installer: modules.commons.dump(modules.commons.LOG_FILE_NAME) shutil.copy(modules.commons.LOG_FILE_NAME, self.photon_root + '/var/log/') shutil.copy(modules.commons.TDNF_LOG_FILE_NAME, self.photon_root + '/var/log/') # unmount the installer directory process = subprocess.Popen( ['umount', os.path.join(self.photon_root, "installer")], stdout=self.output) retval = process.wait() # remove the installer directory process = subprocess.Popen( ['rm', '-rf', os.path.join(self.photon_root, "installer")], stdout=self.output) retval = process.wait() self.unbind_repo_dir() # Disable the swap file process = subprocess.Popen(['swapoff', '-a'], stdout=self.output) retval = process.wait() # remove the tdnf cache directory and the swapfile. process = subprocess.Popen( ['rm', '-rf', os.path.join(self.photon_root, "cache")], stdout=self.output) retval = process.wait() def install_package(self, rpm_file_names): rpms = set(rpm_file_names) rpm_paths = [] for root, dirs, files in os.walk(self.rpm_path): for f in files: if f in rpms: rpm_paths.append(os.path.join(root, f)) # --nodeps is for hosts which do not support rich dependencies rpm_params = [ '--nodeps', '--root', self.photon_root, '--dbpath', '/var/lib/rpm' ] if ('type' in self.install_config and (self.install_config['type'] in ['micro', 'minimal'])) or self.install_config['iso_system']: rpm_params.append('--excludedocs') modules.commons.log( modules.commons.LOG_INFO, "installing packages {0}, with params {1}".format( rpm_paths, rpm_params)) process = subprocess.Popen(['rpm', '-Uvh'] + rpm_params + rpm_paths, stderr=subprocess.STDOUT) return process.wait() def execute_modules(self, phase): modules_paths = glob.glob('modules/m_*.py') for mod_path in modules_paths: module = mod_path.replace('/', '.', 1) module = os.path.splitext(module)[0] try: __import__(module) mod = sys.modules[module] except ImportError: modules.commons.log(modules.commons.LOG_ERROR, 'Error importing module {}'.format(module)) continue # the module default is disabled if not hasattr(mod, 'enabled') or mod.enabled == False: modules.commons.log(modules.commons.LOG_INFO, "module {} is not enabled".format(module)) continue # check for the install phase if not hasattr(mod, 'install_phase'): modules.commons.log( modules.commons.LOG_ERROR, "Error: can not defind module {} phase".format(module)) continue if mod.install_phase != phase: modules.commons.log( modules.commons.LOG_INFO, "Skipping module {0} for phase {1}".format(module, phase)) continue if not hasattr(mod, 'execute'): modules.commons.log( modules.commons.LOG_ERROR, "Error: not able to execute module {}".format(module)) continue mod.execute(module, self.install_config, self.photon_root) def adjust_packages_for_vmware_virt(self): try: if self.install_config['install_linux_esx']: selected_packages = self.install_config['packages'] try: selected_packages.remove('linux') except ValueError: pass try: selected_packages.remove('initramfs') except ValueError: pass selected_packages.append('linux-esx') except KeyError: pass def run(self, command, comment=None): if comment != None: modules.commons.log(modules.commons.LOG_INFO, "Installer: {} ".format(comment)) self.progress_bar.update_loading_message(comment) modules.commons.log(modules.commons.LOG_INFO, "Installer: {} ".format(command)) process = subprocess.Popen([command], shell=True, stdout=subprocess.PIPE) out, err = process.communicate() if err != None and err != 0 and "systemd-tmpfiles" not in command: modules.commons.log( modules.commons.LOG_ERROR, "Installer: failed in {} with error code {}".format( command, err)) modules.commons.log(modules.commons.LOG_ERROR, out) self.exit_gracefully(None, None) return err
''' # 每次运行程序之前都会先把这个文件夹里的东西清空,防止上一次运行会残留文件,但是第一次运行程序之前必须要创建一个空的文件夹 # 删除文件夹 shutil.rmtree(r'C:\Users\Administrator\Desktop\image3') shutil.rmtree(r'C:\Users\Administrator\Desktop\image5') shutil.rmtree(r'C:\Users\Administrator\Desktop\recording') # 创建空的文件夹 os.mkdir(r'C:\Users\Administrator\Desktop\image3') os.mkdir(r'C:\Users\Administrator\Desktop\image5') os.mkdir(r'C:\Users\Administrator\Desktop\recording') # 生成窗体对象 下面两句话的参数 要和相机拍到的图片保持一致 width = 800 height = 600 pro = Window('projector_1', 'projector_2', width, height) pro.createwindow(width, height) # 连投影仪运行这句话,不连就把1改成0,否则会报错 out of range pro.movewindow(1) # 前两个参数是一屏二屏标记的颜色,第三个参数是标记的宽度,最后两个参数 要和生成窗体对象的最后两个参数保持一致,如果想要二屏标记也是绿色就把(255,255,255)改成(0,255,0) pro.bindingwi((0, 255, 0), (255, 255, 255), 3, width, height) pro.nobiaotilan() # n用来计数 n = 0 # 加个trackbar方便快进或快退到某一位置 def nothing(x): pass
def add_ui(self, w: window.Window, g: ReversiGame, results: List, colour_to_player: Dict) -> None: """ Add some UI to the window, such as buttons, and more. """ w.add_text(label="text-score-black-label", text="BLACK:", position=(20, 675)) w.add_text(label="text-score-white-label", text="WHITE:", position=(502, 675)) w.add_text(label="text-score-black-amount", text="0", position=(113, 675)) w.add_text(label="text-score-white-amount", text="0", position=(593, 675)) w.add_button(rect=pygame.Rect(725, 30, 150, 40), label="button-pause-game", text="Pause Game", function=lambda: self.button_pause_game(w)) w.add_text(label="text-choose-players", text="Choose Players", position=(720, 100)) w.add_dropdown( options_list=["Human vs. AI", "AI vs. Human", 'AI vs. AI'], starting_option="Human vs. AI", rect=pygame.Rect(725, 130, 150, 50), label="dropdown-player", function=self.dropdown_select_player(g)) w.add_text(label="text-choose-ai", text="Choose AI types", position=(720, 250)) w.add_text(label="text-choose-ai-black", text="Black AI", position=(705, 280), large_font=False) w.add_text(label="text-choose-ai-white", text="White AI", position=(840, 280), large_font=False) w.add_dropdown(options_list=[ "Random Moves", "Minimax 2", 'Minimax 3', 'Minimax 4', 'Minimax 6' ], starting_option="Minimax 2", rect=pygame.Rect(675, 300, 125, 40), label="dropdown-ai-black", function=self.dropdown_select_ai(1, colour_to_player)) w.add_dropdown(options_list=[ "Random Moves", "Minimax 2", 'Minimax 3', 'Minimax 4', 'Minimax 6' ], starting_option="Minimax 2", rect=pygame.Rect(810, 300, 125, 40), label="dropdown-ai-white", function=self.dropdown_select_ai(-1, colour_to_player)) w.add_text(label="text-choose-board-size", text="Choose Board Size", position=(700, 450)) w.add_dropdown(options_list=["8x8", '12x12', '16x16', '24x24'], starting_option="8x8", rect=pygame.Rect(725, 480, 150, 40), label="dropdown-board-size", function=self.dropdown_select_board_size( g, colour_to_player)) w.add_button(rect=pygame.Rect(675, 610, 125, 40), label="button-show-stats", text="View Stats", function=lambda: plot_game_statistics( g, results, 'black', colour_to_player[1], colour_to_player[-1])) w.add_button(rect=pygame.Rect(810, 610, 125, 40), label="button-clear-stats", text="Clear Stats", function=lambda: self.clear_results(results, w)) w.add_text(label="text-games-stored", text="Games Stored: 0", position=(715, 665)) w.add_text( label="text-credits", text="Anatoly Zavyalov, Baker Jackson, Elliot Schrider, Rachel Kim", position=(20, 2), large_font=False)
class MyField(Field): """An object representing the field. """ cellClass = MyCell connectorClass = MyConnector groupClass = MyGroup def __init__(self): self.m_xmin_field = XMIN_FIELD self.m_ymin_field = YMIN_FIELD self.m_xmax_field = XMAX_FIELD self.m_ymax_field = YMAX_FIELD self.m_xmin_vector = XMIN_VECTOR self.m_ymin_vector = YMIN_VECTOR self.m_xmax_vector = XMAX_VECTOR self.m_ymax_vector = YMAX_VECTOR self.m_xmin_screen = XMIN_SCREEN self.m_ymin_screen = YMIN_SCREEN self.m_xmax_screen = XMAX_SCREEN self.m_ymax_screen = YMAX_SCREEN self.m_path_unit = PATH_UNIT self.m_path_scale = 1.0 / self.m_path_unit self.m_screen_scale = 1 self.m_vector_scale = 1 # our default margins, one will be overwriten below self.m_xmargin = int(self.m_xmax_screen * DEF_MARGIN) self.m_ymargin = int(self.m_ymax_screen * DEF_MARGIN) self.set_scaling() self.m_screen = object self.m_pathgrid = object self.m_pathfinder = object super(MyField, self).__init__() self.make_path_grid() # Screen Stuff def init_screen(self): # initialize window #(xmax_screen,ymax_screen) = self.screenMax() width = self.m_xmax_screen - self.m_xmin_screen height = self.m_ymax_screen - self.m_ymin_screen if dbug.LEV & dbug.FIELD: print "field:init_screen" self.m_screen = Window(self, width=width, height=height) # set window background color = r, g, b, alpha # each value goes from 0.0 to 1.0 # ... perform some additional initialisation # moved to window class #pyglet.gl.glClearColor(*DEF_BKGDCOLOR) #self.m_screen.clear() # register draw routing with pyglet # TESTED: These functions are being called correctly, and params are # being passed correctly self.m_screen.set_minimum_size(XMAX_SCREEN / 4, YMAX_SCREEN / 4) self.m_screen.set_visible() # Scaling def set_scaling(self, pmin_field=None, pmax_field=None, pmin_vector=None, pmax_vector=None, pmin_screen=None, pmax_screen=None, path_unit=None): """Set up scaling in the field. A word about graphics scaling: * The vision tracking system (our input data) measures in meters. * The laser DAC measures in uh, int16? -32,768 to 32,768 * Pyglet measures in pixels at the screen resolution of the window you create * The pathfinding units are each some ratio of the smallest expected radius So we will keep eveything internally in centemeters (so we can use ints instead of floats), and then convert it to the appropriate units before display depending on the output mode """ if pmin_field is not None: self.m_xmin_field = pmin_field[0] self.m_ymin_field = pmin_field[1] if pmax_field is not None: self.m_xmax_field = pmax_field[0] self.m_ymax_field = pmax_field[1] if pmin_vector is not None: self.m_xmin_vector = pmin_vector[0] self.m_ymin_vector = pmin_vector[1] if pmax_vector is not None: self.m_xmax_vector = pmax_vector[0] self.m_ymax_vector = pmax_vector[1] if pmin_screen is not None: self.m_xmin_screen = pmin_screen[0] self.m_ymin_screen = pmin_screen[1] if pmax_screen is not None: self.m_xmax_screen = pmax_screen[0] self.m_ymax_screen = pmax_screen[1] if path_unit is not None: self.m_path_unit = path_unit self.m_path_scale = 1.0 / path_unit xmin_field = self.m_xmin_field ymin_field = self.m_ymin_field xmax_field = self.m_xmax_field ymax_field = self.m_ymax_field xmin_vector = self.m_xmin_vector ymin_vector = self.m_ymin_vector xmax_vector = self.m_xmax_vector ymax_vector = self.m_ymax_vector xmin_screen = self.m_xmin_screen ymin_screen = self.m_ymin_screen xmax_screen = self.m_xmax_screen ymax_screen = self.m_ymax_screen if dbug.LEV & dbug.MORE: print "Field dims:",(xmin_field,ymin_field),\ (xmax_field,ymax_field) # in order to find out how to display this, # 1) we find the aspect ratio (x/y) of the screen or vector (depending on the # mode). # 2) Then if the aspect ratio (x/y) of the reported field is greater, we # set the x axis to stretch to the edges of screen (or vector) and then use # that value to determine the scaling. # 3) But if the aspect ratio (x/y) of the reported field is less than, # we set the y axis to stretch to the top and bottom of screen (or # vector) and use that value to determine the scaling. # aspect ratios used only for comparison field_aspect = float(xmax_field - xmin_field) / (ymax_field - ymin_field) #if GRAPHMODES & GRAPHOPTS['osc']: #vector_aspect = float(xmax_vector-xmin_vector)/(ymax_vector-ymin_vector) if GRAPHMODES & GRAPHOPTS['screen']: screen_aspect = float(xmax_screen - xmin_screen) / (ymax_screen - ymin_screen) if field_aspect > screen_aspect: if dbug.LEV & dbug.MORE: print "Field:SetScaling:Longer in the x dimension" field_xlen = xmax_field - xmin_field if field_xlen: self.m_xmargin = int(xmax_screen * DEF_MARGIN) # scale = vector_width / field_width self.m_vector_scale = \ float(xmax_vector-xmin_vector)/field_xlen # scale = (screen_width - margin) / field_width self.m_screen_scale = \ float(xmax_screen-xmin_screen-(self.m_xmargin*2))/field_xlen self.m_ymargin = \ int(((ymax_screen-ymin_screen)- ((ymax_field-ymin_field)*self.m_screen_scale)) / 2) else: if dbug.LEV & dbug.FIELD: print "Field:SetScaling:Longer in the y dimension" field_ylen = ymax_field - ymin_field if field_ylen: self.m_ymargin = int(ymax_screen * DEF_MARGIN) self.m_vector_scale = \ float(ymax_vector-ymin_vector)/field_ylen self.m_screen_scale = \ float(ymax_screen-ymin_screen-(self.m_ymargin*2))/field_ylen self.m_xmargin = \ int(((xmax_screen-xmin_screen)- ((xmax_field-xmin_field)*self.m_screen_scale)) / 2) if dbug.LEV & dbug.MORE: print "Screen dims:",(xmin_screen,ymin_screen),\ (xmax_screen,ymax_screen) #print "Screen scale:",self.m_screen_scale #print "Screen margins:",(self.m_xmargin,self.m_ymargin) if dbug.LEV & dbug.MORE: print "Used screen space:",\ self.rescale_pt2screen((xmin_field,ymin_field)),\ self.rescale_pt2screen((xmax_field,ymax_field)) # Everything #CHANGE: incorporated into draw #def render_all(self): # """Render all the cells and connectors.""" # self.render_all_cells() # self.render_all_connectors() # self.render_all_groups() def draw_all(self): """Draw all the cells and connectors.""" self.m_screen.draw_guides() self.draw_all_cells() self.calc_all_paths() self.draw_all_connectors() self.draw_all_groups() #CHANGE: incorporated into draw #def render_cell(self,cell): # """Render a cell. # # We first check if the cell is good. # If not, we increment its suspect count # If yes, render it. # """ # if self.is_cell_good_to_go(cell.m_id): # cell.render() # #del self.m_suspect_cells[cell.m_id] #def render_all_cells(self): # # we don't call the Cell's render-er directly because we have some # # logic here at this level # for cell in self.m_cell_dict.values(): # self.render_cell(cell) def draw_cell(self, cell): if self.is_cell_good_to_go(cell.m_id): cell.draw() def draw_all_cells(self): # we don't call the Cell's draw-er directly because we may want # to introduce logic at this level for cell in self.m_cell_dict.values(): self.draw_cell(cell) # Connectors #CHANGE: incorporated into draw #def render_connector(self,connector): # """Render a connector. # # We first check if the connector's two cells are both good. # If not, we increment its suspect count # If yes, render it. # """ # if self.is_conx_good_to_go(connector.m_id): # connector.render() #CHANGE: incorporated into draw #def render_all_connectors(self): # # we don't call the Connector's render-er directly because we have some # # logic here at this level # for connector in self.m_conx_dict.values(): # self.render_connector(connector) def draw_connector(self, connector): if self.is_conx_good_to_go(connector.m_id): connector.draw() def draw_all_connectors(self): # we don't call the Connector's draw-er directly because we may want # to introduce logic at this level for connector in self.m_conx_dict.values(): connector.update() self.draw_connector(connector) # Groups #CHANGE: incorporated into draw #def render_group(self,group): # """Render a group. # # We first check if the group's is in the group list # If yes, render it. # """ # if self.is_group_good_to_go(group.m_id): # group.render() #CHANGE: incorporated into draw #def render_all_groups(self): # # we don't call the Connector's render-er directly because we have some # # logic here at this level # for group in self.m_group_dict.values(): # self.render_group(group) def draw_group(self, group): if self.is_group_good_to_go(group.m_id): group.draw() def draw_all_groups(self): # we don't call the Connector's draw-er directly because we may want # to introduce logic at this level for group in self.m_group_dict.values(): self.draw_group(group) # Distances - TODO: temporary -- this info will come from the conductor subsys #def dist_sqd(self,cell0,cell1): # moved to superclass #def calc_distances(self): # moved to superclass # Paths def calc_all_paths(self): self.reset_path_grid() self.set_path_blocks() self.calc_connector_paths() def make_path_grid(self): # for our pathfinding, we're going to overlay a grid over the field with # squares that are sized by a constant in the config file origdim = (self.m_xmax_field, self.m_ymax_field) newdim = self.rescale_pt2path(origdim) self.m_pathgrid = GridMap(*self.rescale_pt2path((self.m_xmax_field, self.m_ymax_field))) self.m_pathfinder = PathFinder(self.m_pathgrid.successors, self.m_pathgrid.move_cost, self.m_pathgrid.estimate) def reset_path_grid(self): self.m_pathgrid.reset_grid() # we store the results of all the paths, why? Not sure we need to anymore #self.allpaths = [] def set_path_blocks(self): #print "***Before path: ",self.m_cell_dict for cell in self.m_cell_dict.values(): if self.is_cell_good_to_go(cell.m_id): origpt = (cell.m_x, cell.m_y) newpt = self.rescale_pt2path(origpt) self.m_pathgrid.set_blocked( self.rescale_pt2path((cell.m_x, cell.m_y)), self.rescale_num2path(cell.m_diam / 2), BLOCK_FUZZ) def calc_connector_paths(self): """ Find path for all the connectors. We sort the connectors by distance and do easy paths for the closest ones first. """ #conx_dict_rekeyed = self.m_conx_dict #for i in conx_dict_rekeyed.iterkeys(): conx_dict_rekeyed = {} for connector in self.m_conx_dict.values(): if self.is_conx_good_to_go(connector.m_id): # normally we'd take the sqrt to get the distance, but here this is # just used as a sort comparison, so we'll not take the hit for sqrt dist = sqrt((connector.m_cell0.m_x - connector.m_cell1.m_x)**2 + \ (connector.m_cell0.m_y - connector.m_cell1.m_y)**2) # here we save time by reindexing as we go through it connector.update(dist=dist) conx_dict_rekeyed[dist] = connector for i in sorted(conx_dict_rekeyed.iterkeys()): connector = conx_dict_rekeyed[i] #print "findpath--id:",connector.m_id,"dist:",i**0.5 path = self.find_path(connector) connector.add_path(path) #import pdb;pdb.set_trace() def find_path(self, connector): """ Find path in path_grid and then scale it appropriately.""" start = self.rescale_pt2path( (connector.m_cell0.m_x, connector.m_cell0.m_y)) goal = self.rescale_pt2path( (connector.m_cell1.m_x, connector.m_cell1.m_y)) # TODO: Either here or in compute_path we first try several simple/dumb # paths, reserving A* for the ones that are blocked and need more # smarts. We sort the connectors by distance and do easy paths for the # closest ones first. path = list(self.m_pathgrid.easy_path(start, goal)) #if not path: #path = list(self.m_pathfinder.compute_path(start, goal)) # take results of found paths and block them on the map self.m_pathgrid.set_block_line(path) #self.allpaths = self.allpaths + path rescaled_path = self.rescale_path2pt(path) #import pdb;pdb.set_trace() return rescaled_path def print_grid(self): self.m_pathgrid.printme() # Scaling conversions def _convert(self, obj, scale, min1, min2): """Recursively converts numbers in an object. This function accepts single integers, tuples, lists, or combinations. """ if isinstance(obj, (int, float)): #return(int(obj*scale) + min) if isinstance(min1, int) and isinstance(min2, int): return int((obj - min1) * scale) + min2 return (obj - min1) * scale + min2 elif isinstance(obj, list): mylist = [] for i in obj: mylist.append(self._convert(i, scale, min1, min2)) return mylist elif isinstance(obj, tuple): mylist = [] for i in obj: mylist.append(self._convert(i, scale, min1, min2)) return tuple(mylist) def scale2screen(self, n): """Convert internal unit (m) to units usable for screen. """ return self._convert(n, self.m_screen_scale, self.m_xmin_field, self.m_xmin_screen) def scale2vector(self, n): """Convert internal unit (m) to units usable for vector. """ return self._convert(n, self.m_vector_scale, self.m_xmin_field, self.m_xmin_vector) def scale2path(self, n): """Convert internal unit (m) to units usable for pathfinding. """ return self._convert(n, self.m_path_scale, self.m_xmin_field, 0) def path2scale(self, n): """Convert pathfinding units to internal unit (cm). """ #print "m_path_scale",self.m_path_scale return self._convert(n, 1 / self.m_path_scale, 0, self.m_xmin_field) def _rescale_pts(self, obj, scale, orig_pmin, new_pmin, type=None): """Recursively rescales points or lists of points. This function accepts single integers, tuples, lists, or combinations. """ # if this is a point, rescale it if isinstance(obj, tuple) and len(obj) == 2 and \ isinstance(obj[0], (int,float)) and \ isinstance(obj[1], (int,float)): # if we were given ints (pixel scaling), return ints if type == 'int': x = int((obj[0] - orig_pmin[0]) * scale) + new_pmin[0] y = int((obj[1] - orig_pmin[1]) * scale) + new_pmin[1] # otherwise (m scaling), return floats else: x = float(obj[0] - orig_pmin[0]) * scale + new_pmin[0] y = float(obj[1] - orig_pmin[1]) * scale + new_pmin[1] return x, y # if this is a list, examine each element, return list elif isinstance(obj, (list, tuple)): mylist = [] for i in obj: mylist.append( self._rescale_pts(i, scale, orig_pmin, new_pmin, type)) return mylist # if this is a tuple, examine each element, return tuple elif isinstance(obj, tuple): mylist = [] for i in obj: mylist.append(self._rescale_pts(i, scale, orig_pmin, new_pmin)) return tuple(mylist) # otherwise, we don't know what to do with it, return it # TODO: Consider throwing an exception else: print "ERROR: Can only rescale a point, not", obj return obj def rescale_pt2screen(self, p): """Convert coord in internal units (cm) to units usable for the vector or screen. """ orig_pmin = (self.m_xmin_field, self.m_ymin_field) scale = self.m_screen_scale new_pmin = (self.m_xmin_screen + self.m_xmargin, self.m_ymin_screen + self.m_ymargin) return self._rescale_pts(p, scale, orig_pmin, new_pmin, 'int') def rescale_pt2vector(self, p): """Convert coord in internal units (cm) to units usable for the vector or screen. """ orig_pmin = (self.m_xmin_field, self.m_ymin_field) scale = self.m_vector_scale new_pmin = (self.m_xmin_vector, self.m_ymin_vector) return self._rescale_pts(p, scale, orig_pmin, new_pmin, 'float') def rescale_pt2path(self, p): """Convert coord in internal units (cm) to units usable for the vector or screen. """ orig_pmin = (self.m_xmin_field, self.m_ymin_field) scale = self.m_path_scale new_pmin = (0, 0) return self._rescale_pts(p, scale, orig_pmin, new_pmin, 'int') def rescale_path2pt(self, p): """Convert coord in internal units (cm) to units usable for the vector or screen. """ orig_pmin = (0.0, 0.0) scale = 1.0 / self.m_path_scale new_pmin = (self.m_xmin_field, self.m_ymin_field) return self._rescale_pts(p, scale, orig_pmin, new_pmin, 'float') def rescale_num2screen(self, n): """Convert num in internal units (cm) to units usable for screen. """ return int(n * self.m_screen_scale) def rescale_num2vector(self, n): """Convert num in internal units (cm) to units usable for vector. """ return float(n) * self.m_vector_scale def rescale_num2path(self, n): """Convert num in internal units (cm) to units usable for vector. """ return int(n * self.m_path_scale) def rescale_path2num(self, n): """Convert num in internal units (cm) to units usable for vector. """ return float(n) / self.m_path_scale
def changetoMainMenu(): Window.setWindowName("MainMenu")
from window import Window app = Window() app.mainloop()
class GlutWindow(object): def __init__(self, width, height, title): super(GlutWindow, self).__init__() self.width = width self.height = height self.title = title self.texture_id = 0 self.vertices = None self.pixels = np.zeros(self.width * self.height) self.window = Window(self.width, self.height, self.pixels) self.setup() def mouse_event(self, button, state, x, y): self.window.mouse_event(button, state, x, y) def key_event(self, key, key_is_down, x, y): key = ord(key) self.window.key_event(key, key_is_down) def key_down(self, key, x, y): self.key_event(key, True, x, y) def key_up(self, key, x, y): self.key_event(key, False, x, y) def setup(self): self.setup_glut() self.setup_gl() def setup_glut(self): # glutInit(sys.argv) glutInit() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA) glutInitWindowSize(self.width, self.height) glutCreateWindow(self.title) glutDisplayFunc(self.show) glutMouseFunc(self.mouse_event) glutKeyboardFunc(self.key_down) glutKeyboardUpFunc(self.key_up) # glutSetKeyRepeat(GLUT_KEY_REPEAT_ON) def setup_gl(self): glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0, 0, 0, 1) glViewport(0, 0, self.width, self.height) self.texture_id = glGenTextures(1) glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture_id) # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) # glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, self.pixels) self.vertices = [ # (u, v), (x, y, z) (0, 0), (-1, -1, 0), (1, 0), (1, -1, 0), (1, 1), (1, 1, 0), (0, 1), (-1, 1, 0), ] def update(self, dt=100): # clear self.clear() # update delta = dt / 1000.0 self.window.update(delta) # draw self.window.draw() # show glutPostRedisplay() glutTimerFunc(dt, self.update, dt) def run(self): self.update() glutMainLoop() def clear(self): glClear(GL_COLOR_BUFFER_BIT) self.window.clear() def show(self): # update texture and render glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, self.width, self.height, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, self.pixels) vertices = self.vertices glBegin(GL_QUADS) for i in range(0, 4 * 2, 2): glTexCoord2f(*vertices[i]) glVertex3f(*vertices[i + 1]) glEnd() glutSwapBuffers()
self.SCREEN = pygame.transform.flip(self.SCREEN, True, False) self.X_FLIP = False if KEY_PRESSES[pygame.K_a] == 1 and not self.X_FLIP: self.SCREEN = pygame.transform.flip(self.SCREEN, True, False) self.X_FLIP = True def wasdMove(self, KEYPRESSES): super().wasdMove(KEYPRESSES) self.flipImageX(KEYPRESSES) if __name__ == "__main__": from window import Window import sys pygame.init() WINDOW = Window() SPRITE = ImageSprite("assets/bunny.png") SPRITE.setScale(2) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() KEY_PRESSED = pygame.key.get_pressed() SPRITE.wasdMove(KEY_PRESSED) WINDOW.clearScreen() WINDOW.getScreen().blit(SPRITE.getScreen(), SPRITE.getPOS()) WINDOW.updateFrame()
import sys from PyQt5 import QtWidgets from window import Window if __name__ == "__main__": try: app = QtWidgets.QApplication([]) height = int(sys.argv[1]) width = int(sys.argv[2]) max_size = int(sys.argv[3]) window = Window(height, width, max_size) window.update() sys.exit(app.exec_()) except KeyboardInterrupt: pass
from PyQt5.QtWidgets import QApplication from window import Window app = QApplication([]) window = Window() window.show() app.exec_()
def connection_handler(self, client): connection, address_port = client print("-" * 72) print("Connection received from {}.".format(address_port)) connection.setblocking(False) _window = Window() while True: try: recvd_bytes = connection.recv(4) if len(recvd_bytes) == 0: print("Closing client connection ... ") connection.close() break msg_length = int.from_bytes(recvd_bytes, 'big') ## first 4 bytes = size recvd_size = 0 recvd_bytes = b'' while recvd_size < msg_length: try: recvd = connection.recv(Server.RECV_BUFFER_SIZE) if len(recvd) == 0: print("Closing client connection ... ") connection.close() break recvd_size = recvd_size + len(recvd) recvd_bytes = recvd_bytes + recvd if recvd_size == msg_length: print("receive ", len(recvd_bytes), "expected ", msg_length) recvd_img = pickle.loads( recvd_bytes) ## load pil image print("Image received, classifying..") objs = self.classifier.process(recvd_img) send_bytes = pickle.dumps(objs) print("Sending data object back to client..") connection.sendall(send_bytes) print("Displaying new image") for obj in objs: _window.rectangle(recvd_img, ((obj.x1, obj.y1), (obj.x2, obj.y2)), obj.object_type) _window.display(recvd_img) if args.log: recvd_img.save( os.path.join( LOG_DIRECTORY, "{}.jpg").format( time.strftime("%m%d-%H%M%S"))) logged_images = glob.glob( os.path.join(LOG_DIRECTORY, "*.jpg")) if len(logged_images) > args.max_backlog: logged_images.sort() for im in logged_images[:len(logged_images ) - args.max_backlog]: os.remove(im) except KeyboardInterrupt: print("Closing client connection ... ") connection.close() break except socket.error: pass except Exception as msg: print(msg) except KeyboardInterrupt: print("Closing client connection ... ") connection.close() break except socket.error: pass try: _window.update() except: pass try: _window.destroy() except: pass
def __init__(self): self.delta_time = 0 super(MyApp, self).__init__(window=Window( 800, 600, mode='glut', window_name='Zapraszam na herbatke:))))'))
class SelectDisk(object): def __init__(self, maxy, maxx, install_config): self.install_config = install_config self.menu_items = [] self.maxx = maxx self.maxy = maxy self.win_width = 70 self.win_height = 16 self.win_starty = (self.maxy - self.win_height) / 2 self.win_startx = (self.maxx - self.win_width) / 2 self.menu_starty = self.win_starty + 6 self.menu_height = 5 self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx, 'Setup your disk', True) self.devices = Device.refresh_devices() def guided_partitions(self, device_index): menu_height = 9 menu_width = 40 menu_starty = (self.maxy - menu_height) / 2 + 5 confrim_window = ConfirmWindow( menu_height, menu_width, self.maxy, self.maxx, menu_starty, 'This will erase the disk.\nAre you sure?') confirmed = confrim_window.do_action().result['yes'] if not confirmed: return ActionResult(confirmed, None) #self.install_config['disk'] = self.devices[device_index].path #return ActionResult(True, None) # Do the partitioning self.window.clearerror() json_ret = subprocess.check_output([ 'gpartedbin', 'defaultpartitions', self.devices[device_index].path ], stderr=open(os.devnull, 'w')) json_dct = json.loads(json_ret) if json_dct['success']: self.install_config['disk'] = json_dct['data'] else: self.window.adderror('Partitioning failed, you may try again') return ActionResult(json_dct['success'], None) def display(self, params): self.window.addstr( 0, 0, 'First, we will setup your disks.\n\nWe have detected {0} disks, choose disk to be auto-partitioned:' .format(len(self.devices))) self.disk_menu_items = [] # Fill in the menu items for index, device in enumerate(self.devices): #if index > 0: self.disk_menu_items.append( ('{2} - {1} MB @ {0}'.format(device.path, device.size, device.model), self.guided_partitions, index)) self.disk_menu = Menu(self.menu_starty, self.maxx, self.disk_menu_items, self.menu_height) self.window.set_action_panel(self.disk_menu) return self.window.do_action()
def do_activate(self): win = Window(self) win.present()
from window import Window, World if __name__ == "__main__": window = Window() world = World(window) world.execute()
def reset_player_scores(w: window.Window) -> None: """Reset the player score of the corresponding player.""" w.get_ui_element('text-score-black-amount').set_text('0') w.get_ui_element('text-score-white-amount').set_text('0')
import cv2 import sys from camera1 import Camera from window import Window if __name__ == '__main__': # 实例化相机对象 cam = Camera() # 生成窗体对象 pro = Window('projector_1', 'projector_2', 1600, 1200) # 前两个参数是第一个窗体,后两个是第二个窗体 pro.createwindow(1600, 1200) # 连投影仪运行这句话,不连就把1改成0,否则会报错 out of range pro.movewindow(1) # 前两个参数是一屏二屏标记的颜色,第三个参数是标记的宽度,最后两个参数 要和生成窗体对象的最后两个参数保持一致,如果想要二屏标记也是绿色就把(255,255,255)改成(0,255,0) pro.bindingwi((0, 255, 0), (255, 255, 255), 3, 1600, 1200) pro.nobiaotilan() # 创建跟踪器 tracker_type = 'CSRT' tracker = cv2.TrackerCSRT_create() while True: # 读入第一帧 frame = cam.run() frame = cv2.flip(frame, 0) # print(frame.shape) # pro.addimage(frame) pro.showimage(frame) cv2.waitKey(1) pro.movebiaoji() # 定义一个bounding box # bbox = (287, 23, 86, 320)
# from account.pickle_manager import PickleManager from account.sqlite_manager import SQLiteManager from window import Window # accounts = PickleManager() accounts = SQLiteManager() window = Window(accounts) window.run() accounts.close_manager()
import sys import glob from window import Window import numpy as np sys.path.append(os.getcwd()) from viewer import fix from tqdm import tqdm from PIL import Image # to generate: # grep -vIr "\x00" -- */*/ent.txt > /tmp/ents # cat /tmp/ents | sort -t ":" -k2 -n -r > /tmp/entssort BASEDIR = sys.argv[1] win = Window(1164, 874) cc = 0 while len(glob.glob("imgs/h%03d*" % cc)) > 0: cc += 1 print("starting with %d" % cc) seen = set([x[len('imgs/h113_'):] for x in glob.glob("imgs/h*")]) # permanent camera occulusions EXCLUDE_USERS = ["807f77aac0daa4b6", "84e6a31bffe59bee"] dat = open(sys.argv[2]).read().strip().split("\n") for d in tqdm(dat): fn = os.path.join(BASEDIR, d.split(":")[0].replace("/ent.txt", "")) dd = sorted(os.listdir(fn))
def send_data(self, filename, win_size, d_address, d_port, sock_to_send): file_reader = FileReader(filename) # Pre-load file chunks with enough to fill the window at first file_chunks = file_reader.get_chunk(win_size) # load in the first packets window = Window(win_size) packets = [] for chunk in file_chunks: packets.append( Packet.data(self.seq_number, chunk, self.port, d_port)) self.up_sequence_number(len(chunk)) window.add_packets(packets) print("Sending first window...") window.send(sock_to_send, d_address, d_port) done = False while not done: sock_to_send.settimeout(.5) try: print("Waiting for ack...") message, address = sock_to_send.recvfrom(1472) ack_packet = Packet.read_packet(message) print("Packet received, checking...") # checking valid checksum if ack_packet[1]: # adding packets into the window to be sent if ack_packet[0] == 'Ack': print("Ack received") window.remove_packets(ack_packet[2]) file_chunks = file_reader.get_chunk( window.get_packet_space()) # removing empty chunks if they are present if file_chunks[-1] == b'': file_chunks = list(filter(None, file_chunks)) # after removing all the empty chunks, add one more blank if the last packet is exactly 1452 if file_chunks: if len(file_chunks[-1]) == 1452: file_chunks.append(b'') else: file_chunks.append(b'') packets = [] for chunk in file_chunks: if len(chunk) == 1452: packets.append( Packet.data(self.seq_number, chunk, self.port, d_port)) self.up_sequence_number(len(chunk)) else: packets.append( Packet.data(self.seq_number, chunk, self.port, d_port, fin=True)) print("final packet created") print(packets[-1].sequence_number) done = True window.add_packets(packets) window.send(sock_to_send, d_address, d_port) # If the ack packet is instead an error packet, print error, dropped acked packets, then resend elif ack_packet[0] == 'Err': print("Error returned: " + str(ack_packet[2]) + " " + str(ack_packet[3])) print( "Fixing checksums, moving acked packets out of window, and resending..." ) window.re_checksum() window.remove_packets(ack_packet[4], error=True) if window.get_packet_space() > 0: file_chunks = file_reader.get_chunk( window.get_packet_space()) # removing empty chunks if they are present if file_chunks[-1] == b'': file_chunks = list(filter(None, file_chunks)) # after removing all the empty chunks, add one more blank if the last packet is exactly 1452 if file_chunks: if len(file_chunks[-1]) == 1452: file_chunks.append(b'') else: file_chunks.append(b'') packets = [] for chunk in file_chunks: if len(chunk) == 1452: packets.append( Packet.data(self.seq_number, chunk, self.port, d_port)) self.up_sequence_number(len(chunk)) else: packets.append( Packet.data(self.seq_number, chunk, self.port, d_port, fin=True)) done = True window.add_packets(packets) window.send(sock_to_send, d_address, d_port) else: error_packet = Packet.error(0, d_port, self.port, self.seq_number, in_message="Checksum error") sock_to_send.sendto(error_packet.binary_combine(), d_address) self.up_sequence_number(len(error_packet)) except socket.timeout as e: print("Receiving ack timeout, resending...") window.send(sock_to_send, d_address, d_port) sock_to_send.settimeout(2) final_packet_received = False while not final_packet_received: try: final_packet, address = sock_to_send.recvfrom(1472) final_info = Packet.read_packet(final_packet) if final_info[1]: if final_info[0] == "Ack": window.remove_packets(final_info[2]) if window.get_packet_space() == win_size: print("Final ack received, closing connection") sock_to_send.close() final_packet_received = True else: print("Final ack not received, sending whats left") window.send(sock_to_send, d_address, d_port) except socket.timeout as e: print("Final ack timed out, trying to resend") window.send(sock_to_send, d_address, d_port)
def _create_rect_selector(self, _dir, image_list, target_dir): self._window = Window(_dir, image_list, target_dir)
# main.py import pygame pygame.init() from game import Game from window import Window window = Window(pygame) ENTITY_SIZE = 20 running = True game = Game(window) # Main Game Loop while running: # in milliseconds TODO replace with clock pygame.time.delay(100) game.update() game.draw() pygame.display.update() # If loop is broken; quit game and close window pygame.quit()
class TestMainWindow(unittest.TestCase): """Test interface of the GDBee application.""" # ---------------------------------------------------------------------- @classmethod def setUpClass(cls): """Prepare the application configuration and the context.""" super(TestMainWindow, cls).setUpClass() setattr(cls, 'local_gdb', Geodatabase('NYC.gdb')) return # ---------------------------------------------------------------------- def setUp(self): """Restart application before each unit test.""" self.app = QApplication([]) self.ui = Window() self.menu = self.ui.menuBar() self.file_menu = self.menu.actions()[0] self.result_menu = self.menu.actions()[1] self.settings_menu = self.menu.actions()[2] self.tab = None QTest.qWaitForWindowExposed(self.ui) return # ---------------------------------------------------------------------- def tearDown(self): """Clean up after the tests.""" pass # ---------------------------------------------------------------------- def test_create_new_query_tab(self): """Create a new tab triggering the actions and using the keyboard.""" self.assertEqual(self._get_tabs_count(), 0) self._add_new_query_tab() self.assertEqual(self._get_tabs_count(), 1) QTest.keyPress(self.ui, Qt.Key_N, Qt.ControlModifier) self.assertEqual(self._get_tabs_count(), 2) return # ---------------------------------------------------------------------- def test_create_multiple_tabs(self): """Create several tabs.""" self.assertEqual(self._get_tabs_count(), 0) for _i in range(3): self.tab = self._add_new_query_tab() self.assertEqual(self._get_tabs_count(), 3) self.assertEqual(self.ui.tab_widget.tabText(2), 'Query 3') return # ---------------------------------------------------------------------- def test_close_current_tab(self): """Close the current tab triggering the action and using keyboard.""" self.assertEqual(self._get_tabs_count(), 0) self.tab = self._add_new_query_tab() self.tab = self._add_new_query_tab() self.assertEqual(self._get_tabs_count(), 2) self.ui.tab_widget.removeTab(0) self.assertEqual(self._get_tabs_count(), 1) QTest.keyPress(self.ui, Qt.Key_W, Qt.ControlModifier) self.assertEqual(self._get_tabs_count(), 0) return # ---------------------------------------------------------------------- def test_execute_sql(self): """Execute SQL query to a connected geodatabase.""" self.assertEqual(self._get_tabs_count(), 0) self.tab = self._add_new_query_tab() self.assertEqual(self._get_tabs_count(), 1) self._execute_sql('SELECT Name, Type, Oneway FROM streets LIMIT 3') self.assertEqual(self.tab.table.table_data.headers, ['NAME', 'TYPE', 'ONEWAY']) self.assertEqual(self.tab.table.table_data.number_layer_rows, 3) self.assertEqual(self.tab.table.table_data.columnCount(), 3) return # ---------------------------------------------------------------------- def test_include_shape_in_result(self): """Include or exclude shape column from the result set.""" self.assertEqual(self._get_tabs_count(), 0) self.tab = self._add_new_query_tab() self.assertEqual(self._get_tabs_count(), 1) # having the shape column excluded by default self.assertTrue(self.ui.do_include_geometry.isChecked()) self.tab.gdb = self.local_gdb self.tab = self.ui.tab_widget.currentWidget() self.tab.query.setPlainText( 'SELECT Name, Type, Oneway, Shape FROM streets LIMIT 3') self.tab.run_query() self.assertEqual(self.tab.table.table_data.number_layer_rows, 3) self.assertEqual(self.tab.table.table_data.columnCount(), 4) # enable getting geometry columns into the output self.ui.do_include_geometry.setChecked(False) self.assertFalse(self.ui.do_include_geometry.isChecked()) self.tab.run_query() self.assertEqual(self.tab.table.table_data.number_layer_rows, 3) self.assertEqual(self.tab.table.table_data.columnCount(), 3) return # ---------------------------------------------------------------------- def test_export_qgis(self): """Export result of SQL query execution to WKT. The result WKT can be open using QGIS QuickWKT plugin. """ self._prepare_for_export() self.ui.export_result(None, '&QGIS') self.assertEqual( len(self.ui.export_result_window.result.toPlainText().split('\n')), 3) self.assertIn('MULTILINESTRING', self.ui.export_result_window.result.toPlainText()) self.ui.export_result_window.close() return # ---------------------------------------------------------------------- def test_export_markdown(self): """Export result of SQL query execution to a Markdown text.""" self._prepare_for_export() self.ui.export_result(None, '&Markdown') tabulate_found = pkgutil.get_loader('tabulate') if not tabulate_found: raise ValueError( 'Tabulate package should be installed before running this test') self.assertEqual( len(self.ui.export_result_window.result.toPlainText().split('\n')), 5) self.ui.export_result_window.close() return # ---------------------------------------------------------------------- def test_export_pandas(self): """Export result of SQL query execution to a pandas data frame.""" self._prepare_for_export() self.ui.export_result(None, '&DataFrame') self.assertIn('.csv', self.ui.export_result_window.result.toPlainText()) self.ui.export_result_window.close() return # ---------------------------------------------------------------------- def test_export_arcmap(self): """Export result of SQL query execution to arcpy to use in ArcMap.""" self._prepare_for_export() self.ui.export_result(None, '&ArcMap') text = self.ui.export_result_window.result.toPlainText() self.assertTrue([(w in text) for w in ['arcpy', 'MULTILINESTRING']]) self.ui.export_result_window.close() return # ---------------------------------------------------------------------- def test_export_before_execute_sql(self): """Export result table before any SQL query is executed.""" self.assertEqual(self._get_tabs_count(), 0) self.tab = self._add_new_query_tab() self.ui.export_result(None, '&DataFrame') return # ---------------------------------------------------------------------- def test_export_md_with_no_tabulate_installed(self): """Export to markdown table with no tabulate package installed.""" # TODO: implement test pass # ---------------------------------------------------------------------- def test_export_markdown_large_table(self): """Export table with more than 1K rows; goes into .md file.""" self.tab = self._add_new_query_tab() self._execute_sql( 'SELECT Name, Type, Oneway, Shape FROM streets LIMIT 1001') self.ui.export_result(None, '&Markdown') tabulate_found = pkgutil.get_loader('tabulate') if not tabulate_found: raise ValueError( 'Tabulate package should be installed before running this test') self.assertIn('.md', self.ui.export_result_window.result.toPlainText()) self.ui.export_result_window.close() return # ---------------------------------------------------------------------- def test_add_new_tab_after_gdb_is_set(self): """Add a tab, set its gdb, and then add another tab.""" self.tab = self._add_new_query_tab() self.tab.gdb = self.local_gdb self.tab2 = self._add_new_query_tab() self.assertEqual(self.tab2.gdb, self.tab.gdb) return # ---------------------------------------------------------------------- def test_trigger_sql_error(self): """Execute an invalid SQL query.""" self.tab = self._add_new_query_tab() self._execute_sql('SELECT invalid_column FROM streets LIMIT 3') self.assertTrue(self.tab.errors_panel.isVisible()) self.assertIn('no such column', self.tab.errors_panel.toPlainText()) self._execute_sql('SELECT * FROM streets LIMIT 3') self.assertFalse(self.tab.errors_panel.isVisible()) return # ---------------------------------------------------------------------- def test_connecting_to_invalid_gdb(self): """Browse to a folder with that is not a valid file gdb.""" self.tab = self._add_new_query_tab() self._execute_sql('SELECT Name FROM streets LIMIT 1', r'C:\Non\Existing\Path\Database.gdb') # make sure the application still works self.tab = self._add_new_query_tab() self._execute_sql('SELECT Name, Type, Oneway FROM streets LIMIT 3') self.assertEqual(self.tab.table.table_data.number_layer_rows, 3) self.assertEqual(self.tab.table.table_data.columnCount(), 3) return # ---------------------------------------------------------------------- def test_parsing_sql_code_comments(self): """Execute multiple SQL queries each containing various comments.""" self.tab = self._add_new_query_tab() sql_query_string = """ select name --table from streets /* block comment */ limit 3 """ self._prepare_query_text(sql_query_string) self.tab.run_query() self.assertTrue(self.tab.table.isVisible()) self.assertEqual(self.tab.table.table_data.number_layer_rows, 3) self.assertEqual(self.tab.table.table_data.columnCount(), 1) return # ---------------------------------------------------------------------- def test_execute_sql_query_selection(self): """Execute only selected part of the SQL query.""" self.tab = self._add_new_query_tab() sql_query_string = 'SELECT name FROM streets LIMIT 3\n UPDATE' self._prepare_query_text(sql_query_string) self.tab.run_query() self.assertTrue(self.tab.errors_panel.isVisible()) self.assertIn('UPDATE', self.tab.errors_panel.toPlainText()) # position cursor before `\n` in the SQL query cur_pos = 32 cur = self.tab.query.textCursor() cur.setPosition(0) cur.setPosition(cur_pos, QTextCursor.KeepAnchor) self.tab.query.setTextCursor(cur) self.assertEqual(self.tab.query.textCursor().selectedText(), sql_query_string[:cur_pos]) self.tab.run_query() self.assertFalse(self.tab.errors_panel.isVisible()) self.assertTrue(self.tab.table.isVisible()) self.assertEqual(self.tab.table.table_data.number_layer_rows, 3) self.assertEqual(self.tab.table.table_data.columnCount(), 1) return # ---------------------------------------------------------------------- def test_sql_code_styling(self): """Highlight code in SQL query.""" self.tab = self._add_new_query_tab() sql_query_string = 'SELECT name FROM streets LIMIT 3' self._prepare_query_text(sql_query_string) cur = self.tab.query.textCursor() cur.setPosition(0) cur.setPosition(6, QTextCursor.KeepAnchor) self.tab.query.setTextCursor(cur) return # ---------------------------------------------------------------------- def test_copy_result_table_row(self): """Select and copy a row into a clipboard.""" self.tab = self._add_new_query_tab() sql_query_string = """ SELECT name, type FROM streets ORDER BY name desc, type desc LIMIT 1 """ self._prepare_query_text(sql_query_string) self._execute_sql(sql_query_string) self.tab.table.view.model().fetchMore( ) # need to load into `rows` from OGR layer self.assertEqual(len(self.tab.table.view.model().rows), 1) self.tab.table.view.selectRow(0) QTest.keyPress(self.tab.table.view, Qt.Key_C, Qt.ControlModifier) cp = self.app.clipboard().text() parsed_cp = [i.split('\t') for i in cp.split('\n') if i] self.assertEqual(parsed_cp[0], ['NAME', 'TYPE']) self.assertEqual(parsed_cp[1], ['Zwicky Ave', 'residential']) return # ---------------------------------------------------------------------- def test_copy_result_table_cell(self): """Select and copy a column cell value into a clipboard.""" self.tab = self._add_new_query_tab() sql_query_string = """ SELECT name, type FROM streets ORDER BY name desc, type desc LIMIT 1 """ self._prepare_query_text(sql_query_string) self._execute_sql(sql_query_string) self.tab.table.view.model().fetchMore( ) # need to load into `rows` from OGR layer tm = self.tab.table.view.model() sm = self.tab.table.view.selectionModel() idx = tm.index(0, 0, QModelIndex()) sm.select(idx, QItemSelectionModel.Select) QTest.keyPress(self.tab.table.view, Qt.Key_C, Qt.ControlModifier) cp = self.app.clipboard().text() self.assertEqual(cp, 'Zwicky Ave') return # ---------------------------------------------------------------------- def test_filling_toc(self): """Fill the toc with gdb tables and their columns.""" self.tab = self._add_new_query_tab() sql_query_string = 'SELECT name FROM streets LIMIT 3' self._execute_sql(sql_query_string) self.tab._set_gdb_items_highlight() self.tab._fill_toc() self.assertEqual( sorted((i.lower() for i in self.tab.gdb_items)), sorted((self.tab.toc.topLevelItem(i).text(0).lower() for i in range(self.tab.toc.topLevelItemCount())))) return # ---------------------------------------------------------------------- def test_expand_collapse_toc(self): """Expand and collapse all items in the toc.""" self.tab = self._add_new_query_tab() sql_query_string = 'SELECT name FROM streets LIMIT 3' self._execute_sql(sql_query_string) self.tab._set_gdb_items_highlight() self.tab._fill_toc() self.ui.toc_expand_all() self.assertTrue( all((self.tab.toc.topLevelItem(i).isExpanded() for i in range(self.tab.toc.topLevelItemCount())))) self.ui.toc_collapse_all() self.assertTrue(not any(( self.tab.toc.topLevelItem(i).isExpanded() for i in range(self.tab.toc.topLevelItemCount())))) return # ---------------------------------------------------------------------- def test_changing_sql_dialects(self): """Choose OGR SQL dialect and execute the SQL query. Use unsupported keyword and then change back to SQLite. """ self.tab = self._add_new_query_tab() sql_query_string = 'SELECT name FROM streets' self.tab.gdb_sql_dialect_combobox.setCurrentText('OGRSQL') self._execute_sql(sql_query_string) streets_count = 19091 self.assertEqual(self.tab.table.table_data.number_layer_rows, streets_count) sql_query_string = 'select st_x(shape) from homicides limit 5' self._execute_sql(sql_query_string) self.assertIn('Undefined function', self.tab.errors_panel.toPlainText()) self.tab.gdb_sql_dialect_combobox.setCurrentText('SQLite') self._execute_sql(sql_query_string) self.assertEqual(self.tab.table.table_data.number_layer_rows, 5) return # ---------------------------------------------------------------------- def _prepare_query_text(self, sql_query): """Put SQL query string into a tab.""" self.tab.gdb = self.local_gdb sql_query_string = sql_query self.tab.query.setText(sql_query_string) return # ---------------------------------------------------------------------- def _prepare_for_export(self): """Prepare data for exporting the result set.""" self.assertEqual(self._get_tabs_count(), 0) self.tab = self._add_new_query_tab() self.assertEqual(self._get_tabs_count(), 1) self.tab.gdb = (self.local_gdb) self.tab = self.ui.tab_widget.currentWidget() self.tab.query.setPlainText( 'SELECT Name, Type, Oneway, Shape FROM streets LIMIT 3') self.tab.run_query() self.assertEqual(self.tab.table.table_data.number_layer_rows, 3) self.assertEqual(self.tab.table.table_data.columnCount(), 4) return # ---------------------------------------------------------------------- def _execute_sql(self, sql, user_gdb=None): """Execute SQL query in the current tab.""" self.tab = self.ui.tab_widget.currentWidget() if user_gdb: self.tab.gdb = Geodatabase(user_gdb) else: self.tab.gdb = self.local_gdb self.tab.query.setPlainText(sql) self.tab.run_query() return # ---------------------------------------------------------------------- def _get_tabs_count(self): """Get number of tabs in the tabbed widget.""" return len(self.ui.tab_widget.tabBar()) # ---------------------------------------------------------------------- def _add_new_query_tab(self): """Add a new tab with empty query and empty result table.""" new_query_action = self.file_menu.menu().actions()[0] new_query_action.trigger() return self.ui.tab_widget.currentWidget()
class Installer(object): def __init__(self, install_config, maxy=0, maxx=0, iso_installer=False, rpm_path="../stage/RPMS", log_path="../stage/LOGS", ks_config=None): self.install_config = install_config self.ks_config = ks_config self.iso_installer = iso_installer self.rpm_path = rpm_path self.log_path = log_path self.mount_command = "./mk-mount-disk.sh" self.prepare_command = "./mk-prepare-system.sh" self.finalize_command = "./mk-finalize-system.sh" self.install_package_command = "./mk-install-package.sh" self.chroot_command = "./mk-run-chroot.sh" self.setup_grub_command = "./mk-setup-grub.sh" self.unmount_disk_command = "./mk-unmount-disk.sh" if self.iso_installer: self.working_directory = "/mnt/photon-root" elif 'working_directory' in self.install_config: self.working_directory = self.install_config['working_directory'] else: self.working_directory = "/mnt/photon-root" self.photon_root = self.working_directory + "/photon-chroot" self.restart_command = "shutdown" if self.iso_installer: self.output = open(os.devnull, 'w') else: self.output = None if self.iso_installer: #initializing windows self.maxy = maxy self.maxx = maxx self.height = 10 self.width = 75 self.progress_padding = 5 self.progress_width = self.width - self.progress_padding self.starty = (self.maxy - self.height) / 2 self.startx = (self.maxx - self.width) / 2 self.window = Window(self.height, self.width, self.maxy, self.maxx, 'Installing Photon', False) self.progress_bar = ProgressBar( self.starty + 3, self.startx + self.progress_padding / 2, self.progress_width) signal.signal(signal.SIGINT, self.exit_gracefully) # This will be called if the installer interrupted by Ctrl+C or exception def exit_gracefully(self, signal, frame): if self.iso_installer: self.progress_bar.hide() self.window.addstr( 0, 0, 'Opps, Installer got inturrupted.\n\nPress any key to get to the bash...' ) self.window.content_window().getch() sys.exit(1) def install(self, params): try: return self.unsafe_install(params) except: if self.iso_installer: self.exit_gracefully(None, None) else: raise def unsafe_install(self, params): if self.iso_installer: self.window.show_window() self.progress_bar.initialize('Initializing installation...') self.progress_bar.show() self.execute_modules(modules.commons.PRE_INSTALL) self.initialize_system() #install packages for rpm in self.rpms_tobeinstalled: # We already installed the filesystem in the preparation if rpm['package'] == 'filesystem': continue if self.iso_installer: self.progress_bar.update_message('Installing {0}...'.format( rpm['package'])) return_value = self.install_package(rpm['filename']) if return_value != 0: self.exit_gracefully(None, None) if self.iso_installer: self.progress_bar.increment(rpm['size'] * self.install_factor) if self.iso_installer: self.progress_bar.show_loading('Finalizing installation') self.finalize_system() if not self.install_config['iso_system']: # Execute post installation modules self.execute_modules(modules.commons.POST_INSTALL) # install grub try: if self.install_config['boot'] == 'bios': process = subprocess.Popen([ self.setup_grub_command, '-w', self.photon_root, "bios", self.install_config['disk']['disk'], self.install_config['disk']['root'] ], stdout=self.output) elif self.install_config['boot'] == 'efi': process = subprocess.Popen([ self.setup_grub_command, '-w', self.photon_root, "efi", self.install_config['disk']['disk'], self.install_config['disk']['root'] ], stdout=self.output) except: #install bios if variable is not set. process = subprocess.Popen([ self.setup_grub_command, '-w', self.photon_root, "bios", self.install_config['disk']['disk'], self.install_config['disk']['root'] ], stdout=self.output) retval = process.wait() process = subprocess.Popen( [self.unmount_disk_command, '-w', self.photon_root], stdout=self.output) retval = process.wait() if self.iso_installer: self.progress_bar.hide() self.window.addstr( 0, 0, 'Congratulations, Photon has been installed in {0} secs.\n\nPress any key to continue to boot...' .format(self.progress_bar.time_elapsed)) if self.ks_config == None: self.window.content_window().getch() return ActionResult(True, None) def download_file(self, url, directory): # TODO: Add errors handling urlopener = urllib.URLopener() urlopener.retrieve(url, os.path.join(directory, os.path.basename(url))) def download_rpms(self): repodata_dir = os.path.join(self.photon_root, 'RPMS/repodata') process = subprocess.Popen(['mkdir', '-p', repodata_dir], stdout=self.output) retval = process.wait() import hawkey self.install_factor = 1 # Load the repo data sack = hawkey.Sack() repomd_filename = "repomd.xml" repomd_url = os.path.join(self.rpm_path, "repodata/repomd.xml") self.download_file(repomd_url, repodata_dir) # parse to the xml to get the primary and files list tree = ET.parse(os.path.join(repodata_dir, repomd_filename)) # TODO: Get the namespace dynamically from the xml file ns = {'ns': 'http://linux.duke.edu/metadata/repo'} primary_location = tree.find("./ns:data[@type='primary']/ns:location", ns).get("href") filelists_location = tree.find( "./ns:data[@type='filelists']/ns:location", ns).get("href") primary_filename = os.path.basename(primary_location) filelists_filename = os.path.basename(filelists_location) self.download_file(os.path.join(self.rpm_path, primary_location), repodata_dir) self.download_file(os.path.join(self.rpm_path, filelists_location), repodata_dir) repo = hawkey.Repo("installrepo") repo.repomd_fn = os.path.join(repodata_dir, repomd_filename) repo.primary_fn = os.path.join(repodata_dir, primary_filename) repo.filelists_fn = os.path.join(repodata_dir, filelists_filename) sack.load_yum_repo(repo, load_filelists=True) progressbar_num_items = 0 self.rpms_tobeinstalled = [] selected_packages = self.install_config['packages'] for package in selected_packages: # Locate the package q = hawkey.Query(sack).filter(name=package) if (len(q) > 0): progressbar_num_items += q[ 0].size + q[0].size * self.install_factor self.rpms_tobeinstalled.append({ 'package': package, 'size': q[0].size, 'location': q[0].location, 'filename': os.path.basename(q[0].location) }) else: print >> sys.stderr, "Package %s not found in the repo" % package #self.exit_gracefully(None, None) self.progress_bar.update_num_items(progressbar_num_items) # Download the rpms for rpm in self.rpms_tobeinstalled: message = 'Downloading {0}...'.format(rpm['filename']) self.progress_bar.update_message(message) self.download_file(os.path.join(self.rpm_path, rpm['location']), os.path.join(self.photon_root, "RPMS")) self.progress_bar.increment(rpm['size']) # update the rpms path self.rpm_path = os.path.join(self.photon_root, "RPMS") def copy_rpms(self): # prepare the RPMs list self.install_factor = 3 rpms = [] for root, dirs, files in os.walk(self.rpm_path): for name in files: file = os.path.join(root, name) size = os.path.getsize(file) rpms.append({'filename': name, 'path': file, 'size': size}) progressbar_num_items = 0 self.rpms_tobeinstalled = [] selected_packages = self.install_config['packages'] for package in selected_packages: pattern = package + '-[0-9]*.rpm' for rpm in rpms: if fnmatch.fnmatch(rpm['filename'], pattern): rpm['package'] = package self.rpms_tobeinstalled.append(rpm) progressbar_num_items += rpm[ 'size'] + rpm['size'] * self.install_factor break if self.iso_installer: self.progress_bar.update_num_items(progressbar_num_items) # Copy the rpms for rpm in self.rpms_tobeinstalled: if self.iso_installer: message = 'Copying {0}...'.format(rpm['filename']) self.progress_bar.update_message(message) shutil.copy(rpm['path'], self.photon_root + '/RPMS/') if self.iso_installer: self.progress_bar.increment(rpm['size']) def copy_files(self): # Make the photon_root directory if not exits process = subprocess.Popen(['mkdir', '-p', self.photon_root], stdout=self.output) retval = process.wait() # Copy the installer files process = subprocess.Popen( ['cp', '-r', "../installer", self.photon_root], stdout=self.output) retval = process.wait() # Create the rpms directory process = subprocess.Popen(['mkdir', '-p', self.photon_root + '/RPMS'], stdout=self.output) retval = process.wait() if self.rpm_path.startswith("http://"): self.download_rpms() else: self.copy_rpms() def initialize_system(self): #Setup the disk if (not self.install_config['iso_system']): process = subprocess.Popen([ self.mount_command, '-w', self.photon_root, self.install_config['disk']['root'] ], stdout=self.output) retval = process.wait() self.copy_files() #Setup the filesystem basics process = subprocess.Popen( [self.prepare_command, '-w', self.photon_root], stdout=self.output) retval = process.wait() def finalize_system(self): #Setup the disk process = subprocess.Popen([ self.chroot_command, '-w', self.photon_root, self.finalize_command, '-w', self.photon_root ], stdout=self.output) retval = process.wait() initrd_dir = 'boot' initrd_file_name = 'initrd.img-no-kmods' if self.iso_installer: # just copy the initramfs /boot -> /photon_mnt/boot shutil.copy(os.path.join(initrd_dir, initrd_file_name), self.photon_root + '/boot/') # remove the installer directory process = subprocess.Popen( ['rm', '-rf', os.path.join(self.photon_root, "installer")], stdout=self.output) retval = process.wait() else: #Build the initramfs by passing in the kernel version version_string = '' for root, dirs, files in os.walk(self.rpm_path): for name in files: if fnmatch.fnmatch(name, 'linux-[0-9]*.rpm'): version_array = name.split('-') if len(version_array) > 2: version_string = version_array[1] if 'initrd_dir' in self.install_config: initrd_dir = self.install_config['initrd_dir'] process = subprocess.Popen([ self.chroot_command, '-w', self.photon_root, './mkinitramfs', '-n', os.path.join(initrd_dir, initrd_file_name), '-k', version_string ], stdout=self.output) retval = process.wait() def install_package(self, package_name): rpm_params = '' os.environ["RPMROOT"] = self.rpm_path rpm_params = rpm_params + ' --force ' rpm_params = rpm_params + ' --root ' + self.photon_root rpm_params = rpm_params + ' --dbpath /var/lib/rpm ' if ('type' in self.install_config and (self.install_config['type'] in ['micro', 'minimal'])) or self.install_config['iso_system']: rpm_params = rpm_params + ' --excludedocs ' process = subprocess.Popen([ self.install_package_command, '-w', self.photon_root, package_name, rpm_params ], stdout=self.output) return process.wait() def execute_modules(self, phase): modules = glob.glob('modules/m_*.py') for mod_path in modules: module = mod_path.replace('/', '.', 1) module = os.path.splitext(module)[0] try: __import__(module) mod = sys.modules[module] except ImportError: print >> sys.stderr, 'Error importing module %s' % module continue # the module default is disabled if not hasattr(mod, 'enabled') or mod.enabled == False: print >> sys.stderr, "module %s is not enabled" % module continue # check for the install phase if not hasattr(mod, 'install_phase'): print >> sys.stderr, "Error: can not defind module %s phase" % module continue if mod.install_phase != phase: print >> sys.stderr, "Skipping module %s for phase %s" % ( module, phase) continue if not hasattr(mod, 'execute'): print >> sys.stderr, "Error: not able to execute module %s" % module continue mod.execute(module, self.ks_config, self.install_config, self.photon_root) def run(self, command, comment=None): if comment != None: print >> sys.stderr, "Installer: {} ".format(comment) self.progress_bar.update_loading_message(comment) print >> sys.stderr, "Installer: {} ".format(command) process = subprocess.Popen([command], shell=True, stdout=self.output) retval = process.wait() return retval
def __init__(self, filename): self.__window = Window(filename)
""" Nom : Jet Pack Game Présentation du jeu (à venir) Par Jordan Courné Version : 0.5 (Pré Alpha) """ ### - main.py - ### """ Date de la création du fichier : 03/07/2017 Date de la dernière édition du fichier : 20/08/2017 """ ### import ### from window import Window from menu import Menu ### Main ### tailleFenetreLargeur = 1300 fenetre = Window(tailleFenetreLargeur) menu = Menu(fenetre) repeat = True while repeat: menu.afficherMenu(fenetre) fenetre.actualiser() menu.selection(fenetre)
class PackageSelector(object): def __init__(self, maxy, maxx, install_config, options_file): self.install_config = install_config self.maxx = maxx self.maxy = maxy self.win_width = 50 self.win_height = 13 self.win_starty = (self.maxy - self.win_height) / 2 self.win_startx = (self.maxx - self.win_width) / 2 self.menu_starty = self.win_starty + 3 self.load_package_list(options_file) self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx, 'Select Installation', True, self.package_menu, can_go_next=True, position=1) @staticmethod def get_packages_to_install(options, config_type, output_data_path): package_list = [] for install_option in options: if install_option[0] == config_type: for include_type in install_option[1]["include"]: package_list = package_list + PackageSelector.get_packages_to_install(options, include_type, output_data_path) json_wrapper_package_list = JsonWrapper(os.path.join(output_data_path, install_option[1]["file"])) package_list_json = json_wrapper_package_list.read() package_list = package_list + package_list_json["packages"] break return package_list @staticmethod def get_additional_files_to_copy_in_iso(options, base_path, config_type): additional_files = [] for install_option in options: if install_option[0] == config_type: if install_option[1].has_key("additional-files"): additional_files = install_option[1]["additional-files"] break return additional_files def load_package_list(self, options_file): json_wrapper_option_list = JsonWrapper(options_file) option_list_json = json_wrapper_option_list.read() options_sorted = option_list_json.items() self.package_menu_items = [] base_path = os.path.dirname(options_file) package_list = [] default_selected = 0 visible_options_cnt = 0 for install_option in options_sorted: if install_option[1]["visible"] == True: package_list = PackageSelector.get_packages_to_install(options_sorted, install_option[0], base_path) additional_files = PackageSelector.get_additional_files_to_copy_in_iso(options_sorted, base_path, install_option[0]) self.package_menu_items.append((install_option[1]["title"], self.exit_function, [install_option[0], package_list, additional_files] )) if install_option[0] == 'minimal': default_selected = visible_options_cnt visible_options_cnt = visible_options_cnt + 1 self.package_menu = Menu(self.menu_starty, self.maxx, self.package_menu_items, default_selected = default_selected, tab_enable=False) def exit_function(self, selected_item_params): self.install_config['type'] = selected_item_params[0]; self.install_config['packages'] = selected_item_params[1]; self.install_config['additional-files'] = selected_item_params[2] return ActionResult(True, {'custom': False}) def custom_packages(self, params): return ActionResult(True, {'custom': True}) def display(self, params): return self.window.do_action()
class Monitor: """ This code Implements a very simple version of the display that is meant to be used by VNenergy. This includes a nice logo and a formatted configuration. """ def __init__(self, width=1920, height=1080): # Create Screen with the provided resolution self.width = width #1920 self.height = height #1080 self.screen = Screen(width, height) self.logo = self.screen.load_image("logo.png") #self.logo = self.screen.scale(self.logo, 500,100) #self.screen.set_fps(10) # NOTE: Remove comment on next line to add Full screen #self.screen.set_full_screen() size = self.screen.get_size() self.border = 10 b = self.border # Just to make the next line more readable self.battery = Battery(self.screen, x=20, y=self.height - 355, width=140, height=300) # Creates a wyndow with a margin to make it pritty <3 self.window = Window(self.screen, b + 180, b + 130, size[0] - (b * 2 + 270), size[1] - (b * 2 + 180)) self.window.set_all_colors((100, 100, 100)) self.window.set_border_color((200, 200, 200)) self.window.set_border_width(10) self.chart_og = Chart() self.chart_og.set_width(8) self.chart_og.set_color((255, 150, 0)) self.chart_og.add_point([1, 0]) self.chart_og.add_point([2, 0]) self.window.add_chart(self.chart_og) self.chart_optimised = Chart() self.chart_optimised.set_width(8) self.chart_optimised.set_color((0, 150, 255)) self.chart_optimised.add_point([1, 0]) self.chart_optimised.add_point([2, 0]) self.window.add_chart(self.chart_optimised) # Next we add a function that converts the X values to # something the window class can work with, simple numbers # the window class does not know how to handle dates # so they need to be converted to intigers. These X values # are still used as labels in the x axis so format them # wisely. # NOTE: Remove comment on the fallowing line to add convertion function #self.chart.set_conv_funct(self.convert) self.data = Value(self.screen, 22, 150) def clear_charts(self): self.chart_og.clear() self.chart_optimised.clear() self.chart_og.add_point([1, 0]) self.chart_og.add_point([2, 0]) self.chart_optimised.add_point([1, 0]) self.chart_optimised.add_point([2, 0]) def convert(self, data): """ onverts the data so that its in a format that can be later understood. """ d = data.split(":") x = float(d[0]) * 60 + float(d[1]) return [x, data[1]] def set_soc(self, value): self.data.set_value(value) self.battery.set_soc(abs(value)) def add_data(self, data, data2): self.screen.clear() self.chart_og.add_point(data) self.chart_optimised.add_point(data2) # NOTE: Remove comment the fallowing line to add convertion function #self.convert() # This must be called if you have a convertion function self.window.draw() #self.battery.set_soc(abs(data[1])) self.battery.draw() self.data.draw() self.screen.draw_image(self.logo, [20, 30]) return self.screen.render() def close(self): self.screen.close() ### def test(self): counter = 1 while (self.add_data([counter, sin(counter * 0.01) * 100]) != -1): counter += 10 print "Closing" self.close()
def create(self, line_format_factory, args): return Window( Table_Model_Factory(line_format_factory, Is_Dark_Theme_Detector()), Events_Factory(), args)