Пример #1
0
    def get_bugs(self, project_name, statuses, time_range=None, tags=None):
        project = self._get_project(project_name)
        today = date.today()

        # default target_date
        target_date = today + relativedelta(days=-90)
        try:
            target_date = today + relativedelta(days=-int(time_range))
        except (TypeError, ValueError):
            if (time_range == '1d'):
                target_date = today + relativedelta(days=-1)
            elif (time_range == '5d'):
                target_date = today + relativedelta(days=-5)
            elif (time_range == '1m'):
                target_date = today + relativedelta(months=-1)
            elif (time_range == '3m'):
                target_date = today + relativedelta(months=-3)
            elif (time_range == '6m'):
                target_date = today + relativedelta(months=-6)
            elif (time_range == '1y'):
                target_date = today + relativedelta(years=-1)
            else:
                return [Bug(r) for r in project.searchTasks(status=statuses)]

        return [
            Bug(r)
            for r in project.searchTasks(status=statuses,
                                         created_since=target_date.isoformat())
        ]
Пример #2
0
 def __eat(self, bug: Bug):
     # 头的坐标和虫子的坐标一样就发生吃
     if self.__list[0] == bug.point[0]:
         # 虫子瞬移
         bug.quicly_move(self.__list)
         # 蛇加长
         self.__list.append(self.__list[-1])
Пример #3
0
 def __init__(self, n, m):
     self.n = n
     self.m = m
     self.empty = 0
     self.poop = 1
     self.board = get_frame(n, m, self.empty, self.poop)
     self.bug = Bug()
     self.show_bug()
Пример #4
0
 def get_bugs(self,
              project_name,
              statuses,
              milestone_name=None,
              tags=[],
              importance=[],
              **kwargs):
     result_bugs = self.get_all_bugs_by(project_name, milestone_name)
     result_bugs = [task for task in result_bugs if task.status in statuses]
     if milestone_name:
         result_bugs = [
             task for task in result_bugs
             if task.milestone_link.split('/')[-1] in milestone_name
         ]
     if importance:
         result_bugs = [
             task for task in result_bugs if task.importance in importance
         ]
     if tags:
         if kwargs.get("condition"):
             result_bugs = [
                 task for task in result_bugs
                 if len(set(task.bug.tags).difference(set(tags))) > 0
             ]
         else:
             result_bugs = [
                 task for task in result_bugs
                 if len(set(task.bug.tags).intersection(set(tags))) > 0
             ]
     return [Bug(self.serialize_private(bug)) for bug in result_bugs]
Пример #5
0
    def setUp(self):
        self.fp = FlyPaper(None, None, datetime(2011, 1, 1, 0, 0, 0), False,
                           'plain')

        #create a few bugs and changesets
        bug1id = 'bug1'
        self.bug1 = Bug(bug1id)
        self.fp._buglist.add(self.bug1)

        bug2id = 'bug2'
        self.bug2 = Bug(bug2id)
        self.fp._buglist.add(self.bug2)

        #only one bug is part of a changeset
        self.chg1 = Changeset('abc', datetime(2012, 1, 5, 8, 22, 0), bug1id)
        self.fp._changesets.add(self.chg1)
Пример #6
0
class TestBug(unittest.TestCase):

    def setUp(self):
        self.bug = Bug(TestFiles.IMG, TestFiles.RELATIVE_BOUNDING_BOX)


    def test_includes_organism_into_turtle(self):
        self.assertEqual(self.bug.as_turtle(), TestFiles.RDF_SINGLE_BUG)
Пример #7
0
    def search(self):
        r"""
            Call the Bugzilla endpoint that will do the search. It will take
            the information used in other methods on the Search object and
            build up the query string. If no bugs are found then an empty list
            is returned.

            >>> bugs = bugzilla.search_for\
            ...                .keywords("checkin-needed")\
            ...                .include_fields("flags")\
            ...                .search()
        """
        params = {}
        params = dict(params.items() + self._time_frame.items())

        if self._includefields:
            params['include_fields'] = list(self._includefields)
        if self._bug_numbers:
            bugs = []
            for bug in self._bug_numbers:
                result = self._bugsy.request('bug/%s' % bug, params=params)
                bugs.append(Bug(self._bugsy, **result['bugs'][0]))

            return bugs
        else:
            if self._keywords:
                params['keywords'] = list(self._keywords)
            if self._assigned:
                params['assigned_to'] = list(self._assigned)
            if self._summaries:
                params['short_desc_type'] = 'allwordssubstr'
                params['short_desc'] = list(self._summaries)
            if self._whiteboard:
                params['short_desc_type'] = 'allwordssubstr'
                params['whiteboard'] = list(self._whiteboard)
            if self._change_history['fields']:
                params['chfield'] = self._change_history['fields']
            if self._change_history.get('value', None):
                params['chfieldvalue'] = self._change_history['value']

            try:
                results = self._bugsy.request('bug', params=params)
            except Exception as e:
                raise SearchException(e.msg, e.code)

            return [Bug(self._bugsy, **bug) for bug in results['bugs']]
