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 check_for_collision_velocity(node_a, node_b, time_step): #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) #Boxes box_a = Box(node_a.start, x_axis_a, y_axis_a, z_axis_a, node_a.length, node_a.width, node_a.height) box_b = Box(node_b.start, x_axis_b, y_axis_b, z_axis_b, node_b.length, node_b.width, node_b.height) #Velocities velocity_a = node_a.calc_velocity(time_step) velocity_b = node_b.calc_velocity(time_step) #Time t_max = time_step collision = BoxBoxCollision(box_a, box_b) return collision.linear_box_test(t_max, velocity_a, velocity_b)
def __init__(self): self.body = [ Box(70, 0, (255, 0, 0)), Box(60, 0, (255, 0, 0)), Box(50, 0, (255, 0, 0)) ] self.velocity = 10 self.just_ate = False
def main(): head = Box(9) box1 = Box(8) box2 = Box(7) box3 = Box(6) head.Next = box1 box1.Next = box2 box2.Next = box3 print(countElementsInLinkedList(head))
def __iadd__ (self, widget): box = Box ({'class': 'carousel-thumbs'}) box += RawHTML ("%s" %(len(self.images.child) +1)) box += Box ({'class': 'carousel_thumbs-image'}, widget) link = Link (None, Box ({'class': 'carousel_thumbs-link'}, box)) self.images += widget self.pager += link self.pager[-1].props['class'] = 'pagenum' return self
def Render(self): render = Widget.Render(self) # Total pages tmp = len(self.items) / float(self.items_per_page) if int(tmp) < tmp: total_pags = int(tmp) + 1 else: total_pags = int(tmp) or 1 if total_pags > 1 or self.show_footer_1pag: title = Box({'class': 'paginator-counter'}, RawHTML("Page %d of %d" % (self.page_num + 1, total_pags))) render += title.Render() # Content range_start = self.items_per_page * self.page_num range_end = self.items_per_page * (self.page_num + 1) for item in self.items[range_start:range_end]: render += item.Render() # Add footer if total_pags > 1 or self.show_footer_1pag: footer = Paginator_Footer(len(self.items), self.page_num, self.items_per_page, total_pags, self.refreshable) render += footer.Render() return render
def seg_from_json(fname, gt_flag): with open(fname) as data_file: data = json.load(data_file) annotations = {} if gt_flag: annotations = data[0]["annotations"] else: annotations = data["annotations"] # print annotations[0].items() # TODO: make sure to address the box type (article/image/title) assignment problem (i.e. # at box or polygon level) polygon_dict = {} # polygon_dict has key = id, value = list of boxes for segment in annotations: if segment['id'] not in polygon_dict: polygon_dict[segment['id']] = [] coord0 = [segment['y'], segment['x']] coord1 = [coord0[0] + segment['height'], coord0[1] + segment['width']] polygon_dict[segment['id']].append(Box(coor0=coord0, coor1=coord1)) # convert polygons dict to Segmentation object #seg = Segmentation() polygons = [Polygon(boxes=boxList) for boxList in polygon_dict.values()] return Segmentation(segments=polygons)
def enter(): global player, enemys, trees, x, y, map, itemslot, bushes, boxes, bananas game_world.objects = [[], [], []] player = Player() map = Map() enemys = [Enemy_Gun() for n in range(4)] #itemslot = ItemSlot() trees = [Tree() for n in range(23)] bushes = [Bush() for n in range(4)] boxes = [Box() for n in range(5)] bananas = [Banana() for n in range(2)] global key key = Key() game_world.add_object(key, 1) for enemy in enemys: game_world.add_object(enemy, 1) game_world.add_object(player, 1) for tree in trees: game_world.add_object(tree, 1) for banana in bananas: game_world.add_object(banana, 1) for bush in bushes: game_world.add_object(bush, 1) for box in boxes: game_world.add_object(box, 1) game_world.add_object(map, 0) player.hp = main_state.hp
def search(self, table_img): #print(self.relevant_box) if (self.relevant_box == 'ALL'): searched_img = table_img else: searched_img = table_img.crop( (self.relevant_box.left, self.relevant_box.top, self.relevant_box.left + self.relevant_box.width, self.relevant_box.top + self.relevant_box.height)) #print(box_relative) #searched_img.show() try: #Attempt to locate screen item self.box = pyautogui.locate(self.image_file_path, searched_img, confidence=self.detection_confidence) if (self.relevant_box != 'ALL'): self.box = Box(self.box.left + self.relevant_box.left, self.box.top + self.relevant_box.top, self.box.width, self.box.height) if (self.box != None): spotted = True else: spotted = False except: spotted = False #print('ScreenItem : "'+ self.id +'" is NOT available') return spotted
def detect_image(self, image, tracking): if self.model_image_size != (None, None): assert self.model_image_size[ 0] % 32 == 0, 'Multiples of 32 required' assert self.model_image_size[ 1] % 32 == 0, 'Multiples of 32 required' boxed_image = letterbox_image( image, tuple(reversed(self.model_image_size))) else: new_image_size = (image.width - (image.width % 32), image.height - (image.height % 32)) boxed_image = letterbox_image(image, new_image_size) image_data = np.array(boxed_image, dtype='float32') image_data /= 255. # add batch dimension image_data = np.expand_dims(image_data, 0) out_boxes, out_scores, out_classes = self.sess.run( [self.boxes, self.scores, self.classes], feed_dict={ self.yolo_model.input: image_data, self.input_image_shape: [image.size[1], image.size[0]], K.learning_phase(): 0 }) out_boxes = out_boxes.astype(int) orders = tracking.update( [Box(box[1], box[0], box[3], box[2]) for box in out_boxes]) image = np.asarray(image) image = draw_predict_gpu(image, out_boxes, out_scores, orders) return image, out_boxes
class ShapeTester: print('Welcome to the Shape Tester') print('Please type \'Box\', \'Sphere\', or \'Pyramid\'') while True i= input('>') if i == 'Box': print('Alright, let us start with a box.') width= int(input("Please enter a width:")) length= int(input("Please input a length: ")) height= int(input("Please input a height: ")) b1=Box(width,length,height) print('Volume: %s' % b1.getVolume()) print('Surface Area: %s' % b1.getSA()) elif i == 'Sphere': print('Alright, let us start with a sphere.') radius = int(input("Please enter a radius: ")) s1=Sphere(radius) print('Volume: %s' % s1.getVolume()) print('Surface Area: %s' % s1.getSA()) elif i == 'Pyramid': print('Alright, let us start with a pyramid.') width= int(input("Please enter a width:")) length= int(input("Please input a length: ")) height= int(input("Please input a height: ")) p1=Pyramid(length,width,height) print('Volume: %s' % p1.getVolume()) print('Surface Area: %s' % p1.getSA()) else: print('mmmmmmm, try again.')
def test_last_movement(move, speed, pacman): test = Box(pacman.rect.x, pacman.rect.y, RED) global last_movement if move == 'U': test.rect.top -= speed if not pygame.sprite.spritecollide(test, box_group, False): pacman_group.update(move) else: pacman_group.update('') elif move == 'D': test.rect.bottom += speed if not pygame.sprite.spritecollide(test, box_group, False): pacman_group.update(move) else: pacman_group.update('') elif move == 'L': test.rect.left -= speed if not pygame.sprite.spritecollide(test, box_group, False): pacman_group.update(move) else: pacman_group.update('') elif move == 'R': test.rect.right += speed if not pygame.sprite.spritecollide(test, box_group, False): pacman_group.update(move) else: pacman_group.update('')
def __init__(self, frame_skip = 2): height = 400 width = 600 goal_length = 300 self.scene = Scene(width, height) self.frame_skip = frame_skip self.ball_idle = 0 self.ball_idle_limit = 3 self.action_space = ActionSpace([Action.up, Action.down, Action.nomoveshoot]) self.box = Box(0, width, 0, height, 0) self.goal1 = Goal(leftright_margin, height / 2, Way.left, goal_length) self.player1 = Player(80, height / 2, player_radius, player_mass, \ player_restitution, player_damping, player_kick_damping, player_kick_power, Side.red) self.ball = Ball(width - 100, height / 2, ball_radius, ball_mass, ball_restitution, ball_damping) self.penalty_spot = Disc(self.ball.center.x, self.ball.center.y, 4, 0, 0, 0, Color.green).make_ghost().make_hollow() # self.player_border_left = VerticalBorder(50, height / 2, height, 0, visible=True) # self.player_border_right = VerticalBorder(100, height / 2, height, 0, visible=True) self.scene.add_object(self.goal1) self.scene.add_object(self.player1) self.scene.add_object(self.ball) self.scene.add_object(self.penalty_spot) self.scene.add_object(self.box) self.reset()
def get_input(self): # Get each line of letters for x in range(self.rowLength): letters = raw_input() # Use each letter in the line to create a cell. Create the cell list. for letter in letters: self.boxes[letter] = "test" cell = Cell(letter, 0, None, self.rowLength) self.cells.append(cell) # Get Letter to Result/Operation mappings. Create boxes. for x in range(len(self.boxes)): lineSections = raw_input().split(':') character = lineSections[0] numberAndOperation = lineSections[1] operation = numberAndOperation[len(numberAndOperation) - 1] number = numberAndOperation[:-1] box = Box(number, operation) self.boxes[character] = box # Assign boxes to cells for cell in self.cells: box = self.boxes[cell.letter] cell.box = box box.cells.append(cell) # Assign rows and columns to cells for cellIndex in range(len(self.cells)): self.cells[cellIndex].row = self.rows[cellIndex / self.rowLength] self.cells[cellIndex].column = self.columns[cellIndex % self.rowLength]
def read_in_file(path): f = open(path) listOfBoxes = [] for line in f: chars = line.split(" ") listOfBoxes.append(Box(int(chars[0]), int(chars[1]), int(chars[2]))) return listOfBoxes
def run(num_particles, box_width, box_height, temp, num_steps): fig, ax = plt.subplots() particle_array = [] for i in range(num_particles): random_x = np.random.uniform(0, box_width) random_y = np.random.uniform(0, box_height) ptcle = Particle(random_x, random_y) particle_array.append(ptcle) # Box with initial starting configuration box = Box(box_width, box_height, particle_array) points, = ax.plot(box.get_x_array(), 'o', c='red', markersize=5) ax.set_ylim(0, box_height) ax.set_xlim(0, box_width) ani = animation.FuncAnimation(fig, metropolis, frames=np.arange(0, num_steps), fargs=(box, temp, num_particles, points), interval=1) plt.grid() plt.title("Metropolis-Hastings Gas Simulation. %d particles at %d K" % (num_particles, temp)) plt.show()
def __init__(self, fileinit, filegoal): """ filename has the form pathto/sokoInstxy without the .goal or .init This constructor make the static board and give the dynamic items (boxes, char) to the first state. """ self.board = Board(filegoal) self.numbernodes = 0 Io = IO(fileinit) Io.init_reader() self.boxes = [] i = 0 j = 0 for line in Io.file : for elem in line : if elem == "$" : self.boxes.append(Box(i,j)) elif elem == "@": self.char = Char(i,j) j+=1 j=0 i+=1 self.direction = [Direction.UP,Direction.DOWN,Direction.LEFT,Direction.RIGHT] self.goalsize = len(self.board.positionGoal) self.listCombi = heuristic.make_combi(self.board.positionGoal,self.goalsize) self.mini = 10000 Problem.__init__(self, State(self.board,self.boxes,self.char,[]))
def DrawGLScene(): initial_time = time.time() global box, eyeX, eyeY, eyeZ, tori, ecube, sphere, SHAPE, num, number, drawType, time_between_frames, refresh_time glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() # Reset The View if (SHAPE == "C"): if (num != number): box = Box(quad_len) box.subdivide(number) num = number scene.drawPrim(box.primitive3d, eyeX, eyeY, eyeZ, angle_h, angle_v, distance, drawType) if (SHAPE == "S"): if (num != number): sphere = Sphere(2, 2, 2) sphere = Sphere(2, 2 + number, 2 + number) num = number scene.drawPrim(sphere.primitive3d, eyeX, eyeY, eyeZ, angle_h, angle_v, distance, drawType) scene.draw_xyz_axis() time_after_drawing = time.time() if ((time_after_drawing - initial_time) < refresh_time): time.sleep(refresh_time - (time_after_drawing - initial_time)) glutSwapBuffers()
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): 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")
def box_from_json(fname): with open(fname) as data_file: data = json.load(data_file) annotations = data[0]["annotations"] polygon_dict = {} # polygon_dict has key = id, value = list of boxes id = 0 for segment in annotations: id_str = str(id) if id_str not in polygon_dict: polygon_dict[id_str] = [] id += 1 coord0 = [segment['y'], segment['x']] coord1 = [coord0[0] + segment['height'], coord0[1] + segment['width']] polygon_dict[id_str].append( Box(coor0=coord0, coor1=coord1, label=segment['class'])) # convert polygons dict to Segmentation object polygons = [Polygon(boxes=boxList) for boxList in polygon_dict.values()] #img_name = fname[:fname.rfind('/') + 1] + data[0]['filename'] # newsimage = NewsImage(img_name[:img_name.rfind('.')]) # print img_name[:img_name.rfind('.')] #for p in polygons: # p.weight_image = newsimage #Polygon.weight_image = newsimage return Segmentation(segments=polygons)
def set_up_array_board(self): self.array_board = [] for num in range(0, 9): column = [] for num in range(0, 9): column.append(Box(self)) self.array_board.append(column)
class ShapeTester: print('welcome to Shape Tester') print('Please choose \'box\', \'pyramid\', or \'sphere\'') while True: shape = input('>') if shape == 'box': print('You Chose Box') width = int(input('choose a width: ')) height = int(input('choose a height: ')) length = int(input('choose a length: ')) b1 = Box(length, width, height) print('The Volume is: %f' % b1.getVolume()) print('The Surface Area is %f' % b1.getSurfArea()) elif shape == 'pyramid': print('You Chose Pyramid') width = int(input('choose a width: ')) height = int(input('choose a height: ')) length = int(input('choose a length: ')) p1 = Pyramid(length, width, height) print('The Volume is: %f' % p1.getVolume()) print('The Surface Area is %f' % p1.getSurfArea()) elif shape == 'sphere': print('You Chose Sphere') radius = int(input('choose a radius: ')) s1 = Sphere(radius) print('The Volume is: %f' % s1.getVolume()) print('The Surface Area is: %f' % s1.getSurfArea()) else: print('incorrect syntax try again')
def boxDemonstration(): myBox = Box(2.5, 5, 7.5) print("The box dimensions are h: {}, w: {}, l: {}".format( myBox.getHeight(), myBox.getWidth(), myBox.getLength())) print("The volume of the box is {} inches".format(myBox.calcVolume())) print("The surface area of the box is {} inches.".format( myBox.calcSurfaceArea()))
def __init__(self): self.board_length = 7 self.coins_for_daddy = 3 self.board = [[Box() for _ in range(self.board_length)] for _ in range(self.board_length)] self.valid_positions = [] self.loadValidPositions() self.loadDefaultBoard()
def __init__(self): self.board = list() for i in range(BOARD_SIZE): row = list() for j in range(BOARD_SIZE): box = Box() row.append(box) self.board.append(row)
def move_box(self, y, x, direction): newboxes = [] for box in self.boxes: if y == box.y and x == box.x: if direction == Direction.UP: newboxes.append(Box(y - 1, x)) elif direction == Direction.DOWN: newboxes.append(Box(y + 1, x)) elif direction == Direction.LEFT: newboxes.append(Box(y, x - 1)) elif direction == Direction.RIGHT: newboxes.append(Box(y, x + 1)) else: pass else: newboxes.append(box) return self.clone_boxes(newboxes)
def firstStep(): #return row and col global box row = eval(input("Enter the row of the grid: ")) col = eval(input("Enter the col of the grid: ")) box = Box(row, col)
def __init__(self, nsim, x0=np.array([3]), u0=np.array([3, 6]), xs=np.array([4.5]), us=np.array([5.5, 8]), 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 = 2 # Because of offset free control else: self.Nx = 1 self.Nu = 2 self.action_space = Box(low=np.array([-12, -12]), high=np.array([12, 12])) self.Q = q_cost self.R = r_cost * np.eye(self.Nu) self.A = np.array([-3]) self.B = np.array([1, 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 setup_objects_default(self): ''' Function for setting up default simulation parameters\n Input: None\n Output: None ''' self.platform = Platform((200, 200), (10, 10), 50, self.screen, self.font, self.sim_speed) self.box = Box((40, 80), [450, 700, 0], self.sim_speed, self.screen)
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))