def loadBlenderProperties(self, object): Box.loadBlenderProperties(self, object) try: self.border = object.getProperty('border').getData() except AttributeError: # No property, set default self.border = 1.0
def __init__(self,data=None,pos=None,size=None,fontsize=14,colorbg=COLORS['white'],colorfg=COLORS['tablelight']): self.data=data self.pos=pos self.size=[-1,-1] self.fontsize=fontsize self.colorbg=colorbg self.colorfg=colorfg self.alpha=1000 self.updated=False self.centeredx=False self.centeredy=True self.font=FONTS[self.fontsize] if size==None: self.size[0]=125 self.size[1]=int(5*self.fontsize*len(self.data)/4+len(self.data)) else: if size[0]>0: self.size[0]=size[0] else: self.size[0]=125 if size[1]>0: self.size[1]=size[1] else: self.size[1]=int(5*self.fontsize*len(self.data)/4+len(self.data)) Box.__init__(self,self.size,pos,self.colorbg) self.surf.set_alpha(self.alpha) if data: self.update(data)
def __init__ (self, title, widget, comment, props_={}): self.title = title self.widget = widget self.comment = comment # Properties props = props_.copy() if 'id' in props: self.id = props.pop('id') if 'class' in props: props['class'] += ' entry' else: props['class'] = 'entry' # Constructor Box.__init__ (self, props) # Compose self += Box ({'class': 'title'}, RawHTML(self.title)) if self.widget: self += Box ({'class': 'widget'}, widget) else: self += Box ({'class': 'widget'}, Container()) if isinstance(comment, Widget): self += Box ({'class': 'comment'}, comment) else: self += Box ({'class': 'comment'}, RawHTML(comment)) self += RawHTML('<div class="after"></div>')
def render(self, frame, **kwargs): box = kwargs.get('box', None) live = kwargs.get('live', None) tot_votes = kwargs.get('tot_votes', 1) tot_votes = max(tot_votes, 1) thickness = 6 if live: # red = min(4*self.votes/tot_votes, 255) red = min(255*self.votes/tot_votes, 255) green = 0 blue = 0 else: red = 0 green = 0 blue = 0 if box: if live: cv2.rectangle(frame, (box.left+thickness/2,box.top+thickness/2), (box.right-thickness/2, box.bottom-thickness/2), (blue, green, red), thickness) image_box = Box(0,0,self.mask.shape[0], self.mask.shape[1]) [image_box, frame_box] = image_box.intersect(box) frame[frame_box.top:frame_box.bottom, frame_box.left:frame_box.right] \ *= self.mask[image_box.top:image_box.bottom, image_box.left:image_box.right] frame[frame_box.top:frame_box.bottom, frame_box.left:frame_box.right] \ += self.image[image_box.top:image_box.bottom, image_box.left:image_box.right] else: if live: cv2.rectangle(frame, (self.box.left+thickness/2,self.box.top+thickness/2), (self.box.right-thickness/2, self.box.bottom-thickness/2), (blue, green, red), thickness) image_box = Box(0,0,self.mask.shape[0], self.mask.shape[1]) [image_box, frame_box] = image_box.intersect(self.box) frame[frame_box.top:frame_box.bottom, frame_box.left:frame_box.right] \ *= self.mask[image_box.top:image_box.bottom, image_box.left:image_box.right] frame[frame_box.top:frame_box.bottom, frame_box.left:frame_box.right] \ += self.image[image_box.top:image_box.bottom, image_box.left:image_box.right]
def __init__ (self, key, options, _props={}): Box.__init__ (self) self.props = _props.copy() self._options = options if not 'id' in self.props: self.id = 'RadioGroup_%s' %(self.uniq_id) cfg_value = cfg.get_val (key) for o in options: val, desc = o new_props = {} new_props['name'] = key new_props['value'] = val # Initial value if cfg_value != None and \ cfg_value == val: new_props['checked'] = 1 elif 'checked' in self.props: if self.props['checked'] == val: new_props['checked'] = 1 self += RadioText (desc, new_props)
def __init__ (self, txt, props={}): Box.__init__ (self) self.radio = Radio (props.copy()) self += self.radio self.text = Box ({'class': 'radio-text'}, RawHTML(txt)) self += self.text self.text.bind ('click', "$('#%s').attr('checked', true).trigger('change');" %(self.radio.id))
def __init__(self, text, font, color, width, padding=2.0, justify=solidfuel.constants.CENTER): VBox.__init__(self, padding=padding, justify=justify) final_lines = self._splitlines(text, font, width) for x in final_lines: if len(x): self.addChild(Text(font, x, color)) else: s = Box() s.h = font.get_height() self.addChild(s) self.pack()
def __init__ (self, _props={}): # Properties props = _props.copy() if 'class' in props: props['class'] += ' druid-button-panel' else: props['class'] = 'druid-button-panel' # Parent's constructor Box.__init__ (self, props) self.buttons = []
def __init__(self,screen): self.dx=45 self.dy=25 self.colorfg=COLORS['black'] self.font=FONTS[12] screct=screen.get_rect() self.maxrows=8 self.size=[self.dx*DECKDEFS.nseats,self.dy*self.maxrows] self.pos=(screct.right-DECKDEFS.cardsize[0]-self.size[0]-10,screct.centery-90) Box.__init__(self,self.size,self.pos,COLORS['white']) self.visible=False self.drawHeaders(screen)
def __init__(self, image): Box.__init__(self) Visible.__init__(self) if issubclass(image.__class__, Image): self.w = image.w self.h = image.h self.nativeW = image.nativeW self.nativeH = image.nativeH self._texture = image._texture elif issubclass(image.__class__, pygame.Surface): self._texture = None Image.initFromSurface(self, image)
def __init__(self): Box.__init__(self) Visible.__init__(self) self.fillColor = (0.0, 0.0, 0.0) self.borderColor = (1.0, 1.0, 1.0) self.borderWidth = 1.0 self.rotX = 0.0 self.rotY = 0.0 self.rotZ = 0.0 self.borderOpacity = 1.0 self.fillOpacity = 1.0 if Rectangle.fillDisplayList is None: self._genDisplayLists()
def __init__ (self, _props={}): # Properties props = _props.copy() if 'class' in props: props['class'] += ' ui-dialog-buttonpane' else: props['class'] = 'ui-dialog-buttonpane' props['class'] += ' ui-widget-content ui-helper-clearfix' # Parent's constructor Box.__init__ (self, props) self.buttons = []
def __init__ (self, props_={}): props = props_.copy() if 'class' in props: props['class'] += " carousel" else: props['class'] = "carousel" Box.__init__ (self, props.copy()) self.images = List ({'class': 'overview'}) self.pager = List ({'class': 'pager'}) self.controls = None Box.__iadd__ (self, self.images)
def __init__ (self, url, props={}): Box.__init__ (self) self.url = url self.id = "downloader_%d" %(self.uniq_id) # Other GUI components self.progressbar = ProgressBar() self += self.progressbar # Register the uploader path self._url_local = "/downloader_%d_report" %(self.uniq_id) publish (self._url_local, DownloadReport, url=url) download = DownloadEntry_Factory (self.url)
def __init__ (self, props={}): Box.__init__ (self, {'class': 'star-rating'}) assert type(props) == dict self.selected = props.get('selected', '5') self.can_set = props.pop('can_set', False) if 'style' in props: props['style'] += ' display:none;' else: props['style'] = 'display:none;' combo = Combobox (props.copy(), RATING_OPTIONS) self += combo
def __init__ (self, refreshable, _props={}): # Properties props = _props.copy() if 'class' in props: props['class'] += ' druid' else: props['class'] = 'druid' # Parent's constructor Box.__init__ (self, props) # Widget assert isinstance (refreshable, RefreshableURL) self.refreshable = refreshable self += self.refreshable
class Page: def __init__(self, filename): self.bb = Box((0,0),(0,0)) self.words = [] self.read_from(filename) def add_word(self, wordbox): self.words.append(wordbox) self.bb.join_with(wordbox) def read_from(self, filename): #print('reading [%s]...' % filename); stdout.flush() with open(filename) as f: getnum = lambda match, label: float(match.group(label)) data = [(getnum(m,'vpos'),getnum(m,'hpos'), getnum(m,'height'),getnum(m,'width')) for m in p.finditer(f.read())] for y,x,h,w in data: self.add_word(Box([y,x],[y+h,x+w]))
def __init__ (self, results_num, page_num, items_per_page, total_pages, refreshable): Box.__init__ (self, {'class': 'paginator-footer'}) # Get the base URL url = refreshable.url while url[-1] in string.digits+'/': url = url[:-1] # Reckon the range extra = 0 if page_num + FOOTER_OPTIONS > total_pages: extra += abs (total_pages - (page_num + FOOTER_OPTIONS)) if page_num - FOOTER_OPTIONS < 0: extra += abs (page_num - (FOOTER_OPTIONS + 1)) chunk_raw = range(page_num - (FOOTER_OPTIONS + extra), page_num + FOOTER_OPTIONS + extra + 1) chunk = filter (lambda x: x >= 0 and x < total_pages, chunk_raw) # Render it if page_num != 0: url = '%s/%d' %(refreshable.url, page_num-1) link = Link (None, RawHTML (_("Previous")), {'class': 'paginator-footer-prev'}) link.bind ('click', refreshable.JS_to_refresh(url=url)) self += link indexes = Container() for p in chunk: if p == page_num: indexes += RawHTML ("%d"%(p+1)) else: url = '%s/%d' %(refreshable.url, p) link = Link (None, RawHTML ("%d"%(p+1)), {'class': 'paginator-footer-page'}) link.bind ('click', refreshable.JS_to_refresh(url=url)) indexes += link if chunk.index(p) < len(chunk)-1: indexes += RawHTML (", ") self += indexes if page_num < total_pages-1: url = '%s/%d' %(refreshable.url, page_num+1) link = Link (None, RawHTML (_("Next")), {'class': 'paginator-footer-next'}) link.bind ('click', refreshable.JS_to_refresh(url=url)) self += link
def __init__ (self, host, req, props=None): Box.__init__ (self) self._url_local = '/proxy_widget_%d' %(self.uniq_id) if props: self.props = props else: self.props = {} if host == None: scgi = get_scgi() host = scgi.env['HTTP_HOST'] self._async = self.props.pop('async', True) self.id = 'proxy%d'%(self.uniq_id) # Register the proxy path publish (self._url_local, ProxyRequest, host=host, req=req)
def __init__ (self, opener_widget, props={}, params=None, direct=True): Box.__init__ (self) self.id = 'ajax_upload_%d' %(self.uniq_id) self._url_local = '/ajax_upload_%d' %(self.uniq_id) self.props = props.copy() self.opener_widget = opener_widget handler = self.props.get('handler') target_dir = self.props.get('target_dir') # Widgets msg = Box ({'class': 'msg'}, RawHTML(' ')) self += opener_widget self += msg # Register the uploader path publish (self._url_local, UploadRequest, handler=handler, target_dir=target_dir, params=params, direct=direct)
def __init__(self, nsim, delta=1, nx=3, nu=2, nt=10, f0=0.1, t0=350, c0=1, r=0.219, k0=7.2e10, er_ratio=8750, u=54.94, rho=1000, cp=0.239, dh=-5e4, xs=np.array([0.894, 309.8, 2]), us=np.array([300, 0.1]), x0=np.array([1, 310, 2]), control=False): self.Delta = delta self.Nsim = nsim self.Nx = nx self.Nu = nu self.Nt = nt self.F0 = f0 self.T0 = t0 self.c0 = c0 self.r = r self.k0 = k0 self.er_ratio = er_ratio self.U = u self.rho = rho self.Cp = cp self.dH = dh self.xs = xs self.us = us self.xsp = np.zeros([self.Nsim + 1, self.Nx]) self.xsp[0, :] = xs self.x0 = x0 self.x = np.zeros([self.Nsim + 1, self.Nx]) self.x[0, :] = self.x0 self.u = np.zeros([self.Nsim + 1, self.Nu]) self.u[0, :] = us self.control = control self.observation_space = np.zeros(nx) self.action_space = Box(low=np.array([-0, -0.01]), high=np.array([0, 0.01])) self.cstr_sim = mpc.DiscreteSimulator(self.ode, self.Delta, [self.Nx, self.Nu], ["x", "u"]) self.cstr_ode = mpc.getCasadiFunc(self.ode, [self.Nx, self.Nu], ["x", "u"], funcname="odef")
def childUpdateState(self, table_img=None): if (self.never_spotted and self.is_available): self.compCenterPosition() self.relevant_box = Box( int(self.box.left - constants.RESEARCH_MARGIN * self.box.width), int(self.box.top - constants.RESEARCH_MARGIN * self.box.height), (1 + 2 * constants.RESEARCH_MARGIN) * self.box.width, (1 + 2 * constants.RESEARCH_MARGIN) * self.box.height) return
def setupWindow(): global canvas, boxes, window win = Tk() win.title = "Sudoku Solver" canvas = Canvas(win, width=cWidth, height=cHeight) canvas.pack() for row in range(0, 9): for col in range(0, 9): rand = random.randint(1, 9) rect = canvas.create_rectangle(row * boxSize, col * boxSize, (row + 1) * boxSize, (col + 1) * boxSize, fill="white", outline="gray", tag="box") text = canvas.create_text(row * boxSize + (boxSize / 2), col * boxSize + (boxSize / 2), font=("Times new roman", 22), text="", tag="box") box = Box(0, row, col) boxes.append(box) canvas.tag_bind("box", "<Button-1>", boxClicked) # Create borders of sections canvas.create_line(boxSize * 3, 0, boxSize * 3, cHeight, width="2") canvas.create_line(boxSize * 6, 0, boxSize * 6, cHeight, width="2") canvas.create_line(0, boxSize * 3, cWidth, boxSize * 3, width="2") canvas.create_line(0, boxSize * 6, cWidth, boxSize * 6, width="2") separator = Frame(height=2, bd=1, relief=SUNKEN) separator.pack(fill=X, padx=5, pady=5) buttonFrame = Frame() buttonFrame.pack() startButton = Button(buttonFrame, text="Start Solving", command=startSolver) startButton.pack(side=LEFT, anchor=W, padx=20) clearButton = Button(buttonFrame, text="Clear Puzzle", command=clearPuzzle) clearButton.pack(side=LEFT, anchor=E, padx=20) createPuzzleArray() win.mainloop()
def Render (self): # Add pager and arrows if there is more than 1 item if len(self.pager) > 1 and not self.controls: arrows = Box({'class':'arrows'}) arrows += Link (None, RawHTML("%s"%(_('left'))), {'class': "buttons prev"}) arrows += Link (None, RawHTML("%s"%(_('right'))), {'class': "buttons next"}) self.controls = Box({'class':'controls'}) self.controls += arrows self.controls += self.pager Box.__iadd__ (self, self.controls) # Render render = Box.Render (self) render.headers += HEADERS render.js += JS_INIT %({'id': self.id}) return render
def Render(self): render = Box.Render(self) props = { 'id': self.id, 'url': self._url_local, 'progressbar_id': self.progressbar.id } render.js += JS_UPDATING % (props) return render
def __init__(self, nx=4, nu=3, nsim=200): self.Nx = nx self.Nu = nu self.Nsim = nsim self.observation_space = np.zeros(nx) self.action_space = Box(low=np.array([-2, -10, -2]), high=np.array([2, 10, 2])) self.x = np.zeros([self.Nsim, self.Nx]) self.u = np.zeros([self.Nsim, self.Nu]) self.xs = [100, 500, 10, 1] self.x[0, :] = [98, 503, 6, 1]
def __init__(self, grid, width, height, window): self.height = height self.width = width self.window = window self.grid = grid self.rows = 9 self.cols = 9 self.boxes = [[ Box(grid[i][j], i, j, self.width, self.height) for j in range(self.cols) ] for i in range(self.rows)]
def Render(self): props = { 'id': self.id, 'upload_url': self._url_local, 'opener_widget_id': self.opener_widget.id } render = Box.Render(self) render.headers += HEADERS render.js += JS % (props) return render
def check_for_collision(node_a, node_b): #Axes (x_axis_a, y_axis_a, z_axis_a) = CollisionDetection.find_orthnormal_axes( node_a.orientation) (x_axis_b, y_axis_b, z_axis_b) = CollisionDetection.find_orthnormal_axes( node_b.orientation) #Centers center_a = CollisionDetection.find_center(node_a.start, node_a.end) center_b = CollisionDetection.find_center(node_b.start, node_b.end) #Boxes box_a = Box(center_a, x_axis_a, y_axis_a, z_axis_a, node_a.length, node_a.width, node_a.height) box_b = Box(center_b, x_axis_b, y_axis_b, z_axis_b, node_b.length, node_b.width, node_b.height) collision = BoxBoxCollision(box_a, box_b) return collision.static_box_test()
class Driver(DriverContract.Contract): def __init__(self): self.box = Box() def startInitialConfiguration(self): self.box.onInitialConfiguration() """ Callback method Interface logic with processor or controller to determine when a box is open. Run it in loop. deactivate parameter should be removed. For Simulation only. On a separate thread, wait and see if deactivation message is received within stipulated time. If no, continue breach protocol. If yes, start deactivation protocol. """ def open(self): if self.box.initialConfigComplete: self.box.onBreach() else: self.startInitialConfiguration()
def __init__(self, settings, screen): self.settings = settings self.screen = screen self.initial_position = [0, random.randint(0, 5)] self.position = self.initial_position self.boxes = [] row = 0 for box in range(3): col = self.position[1] self.boxes.append(Box(row, col, screen)) row -= 1 self.move_right = False self.move_left = False
def build_boxes(self): ball_counts = self.ballCount() boxes = [] for stock in self.stocks: placement = self.placements[stock] box = Box(stock.name, self.unit_name, ball_counts[stock.name], FlowPlacement(placement), self.rows, self.cols) if boxes: index = self.insertPosition(placement, box, boxes) boxes.insert(index, box) else: boxes.append(box) return boxes
def childUpdateState(self, table_img): if (self.never_spotted and self.is_available): self.compCenterPosition() if self.id == 'Call': self.relevant_box = Box( int(self.box.left - constants.RESEARCH_MARGIN * self.box.width), int(self.box.top - constants.RESEARCH_MARGIN * self.box.height), (2 + 2 * constants.RESEARCH_MARGIN) * self.box.width, (1 + 2 * constants.RESEARCH_MARGIN) * self.box.height) else: self.relevant_box = Box( int(self.box.left - constants.RESEARCH_MARGIN * self.box.width), int(self.box.top - constants.RESEARCH_MARGIN * self.box.height), (1 + 2 * constants.RESEARCH_MARGIN) * self.box.width, (1 + 2 * constants.RESEARCH_MARGIN) * self.box.height) print('[Button] : "' + str(self.id) + '" spotted and available') if (self.contains_value): self.updateValue(table_img) return
def __init__(self, opener_widget, props={}, params=None, direct=True): Box.__init__(self) self.id = 'ajax_upload_%d' % (self.uniq_id) self._url_local = '/ajax_upload_%d' % (self.uniq_id) self.props = props.copy() self.opener_widget = opener_widget handler = self.props.get('handler') target_dir = self.props.get('target_dir') # Widgets msg = Box({'class': 'msg'}, RawHTML(' ')) self += opener_widget self += msg # Register the uploader path publish(self._url_local, UploadRequest, handler=handler, target_dir=target_dir, params=params, direct=direct)
def do_manual(self): input_order = [] with open('./input.txt', 'rt') as f: for line in f: line = line.strip('\n') c = line.split(' ') input_order.append(c) output_str = '' for line in input_order: box = Box(line) box.manual_run() output_str += box.output_string() print('%dth puzzle complete.') counter = 0 flag_counter = 0 for i in output_str.splitlines(): if flag_counter % 2 is 0: counter += len(i) flag_counter += 1 counter = str(counter) output_str += counter output_file(output_str)
def move(self, state): joined = "".join(state) if joined not in self.moves: blank = [i for i, x in enumerate(state) if x == "0"] self.moves[joined] = Box(blank) if self.init_method == 'random': self.moves[joined].random(self.sizes) else: self.moves[joined].uniform(self.sizes) move = self.moves[joined].choose() if move != -1: self.game.append((joined, move)) return move
def __init__(self, data = {}, parent = None): QMainWindow.__init__(self, parent) self.runned = False self.tr = Translator('mailViewer') self.autoLoadImage = False self.privateEnable = False self.data = data self.setWindowTitle(self.tr._translate('Mail Viewer')) self.setWindowIcon(QIcon().fromTheme("mail")) self.reload_ = QAction(QIcon().fromTheme("view-refresh"), '&'+self.tr._translate('Reload Job'), self) self.reload_.setShortcut('Ctrl+R') self.connect(self.reload_, SIGNAL('triggered()'), self.reloadJob) self.exit_ = QAction(QIcon().fromTheme("application-exit"), '&'+self.tr._translate('Exit'), self) self.exit_.setShortcut('Ctrl+Q') self.connect(self.exit_, SIGNAL('triggered()'), self._close) self.image_ = QAction(self.tr._translate('Image AutoLoad'), self) self.image_.setShortcut('Ctrl+I') self.image_.setCheckable(True) self.image_.setChecked(self.autoLoadImage) #self.image_.setIcon(QIcon().fromTheme("arrow-down-double")) self.connect(self.image_, SIGNAL('triggered()'), self._image) self.priv_ = QAction(self.tr._translate('Private Browsing'), self) self.priv_.setShortcut('Ctrl+P') self.priv_.setCheckable(True) self.priv_.setChecked(self.privateEnable) #self.priv_.setIcon(QIcon().fromTheme("user-group-delete")) self.connect(self.priv_, SIGNAL('triggered()'), self._private) self.menubar = self.menuBar() file_ = self.menubar.addMenu('&'+self.tr._translate('File')) file_.addAction(self.reload_) file_.addAction(self.exit_) sett_ = self.menubar.addMenu('&'+self.tr._translate('Settings')) sett_.addAction(self.image_) sett_.addAction(self.priv_) self.statusBar = QStatusBar(self) self.setStatusBar(self.statusBar) self.menuTab = Box(self.data, self) self.setCentralWidget(self.menuTab)
def __init__(self, list=None): self.set_border() if list: if type(list[1]) is str: Box.__init__(self, [list[0]] + list[2:]) self.set_name(list[1]) else: Box.__init__(self, list) else: Box.__init__(self)
def __init__(self, random_start = True, step_limit = None, ball_idle_limit = None, state_output_mode = 'pixels', rendering = True, frame_skip=4): self.action_space = ActionSpace([Action.up, Action.down, Action.forward, Action.backward, Action.nomoveshoot, Action.nomove]) self.step_limit = step_limit self.ball_idle_limit = ball_idle_limit self.state_output_mode = state_output_mode self.rendering = rendering self.ball_idle = 0 self.step_limit = step_limit if state_output_mode == 'pixels': self.rendering = True self.step_count = 0 self.random_start = random_start self.frame_skip = frame_skip self.scene = Scene(c_width, c_height) self.scene.add_object(Box(5, c_width - 5, 5, c_height - 5, 0)) self.scene.add_object(Disc(c_width / 2, c_height / 2, middle_field_radius, 10, 1, 1, Color.white).make_ghost().make_hollow().set_outer_color(Color.border)) self.scene.add_object(VerticalBorder(c_width / 2, c_height / 2, c_height - 2 * topbottom_margin, None).make_ghost()) self.scene.add_object(HorizontalBorder(c_width / 2, topbottom_margin, c_width - 2 * leftright_margin, border_restitution).extend_to(Way.up).set_collision_mask([Ball])) self.scene.add_object(HorizontalBorder(c_width / 2, c_height - topbottom_margin, c_width - 2 * leftright_margin, border_restitution).extend_to(Way.down).set_collision_mask([Ball])) self.scene.add_object(VerticalBorder(leftright_margin, (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.left).set_collision_mask([Ball])) self.scene.add_object(VerticalBorder(leftright_margin, c_height - (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.left).set_collision_mask([Ball])) self.scene.add_object(VerticalBorder(c_width - leftright_margin, (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.right).set_collision_mask([Ball])) self.scene.add_object(VerticalBorder(c_width - leftright_margin, c_height - (c_height / 2 - goal_length / 2 + topbottom_margin) / 2, c_height / 2 - topbottom_margin - goal_length / 2, border_restitution).extend_to(Way.right).set_collision_mask([Ball])) self.goal1 = Goal(leftright_margin, c_height / 2, Way.left, goal_length) self.goal2 = Goal(c_width - leftright_margin, c_height / 2, Way.right, goal_length) self.player1 = Player(120, c_height / 2, player_radius, player_mass, \ player_restitution, player_damping, player_kick_damping, player_kick_power, Side.red) self.player2 = Player(c_width - 120, c_height / 2, player_radius, player_mass, \ player_restitution, player_damping, player_kick_damping, player_kick_power, Side.blue) self.ball = Ball(c_width / 2, c_height / 2, ball_radius, ball_mass, ball_restitution, ball_damping) self.scene.add_object(self.goal1) self.scene.add_object(self.goal2) self.scene.add_object(self.player1) self.scene.add_object(self.player2) self.scene.add_object(self.ball) self.sequence1 = StateSequence([84, 84, 4]) self.sequence2 = StateSequence([84, 84, 4])
def __init__(self, width, height): """ Board class constructor. :param width: :param height: """ self.cols = width self.rows = height self.total_points = width * height self.horizontal_edges = [[False for col in range(self.cols)] for row in range(self.rows + 1)] self.vertical_edges = [[False for col in range(self.cols + 1)] for row in range(self.rows)] self.boxes = [[Box() for col in range(self.cols)] for row in range(self.rows)] self.last_move = None
def __init__ (self, url, _props={}): # Properties props = _props.copy() Dialog.__init__ (self, props) # Widget content img = ImageStock('loading', {'class': 'no-see'}) box = Box({'class': 'dialog-proxy-lazy-loader'}) box += img self += box # Event self.bind ('dialogopen', "$('#%s').show();" %(img.id) + \ JS.Ajax(url, type = 'GET', success = '$("#%s").html(data);'%(box.id)))
def __init__(self, nsim, x0=np.array([2., 2/3]), u0=np.array([2.]), xs=np.array([4., 4/3]), us=np.array([4.]), step_size=0.2, control=False, q_cost=1, r_cost=0.5, random_seed=1): self.Nsim = nsim self.x0 = x0 self.u0 = u0 self.xs = xs self.us = us self.step_size = step_size self.t = np.linspace(0, nsim * self.step_size, nsim + 1) self.control = control # Model Parameters if self.control: self.Nx = 4 # Because of offset free control else: self.Nx = 2 self.Nu = 1 self.action_space = Box(low=np.array([-5]), high=np.array([5])) self.observation_space = np.zeros(self.Nx) self.Q = q_cost * np.eye(self.Nx) self.R = r_cost self.A = np.array([[-2, 0], [0, -3]]) self.B = np.array([[2], [1]]) self.C = np.array([1]) self.D = 0 # State and Input Trajectories self.x = np.zeros([nsim + 1, self.Nx]) self.u = np.zeros([nsim + 1, self.Nu]) self.x[0, :] = x0 self.u[0, :] = u0 # Build the CasaDI functions self.system_sim = mpc.DiscreteSimulator(self.ode, self.step_size, [self.Nx, self.Nu], ["x", "u"]) self.system_ode = mpc.getCasadiFunc(self.ode, [self.Nx, self.Nu], ["x", "u"], funcname="odef") # Set-point trajectories self.xsp = np.zeros([self.Nsim + 1, self.Nx]) self.xsp[0, :] = self.xs self.usp = np.zeros([self.Nsim + 1, self.Nu]) self.usp[0, :] = self.us # Seed the system for reproducability random.seed(random_seed) np.random.seed(random_seed)
def post_process(frame, outs, conf_threshold, nms_threshold, tracking): frame_height = frame.shape[0] frame_width = frame.shape[1] # Scan through all the bounding boxes output from the network and keep only # the ones with high confidence scores. Assign the box's class label as the # class with the highest score. confidences = [] boxes = [] final_boxes = [] for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > conf_threshold: center_x = int(detection[0] * frame_width) center_y = int(detection[1] * frame_height) width = int(detection[2] * frame_width) height = int(detection[3] * frame_height) left = int(center_x - width / 2) top = int(center_y - height / 2) confidences.append(float(confidence)) boxes.append([left, top, width, height]) # Perform non maximum suppression to eliminate redundant # overlapping boxes with lower confidences. indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold) for i in indices: i = i[0] box = boxes[i] left = box[0] top = box[1] width = box[2] height = box[3] final_boxes.append(box) left, top, right, bottom = refined_box(left, top, width, height) orders = tracking.update([Box(*refined_box(*box)) for box in final_boxes]) draw_predict(frame, final_boxes, confidences, orders) return final_boxes
def setupWindow(): global boxes global canvas win = Tk() win.title = "John Conway's Game of Life" canvas = Canvas(win, width=cWidth, height=cHeight) canvas.pack() for row in range(0, int(cHeight / boxSize)): for col in range(0, int(cWidth / boxSize)): temp = canvas.create_rectangle(row * boxSize, col * boxSize, (row * boxSize) + boxSize, (col * boxSize) + boxSize, fill="gray", tag="box") boxes.append(Box(temp, col, row)) canvas.tag_bind("box", "<Button-1>", boxClicked) fillNeighbors() setFirstBoxes() # box = findBoxByCord(10,10) # print("NumOfNeigh = " + str(numOfNeighors(box))) # # print(box.on) # # onTick() # box = findBoxByCord(10,10) # print("NumOfNeigh = " + str(numOfNeighors(box))) # print(box.on) # win.mainloop() while True: win.update_idletasks() win.update() onTick() sleep(tickTime)
def write(self): splice = lambda coor4: ([coor4[1],coor4[0]],[coor4[3],coor4[2]]) from_id = lambda bid: self.canvas.coords(bid) S = Segmentation([Segment([Box(*splice(from_id(bid))) for bid in self.boxids[c]], segtype=self.segtypes[self.boxids[c][0]]) for c in self.colors.keys() if self.boxids[c]]) if self.reveal: with open(self.infilename.get()+'.demo.txt') as f: GT = Segmentation(string = f.read()) print('Pair FScore=%.3f'%S.pair_fscore(GT)) print(' Pair Precision=%.3f'%S.pair_precision(GT)) print(' Pair Recall= %.3f'%S.pair_recall(GT)) print('Jacc FScore=%.3f'%S.jaccard_fscore(GT, gamma=2.0)) print(' Jacc Precision=%.3f'%S.jaccard_precision(GT, gamma=2.0)) print(' Jacc Recall= %.3f'%S.jaccard_recall(GT, gamma=2.0)) print('writing...') with open(self.outfilename.get(),'w') as f: f.write(str(S)) self.canvas.focus_set()
def __init__(self, nsim, x0=np.array([2, 2 / 3]), u0=np.array([2]), xs=np.array([4, 4 / 3]), us=np.array([4]), step_size=0.2, control=False, q_cost=1, r_cost=0.5, s_cost=0.1, random_seed=1): self.Nsim = nsim self.x0 = x0 self.u0 = u0 self.xs = xs self.us = us self.step_size = step_size self.t = np.linspace(0, nsim * self.step_size, nsim + 1) self.control = control # Model Parameters self.Nx = 2 self.Nu = 1 self.action_space = Box(low=np.array([-5]), high=np.array([5])) self.observation_space = np.zeros(self.Nx) self.Q = q_cost * np.eye(self.Nx) self.R = r_cost self.S = s_cost self.A = np.array([[-2, 0], [0, -3]]) self.B = np.array([2, 1]) self.C = np.array([1]) self.D = 0 # State and Input Trajectories self.x = np.zeros([nsim + 1, self.Nx]) self.u = np.zeros([nsim + 1, self.Nu]) self.x[0, :] = x0 self.u[0, :] = u0 # Seed the system for reproducability random.seed(random_seed) np.random.seed(random_seed)
def draw(self): parent_height, parent_width = self.parent.get_size() parent_y, parent_x = self.parent.get_origin() self.widget = self.parent.widget.subwin( parent_height - (self.widget_spacing * 2), parent_width - (self.widget_spacing * 2), parent_y + self.widget_spacing, parent_x + self.widget_spacing) widget_height, widget_width = self.widget.getmaxyx() widget_y, widget_x = self.widget.getbegyx() # Check widgets to display if (widget_height >= self.number_of_widget_to_display + 1) and ( widget_width >= self.number_of_widget_to_display + 1): if len(self.widget_to_display.keys()): devised_box_size = widget_height / self.number_of_widget_to_display for ID in range(0, self.number_of_widget_to_display, 1): if ID == 0: self.widget_subwins[ID] = self.widget.subwin( devised_box_size - self.subwins_spacing, widget_width - self.subwins_spacing * 2, widget_y + self.subwins_spacing, widget_x + self.subwins_spacing) else: self.widget_subwins[ID] = self.widget.subwin( devised_box_size - (self.subwins_spacing / 2), widget_width - self.subwins_spacing * 2, widget_y + (devised_box_size * ID) + (self.subwins_spacing / 2), widget_x + self.subwins_spacing) self.widget_subwins[ID].bkgdset( ord(' '), curses.color_pair( self.get_style_by_type('Debug') + ID)) self.widget_subwins[ID].bkgd( ord(' '), curses.color_pair( self.get_style_by_type('Debug') + ID)) # Check widgets to display self.h_widget_list[ID] = Box(self) self.h_widget_list[ID].add(self.h_widget_list[ID].draw())
def draw_light_box(position): box = Box(1) glTranslatef(position[0], position[1] - 12, position[2]) glBegin(GL_QUADS) for shape in box.primitive3d.shapes: glMaterialfv(GL_FRONT, GL_EMISSION, [1.0, 1.0, 1.0, 1.0]) glVertex3f(shape.vertices[0].x, shape.vertices[0].y, shape.vertices[0].z) glVertex3f(shape.vertices[1].x, shape.vertices[1].y, shape.vertices[1].z) glVertex3f(shape.vertices[2].x, shape.vertices[2].y, shape.vertices[2].z) glVertex3f(shape.vertices[3].x, shape.vertices[3].y, shape.vertices[3].z) glEnd() glTranslatef(-position[0], -position[1] + 12, -position[2])
def update(self, table_img): table_img_portion = table_img.crop( (self.box.left - constants.CARD_REDET_TOL, self.box.top - constants.CARD_REDET_TOL, self.box.left + self.box.width + constants.CARD_REDET_TOL, self.box.top + self.box.height + constants.CARD_REDET_TOL)) card_colors = ['heart', 'diamond', 'club', 'spade'] #print('test') #table_img_portion.show() for i, card_color in enumerate(card_colors): try: box_relative = pyautogui.locate( '../../data/api-data/cards/card_' + card_color + '.png', table_img_portion, confidence=0.9) #print(box) if (box_relative != None): box = Box( box_relative.left + self.box.left - constants.CARD_REDET_TOL, box_relative.top + self.box.top - constants.CARD_REDET_TOL, self.box.width, self.box.height) self.box = box self.color = card_color[0] self.value = self.compCardValue(table_img) self.is_available = True #print('test1') #print("Card with id:" +str(self.id)+ " is "+str(self.value)+str(self.color)) break else: self.is_available = False self.color = None self.value = None except: self.is_available = False self.color = None self.value = None pass
def merge(boxArray): boxes = [] length = len(boxArray) while (len(boxArray) > 0): actualBox = boxArray[0] print "main box num: " + str(len(boxes)) j = 1 while (j < length): print "j: " + str(j) if(j == len(boxArray)): break xOK = 0 yOK = 0 # cast ellenorzese if (actualBox.cast == boxArray[j].cast): if (actualBox.x <= boxArray[j].x and (actualBox.x + actualBox.w) >= boxArray[j].x): xOK = 1 if (actualBox.x >= boxArray[j].x and actualBox.x <= (boxArray[j].x + boxArray[j].w)): xOK = 1 if (actualBox.y <= boxArray[j].y and (actualBox.y + actualBox.h) >= boxArray[j].y): yOK = 1 if (actualBox.y >= boxArray[j].y and actualBox.y <= (boxArray[j].y + boxArray[j].h)): yOK = 1 if (xOK and yOK): minX = min(actualBox.x, boxArray[j].x) maxX = max(actualBox.x + actualBox.w, boxArray[j].x + boxArray[j].w) minY = min(actualBox.y, boxArray[j].y) maxY = max(actualBox.y + actualBox.h, boxArray[j].y + boxArray[j].h) actualBox = Box(minX, minY, maxX-minX, maxY-minY, actualBox.cast, actualBox.prob) del boxArray[j] length -= 1 print "MERGE" if not(xOK and yOK): j += 1 else: j = 1 boxes.append(actualBox) del boxArray[0] return boxes
def __init__(self, id_, color, box, table_img): #ScreenItem.__init__(self,id_,image_path,detection_confidence) self.id = id_ self.box = box self.compCenterPosition() self.is_available = True self.value_detection_confidence = 0.75 self.hero_deg = {'right': 315, 'left': 240} self.card_values_path = "../../data/api-data/cards/values/" self.size_ref = [80, 80] self.relevant_box = Box(box.left - constants.CARD_REDET_TOL, box.top - constants.CARD_REDET_TOL, box.width + 2 * constants.CARD_REDET_TOL, box.height + 2 * constants.CARD_REDET_TOL) #self.redetection_tolerance = 20 self.color = color self.value = self.compCardValue(table_img) self.isHeroCard = self.isHeroCard(glob_file.table)
def __init__(self, nsim, delta=1, nx=3, nu=2, nt=10, f0=0.1, t0=350, c0=1, r=0.219, k0=7.2e10, er_ratio=8750, u=54.94, rho=1000, cp=0.239, dh=-5e4, xs=np.array([0.878, 324.5, 0.659]), us=np.array([300, 0.1]), x0=np.array([1, 310, 0.659]), control=False, q_cost=0.1, r_cost=0.1): self.Delta = delta self.Nsim = nsim self.Nx = nx self.Nu = nu self.Nt = nt self.F0 = f0 self.T0 = t0 self.c0 = c0 self.r = r self.k0 = k0 self.er_ratio = er_ratio self.U = u self.rho = rho self.Cp = cp self.dH = dh self.xs = xs self.us = us self.xsp = np.zeros([self.Nsim + 1, self.Nx]) self.xsp[0, :] = xs self.x0 = x0 self.x = np.zeros([self.Nsim + 1, self.Nx]) self.x[0, :] = self.x0 self.u = np.zeros([self.Nsim + 1, self.Nu]) self.u[0, :] = [300, 0.1] self.u[:, 1] = 0.1 self.control = control self.observation_space = np.zeros(nx) self.action_space = Box(low=-2.5, high=2.5, shape=(1, )) self.cstr_sim = mpc.DiscreteSimulator(self.ode, self.Delta, [self.Nx, self.Nu], ["x", "u"]) self.cstr_ode = mpc.getCasadiFunc(self.ode, [self.Nx, self.Nu], ["x", "u"], funcname="odef") # Cost function Q and R tuning parameters self.q_cost = q_cost self.r_cost = r_cost
def __init__ (self, props_={}): props = props_.copy() if 'class' in props: props['class'] += " carousel" else: props['class'] = "carousel" Box.__init__ (self, props.copy()) self.images = List ({'class': 'overview'}) self.pager = List ({'class': 'pager'}) Box.__iadd__ (self, self.images) arrows = Box({'class':'arrows'}) arrows += Link (None, RawHTML("%s"%(_('left'))), {'class': "buttons prev"}) arrows += Link (None, RawHTML("%s"%(_('right'))), {'class': "buttons next"}) controls = Box({'class':'controls'}) controls += arrows controls += self.pager Box.__iadd__ (self, controls)
def __init__(self,pos,size,colorbg,colorfg,font): self.font=font self.colorfg=colorfg Box.__init__(self,size,pos,colorbg)
def setBlenderProperties(self, object): Box.setBlenderProperties(self, object) object.addProperty('border', self.border, 'FLOAT')
def __init__ (self, **kwargs): Box.__init__ (self, {'class': "propstable"})
def __init__ (self): Box.__init__ (self) url = druid_url_next (request.url) self += RawHTML (js = DruidContent__JS_to_goto (self.id, url))
class MainWindow(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.runned = False self.tr = Translator("Thrifty") # self.resize(450, 350) self.setWindowTitle(self.tr._translate("Thrifty")) self.setWindowIcon(QIcon("/usr/share/thrifty/icons/sniper_soldier.png")) self.Settings = QSettings("thrifty", "thrifty") self.exit_ = QAction(QIcon("/usr/share/thrifty/icons/exit.png"), self.tr._translate("&Exit"), self) self.exit_.setShortcut("Ctrl+Q") self.exit_.setStatusTip(self.tr._translate("Exit application")) self.connect(self.exit_, SIGNAL("triggered()"), self._close) listHelp = QAction(QIcon("/usr/share/thrifty/icons/help.png"), self.tr._translate("&About Thrifty"), self) listHelp.setStatusTip(self.tr._translate("Read help")) self.connect(listHelp, SIGNAL("triggered()"), self.showMSG) self.stopProcess = QAction( QIcon("/usr/share/thrifty/icons/terminate.png"), self.tr._translate("&Terminate Task"), self ) self.stopProcess.setShortcut("Ctrl+T") self.stopProcess.setStatusTip(self.tr._translate("Terminate running task ...")) self.stopProcess.setEnabled(False) self.connect(self.stopProcess, SIGNAL("triggered()"), self.terminateRunningTask) self.separator = QAction("", self) self.separator.setSeparator(True) self.checkMode = QAction(self.tr._translate("check file`s &mode"), self) self.checkMode.setCheckable(True) value = str(self.Settings.value("checkFileMode", "False").toString()) if value.lower() == "true": self.checkMode.setChecked(True) else: self.checkMode.setChecked(False) self.connect(self.checkMode, SIGNAL("changed()"), self.setCheckMode) self.checkOwners = QAction(self.tr._translate("check file`s &owners"), self) self.checkOwners.setCheckable(True) value = str(self.Settings.value("checkFileOwners", "False").toString()) if value.lower() == "true": self.checkOwners.setChecked(True) else: self.checkOwners.setChecked(False) self.connect(self.checkOwners, SIGNAL("changed()"), self.setCheckOwners) self.checkMtime = QAction(self.tr._translate("check file`s mt&ime"), self) self.checkMtime.setCheckable(True) value = str(self.Settings.value("checkFileMtime", "False").toString()) if value.lower() == "true": self.checkMtime.setChecked(True) else: self.checkMtime.setChecked(False) self.connect(self.checkMtime, SIGNAL("changed()"), self.setCheckMtime) self.statusBar = StatusBar(self) self.setStatusBar(self.statusBar) self.prelink = QAction(QIcon("/usr/share/thrifty/icons/prelink.png"), self.tr._translate("&Prelink"), self) self.prelink.setShortcut("Ctrl+P") self.prelink.setStatusTip(self.tr._translate("Prelink now")) self.prelink.setEnabled(prelinkInstalled) self.connect(self.prelink, SIGNAL("triggered()"), self.runPrelink) menubar = self.menuBar() file_ = menubar.addMenu(self.tr._translate("&File")) file_.addAction(self.prelink) file_.addAction(self.exit_) set_ = menubar.addMenu(self.tr._translate("&Control")) set_.addAction(self.stopProcess) set_.addAction(self.separator) set_.addAction(self.checkMode) set_.addAction(self.checkOwners) set_.addAction(self.checkMtime) help_ = menubar.addMenu(self.tr._translate("&Help")) help_.addAction(listHelp) self.menuTab = Box(self) self.setCentralWidget(self.menuTab) def setCheckMode(self): state = self.checkMode.isChecked() print state self.Settings.setValue("checkFileMode", state) def setCheckOwners(self): state = self.checkOwners.isChecked() # print state self.Settings.setValue("checkFileOwners", state) def setCheckMtime(self): state = self.checkMtime.isChecked() # print state self.Settings.setValue("checkFileMtime", state) def detectRunningTask(self): name = "Unknown" obj = None if self.menuTab.checkFile.runned: name = "CheckFile" obj = self.menuTab.checkFile elif self.menuTab.backUp.runned: name = "BackUp" obj = self.menuTab.backUp elif self.menuTab.cleanUp.runned: name = "CleanUp" obj = self.menuTab.cleanUp elif self.menuTab.broken.runned: name = "Search Broken" obj = self.menuTab.broken elif self.runned: name = "Prelink" obj = self return name, obj def terminateRunningTask(self): name, obj = self.detectRunningTask() # print 'Terminated Task : %s' % name if obj is not None: obj.t.terminate() def runPrelink(self): self.prelink.setEnabled(False) self.menuTab.setTabsState(False) # self.progress.show() self.runned = True print "Prelink running ..." self.t = QProcess() Data = QStringList() Data.append("prelink") Data.append("-a") self.t.finished.connect(self.showResult) self.t.start("pkexec", Data) if self.t.waitForStarted(): self.runned = True # print self.t.state() else: self.showResult() def showResult(self): self.prelink.setEnabled(True) self.runned = False self.menuTab.setTabsState(True) def showMSG(self, s=""): msg = ListingText(HELP if s == "" else s, self) msg.exec_() def _close(self): self.Settings.sync() self.close()
def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.runned = False self.tr = Translator("Thrifty") # self.resize(450, 350) self.setWindowTitle(self.tr._translate("Thrifty")) self.setWindowIcon(QIcon("/usr/share/thrifty/icons/sniper_soldier.png")) self.Settings = QSettings("thrifty", "thrifty") self.exit_ = QAction(QIcon("/usr/share/thrifty/icons/exit.png"), self.tr._translate("&Exit"), self) self.exit_.setShortcut("Ctrl+Q") self.exit_.setStatusTip(self.tr._translate("Exit application")) self.connect(self.exit_, SIGNAL("triggered()"), self._close) listHelp = QAction(QIcon("/usr/share/thrifty/icons/help.png"), self.tr._translate("&About Thrifty"), self) listHelp.setStatusTip(self.tr._translate("Read help")) self.connect(listHelp, SIGNAL("triggered()"), self.showMSG) self.stopProcess = QAction( QIcon("/usr/share/thrifty/icons/terminate.png"), self.tr._translate("&Terminate Task"), self ) self.stopProcess.setShortcut("Ctrl+T") self.stopProcess.setStatusTip(self.tr._translate("Terminate running task ...")) self.stopProcess.setEnabled(False) self.connect(self.stopProcess, SIGNAL("triggered()"), self.terminateRunningTask) self.separator = QAction("", self) self.separator.setSeparator(True) self.checkMode = QAction(self.tr._translate("check file`s &mode"), self) self.checkMode.setCheckable(True) value = str(self.Settings.value("checkFileMode", "False").toString()) if value.lower() == "true": self.checkMode.setChecked(True) else: self.checkMode.setChecked(False) self.connect(self.checkMode, SIGNAL("changed()"), self.setCheckMode) self.checkOwners = QAction(self.tr._translate("check file`s &owners"), self) self.checkOwners.setCheckable(True) value = str(self.Settings.value("checkFileOwners", "False").toString()) if value.lower() == "true": self.checkOwners.setChecked(True) else: self.checkOwners.setChecked(False) self.connect(self.checkOwners, SIGNAL("changed()"), self.setCheckOwners) self.checkMtime = QAction(self.tr._translate("check file`s mt&ime"), self) self.checkMtime.setCheckable(True) value = str(self.Settings.value("checkFileMtime", "False").toString()) if value.lower() == "true": self.checkMtime.setChecked(True) else: self.checkMtime.setChecked(False) self.connect(self.checkMtime, SIGNAL("changed()"), self.setCheckMtime) self.statusBar = StatusBar(self) self.setStatusBar(self.statusBar) self.prelink = QAction(QIcon("/usr/share/thrifty/icons/prelink.png"), self.tr._translate("&Prelink"), self) self.prelink.setShortcut("Ctrl+P") self.prelink.setStatusTip(self.tr._translate("Prelink now")) self.prelink.setEnabled(prelinkInstalled) self.connect(self.prelink, SIGNAL("triggered()"), self.runPrelink) menubar = self.menuBar() file_ = menubar.addMenu(self.tr._translate("&File")) file_.addAction(self.prelink) file_.addAction(self.exit_) set_ = menubar.addMenu(self.tr._translate("&Control")) set_.addAction(self.stopProcess) set_.addAction(self.separator) set_.addAction(self.checkMode) set_.addAction(self.checkOwners) set_.addAction(self.checkMtime) help_ = menubar.addMenu(self.tr._translate("&Help")) help_.addAction(listHelp) self.menuTab = Box(self) self.setCentralWidget(self.menuTab)