Пример #8
0
 def create_bug(self, options={}):
     bug = Bug(point=self._point_or_random(options),
               size=self._size_or_default(options, "bug"))
     cell = self.get_cell(bug.point.x, bug.point.y)
     cell.bugs[bug.id] = bug
     self._bug_cells[cell.id] = cell
     self._bugs[bug.id] = bug
     self.update()
     return bug
Пример #9
0
    def ConvertToString(self, prev_time, diff_map, bug_anno_map,
                        issue_detail_mode):
        """Convert this result to HTML display for email.

    Args:
      prev_time: the previous time string that are compared against.
      diff_map: the compared map generated by |CompareResultMaps()|.
      bug_anno_map: a annotation map where keys are bug names and values are
          annotations for the bug.
      issue_detail_mode: includes the issue details in the output string if
          this is True.

    Returns:
      a analyzer result string in HTML format.
    """
        return_str = ''
        if diff_map:
            return_str += (
                '<b>Statistics (Diff Compared to %s):</b><ul>'
                '<li>The number of tests: %d (%s)</li>'
                '<li>The number of failing skipped tests: %d (%s)</li>'
                '<li>The number of failing non-skipped tests: %d (%s)</li>'
                '<li>Passing rate: %d %%</li></ul>'
            ) % (prev_time, len(self.result_map['whole'].keys()),
                 AnalyzerResultMap.GetDiffString(diff_map['whole'], 'whole'),
                 len(self.result_map['skip'].keys()),
                 AnalyzerResultMap.GetDiffString(diff_map['skip'], 'skip'),
                 len(self.result_map['nonskip'].keys()),
                 AnalyzerResultMap.GetDiffString(
                     diff_map['nonskip'], 'nonskip'), self.GetPassingRate())
        if issue_detail_mode:
            return_str += '<b>Current issues about failing non-skipped tests:</b>'
            for (bug_txt, test_info_list) in (
                    self.GetListOfBugsForNonSkippedTests().iteritems()):
                if not bug_txt in bug_anno_map:
                    bug_anno_map[bug_txt] = ''
                else:
                    bug_anno_map[bug_txt] = '(' + bug_anno_map[bug_txt] + ')'
                return_str += '<ul>%s %s' % (Bug(bug_txt),
                                             bug_anno_map[bug_txt])
                for test_info in test_info_list:
                    (test_name, te_info) = test_info
                    gpu_link = ''
                    if 'GPU' in te_info:
                        gpu_link = 'group=%40ToT%20GPU%20Mesa%20-%20chromium.org&'
                    dashboard_link = (
                        'http://test-results.appspot.com/dashboards/'
                        'flakiness_dashboard.html#%stests=%s') % (gpu_link,
                                                                  test_name)
                    return_str += '<li><a href="%s">%s</a> (%s) </li>' % (
                        dashboard_link, test_name, ' '.join(te_info.keys()))
                return_str += '</ul>\n'
        return return_str
Пример #10
0
def run_game():

    s = Settings()
    screen = pg.display.set_mode(s.display_size)
    screen_width = screen.get_width()
    screen_height = screen.get_height()
    pg.display.set_caption('Life')

    map = Map(screen,
              weight=s.weight,
              bias=s.bias,
              pixel_size=s.pixel_size,
              offsetx=randint(-1000, +1000),
              offsety=randint(-1000, +1000))
    #)
    # bias sets the middle value for the map, while weight defines how far
    # other values are from the middle value.
    yavanna = Yavanna(map, screen)

    bugs = Group()
    bugs.add(Bug(s.bug_size, s.bug_color, screen, map, s._x, s._y))
    map.blitme()
    yavanna.draw_trees()
    pg.display.update()

    while True:
        rects_to_update = []

        for event in pg.event.get():
            if event.type == pg.QUIT:
                pg.quit()
                sys.exit()

        for biome in map.sea:
            rects_to_update.extend(biome.draw())

        for alga in yavanna.algae:
            alga.update()
            alga.draw()

        for bug in bugs:
            try:  # if the left eye was calculated yet, update it.
                rects_to_update.extend([
                    bug.rect.copy(),
                    bug.left_eye.copy(),
                    bug.right_eye.copy()
                ])
            except:  # otherwise, only update the rest of the bug.
                rects_to_update.extend([bug.rect.copy()])
            bug.update(s._movement, s._rotation)
            bug.draw_bug()
            rects_to_update.extend([bug, bug.left_eye, bug.right_eye])
        pg.display.update(rects_to_update)
