def loop(self): global gui a = 0 b = 0 c = 0 d = 0 while 1: e.update() self.surf.fill((0,0,0)) gui.update() self.recv.update() pygame.display.flip() self.clock.tick() self.averageFPS.append(int(self.clock.get_fps())) if len(self.averageFPS) > 100: a = 0 cnt = 1 for x in self.averageFPS: a = a + x cnt = cnt + 1 a = a / cnt gui.setValueBoxValue("FPS", int(a)) gui.addGraphEntry("APM", 0, int(a)) self.averageFPS = []
def parse_new_wallet(s): show_main() gui.update(30) # wallet format: # name&descriptor arr = s.split("&") if len(arr) != 2: gui.error("Invalid wallet format") return w = keystore.check_new_wallet(*arr) keys_str = [] for key in w.keys: k = ("%r" % key).replace("]", "]\n") if keystore.owns_key(key): keys_str.append("#7ED321 My key: # %s" % k) else: keys_str.append("#F5A623 External key: # %s" % k) keys = "\n\n".join(keys_str) if w.script_type not in SUPPORTED_SCRIPTS.keys(): raise ValueError("Script type \"%s\" is not supported" % w.script_type) sc = w.script_type msg = "Policy: %s\nScript: %s\n%s\n\n%s" % (w.policy, SUPPORTED_SCRIPTS[w.script_type], sc, keys) scr = popups.prompt("Add wallet \"%s\"?" % arr[0], msg, ok=cb_with_args(new_wallet_confirm, name=arr[0], descriptor=arr[1])) scr.message.set_recolor(True)
def show_xpub(name, derivation, xpub=None): xpubs_menu() gui.update(30) try: if xpub is None: xpub = keystore.get_xpub(derivation) prefix = "[%s]" % bip32.path_to_str(bip32.parse_path(derivation), fingerprint=keystore.fingerprint) except: gui.error("Derivation path \"%s\" doesn't look right..." % derivation) return xpub_str = xpub.to_base58(network["xpub"]) slip132 = xpub.to_base58() if slip132 == xpub_str: slip132 = None popups.show_xpub(name, xpub_str, slip132=slip132, prefix=prefix)
def confirm_new_wallet(s): show_main() gui.update(30) # wallet format: # name&descriptor arr = s.split("&") if len(arr) != 2: gui.error("Invalid wallet format") return try: keystore.check_new_wallet(*arr) except Exception as e: gui.error("%r" % e) return popups.prompt("Add wallet \"%s\"?" % arr[0], arr[1], ok=cb_with_args(new_wallet_confirm, name=arr[0], descriptor=arr[1]))
def update(dt): if dt > 0.25: dt = 0.25 global wave_iter, wave_cond if wave_iter and wave_cond(): try: wave_cond = next(wave_iter) except StopIteration: wave_iter = None manager.update(dt) manager.process_events() gui.update() render.update(dt) text.update(dt)
def microphone_update(audio_samples): global y_roll # Normalize samples between 0 and 1 y = audio_samples / 2.0**15 # Construct a rolling window of audio samples y_roll[:-1] = y_roll[1:] y_roll[-1, :] = np.copy(y) y_data = np.concatenate(y_roll, axis=0).astype(np.float32) vol = np.max(np.abs(y_data)) if vol < config.MIN_VOLUME_THRESHOLD: print('No audio input. Volume below threshold. Volume:', vol) led.pixels = np.tile(0, (3, config.N_PIXELS)) led.update() else: # Transform audio input into the frequency domain N = len(y_data) N_zeros = 2**int(np.ceil(np.log2(N))) - N # Pad with zeros until the next power of two y_data *= fft_window y_padded = np.pad(y_data, (0, N_zeros), mode='constant') YS = np.abs(np.fft.rfft(y_padded)[:N // 2]) # Construct a Mel filterbank from the FFT data mel = np.atleast_2d(YS).T * dsp.mel_y.T # Scale data to values more suitable for visualization # mel = np.sum(mel, axis=0) mel = np.sum(mel, axis=0) mel = mel**2.0 # Gain normalization mel_gain.update(np.max(gaussian_filter1d(mel, sigma=1.0))) mel /= mel_gain.value mel = mel_smoothing.update(mel) # Map filterbank output onto LED strip output = effect(mel) led.pixels = output led.update() if config.USE_GUI: gui.update(mel) if config.USE_GUI: app.processEvents()
import cv2 import numpy as np import scanner import plot import gui import smooth import webserver cap = cv2.VideoCapture(int(sys.argv[1])) cap.set(cv2.CAP_PROP_FPS, 15) gui.init() while True: gui.update() if gui.paused: continue _, image = cap.read() plot.clear() image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) gui.show(image_rgb, "camera_rgb") image_marker_view = image_rgb.copy() markers = scanner.scan(image) reference = None for marker in markers:
#initialize input options next_atomic_number = 1 #start main loop while running: #process the world while command_ticks > 0: #loop through interactables #process time passage command_ticks -=1 total_ticks += 1 #keep gui updated after all processing has completed gui.update() #get command input command = gui.get_command() #quit if q is pressed if command == 'q': running = False #clear everything or generate world elif command == 'c' or command == 'g': #clear current world c.atoms = [] c.particle = [] gui.camera_position = [0,0] total_ticks = 0
def main_game_loop(): '''Main game loop''' global DISPLAYSURF, FPSCLOCK, DECAL, decal_textures pygame.init() #must call init before any pygame functions are used DISPLAYSURF = pygame.display.set_mode( (SCREENWIDTH, SCREENHEIGHT) ) #creates game window FPSCLOCK = pygame.time.Clock() #Use with .tick() quit_game = False map_data.init() DECAL = {} decal_textures = SpriteAtlas('decal.png', 32, 2, 2) all_sprites_list = pygame.sprite.Group() #Initializes Group #OBJECT_MANAGER = {} '''TESTING''' for i in range(5,12): map_data.data[8][i] = LADDER for j in range(7,10): map_data.data[12][j] = LADDER for x in range(9, 12): for y in range(7,10): map_data.data[x][y] = GRASSL #for i in range(25): unit = Unit(5, 9) #Base class in unit_manager all_sprites_list.add(unit) #/ [random.choice((-5, 5)), random.choice((-5, 5))]) #fps vars fps_avg = 0.0 fps_avg_cntr = 0 fps_sum = 0.0 fps_cntr = 0 fps_text = pygame.font.SysFont('comicsansms.tff', 32) fps_low = 250 fps_high = 0 camera = Camera( SCREENWIDTH / 2, SCREENHEIGHT / 2 ) #textRect = fps_text.render(str(30)).get_rect() '''path = pathfinding.get_path(map_data, MAP_WIDTH, MAP_HEIGHT, pathfinding.Node(0,0), pathfinding.Node(13,10)) for pos in path: rint('{}, {}'.format(pos[0], pos[1]))''' #for t in range(2): map_data.data[15][9] = TREE #set stockpile position and add 5 wood items.init((1,9)) for i in range(2): items.add(items.WOOD) #test_surface = pygame.Surface((50,50),10, 10) #test_surface.set_colorkey gui.init() '''ENDTESTING''' #mouse control vars down_pos = None current_pos = None is_down = False paused = False #all_sprites_list = pygame.sprite.Group() #for run in range(25): while not quit_game: #---EVENTS-------------------------------------------------------------------------------------------------------------------EVENTS--- if is_down: cur_x, cur_y = pygame.mouse.get_pos() event_list = pygame.event.get() for event in event_list: if event.type == pygame.QUIT: quit_game = True pygame.quit() elif event.type == pygame.MOUSEBUTTONDOWN: is_down = True #print('Mouse Down', is_down) down_pos = pygame.mouse.get_pos() elif event.type == pygame.MOUSEBUTTONUP: is_down = False #print('Mouse Down', is_down) #x, y = pygame.mouse.get_pos() if gui.on_gui(cur_x,cur_y) == False: x, y = screen_to_grid(cur_x, cur_y) #add_decal(x, y, 0) #print(x, y) #do stuff at modified points #map_data.set_data(x//TILE_SIZE,y//TILE_SIZE, EMPTY) #print(x,y, map_data.get_data(x, y) ) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: camera.x = camera.x - 1 elif event.key == pygame.K_d: camera.x = camera.x + 1 elif event.key == pygame.K_p: paused = not paused elif event.key == pygame.K_s: items.add(items.WOOD) elif event.key == pygame.K_x: for item in items.item_storage: if items.item_storage[item] > 0: print(items.item_database[item], items.item_storage[item]) if paused: continue all_sprites_list.update() #---DRAW GAME-------------------------------------------------------------------------------------------------------------------DRAW GAME--- DISPLAYSURF.fill(BGCOLOR) #Display FPS fps_cntr += 1 fps = FPSCLOCK.get_fps() fps_sum = fps_sum + fps if fps < fps_low: fps_low = fps if fps > fps_high: fps_high = fps if fps_cntr >= 60: fps_avg_cntr += 1 if fps_avg_cntr > 3: fps_avg = fps_sum / (fps_avg_cntr * fps_cntr) fps_sum = 0 fps_avg_cntr = 0 fps_low = 250 fps_high = 0 fps_cntr = 0 #---Draw Game----------------------------------------------------------------------- draw_map() DISPLAYSURF.blit(fps_text.render('{0:.2f} {1:2.2f} L:{2:.2f} H:{3:.2f}'.format( fps, fps_avg, fps_low, fps_high ), 0, (0,0,0)), [0, 0]) draw_decal() all_sprites_list.draw(DISPLAYSURF) gui.update(DISPLAYSURF) pygame.display.flip() FPSCLOCK.tick(FPS) #Delays until FPS == 1sec, If code finishes before FPS timer
def update(dt=30): gui.update(dt) qr_scanner.update(qr_scanner_error) usb_host.update() QrA.handle()
def scan_address(): screens.show_progress("Scan address to verify", "Scanning.. Click \"Cancel\" to stop.", callback=cancel_scan) gui.update(30) qr_scanner.start_scan(verify_address)
def scan_transaction(): screens.show_progress("Scan transaction to sign", "Scanning.. Click \"Cancel\" to stop.", callback=cancel_scan) gui.update(30) qr_scanner.start_scan(parse_transaction)
def add_new_wallet(): screens.show_progress("Scan wallet to add", "Scanning.. Click \"Cancel\" to stop.", callback=cancel_scan) gui.update(30) qr_scanner.start_scan(parse_new_wallet)
def update(dt=30): gui.update(dt) qr_scanner.update() usb_host.update()
def main(): now = (datetime.datetime.today()).date() gui.setup() #GRABS THE GOALS FOR THE MONTH, QUARTER, AND YEAR FROM OUR EXCEL FILE Reports.goalstxt() #GRABS TECHNICIAN LIST FROM OUR EXCEL FILE OF TECHS WE WANT ON THE SHEET Reports.techstxt() Reports.csrstxt() gui.inputgoals() gui.print("Starting Daily Reports...") time.sleep(2) gui.print("Clearing Directory...") #REPORTS- CLEAR DIRECTORY OF ALL .CSV FILES Reports.cleardir() gui.print("Getting Data File From ServiceTitan...") #REPORTS- GO TO SERVICETITAN AND GRAB NEW CSV FILE Reports.get_reports() gui.print("Processing Data File...") #REPORTS- ANALYZES AND SORTS DATA FROM CSV FILE Reports.csvgetter() gui.print("Clearing Directory Again...") #REPORTS- CLEAR DIRECTORY OF ALL .CSV FILES Reports.cleardir() gui.print("Getting CSR Memberships File From ServiceTitan...") #REPORTS- GO TO SERVICETITAN AND GRAB NEW CSV FILE Reports.get_memberships() gui.print("Processing Memberships File...") #REPORTS- ANALYZES AND SORTS DATA FROM CSV FILE Reports.membershipsgetter() gui.print("Exporting Data to SoldBy Sheet...") #REPORTS SOLDBY SHEET Reports.soldbysheet() gui.print("Exporting Data to SOAC Sheet...") #REPORTS SOAC SHEET Reports.soacsheet() #^ doing these two back-to-back is hitting 95 write requests, will have to wait 100 seconds after them gui.print("Waiting 100 seconds to Bypass Google API limit...") trey1 = os.path.join(sys.path[0], 'trey_1.ico') trey2 = os.path.join(sys.path[0], 'trey_2.ico') for i in range(100, 0, -1): time.sleep(0.25) if (i % 10 == 0): gui.loadingprint(str(i) + " Seconds Left") gui.dots() gui.changeicon(trey2) time.sleep(0.25) gui.changeicon(trey1) time.sleep(0.25) gui.changeicon(trey2) time.sleep(0.25) gui.changeicon(trey1) gui.print("Exporting Data to Slides Sheet...") #REPORTS- SLIDES SHEET Reports.slidessheet() gui.print("Exporting Data to CSR Revenue Sheet...") #REPORTS- REVENUE SHEET Reports.revenuesheet() gui.print("Exporting Data to CSR Club Conversion Sheet...") #REPORTS- CONVERSION RATE SHEET Reports.conversionsheet() # if(now.weekday() == 0): gui.print( "It's Monday! Exporting Data to Weekly Management Meeting Sheet...") #REPORTS- WEEKLY MGMT MEETING SHEET Reports.weeklymgmtsheet() gui.print("ALL DONE! You may now close this window.") gui.update() #KEEPS WINDOW OPEN UNTIL USER CLOSES IT
def main(): pygame.init() #Startup pygame font = pygame.font.Font (None, 10) #Create the font object that will be used to draw things screen = pygame.display.set_mode(DEFAULTSCREENSIZE, HWSURFACE|OPENGL|DOUBLEBUF) resize(DEFAULTSCREENSIZE) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) #Smooth shading #Create one main light glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse) glLightfv(GL_LIGHT1, GL_POSITION,LightPosition) glEnable(GL_LIGHT1) glEnable(GL_LIGHTING) #Enable lighting glClearColor(0, 0, 0, 0.0) glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); clock = pygame.time.Clock() #Clock object for calculating a dt running = True #When this is set to false, the main loop will no longer repeat mousedown = [0, 0] #What position was the mouse at when the left click is first pressed mousecolor = None #What color was under the mouse when the left click is first pressed center = [0,0,0] #Value for storing the center of the current selection of objects (Averages the individual center of the objects in the selection) #This is important because it is where the move tool is drawn #Quick set of utilities for handling the edit mode def isEdit(): #Are we in edit mode? Basically checks to see if any object has its edit value set to True for obj in scene.objects.values(): if obj.edit: return True return False def getEdit(): #What object is currently being edited for obj in scene.objects.values(): if obj.edit: return obj return None def endEdit(): #End edit mode - basically set every single objects edit value to false for obj in scene.objects.values(): obj.edit = False #Main loop while running: gui.update() #Update gui system - handle event polling #Process all pygame events for event in pygame.event.get(): keys = pygame.key.get_pressed() #Quitting if event.type == QUIT: running = False if event.type == KEYUP: if event.key == K_ESCAPE: running = False #Handle deleting of objects from scene if event.key == K_DELETE and not isEdit(): #Can't delete objects in edit mode for obj in scene.objects.values(): if obj.selected: gui.tree_ctrl.Delete(obj.treeitem) del scene.objects[obj.name] #Hitting space duplicates the current selection if event.key == K_SPACE and not isEdit(): #Can't duplicate objects in edit mode for obj in scene.objects.values(): if obj.selected: newobj = obj.duplicate( None ) #The e key enables edit mode if event.key == K_e: if isEdit(): endEdit() else: for obj in scene.objects.values(): if obj.selected: obj.edit = True break print getEdit() if event.type == MOUSEBUTTONDOWN: if event.button == 4: cam.speed *= 1.1 if event.button == 5: cam.speed *= 0.9 if event.button == 1: mousedown = event.pos data = glReadPixels( 0,0, DEFAULTSCREENSIZE[0], DEFAULTSCREENSIZE[1], GL_RGB, GL_UNSIGNED_BYTE) surface = pygame.image.fromstring(str(buffer(data)), DEFAULTSCREENSIZE, 'RGB', True) mousecolor = surface.get_at( (event.pos[0], event.pos[1]) ) if event.type == MOUSEMOTION: relx = -event.rel[0]*0.002*dist( center, [cam.x, cam.y, cam.z] ) rely = event.rel[1]*0.002*dist( center, [cam.x, cam.y, cam.z] ) modelViewMatrix = glGetDouble( GL_MODELVIEW_MATRIX ) projectionMatrix = glGetDouble( GL_PROJECTION_MATRIX ) viewport = glGetInteger(GL_VIEWPORT) if event.buttons[0]: if dist(mousedown, event.pos) > 5: if mousecolor == (0,255,0,255): v = subtract( gluProject(center[0], center[1], center[2], modelViewMatrix, projectionMatrix, viewport), gluProject(center[0], center[1] + 10, center[2], modelViewMatrix, projectionMatrix, viewport) ) v = norm(v) move = dot( [ v[0], v[1] ], [relx, rely] ) for obj in scene.objects.values(): if obj.selected == True: obj.move( 0, move, 0 ) if mousecolor == (255,0,0,255): v = subtract( gluProject(center[0], center[1], center[2], modelViewMatrix, projectionMatrix, viewport), gluProject(center[0] + 10, center[1], center[2], modelViewMatrix, projectionMatrix, viewport) ) v = norm(v) move = dot( [ v[0], v[1] ], [relx, rely] ) for obj in scene.objects.values(): if obj.selected == True: obj.move( move, 0, 0 ) if mousecolor == (0,0,255,255): v = subtract( gluProject(center[0], center[1], center[2], modelViewMatrix, projectionMatrix, viewport), gluProject(center[0], center[1], center[2] + 10, modelViewMatrix, projectionMatrix, viewport) ) v = norm(v) move = dot( [ v[0], v[1] ], [relx, rely] ) for obj in scene.objects.values(): if obj.selected == True: obj.move(0, 0, move) if event.type == MOUSEBUTTONUP: if event.button == 1: if dist(mousedown, event.pos) < 5: if not isEdit(): #You cant select other objects in edit mode if keys[K_LSHIFT]: pass else: for obj in scene.objects.values(): obj.selected = False gui.tree_ctrl.UnselectAll() modelViewMatrix = glGetDouble( GL_MODELVIEW_MATRIX ) projectionMatrix = glGetDouble( GL_PROJECTION_MATRIX ) viewport = glGetInteger(GL_VIEWPORT) ro = gluUnProject( event.pos[0] , DEFAULTSCREENSIZE[1] - event.pos[1], 0.0, modelViewMatrix, projectionMatrix, viewport ) re = gluUnProject( event.pos[0] , DEFAULTSCREENSIZE[1] - event.pos[1], 1.0, modelViewMatrix, projectionMatrix, viewport ) rd = norm( [re[0] - ro[0], re[1] - ro[1], re[2] - ro[2] ] ) cam.ro = ro cam.rd = rd selected = None tm = 10000.0 t = tm for obj in scene.objects.values(): result, t = obj.collide(ro, rd) if result and t < tm: tm = t selected = obj if selected != None: selected.selected = not selected.selected gui.tree_ctrl.ToggleItemSelection(selected.treeitem) selection = "" for obj in scene.objects.values(): if obj.selected == True: selection += obj.name selection += " " else: getEdit().click(event.pos) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) time_passed = clock.tick() dt = time_passed / 1000.0 cam.update(dt) keys = pygame.key.get_pressed() glMatrixMode(GL_MODELVIEW) glLoadIdentity() cam.render() axes() selection = [] center = [0, 0, 0] for obj in scene.objects.values(): if obj != getEdit() and obj.transparent == False: obj.draw() if obj.selected == True: selection.append(obj) for obj in scene.objects.values(): if obj != getEdit() and obj.transparent == True: obj.draw() #Make sure that the current object being edited is drawn last if isEdit(): getEdit().draw() for obj in selection: center = add( center, obj.center() ) if len(selection) > 0: center = mult( 1/float(len(selection)) , center) distance = dist( center, [cam.x, cam.y, cam.z] ) if not isEdit(): #Don't draw move tool in edit mode movetool(center[0] , center[1], center[2], distance*0.3) drawText2d ( (0,720-25), "Camera Speed = " + str(cam.speed) , 30) pygame.display.flip() pygame.quit()