def main(self, stdscr): d=self.dbDict if self.all: l = [ x for x in filter(lambda x: x!=0, d) ] else: l = [ x for x in filter(lambda x: x!=0 and len(d[x])>1, d) ] ll=[] for x in l: ll .append(d[x].copy()) pikr = Picker( title = 'duplicate media manager' , options = ll , log = self.log ) while 1: pikr.run() removed = pikr.getRemoved() if removed: self.updateDict(d, removed) print ("hit a key to continue ... ") c = sys.stdin.read(1) if pikr.aborted: break
def select_laps_to_render(videos, lap_comparison_mode=False, select_sessions=False): if select_sessions: return select_sessions_to_render(videos) laps = {} for video in videos: for lap in video.matched_laps: print lap['lap'] key = float(lap['lap']) laps[key] = lap lap["render"] = False keys = laps.keys() keys.sort() title = 'Select laps to render' if lap_comparison_mode: title = "Select at most 2 laps to render in side-by-side mode" picker = Picker(title=title, options=keys) picker.start() opts = picker.getSelected() if lap_comparison_mode: opts = opts[:2] for lap in opts: laps[lap]['render'] = True
class ShareSendExample(App): def build(self): self.create_test_file() self.share = ShareSend() self.picker = Picker(self.picker_callback) request_permissions([Permission.READ_EXTERNAL_STORAGE]) b1 = Button(text='Share plain TEXT via a ShareSheet', on_press=self.button1_pressed) b2 = Button(text='Share "test.html" FILE via a ShareSheet', on_press=self.button2_pressed) b3 = Button(text='Pick a file to share with Gmail', on_press=self.button3_pressed) b4 = Button( text= 'Pick a video/mp4 to share with Receive\nThe Recieve example must be installed.', on_press=self.button4_pressed) box = BoxLayout(orientation='vertical') box.add_widget(b1) box.add_widget(b2) box.add_widget(b3) box.add_widget(b4) self.box = box return box def button1_pressed(self, b): self.share.share_text('Greetings Earthlings') def button2_pressed(self, b): uri = SharedStorage().getUri('test.html') if uri: self.share.share_uri(uri) def button3_pressed(self, b): self.target = 'com.google.android.gm' self.picker.pick_file() def button4_pressed(self, b): self.target = 'org.test.receive' self.picker.pick_file('video/mp4') def picker_callback(self, uri): if uri: self.share.share_uri(uri, self.target) def create_test_file(self): # create a file in Private storage filename = join(PrivateStorage().getCacheDir(), 'test.html') with open(filename, "w") as f: f.write("<html>\n") f.write(" <head>\n") f.write(" </head>\n") f.write(" <body>\n") f.write(" <h1>Greetings Earthlings<h1>\n") f.write(" <h1>We come in please?<h1>\n") f.write(" </body>\n") f.write("</html>\n") # Insert the test case in this app's Shared Storage so it will have a Uri SharedStorage().insert(filename)
def analysis_results(): parser = OptionParser() parser.add_option("--inputFile", dest="inputFile", help="Input picking results file, like '/PATH/autopick_results.list'", metavar="FILE") parser.add_option("--inputDir", dest="inputDir", help="Reference coordinate directory", metavar="DIRECTORY") parser.add_option("--coordinate_symbol", dest="coordinate_symbol", help="The symbol of the coordinate file, like '_manualPick'", metavar="STRING") parser.add_option("--particle_size", dest="particle_size", help="the size of the particle.", metavar="VALUE", default=-1) parser.add_option("--minimum_distance_rate", dest="minimum_distance_rate", help="Use the value particle_size*minimum_distance_rate as the distance threshold for estimate the number of true positive samples, the default value is 0.2", metavar="VALUE", default=0.2) (opt, args) = parser.parse_args() pick_results_file = opt.inputFile reference_mrc_file_dir = opt.inputDir reference_coordinate_symbol = opt.coordinate_symbol particle_size = int(opt.particle_size) minimum_distance_rate = float(opt.minimum_distance_rate) Picker.analysis_pick_results(pick_results_file, reference_mrc_file_dir, reference_coordinate_symbol, particle_size, minimum_distance_rate)
def customReset(self): self.spinner.start() time.sleep(3) self.getMissingPackages() rapps = [] if self.lineCount('apps-to-remove') > 0: self.getLocalUserList() self.getOldKernels() self.getLocalUserList() self.findNonDefaultUsers() with open('apps-to-remove', 'r') as atr: for line in atr: rapps.append(line) self.spinner.stop() rapps.sort() opts = Picker( title='Custom Reset: Select packages to remove', options=rapps ).getSelected() if not opts: print("") else: path = 'custom-remove' mode = 'a' if self.isWritten else 'w' with open(path, mode) as f_out: for item in opts: f_out.write(item) else: print("All removable packages have already been removed, there are no more packages left")
def autoReset(self): yes = set(['yes', 'y', '']) no = set(['no', 'n']) choice = input(colored("This will reset your " + str(self.os_info['DESCRIPTION']) + " installation to its factory defaults. " "Local user accounts and all their contents will also be removed. " "Are you sure you'd like to continue?: ", 'yellow')).lower() if str(choice).lower() in yes: rapps = [] self.spinner.start() self.getMissingPackages() if self.lineCount('apps-to-remove') > 0: self.getLocalUserList() self.findNonDefaultUsers() with open('apps-to-remove') as atr: for line in atr: rapps.append(line) self.spinner.stop() rapps.sort() opts = Picker( title='Automatic Reset: All of these packages will be removed', options=rapps, checkall=True, mut=True ).getSelected() if not opts: print('') else: print("All removable packages have already been removed, there are no more packages left") elif choice.lower() in no: pass else: print("Please respond with 'yes' or 'no'")
async def roll(self, ctx, *args): try: p = Picker(self.bot,ctx,self.debug) result = await p.select(args) except SystemException as err: await self.bot.sys_ex(err, ctx) result = '''```diff\n- Something went wrong on our end.\n```''' await ctx.send(f"{result}")
async def roll_supp(self, ctx, *args): try: p = Picker(self.bot, ctx,self.debug) params = ['supp'] for arg in args: params.append(arg) result = await p.select(params) except SystemException as err: await self.bot.sys_ex(err, ctx) result = '''```diff\n- Something went wrong on our end.\n```''' await ctx.send(f"{result}")
def __init__( self ) : self.dict = Dictionary() self.spliter = PinyinSpliter() self.fitter = Fitter() self.picker = Picker( self.dict ) #self.picker.set( [], [], True ) self.cache = [ [ 0, [], "" ] ] self.candCacheIndex = 0 self.candStartIndex = 0 self.candList = []
def __init__(self, picker: Picker, results_path: Path, train_set: SeisDataset, valid_set: SeisDataset, test_set: SeisDataset, device: torch.device, batch_size: int, lr: float, num_workers: int, freq_valid: int, visual: Dict[str, List[int]], dt_ms: float, height_model: int, width_model: int, stopper: Stopper, weights: torch.Tensor): self._picker = picker self._results_path = results_path self._train_set = train_set self._valid_set = valid_set self._test_set = test_set self._device = device self._batch_size = batch_size self._lr = lr self._num_workers = num_workers self._freq_valid = freq_valid self._visual = visual self._dt_ms = dt_ms self._height_model = height_model self._width_model = width_model self._stopper = stopper self._weights = weights # self._criterion = nn.CrossEntropyLoss(weight=self._weights).to(self._device) self._criterion = FocalLoss(alpha=self._weights, gamma=2) self._optimizer = torch.optim.Adam(picker.parameters(), lr=self._lr) self._net_path, self._tensorboard_path = self._results_path / 'net', self._results_path / 'tensorboard' for folder in [self._net_path, self._tensorboard_path]: folder.mkdir(exist_ok=True, parents=True) self._writer_tb = SummaryWriter(log_dir=str(self._tensorboard_path), flush_secs=20) self._picker.to(self._device) self._num_batch = 0 self._correct_visual() self._freq_valid = min((self._freq_valid, len(self._train_set) // self._batch_size + 1))
def build(self): self.create_test_file() self.share = ShareSend() self.picker = Picker(self.picker_callback) request_permissions([Permission.READ_EXTERNAL_STORAGE]) b1 = Button(text='Share plain TEXT via a ShareSheet', on_press=self.button1_pressed) b2 = Button(text='Share "test.html" FILE via a ShareSheet', on_press=self.button2_pressed) b3 = Button(text='Pick a file to share with Gmail', on_press=self.button3_pressed) b4 = Button( text= 'Pick a video/mp4 to share with Receive\nThe Recieve example must be installed.', on_press=self.button4_pressed) box = BoxLayout(orientation='vertical') box.add_widget(b1) box.add_widget(b2) box.add_widget(b3) box.add_widget(b4) self.box = box return box
def build(self): # create picker listener self.picker = Picker(self.picker_callback) # Permission required for Picker() request_permissions([Permission.READ_EXTERNAL_STORAGE]) # cleanup temp = PrivateStorage().getCacheDir() if not temp: temp = PrivateStorage().getCacheDir('internal') temp = join(temp,"MediaStore") if exists(temp): rmtree(temp) # layout self.label_lines = [] self.label = Label(text = 'Greetings Earthlings') self.button = Button(text = 'Use Picker to get a Document', on_press = self.picker_start, size_hint=(1, .15)) self.layout = BoxLayout(orientation='vertical') self.layout.add_widget(self.label) self.layout.add_widget(self.button) return self.layout
def collect_items(show_video=True, record_video=False): manipulator = Manipulator() # set up items to be collected items = [{'size': 30, 'place': (210, EARTH_LEVEL), 'name': 'red', 'color': (35, 35, 215)}, {'size': 40, 'place': (250, EARTH_LEVEL), 'name': 'green', 'color': (50, 150, 0)}, {'size': 50, 'place': (300, EARTH_LEVEL), 'name': 'yellow', 'color': (25, 220, 230)}] dest_range = (350, 640) # generate random positions within dest_range # To make items not to be overlapping, first point positions in [0, free_size) interval are # generated, then every point expands to the required size (with spaces between points saved) range_size = dest_range[1] - dest_range[0] sum_size = sum(item['size'] for item in items) free_size = range_size - sum_size x_positions = dest_range[0] + np.random.randint(free_size, size=len(items)) for i, (item, pos) in enumerate(zip(items, x_positions)): x_positions[x_positions > pos] += item['size'] x_positions[i] += item['size'] // 2 for x, item in zip(x_positions, items): item['position'] = (x, EARTH_LEVEL - item['size'] // 2) # set up video showing and recording window = "collect items demo" if show_video else None writer = cv2.VideoWriter("collect items demo.avi", VIDEO_FOURCC, VIDEO_FPS, FRAME_RES) if record_video else None # collect items picker = Picker(manipulator, items, window, writer) picker.collect() if show_video: cv2.destroyWindow(window) if record_video: writer.release()
def main(args: Namespace): results_path = args.log_dir / str(datetime.now()) results_path.mkdir(exist_ok=True, parents=True) write_args(results_path, vars(args)) fix_seed(args.seed) height_model = 1000 width_model = 24 filenames_train, filenames_valid, filenames_test = split_dataset(args.data_root, args.fracs_dataset) train_set = SeisDataset(filenames_train, height_model=height_model, width_model=width_model, prob_aug=args.prob_aug) valid_set = SeisDataset(filenames_valid, height_model=height_model, width_model=width_model, prob_aug=args.prob_aug) test_set = SeisDataset(filenames_test, height_model=height_model, width_model=width_model, prob_aug=args.prob_aug) net = UNetFB() picker = Picker(net) stopper = Stopper(args.n_wrongs, args.delta_wrongs) trainer = Trainer(picker=picker, results_path=results_path, train_set=train_set, valid_set=valid_set, test_set=test_set, device=args.device, batch_size=args.batch_size, lr=args.lr, freq_valid=args.freq_valid, num_workers=args.num_workers, dt_ms=args.dt_ms, height_model=height_model, width_model=width_model, visual=args.visual, stopper=stopper, weights=torch.tensor(args.weights)) trainer.train(num_epoch=args.num_epoch)
def select_sessions_to_render(videos): s_videos = {} for video in videos: key = str(video) s_videos[key] = video for lap in video.matched_laps: lap["render"] = False keys = s_videos.keys() keys.sort() title = 'Select sessions to render' picker = Picker(title=title, options=keys) picker.window_width = 150 picker.window_height = 30 picker.start() opts = picker.getSelected() for videoname in opts: video = s_videos[videoname] for lap in video.matched_laps: lap['render'] = True
class Game(ShowBase): """Sets up the game, camera, controls, and loads models.""" def __init__(self): ShowBase.__init__(self) self.xray_mode = False self.show_model_bounds = False self.lastHighlight = None # Display instructions add_title("TrenchAssessment") add_instructions(0.06, "[Esc]: Quit") #add_instructions(0.12, "[W]: Move Forward") #add_instructions(0.18, "[A]: Move Left") #add_instructions(0.24, "[S]: Move Right") #add_instructions(0.30, "[D]: Move Back") #add_instructions(0.36, "Arrow Keys: Look Around") add_instructions(0.12, "[F]: Toggle Wireframe") add_instructions(0.18, "[X]: Toggle X-Ray Mode") add_instructions(0.24, "[B]: Toggle Bounding Volumes") self.keys = {} self.accept('f', self.toggleWireframe) self.accept('x', self.toggle_xray_mode) self.accept('b', self.toggle_model_bounds) self.accept('escape', __import__('sys').exit, [0]) self.disableMouse() # Setup camera self.cameraarm = render.attachNewNode('arm') self.cameraarm.setEffect( CompassEffect.make(render)) # NOT inherit rotation self.lens = PerspectiveLens() self.lens.setFov(60) self.lens.setNear(0.01) self.lens.setFar(10000000.0) self.cam.node().setLens(self.lens) self.heading = 0 self.pitch = 0.0 self.camera.reparentTo(self.cameraarm) self.camera.setY(-10) # camera distance from model self.accept( 'wheel_up', lambda: base.camera.setY(self.camera.getY() + 400 * globalClock.getDt())) self.accept( 'wheel_down', lambda: base.camera.setY(self.camera.getY() - 400 * globalClock.getDt())) self.accept( 'shift-wheel_up', lambda: base.camera.setY(self.camera.getY( ) + 2000 * globalClock.getDt())) self.accept( 'shift-wheel_down', lambda: base.camera.setY(self.camera.getY( ) - 2000 * globalClock.getDt())) self.isMouse3Down = False self.accept('mouse3', self.setMouse3Down) self.accept('mouse3-up', self.setMouse3Up) self.taskMgr.add(self.thirdPersonCameraTask, 'thirdPersonCameraTask') # Add Camera picking #self.rollover = Picker(render) #taskMgr.add(self.rolloverTask, 'rollover') self.picker = Picker(render) self.accept('mouse1', self.tryPick) self.accept('mouse1-up', self.stopRotation) # Setup Lights dlight = DirectionalLight('dlight') dlight2 = DirectionalLight('dlight2') alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.2, 0.2, 1)) self.lightnode = render.attachNewNode(dlight) self.lightnode2 = render.attachNewNode(dlight2) self.lightnode2.setHpr(0, -90, 0) self.alightnode = render.attachNewNode(alight) render.setLight(self.lightnode) render.setLight(self.lightnode2) render.setLight(self.alightnode) # load models m = loader.loadModel("models/grube_simplified_rotated.egg") self.trench = render.attachNewNode("trench") m.reparentTo(self.trench) tbounds = self.trench.getTightBounds() p1 = tbounds[0] p2 = tbounds[1] po = p2 - (p2 - p1) / 2 m.setPos(-po) self.trench.setColor(WHITE) self.trench.setCollideMask(BitMask32.allOff()) self.attachGizmos(self.trench) self.rotEnabled = False # load grid grid = ThreeAxisGrid() gridnodepath = grid.create() gridnodepath.setTransparency(TransparencyAttrib.MAlpha) gridnodepath.setAlphaScale(0.25) gridnodepath.reparentTo(render) # buttons a = DirectButton(text=("X-Sections", "X-Sections", "X-Sections", "disabled"), scale=.05, pos=(-1.2, 0, -0.95), command=self.calculateXSessions) a = DirectButton(text=("RotGimbal", "RotGimbal", "RotGimbal", "disabled"), scale=.05, pos=(-0.9, 0, -0.95), command=self.toggleRotGimbal) def calculateXSessions(self): """ Calculates cross-section profiles """ # Check for extension planes = self.createCuttingPlanes() profiles = self.calculateProfiles() def calculateProfiles(self): vertexToPlane = {} # init dict for p in self.planedata: vertexToPlane[p] = [[], []] geomNodeCollection = self.trench.findAllMatches('**/+GeomNode') print(geomNodeCollection) # 0 will be the trench - change later geomNode = geomNodeCollection[0].node() for i in range(geomNode.getNumGeoms()): geom = geomNode.getGeom(i) state = geomNode.getGeomState(i) vdata = geom.getVertexData() vertex = GeomVertexReader(vdata, 'vertex') while not vertex.isAtEnd(): v = vertex.getData3f() # calculate distance to planes for p in self.planedata: if self.deltaInclude(v, p): if v[1] not in vertexToPlane[p][ 0]: # prevent double addition of x values vertexToPlane[p][0].append(v[1]) vertexToPlane[p][1].append(v[2]) #print(vertexToPlane[1]) # filter xy coordinates #new_x, new_y = self.deltaFilter() i = 0 for p in self.planedata: plt.figure(i) # sort x coordinates L = sorted(zip(vertexToPlane[p][0], vertexToPlane[p][1])) new_x, new_y = zip(*L) # signal process y values yhat = savgol_filter(new_y, 21, 5) #81,5 # 1d interpolation f = interp1d(new_x, yhat, 'quadratic') i += 1 #print(new_x) plt.plot(new_x, new_y, color='k', alpha=0.5, linewidth=0.8) plt.plot(new_x, yhat, color='b', alpha=0.5, linewidth=0.8) plt.plot(new_x, f(new_x), color='r', alpha=0.5, linewidth=2.0) plt.legend(['original', 'savgol_filter', 'interpolated (cubic)']) #plt.plot(new_x, new_y) #plt.plot(new_x, f(new_x)) plt.show() def deltaInclude(self, v, p): if v[0] >= p - PROFILE_DELTA and v[0] <= p + PROFILE_DELTA: return True else: return False def deltaFilter(self, v, p): return False def createCuttingPlanes(self): self.planes = self.render.attachNewNode("planes") pl = self.planes.attachNewNode("pl") data = EggData() self.planedata = [] vp = EggVertexPool('plane') data.addChild(vp) fac = 1.0 expanse = 10.0 rng = 4 for i in range(-rng, rng): poly = EggPolygon() data.addChild(poly) self.planedata.append(i * fac) v = EggVertex() v.setPos(Point3D(i * fac, -expanse, -expanse)) poly.addVertex(vp.addVertex(v)) v = EggVertex() v.setPos(Point3D(i * fac, -expanse, +expanse)) poly.addVertex(vp.addVertex(v)) v = EggVertex() v.setPos(Point3D(i * fac, +expanse, +expanse)) poly.addVertex(vp.addVertex(v)) v = EggVertex() v.setPos(Point3D(i * fac, +expanse, -expanse)) poly.addVertex(vp.addVertex(v)) node = loadEggData(data) np = NodePath(node) np.reparentTo(pl) np.setColor(0, 1, 0, 1) np.setTwoSided(True) np.setTransparency(TransparencyAttrib.MAlpha) np.setAlphaScale(0.1) np.setCollideMask(BitMask32(0x0)) return self.planes def toggleRotGimbal(self): if self.rotEnabled: self.gizmos.setAlphaScale(0) self.rotEnabled = False else: self.gizmos.setAlphaScale(0.1) self.rotEnabled = True def startRotation(self): self.isRotating = True md = self.win.getPointer(0) self.mouselasttick = (md.getX(), md.getY()) self.taskMgr.add(self.onRotateMoveTask, 'RotationTask') def stopRotation(self): self.isRotating = False self.taskMgr.remove("RotationTask") props = WindowProperties() props.setCursorHidden(False) self.win.requestProperties(props) #unselect on mouse up if self.lastHighlight: self.lastHighlight.setAlphaScale(0.1) self.lastHighlight = None def onRotateMoveTask(self, task): md = self.win.getPointer(0) props = WindowProperties() x = md.getX() y = md.getY() if self.isRotating: props.setCursorHidden(True) obj = self.trench rotAx = self.lastHighlight.getTag("axis") hpr = obj.getHpr(obj) if rotAx == "xy": hpr[0] = hpr[0] - (x - float(self.mouselasttick[0])) * 0.5 elif rotAx == "xz": hpr[2] = hpr[2] - (y - float(self.mouselasttick[1])) * 0.5 elif rotAx == "yz": hpr[1] = hpr[1] - (y - float(self.mouselasttick[1])) * 0.5 obj.setHpr(obj, hpr) self.mouselasttick = (md.getX(), md.getY()) else: props.setCursorHidden(False) self.win.requestProperties(props) return task.cont def tryPick(self): obj, point, raw = self.picker.pick() #print(obj) if obj and self.rotEnabled: #dt = globalClock.getDt() #print(self.lastHighlight) if obj != self.lastHighlight: if self.lastHighlight: self.lastHighlight.setAlphaScale(0.1) #print("Set Highlight") self.lastHighlight = obj obj.setAlphaScale(0.3) self.startRotation() else: if self.lastHighlight != None: #print("Unset Highlight") self.lastHighlight.setAlphaScale(0.1) self.lastHighlight = None def rolloverTask(self, task): """ an alternate way to use the picker. Handle the mouse continuously """ obj, point, raw = self.rollover.pick() if obj: dt = globalClock.getDt() print(self.lastHighlight) if obj != self.lastHighlight or self.lastHighlight == None: print("Set Highlight") self.lastHighlight = obj obj.setAlphaScale(0.7) else: if self.lastHighlight: print("Unset Highlight") self.lastHighlight.setAlphaScale(0.1) self.lastHighlight = None return task.cont def attachGizmos(self, ref): self.gizmos = ref.attachNewNode("gizmos") self.gizmos.setAlphaScale(0) """ XZ """ xz = self.gizmos.attachNewNode("xz") xzG = self.createGizmo(360, 30, 0, 10) xzG.setTransparency(TransparencyAttrib.MAlpha) xzG.setColor(0, 1, 0, 1) xzG.setTwoSided(True) xzG.reparentTo(xz) #xzG.setCollideMask(BitMask32(0x10)) #xz.setPos(po) #xz.setAlphaScale(0.1) xz.setTag("axis", "xz") """ XY """ xy = self.gizmos.attachNewNode("xy") xyG = self.createGizmo(360, 30, 1, 10) xyG.setTransparency(TransparencyAttrib.MAlpha) xyG.setColor(0, 0, 1, 1) xyG.setTwoSided(True) xyG.reparentTo(xy) #xzG.setCollideMask(BitMask32(0x10)) #xy.setPos(po) #xy.setAlphaScale(0.1) xy.setTag("axis", "xy") """ YZ """ yz = self.gizmos.attachNewNode("yz") yzG = self.createGizmo(360, 30, 2, 10) yzG.setTransparency(TransparencyAttrib.MAlpha) yzG.setColor(1, 0, 0, 1) yzG.setTwoSided(True) yzG.reparentTo(yz) #yz.setPos(po) #yz.setAlphaScale(0.1) yz.setTag("axis", "yz") def createGizmo(self, angleDegrees=360, numSteps=16, axis=0, scale=10): data = EggData() vp = EggVertexPool('fan') data.addChild(vp) poly = EggPolygon() data.addChild(poly) v = EggVertex() v.setPos(Point3D(0, 0, 0)) poly.addVertex(vp.addVertex(v)) angleRadians = deg2Rad(angleDegrees) for i in range(numSteps + 1): a = angleRadians * i / numSteps y = math.sin(a) * scale x = math.cos(a) * scale v = EggVertex() if axis is 0: v.setPos(Point3D(x, 0, y)) elif axis is 1: v.setPos(Point3D(x, y, 0)) else: v.setPos(Point3D(0, x, y)) poly.addVertex(vp.addVertex(v)) node = loadEggData(data) return NodePath(node) def setMouse3Down(self): md = self.win.getPointer(0) self.mouseorigin = (md.getX(), md.getY()) self.mouselasttick = (md.getX(), md.getY()) self.isMouse3Down = True def setMouse3Up(self): self.isMouse3Down = False self.win.movePointer(0, int(self.mouseorigin[0]), int(self.mouseorigin[1])) # camera rotation task def thirdPersonCameraTask(self, task): md = self.win.getPointer(0) props = WindowProperties() x = md.getX() y = md.getY() if self.isMouse3Down: props.setCursorHidden(True) self.heading = self.heading - (x - float(self.mouselasttick[0])) * 0.5 self.pitch = self.pitch - (y - float(self.mouselasttick[1])) * 0.5 self.cameraarm.setHpr(self.heading, self.pitch, 0) self.mouselasttick = (md.getX(), md.getY()) else: props.setCursorHidden(False) self.win.requestProperties(props) return task.cont #self.mouseLook = FirstPersonCamera(self, self.cam, self.render) def toggle_model_bounds(self): """Toggle bounding volumes on and off on the models.""" self.show_model_bounds = not self.show_model_bounds if self.show_model_bounds: self.trench.showBounds() else: self.trench.hideBounds() def toggle_xray_mode(self): """Toggle X-ray mode on and off. This is useful for seeing the effectiveness of the occluder culling.""" self.xray_mode = not self.xray_mode if self.xray_mode: self.trench.setColorScale((1, 1, 1, 0.5)) self.trench.setTransparency(TransparencyAttrib.MDual) else: self.trench.setColorScaleOff() self.trench.setTransparency(TransparencyAttrib.MNone) def push_key(self, key, value): """Stores a value associated with a key.""" self.keys[key] = value def update(self, task): """Updates the camera based on the keyboard input.""" delta = globalClock.getDt() move_x = delta * 3 * -self.keys['a'] + delta * 3 * self.keys['d'] move_z = delta * 3 * self.keys['s'] + delta * 3 * -self.keys['w'] self.camera.setPos(self.camera, move_x, -move_z, 0) self.heading += (delta * 90 * self.keys['arrow_left'] + delta * 90 * -self.keys['arrow_right']) self.pitch += (delta * 90 * self.keys['arrow_up'] + delta * 90 * -self.keys['arrow_down']) self.camera.setHpr(self.heading, self.pitch, 0) return task.cont
class PinyinLookup() : def __init__( self ) : self.dict = Dictionary() self.spliter = PinyinSpliter() self.fitter = Fitter() self.picker = Picker( self.dict ) #self.picker.set( [], [], True ) self.cache = [ [ 0, [], "" ] ] self.candCacheIndex = 0 self.candStartIndex = 0 self.candList = [] def load( self, filePath ) : newKeys = self.dict.load( filePath ) print "start build index" newPinyinSet = set() for key in newKeys : if key.count( "'" ) <= 0 : self.fitter.pinyinSet.add( key ) newPinyinSet.add( key ) self.fitter.dictTree.addKey( key ) for pinyin in newPinyinSet : self.spliter.beginCharSet.add( pinyin[0] ) self.spliter.pinyinTree.addPath( pinyin ) print "built" def update( self, key, word, freq ) : newKey = self.dict.update( key, word, freq ) if newKey : if newKey.count( "'" ) <= 0 : self.fitter.pinyinSet.add( newKey ) self.spliter.beginCharSet.add( newKey[0] ) self.spliter.pinyinTree.addPath( newKey ) self.fitter.dictTree.addKey( newKey ) def subFit( self, fitList, pinyinStringList ) : subFitPoint = -999 #for key in fitList : for i in range( len( fitList ) ) : key = fitList[i] #currentSubFitPoint = len( key ) - key.count( "'" ) - len( self.spliter.code ) currentSubFitPoint = key.count( "'" ) + 1 - len( pinyinStringList[i].string ) #print key, pinyinStringList[i].string, currentSubFitPoint if currentSubFitPoint > 0 : currentSubFitPoint = -998 if currentSubFitPoint > subFitPoint : subFitPoint = currentSubFitPoint #print key, currentSubFitPoint, subFitPoint newFitList = [] preeditList = [] for i in range( len( fitList ) ) : key = fitList[i] currentSubFitPoint = key.count( "'" ) + 1 - len( pinyinStringList[i].string ) if currentSubFitPoint >= subFitPoint : newFitList.append( key ) preeditList.append( str( pinyinStringList[i] ) ) #print newFitList, newPreeditList return newFitList, preeditList def append( self, code ) : #print "append", code self.spliter.append( code ) fitList = [] #preeditList = [] pinyinStringList = [] fitPoint = -999 for pinyinString in self.spliter.stack : #print pinyinString if pinyinString.length < len( self.spliter.code ) : pass else : currentFitPoint, keys = self.fitter.fit( pinyinString.string ) #print currentFitPoint, keys if currentFitPoint > fitPoint : fitPoint = currentFitPoint fitList = [] preeditList = [] fitList.extend( keys ) #preeditList.extend( [ str( pinyinString ) ] * len( keys ) ) pinyinStringList.extend( [ pinyinString ] * len( keys ) ) elif currentFitPoint == fitPoint : fitList.extend( keys ) #preeditList.extend( [ str( pinyinString ) ] * len( keys ) ) pinyinStringList.extend( [ pinyinString ] * len( keys ) ) fitList, preeditList = self.subFit( fitList, pinyinStringList ) #print fitList self.picker.set( fitList, preeditList, True ) cache = [ fitPoint, fitList, preeditList ] self.cache.append( cache ) self.candList = [] self.candCacheIndex = len( self.cache ) - 1 self.candStartIndex = 0 def pop( self ) : if len( self.cache ) > 1 : self.spliter.pop() self.cache = self.cache[:-1] cache = self.cache[-1] fitList = cache[1] preeditList = cache[2] self.picker.set( fitList, preeditList, True ) self.candList = [] self.candCacheIndex = len( self.cache ) - 1 self.candStartIndex = 0 def checkCache( self ) : fitList = [] cache = self.cache[self.candCacheIndex] currentFitPoint = cache[0] while self.candCacheIndex >= 1 : self.candCacheIndex -= 1 cache = self.cache[self.candCacheIndex] fitPoint = cache[0] fitList = cache[1] preeditList = cache[2] #print self.candCacheIndex, fitList if len( fitList ) >= 0 : if len( self.candList ) <= 0 : break elif fitPoint >= currentFitPoint : break if self.candCacheIndex >= 1 : self.picker.set( fitList, preeditList, False ) return True else : return False def getCand( self, index ) : flag = True while flag and len( self.candList ) <= index : key, word, freq, preeditString = self.picker.pick() if key : self.candList.append( [ key, word, freq, preeditString, self.candStartIndex ] ) else : flag = self.checkCache() self.candStartIndex = len( self.candList ) if flag : return self.candList[index] else : return None #print candList def clear( self ) : self.spliter.clear() self.picker.set( [], [], True ) self.cache = [ [ 0, [], "" ] ] self.candList = [] self.candCacheIndex = 0 self.candStartIndex = 0
def __init__(self,config): Strategy.__init__(self,config) self.placer = Placer(config) self.picker = Picker(config)
class BasicStrategy(Strategy): def __init__(self,config): Strategy.__init__(self,config) self.placer = Placer(config) self.picker = Picker(config) def pickAndPlace(self,jobName,stepName,stream): boards={} jobs={} tapes={} tapeTemplates={} if self.config['boards']: for board in self.config['boards']: newBoard = Board(self.config) if 'name' in board: newBoard.setName(board['name']) if 'placements' in board: newBoard.setPlacements(PartPlacement.readFile(board['placements'])) else: print "No placement specified for board:",board['name'] if 'height' in board: newBoard.height=board['height']; boards[newBoard.name]=newBoard # Load up the tape templates for tapeTemplate in self.config['tapeTemplates']: template = TapeTemplate() if 'name' in tapeTemplate: template.name = tapeTemplate['name'] else: raise Exception("Missing tape template name") for name in tapeTemplate: if hasattr(template,name): setattr(template,name,tapeTemplate[name]) tapeTemplates[template.name]=template; # FIXME Should validate the tapetemplate here for tape in self.config['tapes']: if not 'name' in tape: raise Exception("No name specified for tape") if not 'template' in tape: raise Exception("No template specified for tape") if not tape['template'] in tapeTemplates: raise Exception("Invalid tape template specified:",tape['template']) partTape = Tape() for name in tape: if hasattr(partTape,name): setattr(partTape,name,tape[name]) partTape.tapeTemplate=tapeTemplates[tape['template']] tapes[partTape.name]=partTape for job in self.config['jobs']: j = Job() for name in job: if hasattr(j,name) and name!="steps" and name!="boards": setattr(j,name,job[name]) for board in job['boards']: if not 'name' in board: raise Exception("Invalid board specified") if not board['name'] in boards: raise Exception("Invalid board name:"+board['name']) j.addBoard(boards[board['name']], board['reference'],board['x'],board['y'], board['second_reference']) for step in job['steps']: js = JobStep() for name in step: if hasattr(js,name): setattr(js,name,step[name]) j.steps.append(js) jobs[j.name]=j ################################## #1 Get the current job and step if not jobName in jobs: raise Exception("Invalid job name:"+jobName) currentJob = jobs[jobName] currentStep = next((step for step in currentJob.steps if step.name == stepName), None) #2 Setup the placer with the boards stream.write("G28\n") stream.write("M302\n") stream.write("M92 E400\n") for board in currentJob.boards: self.placer.addBoard(board) self.placer.organizeBoards(stream) #3 Setup the picker with the tapes for tape in currentStep.tapes: self.picker.addTape(tapes[tape]) self.picker.organizeTapes(stream) self.picker.generatePlacements(self.placer.boards) while True: pn = self.picker.pickPart(stream); if None==pn: break self.placer.placePart(pn.board,pn.placement,pn.tape,stream);
def __init__(self): ShowBase.__init__(self) self.xray_mode = False self.show_model_bounds = False self.lastHighlight = None # Display instructions add_title("TrenchAssessment") add_instructions(0.06, "[Esc]: Quit") #add_instructions(0.12, "[W]: Move Forward") #add_instructions(0.18, "[A]: Move Left") #add_instructions(0.24, "[S]: Move Right") #add_instructions(0.30, "[D]: Move Back") #add_instructions(0.36, "Arrow Keys: Look Around") add_instructions(0.12, "[F]: Toggle Wireframe") add_instructions(0.18, "[X]: Toggle X-Ray Mode") add_instructions(0.24, "[B]: Toggle Bounding Volumes") self.keys = {} self.accept('f', self.toggleWireframe) self.accept('x', self.toggle_xray_mode) self.accept('b', self.toggle_model_bounds) self.accept('escape', __import__('sys').exit, [0]) self.disableMouse() # Setup camera self.cameraarm = render.attachNewNode('arm') self.cameraarm.setEffect( CompassEffect.make(render)) # NOT inherit rotation self.lens = PerspectiveLens() self.lens.setFov(60) self.lens.setNear(0.01) self.lens.setFar(10000000.0) self.cam.node().setLens(self.lens) self.heading = 0 self.pitch = 0.0 self.camera.reparentTo(self.cameraarm) self.camera.setY(-10) # camera distance from model self.accept( 'wheel_up', lambda: base.camera.setY(self.camera.getY() + 400 * globalClock.getDt())) self.accept( 'wheel_down', lambda: base.camera.setY(self.camera.getY() - 400 * globalClock.getDt())) self.accept( 'shift-wheel_up', lambda: base.camera.setY(self.camera.getY( ) + 2000 * globalClock.getDt())) self.accept( 'shift-wheel_down', lambda: base.camera.setY(self.camera.getY( ) - 2000 * globalClock.getDt())) self.isMouse3Down = False self.accept('mouse3', self.setMouse3Down) self.accept('mouse3-up', self.setMouse3Up) self.taskMgr.add(self.thirdPersonCameraTask, 'thirdPersonCameraTask') # Add Camera picking #self.rollover = Picker(render) #taskMgr.add(self.rolloverTask, 'rollover') self.picker = Picker(render) self.accept('mouse1', self.tryPick) self.accept('mouse1-up', self.stopRotation) # Setup Lights dlight = DirectionalLight('dlight') dlight2 = DirectionalLight('dlight2') alight = AmbientLight('alight') alight.setColor(VBase4(0.2, 0.2, 0.2, 1)) self.lightnode = render.attachNewNode(dlight) self.lightnode2 = render.attachNewNode(dlight2) self.lightnode2.setHpr(0, -90, 0) self.alightnode = render.attachNewNode(alight) render.setLight(self.lightnode) render.setLight(self.lightnode2) render.setLight(self.alightnode) # load models m = loader.loadModel("models/grube_simplified_rotated.egg") self.trench = render.attachNewNode("trench") m.reparentTo(self.trench) tbounds = self.trench.getTightBounds() p1 = tbounds[0] p2 = tbounds[1] po = p2 - (p2 - p1) / 2 m.setPos(-po) self.trench.setColor(WHITE) self.trench.setCollideMask(BitMask32.allOff()) self.attachGizmos(self.trench) self.rotEnabled = False # load grid grid = ThreeAxisGrid() gridnodepath = grid.create() gridnodepath.setTransparency(TransparencyAttrib.MAlpha) gridnodepath.setAlphaScale(0.25) gridnodepath.reparentTo(render) # buttons a = DirectButton(text=("X-Sections", "X-Sections", "X-Sections", "disabled"), scale=.05, pos=(-1.2, 0, -0.95), command=self.calculateXSessions) a = DirectButton(text=("RotGimbal", "RotGimbal", "RotGimbal", "disabled"), scale=.05, pos=(-0.9, 0, -0.95), command=self.toggleRotGimbal)
def download_singles(self): """ Downloads songs based on youtube search. Takes a string as an input. """ cm = common() try: os.chdir("singles") except: os.mkdir("singles") os.chdir("singles") Console().print( Columns([ Panel( "\ntip:\n [bold white]* give the name of song and the artist for better search results)\n * you could paste the youtube video url itself if you're looking for a specific song.[/bold white]\n" ) ])) s = input("\nEnter the song name: ") print(f"\nLoading search results for {s}...\n") s = s.replace(" ", "+") # Get top 7 video URLs video_url = cm.get_url(s) j = 1 names = [] for i in video_url: if len(video_url) == 0: print( "\nThere were no results :(\nmaybe try checking the spelling of the song\n" ) quit() try: t = pafy.new(i) names.append(f"{j} - {t.title} ({t.duration})") j += 1 except: j += 1 # print(traceback.format_exc()) # time.sleep(2) continue picker = Picker( names, "Select your choice using arrow keys or press q to quit", indicator=" => ") picker.register_custom_handler(ord('q'), lambda picker: exit()) picker.register_custom_handler(ord('Q'), lambda picker: exit()) op, c = picker.start() Console().print( Columns([ Panel( f"\nDownload size: [green]{int((pafy.new(video_url[c]).getbestaudio().get_filesize()/1048576)*100)/100} MB[/green]\n" ) ])) print() print("\nWould you like an mp3 or flac conversion?\n") Console().rule( "[bold]**** Here's a quick comparison on both codec ****[bold]", style="black", align="center") print("\n") table = Table(show_header=True, header_style="bold cyan") table.add_column("Avaliable Codec") table.add_column("Bit-rate") table.add_column("File Size") table.add_column("Remarks") table.add_row("mp3", "320kbps (default)", "~7.3MB for 3min song", "Standard codec with normal experience") table.add_row() table.add_row( "flac", "usually >800kbps (1713kbps while testing, 5x of mp3)", "~39MB for 3min song", "Takes fair amount of disk space but gives amazing experience") Console().print(table) Console().rule( "\n[bold]Note: this step [red]does not use internet[/red] [bold]\n", style="black", align="center") print('\nIf you are confused on what to select, select mp3 (default)') z = input("\tEnter\n\t1/flac/f - flac\n\tany key - mp3 : ") cm.download_song(video_url[c], '', '', z) print("\n\n") Console().print( Columns([ Panel( f"\n Your song is downloaded in \"[bold cyan]/musicDL downloads/singles[/bold cyan]\" folder on desktop \n" ) ])) print("\n\n") time.sleep(3) picker = Picker( ["Open the song directory", "Open the song itself"], "Select your choice using arrow keys or press q to quit", indicator=" => ") picker.register_custom_handler(ord('q'), lambda picker: 'qq') picker.register_custom_handler(ord('Q'), lambda picker: 'QQ') _, op = picker.start() if op == 0: if sys.platform == 'win32' or os.name == 'nt': os.startfile(".") elif sys.platform == 'linux' or os.name == 'posix': subprocess.call(['xdg-open', '.']) elif op == 1: file = pafy.new(video_url[c - 1]).title a, t = get_artist_title(file) if file + ".mp3" in os.listdir(): if sys.platform == 'win32' or os.name == 'nt': os.startfile(file + ".mp3") elif sys.platform == 'linux' or os.name == 'posix': subprocess.call(['xdg-open', file + ".mp3"]) elif t + " - " + a + ".mp3" in os.listdir(): if sys.platform == 'win32' or os.name == 'nt': os.startfile(t + " - " + a + ".mp3") elif sys.platform == 'linux' or os.name == 'posix': subprocess.call(['xdg-open', t + " - " + a + ".mp3"]) else: files = glob.glob("./*") song = max(files, key=os.path.getctime) if sys.platform == 'win32' or os.name == 'nt': os.startfile(song) elif sys.platform == 'linux' or os.name == 'posix': subprocess.call(['xdg-open', song]) else: return
class StorageExample(App): def build(self): # create picker listener self.picker = Picker(self.picker_callback) # Permission required for Picker() request_permissions([Permission.READ_EXTERNAL_STORAGE]) # cleanup temp = PrivateStorage().getCacheDir() if not temp: temp = PrivateStorage().getCacheDir('internal') temp = join(temp,"MediaStore") if exists(temp): rmtree(temp) # layout self.label_lines = [] self.label = Label(text = 'Greetings Earthlings') self.button = Button(text = 'Use Picker to get a Document', on_press = self.picker_start, size_hint=(1, .15)) self.layout = BoxLayout(orientation='vertical') self.layout.add_widget(self.label) self.layout.add_widget(self.button) return self.layout def on_start(self): # Private Storage operations self.append("PRIVATE STORAGE") self.append("Install Dir: " + str(exists(getcwd()))) self.append("FilesDir: " + str(exists(PrivateStorage().getFilesDir()))) self.append("CacheDir: " + str(exists(PrivateStorage().getCacheDir()))) # Shared Storage operations self.append("PUBLIC STORAGE:") res0 = SharedStorage().insert('./test.txt', 'Documents') res1 = SharedStorage().insert('./test.txt', sub_dir= 'a/b') res2 = SharedStorage().insert('./test.txt', 'Downloads') res3 = SharedStorage().insert('./test.jpg', 'Pictures') res4 = SharedStorage().insert('./test.mp3') res5 = SharedStorage().insert('./test.ogg', 'Music') copy_path1 = SharedStorage().retrieve('test.txt') copy_path2 = SharedStorage().retrieve('test.txt', sub_dir = 'a/b') res6 = SharedStorage().delete('test.mp3', 'Music') self.append("insert test.txt " + str(res0)) self.append("insert a/b/test.txt: " + str(res1)) self.append("insert test.txt in Downloads: " + str(res2)) self.append("insert test.jpg: " + str(res3)) self.append("insert test.mp3: " + str(res4)) self.append("insert test.ogg: " + str(res5)) self.append("retrieve test.txt " + str(exists(copy_path1))) self.append("retrieve a/b/test.txt " + str(exists(copy_path2))) self.append("deleted test.mp3 " + str(res6)) self.display() # Picker interface def picker_start(self,bt): self.picker.pick_file("application/*") def picker_callback(self,uri): try: path = SharedStorage().retrieveUri(uri) self.append("Retrieved from Picker " + str(exists(path))) self.display() except Exception as e: print('ERROR StorageExample.picker_callback():\n' + str(e)) # Label text def append(self, name): self.label_lines.append(name) @run_on_ui_thread def display(self): if self.label: self.label.text = '' for r in self.label_lines: self.label.text += fill(r, 40) + '\n'
def main(): currency = unichr(163).encode('utf-8').strip() groups = makeGroups() for g in groups: print "Group", g.name for t in g.teams: print " ", t.name, currency + str(t.cost) print "" predictor = HistoryPredictor(CostPredictor()) matchSimulator = MatchSimulator(predictor) # simulate group groupSimulator = GroupSimulator(groups, matchSimulator) groupResults = groupSimulator.simulateAllGroups() # simulate knockout round16 = makeRound16(groupResults) bracket = Bracket(round16) koSimulator = KnockoutSimulator(bracket, matchSimulator) koSimulator.simulateAllStages() print "" print "Finishing Order:" print "Winner: ", bracket.champion[0].name print "Runner Up:", bracket.runnerUp[0].name print "Third: ", bracket.third[0].name print "" # score teams scoringCriteria = ScoringCriteria(Stats(10, 7, 5, 5, 2, 0, 3, -2, 5, 0)) teams = [] for g in groups: for t in g.teams: teamScore = scoringCriteria.teamScore(t) t.score = teamScore teamTuple = (t, float(teamScore)/float(t.cost)) teams.append(teamTuple) teams.sort(key=lambda x: (x[1], -x[0].cost), reverse=True) # display teams scored by best to worst based on a per-cost basis print "Team Scores:" printLine() pFormat = "| {:>13} | {:>6} | {:>6} | {:>8} |" print pFormat.format("Team", "Score", "Cost", "S/C") printLine() for tup in teams: print pFormat.format(tup[0].name, tup[0].score, tup[0].cost, "{:.4f}".format(tup[1])) printLine() print "" print "Picks:" # pick best team from all the groups (picker params taken from scoring criteria) groupPicks, score, underfundedScore, cost = Picker(250, 0.2, 10).bestPick(groups) i = 1 for g in groupPicks: for t in g.picks: print " {:2}. (Group {:1}) {:13}".format(i, g.group.name, t.name), if DISPLAY_FINAL_STATS: print " (score = {:6} cost = {}{:5} s/c = {:>5.2f})".format(str(t.score) + ",", currency, str(t.cost) + ",", float(t.score)/float(t.cost)), else: print currency + str(t.cost), print "" i += 1 printLine() if DISPLAY_FINAL_STATS: print " Total Cost = {}{}".format(currency, cost) print " Total Score = {:.1f} (incld. underfunded score = {})".format(score + underfundedScore, underfundedScore) else: print " Total Cost {:>19}{}".format(currency, cost) printLine()
def __init__(self, config): Strategy.__init__(self, config) self.placer = Placer(config) self.picker = Picker(config)
class BasicStrategy(Strategy): def __init__(self, config): Strategy.__init__(self, config) self.placer = Placer(config) self.picker = Picker(config) def pickAndPlace(self, jobName, stepName, stream): boards = {} jobs = {} tapes = {} tapeTemplates = {} if self.config['boards']: for board in self.config['boards']: newBoard = Board(self.config) if 'name' in board: newBoard.setName(board['name']) if 'placements' in board: newBoard.setPlacements( PartPlacement.readFile(board['placements'])) else: print "No placement specified for board:", board['name'] if 'height' in board: newBoard.height = board['height'] boards[newBoard.name] = newBoard # Load up the tape templates for tapeTemplate in self.config['tapeTemplates']: template = TapeTemplate() if 'name' in tapeTemplate: template.name = tapeTemplate['name'] else: raise Exception("Missing tape template name") for name in tapeTemplate: if hasattr(template, name): setattr(template, name, tapeTemplate[name]) tapeTemplates[template.name] = template # FIXME Should validate the tapetemplate here for tape in self.config['tapes']: if not 'name' in tape: raise Exception("No name specified for tape") if not 'template' in tape: raise Exception("No template specified for tape") if not tape['template'] in tapeTemplates: raise Exception("Invalid tape template specified:", tape['template']) partTape = Tape() for name in tape: if hasattr(partTape, name): setattr(partTape, name, tape[name]) partTape.tapeTemplate = tapeTemplates[tape['template']] tapes[partTape.name] = partTape for job in self.config['jobs']: j = Job() for name in job: if hasattr(j, name) and name != "steps" and name != "boards": setattr(j, name, job[name]) for board in job['boards']: if not 'name' in board: raise Exception("Invalid board specified") if not board['name'] in boards: raise Exception("Invalid board name:" + board['name']) j.addBoard(boards[board['name']], board['reference'], board['x'], board['y'], board['second_reference']) for step in job['steps']: js = JobStep() for name in step: if hasattr(js, name): setattr(js, name, step[name]) j.steps.append(js) jobs[j.name] = j ################################## #1 Get the current job and step if not jobName in jobs: raise Exception("Invalid job name:" + jobName) currentJob = jobs[jobName] currentStep = next( (step for step in currentJob.steps if step.name == stepName), None) #2 Setup the placer with the boards stream.write("G28\n") stream.write("M302\n") stream.write("M92 E400\n") for board in currentJob.boards: self.placer.addBoard(board) self.placer.organizeBoards(stream) #3 Setup the picker with the tapes for tape in currentStep.tapes: self.picker.addTape(tapes[tape]) self.picker.organizeTapes(stream) self.picker.generatePlacements(self.placer.boards) while True: pn = self.picker.pickPart(stream) if None == pn: break self.placer.placePart(pn.board, pn.placement, pn.tape, stream)