Пример #11
0
class Board:
    def __init__(self, n, m):
        self.n = n
        self.m = m
        self.empty = 0
        self.poop = 1
        self.board = get_frame(n, m, self.empty, self.poop)
        self.bug = Bug()
        self.show_bug()

    def show_bug(self):
        self.board[self.bug.y][self.bug.x] = self.bug.sign

    def poop_bug(self):
        self.board[self.bug.y][self.bug.x] = self.poop

    def __str__(self):
        s = ''
        for e in self.board:
            s += str(e) + '\n'
        return s

    def move_bug(self) -> bool:
        self.poop_bug()
        turn_number = 0
        while turn_number < 4:
            self.bug.move()
            if self.board[self.bug.y][self.bug.x] == self.poop:
                self.bug.move_back()
                self.bug.turn()
                turn_number += 1
            else:
                break
        self.show_bug()
        return turn_number < 4
Пример #12
0
    def get(self, bug_number):
        """
            Get a bug from Bugzilla. If there is a login token created during object initialisation
            it will be part of the query string passed to Bugzilla

            :param bug_number: Bug Number that will be searched. If found will return a Bug object.

            >>> bugzilla = Bugsy()
            >>> bug = bugzilla.get(123456)
        """
        bug = self.request('bug/%s' % bug_number,
                           params={
                               "include_fields": self.DEFAULT_SEARCH
                           }).json()
        return Bug(self, **bug['bugs'][0])
Пример #13
0
def get_bugs(s):
    d = {}
    mapping = {'.': 0,
               'x': 1}
    for block in s.split('\n\n'):
        block = block.strip()
        if not block:
            continue
        lines = block.split('\n')
        name = lines[0].strip()
        desc = []
        for line in lines[1:]:
            desc.append(map(mapping.get, line))
        d[name] = Bug(name, desc)

    return d
Пример #14
0
def update():
    global show_labels, eye_debug
    if pyxel.btnp(pyxel.KEY_Q):
        pyxel.quit()

    if pyxel.btnp(pyxel.KEY_T):
        show_labels = not show_labels

    if pyxel.btnp(pyxel.KEY_D):
        eye_debug = not eye_debug

    for bug in bugs:
        bug.update(food, bugs)

    for bit in food:
        bit.update()

    for bit in list(food):
        if bit.eaten:
            food.remove(bit)

    if pyxel.frame_count % 4 == 0:
        empty_spot = False
        while empty_spot == False:

            x = random.uniform(10, 246)
            y = random.uniform(10, 246)
            empty_spot = True

            for bug in bugs:
                dist = math.sqrt((x - bug.x)**2 + (y - bug.y)**2)

                if dist < 30:
                    empty_spot = False
                    break

        food.append(Food(x, y, False))

    for bug in list(bugs):
        if bug.dead:
            bugs.remove(bug)
            if len(bugs) < 15:
                bugs.append(
                    Bug(random.uniform(10, 246), random.uniform(10, 246)))
Пример #15
0
    def get_bugs(self, project_name, statuses, milestone_name=None,
                 tags=[], importance=[], **kwargs):
        project = db[project_name]

        search = [{"status": {"$in": statuses}}]

        if milestone_name:
            search.append({'milestone': milestone_name})

        if importance:
            search.append({"importance": {"$in": importance}})

        if tags:
            if kwargs.get("condition"):
                search.append({"tags": {"$nin": tags}})
            else:
                search.append({"tags": {"$in": tags}})

        return [Bug(r) for r in project.find({"$and": search})]
Пример #16
0
def GetRevisionString(prev_time, current_time, diff_map):
    """Get a string for revision information during the specified time period.

  Args:
    prev_time: the previous time as a floating point number expressed
        in seconds since the epoch, in UTC.
    current_time: the current time as a floating point number expressed
        in seconds since the epoch, in UTC. It is typically obtained by
        time.time() function.
    diff_map: a map that has 'whole', 'skip' and 'nonskip' as keys.
        Please refer to |diff_map| in |SendStatusEmail()|.

  Returns:
    a tuple of strings:
        1) full string containing links, author, date, and line for each
           change in the test expectation file.
        2) shorter string containing only links to the change.  Used for
           trend graph annotations.
        3) last revision number for the given test group.
        4) last revision date for the given test group.
  """
    if not diff_map:
        return ('', '', '', '')
    testname_map = {}
    for test_group in ['skip', 'nonskip']:
        for i in range(2):
            for (k, _) in diff_map[test_group][i]:
                testname_map[k] = True
    rev_infos = TestExpectationsHistory.GetDiffBetweenTimes(
        prev_time, current_time, testname_map.keys())
    rev_str = ''
    simple_rev_str = ''
    rev = ''
    rev_date = ''
    if rev_infos:
        # Get latest revision number and date.
        rev = rev_infos[-1][1]
        rev_date = rev_infos[-1][3]
        for rev_info in rev_infos:
            (old_rev, new_rev, author, date, _, target_lines) = rev_info
            link = urllib.unquote(
                'http://trac.webkit.org/changeset?new=%d%40trunk'
                '%2FLayoutTests%2Fplatform%2Fchromium%2F'
                'test_expectations.txt&old=%d%40trunk%2F'
                'LayoutTests%2Fplatform%2Fchromium%2F'
                'test_expectations.txt') % (new_rev, old_rev)
            rev_str += '<ul><a href="%s">%s->%s</a>\n' % (link, old_rev,
                                                          new_rev)
            simple_rev_str = '<a href="%s">%s->%s</a>,' % (link, old_rev,
                                                           new_rev)
            rev_str += '<li>%s</li>\n' % author
            rev_str += '<li>%s</li>\n<ul>' % date
            for line in target_lines:
                # Find *.html pattern (test name) and replace it with the link to
                # flakiness dashboard.
                test_name_pattern = r'(\S+.html)'
                match = re.search(test_name_pattern, line)
                if match:
                    test_name = match.group(1)
                    gpu_link = ''
                    if 'GPU' in line:
                        gpu_link = 'group=%40ToT%20GPU%20Mesa%20-%20chromium.org&'
                    dashboard_link = (
                        'http://test-results.appspot.com/dashboards/'
                        'flakiness_dashboard.html#%stests=%s') % (gpu_link,
                                                                  test_name)
                    line = line.replace(
                        test_name,
                        '<a href="%s">%s</a>' % (dashboard_link, test_name))
                # Find bug text and replace it with the link to the bug.
                bug = Bug(line)
                if bug.bug_txt:
                    line = '<li>%s</li>\n' % line.replace(
                        bug.bug_txt, str(bug))
                rev_str += line
            rev_str += '</ul></ul>'
    return (rev_str, simple_rev_str, rev, rev_date)
Пример #17
0
def play(headless=False, nets=None, verbose=False):
    N = len(nets)
    H = xDim * (WIDTH + MARGIN)
    W = yDim * (HEIGHT + MARGIN)
    WINDOW_SIZE = [H, W]
    framerate = 30
    invSpeed = 20
    done = False
    frame = 0
    counter = 1
    time = 0
    start = True
    pygame.init()
    bugs = []
    if not headless:
        screen = pygame.display.set_mode(WINDOW_SIZE)
        clock = pygame.time.Clock()
    grid = genBoard(xDim, yDim)
    for i in range(N):
        bugs.append(Bug(xDim, yDim))
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
        inputs = []
        for b in bugs:
            inputs.append(calcInputs(grid, b))
        actions = []
        if nets:
            for b, n in zip(bugs, nets):
                if b.alive:
                    nnAction = n.forward(inputs[i])
                    maximum = np.max(nnAction)
                    action = np.where(nnAction == maximum)[0][0]
                    # print(action)
                    if action == 0:
                        b.left(grid)
                        actions.append("left")
                    elif action == 2:
                        b.right(grid)
                        actions.append("right")
                    else:
                        actions.append("nothing")
        if verbose:
            print(actions)

        if not headless:
            screen.fill(BLACK)
        for row in range(yDim):
            for column in range(xDim):
                color = BLACK
                if grid[row][column] == 1:
                    color = GREEN
                if not headless:
                    pygame.draw.rect(
                        screen, color,
                        [(MARGIN + WIDTH) * column + MARGIN,
                         (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT])

        if not headless:
            for b in bugs:
                if b.alive:
                    color = b.colour
                    pygame.draw.rect(
                        screen, color,
                        [(MARGIN + WIDTH) * b.x + MARGIN,
                         (MARGIN + HEIGHT) * b.y + MARGIN, WIDTH, HEIGHT])
            pygame.display.flip()

        if frame % invSpeed == 0:
            grid = updateGrid(grid)
            for b in bugs:
                if b.alive:
                    b.score += 1

        for b in bugs:
            if b.score >= 300:
                scores = getBugsScores(bugs)
                pygame.quit()
                return scores
            if b.alive:
                b.alive = b.checkCollide(grid)

        frame += 1

        allDead = getBugsDead(bugs)
        if allDead:
            scores = getBugsScores(bugs)
            pygame.quit()
            return scores
Пример #18
0
            if event.key == pygame.K_ESCAPE:
                timer.pause_game()
                menu.menu(window)
                timer.unpause_game()

    '''Заливка'''
    screen.blit(bg_image, (0, 0))
    info_screen.fill((50, 50, 50))

    player.move(left, right)
    # Створюємо баги
    if len(bug_army) < 4:
        while len(bug_army) != 4:
            rand = random.randrange(10, 550)
            rand_speed = random.randrange(1, 5)
            bug = Bug(x=rand, speed=rand_speed)
            bug_army.append(bug)
            sprite_group.add(bug)
    # Створюємо не баги
    if len(bug_police) < 2:
        while len(bug_police) != 2:
            rand = random.randrange(10, 550)
            rand_speed = random.randrange(1, 5)
            notbug = NotBug(x=rand, speed=rand_speed)
            bug_police.append(notbug)
            sprite_group.add(notbug)

    if not bonus_array and int(timer.lost_time()) % 10 == 0:
            rand = random.randrange(10, 550)
            rand_speed = random.randrange(10, 11)
            bonus = Bonus(x=rand, speed=rand_speed)
Пример #19
0
class TestBug(unittest.TestCase):
    def setUp(self):
        self.bugid = 'abc'
        self.bug = Bug(self.bugid)

    def test_bug_stores_bugid(self):
        self.assertEquals(self.bugid, self.bug.bugid)

    def test_bug_stores_fixing_changeset(self):
        changeset = MockChangeset()
        self.bug.add_fixing_changeset(changeset)
        self.assertIs(changeset, self.bug.fixing_changesets.pop())

    def test_bug_stores_multiple_fixing_changesets(self):
        self.bug.add_fixing_changeset(MockChangeset())
        self.bug.add_fixing_changeset(MockChangeset())
        self.assertEquals(2, len(self.bug.fixing_changesets))

    def test_bug_has_score_of_changeset_with_highest_score(self):
        self.bug.add_fixing_changeset(MockChangeset(2))
        self.bug.add_fixing_changeset(MockChangeset(4))
        self.bug.add_fixing_changeset(MockChangeset(3))
        self.assertEquals(4, self.bug.get_score(None))

    def test_bug_passes_startdate_information_to_changeset(self):
        changeset = MockChangeset()
        dt = datetime(2011, 12, 22, 19, 4, 00)
        self.bug.add_fixing_changeset(changeset)
        self.bug.get_score(dt)
        self.assertEquals(dt, changeset.startdate_asked_for)

    def test_bug_returns_zero_for_score_when_no_changesets_fix_it(self):
        self.assertEquals(0, self.bug.get_score(None))

    def test_bug_memoizes_score(self):
        changeset = MockChangeset()
        self.bug.add_fixing_changeset(changeset)
        self.bug.get_score(None)
        self.bug.get_score(None)
        self.bug.get_score(None)
        self.assertEquals(1, changeset.num_times_score_checked)

    def test_bug_to_string(self):
        self.assertEquals(self.bugid, str(self.bug))
Пример #20
0
#!/usr/bin/python
#
# bug_node.py
#
#Noa Dagan 311302137
#Nofar Bar-zakai 205643638


import rospy, sys
from bug import Bug

if __name__ == "__main__":
    #rospy.init_node("bug_node", argv=sys.argv)
    forward_speed = 0.5
    rotate_speed = 20
    x_goal = -7
    y_goal = -5
    min_dist_from_obstacle = 1.2
    if rospy.has_param('~forward_speed'):
        forward_speed = rospy.get_param('~forward_speed')
    if rospy.has_param('~rotate_speed'):
        forward_speed = rospy.get_param('~rotate_speed')
    if rospy.has_param('~min_dist_from_obstacle'):
        min_dist_from_obstacle = rospy.get_param('~min_dist_from_obstacle')
    if rospy.has_param('~x_goal'):
        x_goal = rospy.get_param('~x_goal')
    if rospy.has_param('~y_goal'):
        y_goal = rospy.get_param('~y_goal')
    my_bug = Bug(forward_speed,rotate_speed,min_dist_from_obstacle,x_goal,y_goal)
    my_bug.start()
Пример #21
0
def handle(clock, event_handler):
    #print('Mode: Demo')

    # Make the bugs (not too close to center)
    bugs = []
    for _ in range(16):
        while True:
            cx = random.randint(0, 19)
            cy = random.randint(0, 15)
            if (cx >= 6 and cx < 14) and (cy >= 6 and cy < 14):
                continue
            break
        bugs.append(Bug(cx * 4 + 25, cy * 4 + 17, random.randint(0, 3)))

    pic = Frame()

    # Draw the bugs
    mega = Maze(20, 16, 192)
    mode_game.draw_maze(mega._maze, pic)

    # Draw the big bugs
    bugimage = GR.BIG_BUG
    pic.draw_image(3, 32, bugimage['standing'])
    pic.draw_image(108, 32, bugimage['standing'])

    # The mouth
    mouth = Mouth(25 + 10 * 4, 17 + 8 * 4, random.randint(0, 3))

    # Don't start on a dot
    pic.set_pixel(mouth.x, mouth.y, 0)

    hs = str(mode_game.HIGH_SCORE).rjust(4, '0')
    text.draw_text(pic, 19, 4, 'High Score ' + hs, GR.COLOR_SCORE)
    text.draw_text(pic, 26, 84, 'Play Giga-Bug', GR.COLOR_SCORE)

    transitions.wipe_in(pic)
    """
    base_frame = Frame()
    
    base_frame.draw_image(10,15, GR.CHARS['A']) # The letter 'A'
    base_frame.draw_text(5,5,    GR.CHARS,'Demonstration')
    base_frame.draw_image(20,25, GR.BIG_BUG['standing']) # Bug standing
    base_frame.draw_image(50,25, GR.BIG_BUG['dancing'][0]) # Bug dancing ...
    base_frame.draw_image(70,25, GR.BIG_BUG['dancing'][1]) # ... two animations   
    
    direction = 1 # 0=UP, 1=RIGHT, 2=DOWN, 3=LEFT
    animation = 0 # 0 or 1 ... two animations
    
    while True:
        frame = Frame(base_frame)        
             
        frame.draw_image(10,60, GR.MOUTH[direction][animation])
            
        hardware.render_frame(frame)
        
        animation = (animation + 1) % 2
    
        time.sleep(0.25)  
    """

    clock.tick(0.75)
    nf = MAG.draw_magnifier(pic, mouth.x - 8, mouth.y - 8, 17)
    MAG.draw_mouth_on_magnifier(nf, mouth)
    hardware.render_frame(nf)
    clock.tick(0.75)

    # Play this setup
    return play_game(clock, pic, mouth, bugs, event_handler)
Пример #22
0
from bug import Bug

print("Bug 1:")
bug1 = Bug(10)  # creates an instance of a bug whose initial position is at 10
print(bug1)

for i in range(1, 3):
    bug1.move()
    print(bug1)

bug1.turn()

for i in range(1, 5):
    bug1.move()
    print(bug1)

print("Bug 2:")
bug2 = Bug(5)  # creates an instance of a bug whose initial position is at 5
bug2.turn()
bug2.move()
print(bug2)

assert not bug2 > bug1
if bug1 > bug2:
    print("Bug1 has travelled further than bug2")

print("Bug 3:")
# creates an instance of a bug whose initial position is the sum of the position of bug1 and bug2
bug3 = bug1 + bug2
print(bug3)
bug3.move()
Пример #23
0
    def parse_html(self, handle):
        """Parses a bugzila-generated html file

        This functions gets a bugzilla-generated html file and returns
        a list of bug objects"""

        soup = BeautifulSoup(handle.read())
        bugs = []

        rows = soup.find("table", attrs = { "class" : "bz_buglist" })
        if not rows:
            # no bugs?
            if soup.find(text = lambda(str): str.find("Zarro") == 0):
                return bugs
            else:
                raise BugListParseError, "Couldn't find the bugs table"
        rows = rows.findAll("tr")[1:]

        for row in rows:
            cells = row.findAll("td")
            
            bug = Bug(cells[0].a.string, self)

            # Bug severity 
            if cells[1].string != None:
                severity = cells[1].string.strip()
            elif cells[1].nobr.string != None: # KDE's bugzilla
                severity = cells[1].nobr.string.strip()
            else:
                raise BugListParseError, "Couldn't get bug severity"

            if severity == "blo":
                bug.set_severity("blocker")
            elif severity == "cri":
                bug.set_severity("critical")
            elif severity == "maj":
                bug.set_severity("major")
            elif severity == "nor":
                bug.set_severity("normal")
            elif severity == "min":
                bug.set_severity("minor")
            elif severity == "tri":
                bug.set_severity("trivial")
            elif severity == "enh":
                bug.set_severity("enhancement")
            elif severity == "gra":  # KDE's bugzilla
                bug.set_severity("grave")
            elif severity == "cra":  # KDE's bugzilla
                bug.set_severity("crash")
            elif severity == "wis":
                bug.set_severity("wishlist")
            else:
                bug.set_severity(severity) 
            
            # Bug priority
            if cells[2].string:
                bug.set_priority(cells[2].string.strip())
            elif cells[2].nobr.string: # KDE's bugzilla
                bug.set_priority(cells[2].nobr.string.strip())
            else:
                raise BugListParseError, "Couldn't get bug priority"

            # Bug owner
            if cells[3].string:
                bug.set_assignee(cells[3].string.strip())
            elif cells[3].nobr.string: # KDE's bugzilla
                bug.set_assignee(cells[3].nobr.string.strip())
            else:
                raise BugListParseError, "Couldn't get bug owner"

            # Bug reporter
            if cells[4].string:
                bug.set_reporter(cells[4].string.strip())
            elif cells[4].nobr.string: # KDE's bugzilla
                bug.set_reporter(cells[4].nobr.string.strip())
            else:
                raise BugListParseError, "Couldn't get bug reporter"

            # Bug status
            if cells[5].string:
                status = cells[5].string.strip()
            elif cells[5].nobr.string: # KDE's bugzilla
                status = cells[5].nobr.string.strip()
            else:
                raise BugListParseError, "Couldn't get bug status"

            if status == "UNCO":
                bug.set_status("UNCONFIRMED")
            elif status == "ASSI":
                bug.set_status = ("ASSIGNED")
            elif status == "REOP":
                bug.set_status = ("REOPENED")
            elif status == "RESO":
                bug.set_status("RESOLVED")
            elif status == "VERI":
                bug.set_status("VERIFIED")
            elif status == "CLOS":
                bug.set_status("CLOSED")
            elif status == "NEED": # Gnome's Bugzilla
                bug.set_status("NEEDINFO")
            else:
                bug.set_status(status)
    
            # Bug resolution
            if cells[6].string:
                resolution = cells[6].string.strip()
            elif cells[6].nobr.string: # KDE's bugzilla
                resolution = cells[6].nobr.string.strip()
            else:
                if bug.get_status() in ["RESOLVED", "VERIFIED", "CLOSED"]:
                    raise BugListParseError, "Couldn't get bug resolution"
                else:
                    resolution = ""

            if resolution == "FIXE":
                bug.set_resolution("FIXED")
            elif resolution == "INVA":
                bug.set_resolution("INVALID")
            elif resolution == "WONT":
                bug.set_resolution("WONTFIX")
            elif resolution == "LATE":
                bug.set_resolution("LATER")
            elif resolution == "REMI":
                bug.set_resolution("REMIND")
            elif resolution == "DUPL":
                bug.set_resolution("DUPLICATE")
            elif resolution == "WORK":
                bug.set_resolution("WORKSFORME")
            elif resolution == "MOVE":
                bug.set_resolution("MOVED")
            elif resolution == "NOTA":  # Gnome's Bugzilla
                bug.set_resolution("NOTABUG")
            elif resolution == "NOTG":  # Gnome's Bugzilla
                bug.set_resolution("NOTGNOME")
            elif resolution == "INCO":  # Gnome's Bugzilla
                bug.set_resolution("INCOMPLETE")
            elif resolution == "GNOM":  # Gnome's Bugzilla
                bug.set_resolution("GNOME1.X")
            elif resolution == "OBSO":  # Gnome's Bugzilla
                bug.set_resolution("OBSOLETE")
            elif resolution == "NOTX":  # Gnome's Bugzilla
                bug.set_resolution("NOTXIMIAN")
            else:
                bug.set_resolution(resolution)

            # Bug product
            if cells[7].string:
                bug.set_product(cells[7].string.strip())
            elif cells[7].nobr.string: # KDE's bugzilla
                bug.set_product(cells[7].nobr.string.strip())
            else:
                raise BugListParseError, "Couldn't get bug product"

            # Bug component
            if cells[8].string:
                bug.set_component(cells[8].string.strip())
            elif cells[8].nobr.string: # KDE's bugzilla
                bug.set_component(cells[8].nobr.string.strip())
            else:
                raise BugListParseError, "Couldn't get bug component"

            # Bug version
            if cells[9].string:
                bug.set_version(cells[9].string.strip())
            elif cells[9].nobr.string: # KDE's bugzilla
                bug.set_version(cells[9].nobr.string.strip())
            else:
                raise BugListParseError, "Couldn't get bug version"

            # Bug summary
            if cells[10].string:
                bug.set_summary(cells[10].string.strip())
            elif cells[10].nobr.string: # KDE's bugzilla
                bug.set_summary(cells[10].nobr.string.strip())
            else:
                raise BugListParseError, "Couldn't get bug summary"

            # Bug URL
            bug.set_url("%s/show_bug.cgi?id=%s" % (self.baseurl, bug.get_id()))

            bugs.append(bug)

        return bugs
Пример #24
0
class Soldier(CompositeUnit, Observable):

    __age = None
    __strategy = None
    __is_dead = False

    def __init__(self, military_unit_number, name):
        self.__bug = Bug()
        self.__name = name
        self.__military_unit_number = military_unit_number
        self.__soldier_key = SoldierKey(self.__military_unit_number,
                                        self.__name)

    def set_strategy_kill(self, strategy):
        self.__strategy = strategy

    def kill(self):
        if self.__strategy is not None:
            self.__is_dead = self.__strategy.kill(self)
        else:
            raise Exception(
                'Please choice strategy for kill in set_strategy_kill method')
        Observable.notify(self, 'kill')

    @property
    def is_dead(self):
        return self.__is_dead

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, value):
        self.__age = value

    def get_weapon_price(self):
        stack_list = []
        while True:
            weapon = self.remove_top_weapon
            if weapon is not False:
                stack_list.append(weapon)
            else:
                break
        first_from_stack_list = stack_list.pop()
        return_price = first_from_stack_list.price
        for price in stack_list[::-1]:
            return_price = return_price.add(price.price)
        stack_list.append(first_from_stack_list)
        for stack_full in stack_list[::-1]:
            self.add_weapon(stack_full)
        return return_price

    def add_weapon(self, value):
        self.__bug.add(value)

    @property
    def remove_top_weapon(self):
        return self.__bug.remove_last_added()

    def get_soldier_key(self):
        return self.__soldier_key.name + self.__soldier_key.military_unit_number

    def add_soldier_key(self, military_unit_number, name):
        self.__soldier_key = SoldierKey(military_unit_number, name)

    @property
    def name(self):
        return self.__soldier_key.name

    def clone(self):
        return copy.deepcopy(self)
Пример #25
0
from wall import Wall
from wall import Radblock
from displayer import Displayer
from snake import Snake
from bug import Bug
import time
import threading
import msvcrt

displayer = Displayer()
wall = Wall()
snake = Snake()
radblock = Radblock()
bug = Bug(snake.points)

running = True


class InputThread(threading.Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        global running, snake
        while running:
            c = str(msvcrt.getch())
            if c == "b'q'":
                running = False
            elif c == "b'w'":
                snake.set_toward("UP")
            elif c == "b's'":
Пример #26
0
 def setUp(self):
     self.bug = Bug(TestFiles.IMG, TestFiles.RELATIVE_BOUNDING_BOX)
Пример #27
0
class TestBug(unittest.TestCase):
    def setUp(self):
        self.bug = Bug(TestFiles.IMG, TestFiles.RELATIVE_BOUNDING_BOX)

    def test_includes_organism_into_turtle(self):
        self.assertEqual(self.bug.as_turtle(), TestFiles.RDF_SINGLE_BUG)
Пример #28
0
 def add_bug(self, x, y, width, height):
     """Drawn a box around a bug? Tel me with this method"""
     relative_coordinates = self.__iohelper.transform(x, y, width, height)
     bug = Bug('img', relative_coordinates)
     self.__add_taxon_information(bug)
     self.__bugs.append(bug)
Пример #29
0
 def setUp(self):
     self.bug = Bug(TestFiles.IMG, TestFiles.RELATIVE_BOUNDING_BOX)
Пример #30
0
from bug import Bug

print("Bug 1:")
bug1 = Bug(18)  # creates an instance of a bug whose initial position is at 18
print(bug1)

for i in range(1, 5):
    bug1.move()
    print(bug1)
Пример #31
0
 def setUp(self):
     self.bugid = 'abc'
     self.bug = Bug(self.bugid)
Пример #32
0
from bug import Bug

bug1 = Bug(25)
print(bug1)

bug2 = Bug(-5)
print(bug2)
Пример #33
0
 def __eat(self, bug: Bug):
     if self.__list[0] == bug.point[0]:
         #虫子瞬移
         bug.quickly_move(self.__list)
         #蛇会加长
         self.__list.append(self.__list[-1])
Пример #34
0
from displayer import Displayer
from wall import Wall
from snake import Snake
import time
import threading
from bug import Bug
import sys

displayer = Displayer()  # 创建显示管理类对象
wall = Wall()  # 创建墙的对象
snake = Snake()  # 创建蛇的对象
bug = Bug(snake.points)  # 创建虫子

running = True


class InputThread(threading.Thread):
    def __init__(self):
        super().__init__()

    def run(self):
        global running, snake  # 引入声明在函数外的变量
        while True:  # sys.stdin.readline( ) sys.stdin.getch()
            c = str(sys.stdin())
            print(c)
            if c == "b'q'":
                running = False
            elif c == "b'w'":
                snake.set_toward("UP")
            elif c == "b's'":
                snake.set_toward("DOWN")
Пример #35
0
    def parse_csv(self, file):
        """Parses a bugzilla-generated csv file

        This function gets a bugzilla-generated csv file and returns a list
        of bug objects."""

        data = csv.reader(file)
        data.next() # skips the header

        bugs = []

        for report in data: 
            bug = Bug(report[0], self)
            bug.set_severity(report[1])
            bug.set_priority(report[2])
            bug.set_assignee(report[3])
            bug.set_reporter(report[4])
            bug.set_status(report[5])
            bug.set_resolution(report[6])
            bug.set_product(report[7])
            bug.set_component(report[8])
            bug.set_version(report[9])
            bug.set_summary(report[10])
            bug.set_url("%s/show_bug.cgi?id=%s" % (self.baseurl, bug.get_id()))
            bugs.append(bug)

        return bugs
Пример #36
0
 def __init__(self, military_unit_number, name):
     self.__bug = Bug()
     self.__name = name
     self.__military_unit_number = military_unit_number
     self.__soldier_key = SoldierKey(self.__military_unit_number,
                                     self.__name)