Пример #1
0
    def find_top_labels(self, g, k=6):
        labels = self.__ontology.get_labels()
        label_score = []
        for i in range(len(labels)):
            # put a condition that verifies if the labels is
            #print labels[i] + ' -- ' + g.get_name()
            score = self.__predictor.run(labels[i], g)

            label_score.append((score, labels[i]))

        #print 'feature: ' + repr(g.get_features())
        #print 'labels: ' + repr(labels)
        #print 'scores: ' + repr(label_score)
        label_score.sort(reverse=True)
        #print 'scores: ' + repr(label_score)

        feature_bond_structure = self.__ontology.get_bond_structure(
            g.get_name())
        #print g.get_name() + ' ' + repr(feature_bond_structure)

        for i in range(k):
            name = label_score[i][1]
            print 'label: ' + name
            # when features connect to labels
            label_modalities = self.__ontology.get_modalities(name)
            #print 'modalities: '+repr(label_modalities)
            for bond in feature_bond_structure:
                if bond[0] in label_modalities:
                    score = label_score[i][0]
                    level = self.__ontology.get_level(name)
                    modality = self.__ontology.get_modalities(name)
                    g.add_top_label(
                        Label(name, modality, level, score, -1, 0.0))
                    break
Пример #2
0
    def create_widgets(self):
        self.radio_buttons.append(
            RadioButton(0, 450, 100, 50, "Erase", self.button_font, (0, 0, 0),
                        (150, 150, 150)))

        self.radio_buttons.append(
            RadioButton(0, 0, 100, 50, "Straight", self.button_font, (0, 0, 0),
                        (175, 245, 245)))
        self.radio_buttons.append(
            RadioButton(0, 50, 100, 50, "Left", self.button_font, (0, 0, 0),
                        (245, 245, 175)))
        self.radio_buttons.append(
            RadioButton(0, 100, 100, 50, "Right", self.button_font, (0, 0, 0),
                        (245, 175, 245)))
        self.radio_buttons.append(
            RadioButton(0, 150, 100, 50, "Switch", self.button_font, (0, 0, 0),
                        (145, 75, 145)))
        self.radio_buttons.append(
            RadioButton(0, 200, 100, 50, "Trigger", self.button_font,
                        (0, 0, 0), (150, 125, 125)))
        self.radio_buttons.append(
            RadioButton(0, 250, 100, 50, "Wait", self.button_font, (0, 0, 0),
                        (250, 225, 225)))
        self.radio_buttons.append(
            RadioButton(0, 300, 100, 50, "Rebound", self.button_font,
                        (0, 0, 0), (245, 175, 175)))
        self.radio_buttons.append(
            RadioButton(0, 350, 100, 50, "Bounce", self.button_font, (0, 0, 0),
                        (255, 200, 75)))

        self.start_button = Button(600, 350, 100, 50, "Start",
                                   self.button_font, (255, 255, 255),
                                   (0, 200, 0))
        self.clear_button = Button(600, 450, 100, 50, "Clear",
                                   self.button_font, (255, 255, 255),
                                   (255, 0, 0))
        self.level_text = Label(600, 0, 100, 50,
                                "Level " + str(self.level_number + 1),
                                self.button_font, (0, 0, 0), (175, 175, 175))

        self.level_description_label = Label(0, 500, 150, 50, "Description:",
                                             self.button_font, (0, 0, 0),
                                             (235, 235, 235))
        self.level_description = Label(
            0, 550, 700, 150,
            "you are not supposed to see this text restart the game",
            self.button_font, (0, 0, 0), (235, 235, 235))
Пример #3
0
    def handleScannedPartId(self, partId):
        result = self.partDB.db.query(filter=lambda k, v: (k == partId))

        if len(result) == 0:
            raise Exception('Part ID %s not found in database.' % (partId))

        if self.partDB.args.fix:
            result = self.partDB.db.query(filter=lambda k, v: (k == partId))
            data = result[partId]

            distributorMatches = {}
            for distributorName in data['distributor']:
                minimumData = {
                    'distributor': {
                        distributorName: {
                            'distributorPartNumber':
                            data['distributor'][distributorName]
                            ['distributorPartNumber']
                        }
                    }
                }

                newData = self.partDB.distributors[distributorName].getData(
                    minimumData)

                Database.mergeData(data, newData, override=True)

            self.partDB.db.update(data)

            if len(result) > 0:
                if (self.partDB.args.printLabel):
                    label = Label.Label()
                    label.createLabelFromData(data=data)
                    label.cupsPrint(printerName=self.partDB.args.printerName)
            else:
                raise Exception('ID %s not found in database.' %
                                (self.partDB.args.id))

            return

        data = result[partId]

        self.partDB.displayItem(data)

        print(
            'Quantity is %u. Scan/Enter new quantity (+/- for relative) or press return:'
            % data['quantity'])
        quantityInput = self.scanAndInput()
        if quantityInput != b'':
            quantityInputAscii = quantityInput.decode('ascii')
            # check if first character is + or -
            if (quantityInputAscii[0]) == '+' or (quantityInputAscii[0]
                                                  == '-'):
                data['quantity'] += int(quantityInputAscii)
            else:
                data['quantity'] = int(quantityInputAscii)

            print('New quantity is %u.' % (data['quantity']))
            self.partDB.db.update(data)
Пример #4
0
 def _useAttributes(self, attributes):
     if "assignee" in attributes:  # pragma no branch
         assert attributes["assignee"] is None or isinstance(attributes["assignee"], dict), attributes["assignee"]
         self._assignee = None if attributes["assignee"] is None else NamedUser.NamedUser(self._requester, attributes["assignee"], completed=False)
     if "body" in attributes:  # pragma no branch
         assert attributes["body"] is None or isinstance(attributes["body"], (str, unicode)), attributes["body"]
         self._body = attributes["body"]
     if "closed_at" in attributes:  # pragma no branch
         assert attributes["closed_at"] is None or isinstance(attributes["closed_at"], (str, unicode)), attributes["closed_at"]
         self._closed_at = self._parseDatetime(attributes["closed_at"])
     if "closed_by" in attributes:  # pragma no branch
         assert attributes["closed_by"] is None or isinstance(attributes["closed_by"], dict), attributes["closed_by"]
         self._closed_by = None if attributes["closed_by"] is None else NamedUser.NamedUser(self._requester, attributes["closed_by"], completed=False)
     if "comments" in attributes:  # pragma no branch
         assert attributes["comments"] is None or isinstance(attributes["comments"], (int, long)), attributes["comments"]
         self._comments = attributes["comments"]
     if "created_at" in attributes:  # pragma no branch
         assert attributes["created_at"] is None or isinstance(attributes["created_at"], (str, unicode)), attributes["created_at"]
         self._created_at = self._parseDatetime(attributes["created_at"])
     if "html_url" in attributes:  # pragma no branch
         assert attributes["html_url"] is None or isinstance(attributes["html_url"], (str, unicode)), attributes["html_url"]
         self._html_url = attributes["html_url"]
     if "id" in attributes:  # pragma no branch
         assert attributes["id"] is None or isinstance(attributes["id"], (int, long)), attributes["id"]
         self._id = attributes["id"]
     if "labels" in attributes:  # pragma no branch
         assert attributes["labels"] is None or all(isinstance(element, dict) for element in attributes["labels"]), attributes["labels"]
         self._labels = None if attributes["labels"] is None else [
             Label.Label(self._requester, element, completed=False)
             for element in attributes["labels"]
         ]
     if "milestone" in attributes:  # pragma no branch
         assert attributes["milestone"] is None or isinstance(attributes["milestone"], dict), attributes["milestone"]
         self._milestone = None if attributes["milestone"] is None else Milestone.Milestone(self._requester, attributes["milestone"], completed=False)
     if "number" in attributes:  # pragma no branch
         assert attributes["number"] is None or isinstance(attributes["number"], (int, long)), attributes["number"]
         self._number = attributes["number"]
     if "pull_request" in attributes:  # pragma no branch
         assert attributes["pull_request"] is None or isinstance(attributes["pull_request"], dict), attributes["pull_request"]
         self._pull_request = None if attributes["pull_request"] is None else IssuePullRequest.IssuePullRequest(self._requester, attributes["pull_request"], completed=False)
     if "repository" in attributes:  # pragma no branch
         assert attributes["repository"] is None or isinstance(attributes["repository"], dict), attributes["repository"]
         self._repository = None if attributes["repository"] is None else Repository.Repository(self._requester, attributes["repository"], completed=False)
     if "state" in attributes:  # pragma no branch
         assert attributes["state"] is None or isinstance(attributes["state"], (str, unicode)), attributes["state"]
         self._state = attributes["state"]
     if "title" in attributes:  # pragma no branch
         assert attributes["title"] is None or isinstance(attributes["title"], (str, unicode)), attributes["title"]
         self._title = attributes["title"]
     if "updated_at" in attributes:  # pragma no branch
         assert attributes["updated_at"] is None or isinstance(attributes["updated_at"], (str, unicode)), attributes["updated_at"]
         self._updated_at = self._parseDatetime(attributes["updated_at"])
     if "url" in attributes:  # pragma no branch
         assert attributes["url"] is None or isinstance(attributes["url"], (str, unicode)), attributes["url"]
         self._url = attributes["url"]
     if "user" in attributes:  # pragma no branch
         assert attributes["user"] is None or isinstance(attributes["user"], dict), attributes["user"]
         self._user = None if attributes["user"] is None else NamedUser.NamedUser(self._requester, attributes["user"], completed=False)
Пример #5
0
 def run(self):
     result = self.partDB.db.query(
         filter=lambda k, v: (k == self.partDB.args.id))
     if len(result) > 0:
         label = Label.Label()
         label.createLabelFromData(data=result[self.partDB.args.id])
         label.cupsPrint(printerName=self.partDB.args.printerName)
     else:
         raise Exception('ID %s not found in database.' %
                         (self.partDB.args.id))
Пример #6
0
 def create_label(self, name, color):
     assert isinstance(name, (str, unicode)), name
     assert isinstance(color, (str, unicode)), color
     post_parameters = {
         "name": name,
         "color": color,
     }
     headers, data = self._requester.requestAndCheck(
         "POST", self.url + "/labels", None, post_parameters)
     return Label.Label(self._requester, data, completed=True)
Пример #7
0
 def getSurface(self):
     self.labelAmount = Label.Label(
         "Amount: " + str(self.amount))  #Update the amount label
     #Recreate surface after amount change
     self.surface = pygame.image.load(self.icon).convert()
     self.surface.blit(self.labelName.getSurface(), (0, 0))
     self.surface.blit(self.labelPrice.getSurface(),
                       (0, 0 + self.height / 3))
     self.surface.blit(self.labelAmount.getSurface(),
                       (0, 0 + self.height * 2 / 3))
     return self.surface
Пример #8
0
 def __init__(self, name, id, price, amount, location, width, height, icon,
              command, commandRight):
     self.name = name
     self.id = id
     self.price = price
     self.amount = amount
     self.location = location
     self.width = width
     self.height = height
     self.icon = icon
     self.surface = pygame.image.load(icon).convert()
     self.button = Button.Button(width, height, location, command,
                                 commandRight, self)
     self.totalPrice = price * amount
     self.labelName = Label.Label("Name: " + str(name))
     self.labelPrice = Label.Label("Price: " + str(price))
     self.labelAmount = Label.Label("Amount: " + str(amount))
     self.surface.blit(self.labelName.getSurface(), (0, 0))
     self.surface.blit(self.labelPrice.getSurface(), (0, 0 + height / 3))
     self.surface.blit(self.labelAmount.getSurface(),
                       (0, 0 + height * 2 / 3))
Пример #9
0
    def __init__(self, master):
        self.master = master
        master.title("A simple GUI")

        self.label = Label(master, text="This is our first GUI!")
        self.label.pack()

        self.greet_button = Button(master, text="Greet", command=self.greet)
        self.greet_button.pack()

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.pack()
    def on_loop(self):
        if self._screen == "Main":
            self.title = Label.Label("Main Screen").getSurface()
            self.buttons = []
            for itemCat in self._itemCategories:
                self.buttons.append(itemCat.getButton())
            self.buttons.append(self.checkoutButton)

        elif self._screen.find("itemCatScreen:") != -1:
            self.title = Label.Label(
                "Item Category Screen of: " + self._itemCategories[int(
                    self._screen.replace("itemCatScreen:", ""))].name
            ).getSurface()
            itemCatNumber = int(self._screen.replace("itemCatScreen:", ""))
            self.buttons = []
            for item in self._itemCategories[itemCatNumber].items:
                self.buttons.append(item.getButton())
            self.buttons.append(self.backButton)

        elif self._screen == "checkOut":
            self.title = Label.Label("Check Out Screen").getSurface()
            self.buttons = []

            self.buttons.append(self.finishButton)
            self.buttons.append(self.addMoney10Button)
            self.buttons.append(self.addMoney10MButton)
            self.buttons.append(self.backButton)
            itemsShopped = []
            for itemCat in self._itemCategories:
                for item in itemCat.items:
                    if item.amount > 0:
                        itemsShopped.append(item)

            self.surfacesOfItemsShopped = []
            for item in itemsShopped:
                self.surfacesOfItemsShopped.append(
                    Label.Label("Name: " + item.name + "Price: " +
                                str(item.price) + " Amount: " +
                                str(item.amount) + " TotPrice: " +
                                str(item.getTotalPrice())))
Пример #11
0
 def __init__(self, position, text):
     self.inner_circle = Circle.Circle(position=position,
                                       radius=20,
                                       width=0,
                                       color=pygame.Color(41, 45, 54))
     self.circle = Circle.Circle(position=position,
                                 radius=20,
                                 width=2,
                                 color=pygame.Color("white"))
     self.label = Label.Label(position=position,
                              text=text,
                              color=pygame.Color("white"))
     self.number = int(text)
Пример #12
0
 def state_six(self,name):
     state_six = pygame.image.load('state_six.bmp')
     play_again_button_parameters = Rect(340, 590, 230, 80)
     quit_button_parameters = Rect(790, 590, 230, 80)
     clear_button_parameters = Rect(1190,40,155,60)
     self.s.game_display.blit(state_six, (0, 0))
     maximum_score_players_tuple=self.d.get_max_score_players()
     maximum_score_players_name_list = []
     maximum_score_players_score_list = []
     count=0
     y=255
     for external_tuple in maximum_score_players_tuple:
         maximum_score_players_name_list.append(Label(external_tuple[0] , 515, y, white, 50))
         maximum_score_players_score_list.append(Label(str(external_tuple[1]), 770, y, white, 50))
         maximum_score_players_name_list[count].draw_label(self.s)
         maximum_score_players_score_list[count].draw_label(self.s)
         y+=70
         count+=1
         if count==4:
             break
     self.s.refresh_background()
     while self.run_game:
         for event in pygame.event.get():
             if event.type == pygame.MOUSEBUTTONDOWN:
                 if play_again_button_parameters.collidepoint(event.pos):
                     self.state_two(name)
                 elif quit_button_parameters.collidepoint(event.pos):
                     self.state_seven()
                 elif clear_button_parameters.collidepoint(event.pos):
                     self.s.game_display.blit(state_six, (0, 0))
                     self.s.refresh_background()
                     self.d.clear_data()
             if event.type == pygame.QUIT:
                 self.run_game = False
     pygame.quit()
     quit()
    def on_render(self):
        self._display_surf.fill(self._background)
        self._display_surf.blit(self.title, self.titleLocation)
        for button in self.buttons:
            self._display_surf.blit(button.getSurface(), button.location)

        if self._screen == "Main":
            for itemCat in self._itemCategories:
                self._display_surf.blit(itemCat.getSurface(), itemCat.location)
            self._display_surf.blit(
                Label.Label("Money Inside Machine: " +
                            str(self.moneyPutInside)).getSurface(), (500, 175))
            self._display_surf.blit(
                Label.Label("NOTE: Left over change is carri").getSurface(),
                (500, 200))
            self._display_surf.blit(
                Label.Label("ed on, to future transactions!").getSurface(),
                (500, 225))

        elif self._screen.find("itemCatScreen:") != -1:
            itemCatNumber = int(self._screen.replace("itemCatScreen:", ""))
            for item in self._itemCategories[itemCatNumber].items:
                self._display_surf.blit(item.getSurface(), item.location)

        elif self._screen == "checkOut":
            for x in xrange(self.surfacesOfItemsShopped.__len__()):
                self._display_surf.blit(
                    self.surfacesOfItemsShopped[x].getSurface(),
                    (100, 100 + x * 40))

            totalMoneyNeeded = 0
            for itemCat in self._itemCategories:
                for item in itemCat.items:
                    totalMoneyNeeded += item.amount * item.price
            self._display_surf.blit(
                Label.Label("Total Money Due: " +
                            str(totalMoneyNeeded)).getSurface(), (575, 100))
            self._display_surf.blit(
                Label.Label("Total Money Put In: " +
                            str(self.moneyPutInside)).getSurface(), (575, 125))

            def getMaxInt(a, b):
                if a > b:
                    return a
                else:
                    return b

            self._display_surf.blit(
                Label.Label(
                    "Change Due: " +
                    str(getMaxInt(self.moneyPutInside -
                                  totalMoneyNeeded, 0))).getSurface(),
                (575, 150))
        #self._display_surf.blit(self._image_surf, self._image_loc, pygame.Rect(0, 0, 144, 144))
        #self._display_surf.blit(self._testText.getSurface(), (100,100))
        pygame.display.flip()
Пример #14
0
    def __init__(self,
                 text,
                 handler=None,
                 x=None,
                 y=None,
                 width=0,
                 height=0,
                 icon=None,
                 vertical_expansion=1,
                 text_prop=None,
                 parent='osd'):

        self.handler = handler
        Window.__init__(self, parent, x, y, width, height)
        self.text_prop = text_prop or {
            'align_h': 'center',
            'align_v': 'center',
            'mode': 'soft',
            'hfill': True
        }

        self.font = None
        if self.skin_info_font:
            self.set_font(self.skin_info_font.name, self.skin_info_font.size,
                          Color(self.skin_info_font.color))
        else:
            self.set_font(config.OSD_DEFAULT_FONTNAME,
                          config.OSD_DEFAULT_FONTSIZE)

        if not width:
            tw = self.font.stringsize(text) + self.h_margin * 2
            if tw < self.osd.width * 2 / 3:
                self.width = max(self.osd.width / 2, tw)

        self.__init__content__()

        if type(text) in StringTypes:
            self.label = Label(text,
                               self,
                               Align.CENTER,
                               Align.CENTER,
                               text_prop=self.text_prop)
        else:
            raise TypeError, text

        if icon:
            self.set_icon(icon)
Пример #15
0
    def set_text(self, text):
        if type(text) in StringTypes:
            self.text = text
        else:
            raise TypeError, type(text)

        if not self.label:
            self.label = Label(h_align=Align.CENTER,
                               v_align=Align.CENTER,
                               text_prop={
                                   'align_h': 'center',
                                   'align_v': 'center',
                                   'mode': 'hard',
                                   'hfill': False
                               })
            self.label.set_text(text)
            self.add_child(self.label)
        else:
            self.label.set_text(text)
Пример #16
0
  def __init__(self, filename):

    fp = open(filename, 'r')

    # Read metadata
    line = fp.readline().strip().split()

    self.numLabels = int(line[0])
    self.numLabelers = int(line[1])
    self.numImages = int(line[2])

    tmp_priorZ1 = float(line[3])
    print "Reading %d labels of %d labelers over %d images for prior P(Z=1) = %f" % (self.numLabels, self.numLabelers, self.numImages, tmp_priorZ1)

    print "Assuming prior on alpha has mean 1 and std 1"
    self.priorAlpha = [1 for i in range(self.numLabelers)]

    print "Assuming prior on beta has mean 1 and std 1."
    self.priorBeta = [1 for i in range(self.numImages)]

    print "Also assuming p(Z=1) is the same for all images."
    self.priorZ1 = [tmp_priorZ1 for i in range(self.numImages)]

    # Read labels
    self.labels = []
    line = fp.readline()
    while line != "":
      line = line.strip().split()
      # Image ID, Labeler ID, Label
      lbl = Label(int(line[0]), int(line[1]), int(line[2]))
      self.labels.append(lbl)

      if lbl.label != 0 and lbl.label != 1:
        print "Invalid label value"
        exit()

      line = fp.readline()

    # Empty arrays to store these later
    self.probZ1 = []
    self.probZ0 = []
    self.alpha = []
    self.beta =[]
Пример #17
0
 def __init__(self, Dialog, dict):
     super().__init__(Dialog)
     self.setObjectName("gridLayoutWidget")
     self.setGeometry(QtCore.QRect(160, 60, 341, 321))
     self.gridLayout = gl.gridLayout(self)
     #题目号初始化
     self.uuid = dict['uuid']
     self.step = dict['step']
     self.swap = dict['swap']
     self.change = []
     self.blocks = []
     self.imgList = []
     self.zero_row = 0
     self.zero_column = 0
     self.operates = ""
     #获取图片,并将它放入九宫格
     for i in range(0, 3):
         self.blocks.append([])
         for j in range(0, 3):
             block = Label.Label(self, i * 3 + j)
             self.gridLayout.addWidget(block, i, j, 1, 1)
             self.blocks[i].append(block)
             #得到图片
             self.imgList.append(block.getImg())
             #if i * 3 + j == 0:#获取空白图片的位置
             #self.zero_row = i
             #self.zero_column = j
     #进行第一次比较,确定是哪张图片文件夹
     self.picturesLoad = PM.MatchFirst(self.imgList)
     #进行第二次比较,确定是哪张图
     Total = 45  #所有的图片序号之和
     for i in self.blocks:
         for j in i:
             j.number = PM.matchSecond(self.picturesLoad, j.getImg())
             Total -= j.number
             if j.number == 0:
                 self.zero_column = j.column
                 self.zero_row = j.row
     print("j.column:" + str(self.zero_column))
     print("j.row:" + str(self.zero_row))
     self.blocks[self.zero_row][self.zero_column].number = Total
     print(Total)
     self.show()
Пример #18
0
 def state_five(self,name):
     # print("{} Score is {}".format(name,self.score))
     state_five = pygame.image.load('state_five.bmp')
     yes_button_parameters = Rect(480, 335, 175,85)
     no_button_parameters = Rect(700, 335, 175, 85)
     self.s.game_display.blit(state_five, (0, 0))
     l_score=Label(self.score,800,160,label_score_green,75)
     l_score.draw_label(self.s)
     self.d.insert(name,self.score)
     self.s.refresh_background()
     while self.run_game:
         for event in pygame.event.get():
             if event.type == pygame.MOUSEBUTTONDOWN:
                 if yes_button_parameters.collidepoint(event.pos):
                     self.score=0
                     self.state_two(name)
                 elif no_button_parameters.collidepoint(event.pos):
                     self.state_six(name)
             if event.type == pygame.QUIT:
                 self.run_game = False
     pygame.quit()
     quit()
Пример #19
0
    def find_top_labels(self, g, k=6):
        labels = self.__ontology.get_labels()
        label_score = []
        for i in range(len(labels)):
            # put a condition that verifies if the labels is
            print labels[i] + ' -- ' + g.get_name()
            score = self.__predictor[g.get_name()].run(labels[i], g)
            label_score.append((score, labels[i]))

        #print 'feature: ' + repr(g.get_features())
#       label_score.sort(reverse=True) -- if positive numbers are desired

# The scores are sorted in ascending order because the scores are already transformed to negative values
        label_score.sort()
        print 'labels: ' + repr(labels)
        print 'scores: ' + repr(label_score)

        #print 'scores: ' + repr(label_score)

        feature_bond_structure = self.__ontology.get_bond_structure(
            g.get_name())
        #print g.get_name() + ' ' + repr(feature_bond_structure)

        k = len(labels)
        for i in range(k):
            name = label_score[i][1]
            #print 'label:' + name
            # when features connect to labels
            label_modalities = self.__ontology.get_modalities(name)
            #print 'modalities: '+repr(label_modalities)
            for bond in feature_bond_structure:
                if bond[0] in label_modalities:
                    score = label_score[i][0]
                    level = self.__ontology.get_level(name)
                    modality = self.__ontology.get_modalities(name)
                    g.add_top_label(
                        Label(name, modality, level, score, -1, 0.0))
                    break
Пример #20
0
        "The day began. How many hours later will the clock return to where it stood at the beginning of the day?",
        3, ["12", "24", "6"], "12"
    ],
    [
        30, "The car crossed the road in 6 hours. S = 60 km car speed-?", 3,
        ["10km/h", "15km/h", "6km/h"], "10km/h"
    ]
]
max_rating = 10
rating = 0
num = 1
for level in levels:
    answer = Quiz(level[0], f"{num} of {len(levels)}", level[1], level[2],
                  level[3], level[4])
    if answer:
        rating += max_rating / len(levels)
    num += 1
rating_label = Label(window_width // 2, window_height // 2, window_width // 2,
                     f"rating is {round(rating)} from {max_rating}",
                     fonts["PixelArt"], (255, 255, 255), "yes")
while True:
    window.fill((45, 5, 42))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        quit_button.update(event)
        if quit_button.pressed:
            pygame.quit()
    quit_button.draw(window)
    rating_label.draw(window)
    pygame.display.flip()
Пример #21
0
    def __init__ (self,
        master,
        name,
        optionList,
        helpURLPrefix=None,
        headerText=None,
        defButton=None,
        clearButton=None,
        omitDef = True,
        setDefIfAbsent = True,
        formatFunc = None,
        **kargs
    ):
        """Create a widget showing a set of options as checkboxes.

        Inputs:
        - name: name of option set;
            used as a namespace when multiple option sets are combined,
            and used as the name of the VMS qualifier, if relevant
        - optionList: data about the options.
            Each entry is a list of:
            - option name (used by getString)
            - option label text
            - default logical value
            - help text (optional)
            - help URL (optional)
        - helpURLPrefix: if supplied, every item in optionList
          will by default have a helpURL of _htlpURLPrefix + option name
          (but a specified help URL will override this for any individual entry).
          Also used as the help URL for the optional label.
        - headerText: text for an optional heading
        - defButton: controls whether there is a button to restore defaults; one of:
            - True: for a button entitled "Defaults"
            - False or None: no button
            - a string: text for the default button
        - clearButton: text for an optional "clear" button
            - if None, no button is supplied
            - if "", the button is entitled "Clear"
        - omitDef: if True: getValueDict returns {} if all values are default
            and getValueDict and getValueList omit individual values whose widgets are default
        - setDefIfAbsent: if True: setValueDict sets all widgets to their default value if name is absent
            and setValueDict and setValueList set individual widgets to their default value
            if they are missing from the value list.
        - formatFunc: the format function; takes one input, an RO.InputCont.BoolNegCont
            containing all of the option checkboxes, and returns a string
            The default format is RO.InputCont.BasicFmt.
        **kargs: keyword arguments for Frame
        """
        InputContFrame.InputContFrame.__init__(self, master, **kargs)

        # optional header
        if headerText:
            helpURL = helpURLPrefix
            if helpURL and helpURL.endswith("#"):
                helpURL = helpURL[:-1]
            Label.Label(
                master = self,
                text = headerText,
                helpURL = helpURL,
            ).pack(side="top", anchor="w")
        
        if formatFunc is None:
            formatFunc = RO.InputCont.BasicFmt()

        # create option checkboxes
        # and a list of input containers for them
        wdgNames = []
        wdgList = []
        for optionData in optionList:
            # the items in optionData are:
            # name, label, default value, helpURL, helpText
            # and the last two items are optional
            nameStr, labelStr, defVal = optionData[0:3]
            
            def listGet(aList, ind, defVal=None):
                try:
                    return aList[ind]
                except LookupError:
                    return defVal

            helpText = listGet(optionData, 3)
            helpURL = listGet(optionData, 4)
            if helpURLPrefix and not helpURL:
                helpURL = helpURLPrefix + nameStr
            wdg = Checkbutton.Checkbutton(self,
                text=labelStr,
                defValue = defVal,
                helpText = helpText,
                helpURL = helpURL,
            )
            wdg.pack(side="top", anchor="w")
            wdgList.append(wdg)
            wdgNames.append(nameStr)
        
        # create input container
        self.inputCont = (
            RO.InputCont.BoolNegCont (
                name = name,
                wdgs = wdgList,
                wdgNames = wdgNames,
                omitDef = omitDef,
                setDefIfAbsent = setDefIfAbsent,
                formatFunc = formatFunc,
            )
        )
    
        # optional extra buttons
        self.optWdgList = []

        # optional "restore defaults" button
        if defButton is True:
            defButton = "Defaults"
        if defButton not in (False, None):
            defButtonWdg = Button.Button(self,
                text=defButton,
                command=self.restoreDefault,
                helpText = "Restore defaults",
            )
            self.optWdgList.append(defButtonWdg)
        
        # optional "clear" button
        if clearButton is True:
            clearButton = "Clear"
        if clearButton not in (False, None):
            clearButtonWdg = Button.Button(self,
                text=clearButton,
                command=self.clear,
                helpText = "Uncheck all checkboxes",
            )
            self.optWdgList.append(clearButtonWdg)

        # pack optional buttons, if any
        for wdg in self.optWdgList:
            wdg.pack(side="top", anchor="nw")
Пример #22
0
    def create(self):

        self.setTitle("Rectangle Destroyer")
        self.fpsDisplay = True

        background = Sprite()
        background.setTexture(
            Texture.load("assets/rectangle-destroyer/background.jpg"))
        background.setPosition(400, 300)
        self.group.addEntity(background)

        self.paddle = Sprite()
        self.paddle.setTexture(
            Texture.load("assets/rectangle-destroyer/paddle.png"))
        self.paddle.setPosition(400, 550)
        self.group.addEntity(self.paddle)

        self.ball = Sprite()
        self.ball.setTexture(
            Texture.load("assets/rectangle-destroyer/ball.png"))
        self.ball.setPosition(400, 525)
        self.ball.setPhysics(0, 1000, 0)
        self.group.addEntity(self.ball)

        self.wallGroup = Group()
        self.group.addEntity(self.wallGroup)
        wallSideTexture = Texture.load(
            "assets/rectangle-destroyer/wall-side.jpg")  # 20 x 600
        wallTopTexture = Texture.load(
            "assets/rectangle-destroyer/wall-top.jpg")  # 800 x 60
        leftWall = Sprite()
        leftWall.setTexture(wallSideTexture)
        leftWall.setPosition(10, 300)
        rightWall = Sprite()
        rightWall.setTexture(wallSideTexture)
        rightWall.setPosition(790, 300)
        topWall = Sprite()
        topWall.setTexture(wallTopTexture)
        topWall.setPosition(400, 30)
        self.wallGroup.addEntity(leftWall)
        self.wallGroup.addEntity(rightWall)
        self.wallGroup.addEntity(topWall)

        self.brickGroup = Group()
        self.group.addEntity(self.brickGroup)

        brickTexture = Texture.load("assets/rectangle-destroyer/brick.jpg")

        for col in range(0, 11):
            for row in range(0, 8):
                brick = Sprite()
                brick.setTexture(brickTexture)
                brick.setPosition(80 + 64 * col, 120 + row * 32)
                self.brickGroup.addEntity(brick)

        self.messageLabel = Label()
        self.messageLabel.loadFont("assets/starfish-collector/OpenSans.ttf",
                                   48)
        self.messageLabel.fontColor = (128, 128, 128)
        self.messageLabel.text = "click to start"
        self.messageLabel.setPosition(400, 400)
        self.messageLabel.alignment = "CENTER"
        self.group.addEntity(self.messageLabel)

        self.score = 0
        self.scoreLabel = Label()
        self.scoreLabel.loadFont("assets/starfish-collector/OpenSans.ttf", 36)
        self.scoreLabel.fontColor = (255, 255, 0)
        self.scoreLabel.text = "Score: " + str(self.score)
        self.scoreLabel.setPosition(400, 0)
        self.scoreLabel.alignment = "CENTER"
        self.group.addEntity(self.scoreLabel)
    sys.exit()

g_repo_path = os.environ['PHYSIM_GENDATA']

# Initialization
g_blender_executable_path = os.environ['BLENDER_PATH']

blank_file = osp.join('blank.blend')
empty_bin_file = osp.join('empty_bin.blend')

push_code = osp.join('push.py')
drop_code = osp.join('drop_and_render.py')

cfg = ConfigParser("config.yml", "camera_info.yml")
frame_number = cfg.getNumSimulationSteps() - 1
pLabel = Label.Label()


def get_initial_pose_and_control(pc_path, target_pose, noise):
	# pc_path: Path to the point cloud representing the current state
	# target_pose: Target pose for the object being manipulated
	# noise: Simulating perception/execution noise

	# currently set as a static offset wrt target pose; this is generally computed using the sensing data
	offset_position = [0.03, -0.03, 0.01]

	init_pose = [target_pose.position.x, target_pose.position.y, target_pose.position.z,
				 target_pose.orientation.w, target_pose.orientation.x, target_pose.orientation.y, target_pose.orientation.z]

	init_pose[0] += offset_position[0]
	init_pose[1] += offset_position[1]
    def on_init(self):
        pygame.init()
        self._display_surf = pygame.display.set_mode(
            self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)
        self._display_surf.fill(self._background)
        self._running = True
        self._screen = "Main"  #Main - original screen. itemCat - screen showing items. checkOut - checkout screen.
        self.buttons = []
        self._itemCategories = []

        def itemCategory0Command(self):
            print "itemCat0Command"
            self._screen = "itemCatScreen:00"

        def itemCategory1Command(self):
            print "itemCat0Command"
            self._screen = "itemCatScreen:01"

        def itemCategory2Command(self):
            print "itemCat0Command"
            self._screen = "itemCatScreen:02"

        def itemCategory3Command(self):
            print "itemCat0Command"
            self._screen = "itemCatScreen:03"

        def itemIncrementCommand(self):
            print "itemIncerementCommand"
            self.incriment()

        def itemDecrementCommand(self):
            print "itemDecrementCommand"
            self.decrement()

        itemsToAdd = []
        itemCat0ItemNumber0 = Items.item("Apollo", 0000, 40000, 0, (100, 100),
                                         144, 144, "Images/APOLLO.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat0ItemNumber1 = Items.item("Mercury", 0001, 40000, 0, (100, 300),
                                         144, 144, "Images/Mercury.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat0ItemNumber2 = Items.item("x38", 0002, 40000, 0, (300, 100),
                                         144, 144, "Images/x38c.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat0ItemNumber3 = Items.item("GEMINI", 0003, 40000, 0, (300, 300),
                                         144, 144, "Images/GEMINI.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)

        itemsToAdd.append(itemCat0ItemNumber0)
        itemsToAdd.append(itemCat0ItemNumber1)
        itemsToAdd.append(itemCat0ItemNumber2)
        itemsToAdd.append(itemCat0ItemNumber3)
        self._itemCategories.append(
            iC.itemCatergory("NASA", 00, itemsToAdd, (100, 100), 144, 144,
                             "Images/NASA.jpg", itemCategory0Command, self))

        itemsToAdd = []
        itemCat1ItemNumber0 = Items.item("Sputnik", 0100, 40000, 0, (100, 100),
                                         144, 144, "Images/Sputnik.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat1ItemNumber1 = Items.item("Vostok", 0101, 40000, 0, (100, 300),
                                         144, 144, "Images/Vostok.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat1ItemNumber2 = Items.item("Voskhod", 0102, 40000, 0, (300, 100),
                                         144, 144, "Images/voskhod-1__1.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)

        itemsToAdd.append(itemCat1ItemNumber0)
        itemsToAdd.append(itemCat1ItemNumber1)
        itemsToAdd.append(itemCat1ItemNumber2)
        self._itemCategories.append(
            iC.itemCatergory("Russian Spaceships", 01, itemsToAdd, (300, 100),
                             144, 144, "Images/Sputnik.jpg",
                             itemCategory1Command, self))

        itemsToAdd = []
        itemCat2ItemNumber0 = Items.item("SPACEX - DRAGON 7", 0200, 40000, 0,
                                         (100, 100), 144, 144,
                                         "Images/SPACEX - DRAGON 7.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat2ItemNumber1 = Items.item("DREAMCHASER 7", 0201, 40000, 0,
                                         (100, 300), 144, 144,
                                         "Images/DREAMCHASER 7.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat2ItemNumber2 = Items.item("CST-100", 0202, 40000, 0, (300, 100),
                                         144, 144, "Images/CST-100.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)

        itemsToAdd.append(itemCat2ItemNumber0)
        itemsToAdd.append(itemCat2ItemNumber1)
        itemsToAdd.append(itemCat2ItemNumber2)
        self._itemCategories.append(
            iC.itemCatergory("Other Spaceships", 02, itemsToAdd, (100, 300),
                             144, 144, "Images/CST-100.jpg",
                             itemCategory2Command, self))

        itemsToAdd = []
        itemCat3ItemNumber0 = Items.item("Lemonade", 0300, 40000, 0,
                                         (100, 100), 144, 144,
                                         "Images/Lemonade.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat3ItemNumber1 = Items.item("Orange", 0301, 40000, 0, (100, 300),
                                         144, 144, "Images/Orange.jpeg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat3ItemNumber2 = Items.item("Grapefruit", 0302, 40000, 0,
                                         (300, 100), 144, 144,
                                         "Images/Grapefruit.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)
        itemCat3ItemNumber3 = Items.item("Peach Mango", 0303, 40000, 0,
                                         (300, 300), 144, 144,
                                         "Images/Peach Mango.jpg",
                                         itemIncrementCommand,
                                         itemDecrementCommand)

        itemsToAdd.append(itemCat3ItemNumber0)
        itemsToAdd.append(itemCat3ItemNumber1)
        itemsToAdd.append(itemCat3ItemNumber2)
        itemsToAdd.append(itemCat3ItemNumber3)
        self._itemCategories.append(
            iC.itemCatergory("TROPICANA FLORIDA SUNSHINE", 03, itemsToAdd,
                             (300, 300), 144, 144, "Images/Orange.jpeg",
                             itemCategory3Command, self))

        def goBackCommand(self):
            self._screen = "Main"

        self.backButton = Button.Button(144, 50, (50, 50), goBackCommand, None,
                                        self)
        self.backButton.currentColor = self.backButton.default_color = self.backButton.hover_color = None  #Make sure that the surface is not overwritten
        self.backButton.surface = Label.Label("BACK").getSurface()

        def goToCheckout(self):
            self._screen = "checkOut"

        self.checkoutButton = Button.Button(144, 50, (500, 275), goToCheckout,
                                            None, self)
        self.checkoutButton.currentColor = self.checkoutButton.default_color = self.checkoutButton.hover_color = None  #Make sure that the surface is not overwritten
        self.checkoutButton.surface = Label.Label("CHECK OUT").getSurface()
        self.surfacesOfItemsShopped = [
        ]  #Used for listing items in checkout screen
        self.title = Label.Label("Main Screen").getSurface()
        self.titleLocation = (200, 50)
        #self._image_surf = pygame.image.load("Images/myimage.jpg").convert()
        #self._image_loc = pygame.Rect(70, 70, 50, 20)
        #self._testText = Label.Label("Heyyy")

        self.moneyPutInside = 0

        def finishButtonClicked(self):
            totalMoneyNeeded = 0
            for itemCat in self._itemCategories:
                for item in itemCat.items:
                    totalMoneyNeeded += item.amount * item.price

            if self.moneyPutInside >= totalMoneyNeeded:
                self._screen = "Main"
                for itemCat in self._itemCategories:
                    for item in itemCat.items:
                        item.amount = 0
                self.moneyPutInside = self.moneyPutInside - totalMoneyNeeded

        self.finishButton = Button.Button(100, 50, (600, 250),
                                          finishButtonClicked, None, self)
        self.finishButton.currentColor = self.finishButton.default_color = self.finishButton.hover_color = None
        self.finishButton.surface = Label.Label("FINISH").getSurface()

        def addMoney10(self):
            self.moneyPutInside += 10

        self.addMoney10Button = Button.Button(60, 50, (575, 200), addMoney10,
                                              None, self)
        self.addMoney10Button.currentColor = self.addMoney10Button.default_color = self.addMoney10Button.hover_color = None
        self.addMoney10Button.surface = Label.Label("+$10").getSurface()

        def addMoney10M(self):
            self.moneyPutInside += 10000000

        self.addMoney10MButton = Button.Button(100, 50, (650, 200),
                                               addMoney10M, None, self)
        self.addMoney10MButton.currentColor = self.addMoney10MButton.default_color = self.addMoney10MButton.hover_color = None
        self.addMoney10MButton.surface = Label.Label("+$10M").getSurface()
Пример #25
0
    def __init__(self,
                 text,
                 handler=None,
                 x=0,
                 y=0,
                 width=0,
                 height=0,
                 icon=None,
                 vertical_expansion=1,
                 text_prop=None,
                 parent='osd'):
        """
        Initialise an instance of a PopupBox

        @ivar x: x coordinate. Integer
        @ivar y: y coordinate. Integer
        @ivar width: Integer
        @ivar height: Integer
        @ivar text: String to print.
        @ivar icon: icon
        @ivar text_prop: A dict of 4 elements composing text proprieties
          { 'align_h': align_h, 'align_v': align_v, 'mode': mode, 'hfill': hfill }:
            - align_v = text vertical alignment
            - align_h = text horizontal alignment
            - mode    = hard (break at chars); soft (break at words)
            - hfill   = True (don't shorten width) or False
        """

        self.handler = handler
        Window.__init__(self, parent, x, y, width, height)
        self.text_prop = text_prop or {
            'align_h': 'center',
            'align_v': 'center',
            'mode': 'soft',
            'hfill': True
        }

        self.font = None
        if self.skin_info_font:
            self.set_font(self.skin_info_font.name, self.skin_info_font.size,
                          Color(self.skin_info_font.color))
        else:
            self.set_font(config.OSD_DEFAULT_FONTNAME,
                          config.OSD_DEFAULT_FONTSIZE)

        if not width:
            tw = self.font.stringsize(text) + self.h_margin * 2
            if tw < self.osd.width * 2 / 3:
                self.width = max(self.osd.width / 2, tw)

        self.__init__content__()

        if type(text) in StringTypes:
            self.label = Label(text,
                               self,
                               Align.CENTER,
                               Align.CENTER,
                               text_prop=self.text_prop)
        else:
            raise TypeError, text

        if icon:
            self.set_icon(icon)
Пример #26
0
def Quiz(timer, number, question, buttons_num, buttons_texts, true_answer):
    number_label = Label(20, 20, window_width // 2, number, fonts["PixelArt"],
                         (255, 255, 255))
    question_label = Label(window_width // 2, window_height // 2,
                           window_width // 2, question, fonts["PixelArt"],
                           (255, 255, 255), "yes")
    space = 20
    buttons = []
    x = 0
    button_width = 100
    button_height = 100
    heights = []
    widths = []
    for button_text in buttons_texts:
        answer = Label(0, 0, button_width, button_text, fonts["PixelArt"],
                       (255, 255, 255))
        heights.append(answer.height * 2)
        widths.append(answer.width * 2)
    button_height = max(heights)
    button_width = max(widths) * 2
    buttons_surface_width = button_width * buttons_num + space * (buttons_num -
                                                                  1)
    buttons_surface = pygame.Surface((buttons_surface_width, button_height))
    buttons_surface.fill((45 - 5, 5 - 5, 42 - 5))
    buttons_surface_x = window_width // 2 - buttons_surface_width // 2
    buttons_surface_y = window_height - button_height
    question_label.y = buttons_surface_y - question_label.height
    for button_text in buttons_texts:
        button_image = pygame.Surface((button_width, button_height))
        button_image.fill((253, 176, 30))
        answer = Label(button_width // 2, button_height // 2, button_width,
                       button_text, fonts["PixelArt"], (0, 0, 0), "yes")
        answer.draw(button_image)
        buttons.append([
            button_text,
            Button(x, 0, button_image, button_image, buttons_surface_x,
                   buttons_surface_y)
        ])
        x += button_width + space
    second_width = round(window_width / timer)
    time_1 = time()
    while True:
        time_2 = time()
        if window_width - (round(time_2 - time_1) * second_width) == 0:
            return False
        window.fill((45, 5, 42))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            for button in buttons:
                button[-1].update(event)
                if button[-1].pressed:
                    if button[0] == true_answer:
                        return True
                    else:
                        return False
            quit_button.update(event)
            if quit_button.pressed:
                pygame.quit()
        pygame.draw.rect(window, (45 - 5, 5 - 5, 42 - 5),
                         (0, buttons_surface_y, window_width,
                          window_height - buttons_surface_y))
        for button in buttons:
            button[-1].draw(buttons_surface)
        window.blit(buttons_surface, (buttons_surface_x, buttons_surface_y))
        question_label.draw(window)
        number_label.draw(window)
        quit_button.draw(window)
        pygame.draw.rect(window, (255, 255, 255),
                         (0, 0, window_width -
                          (round(time_2 - time_1) * second_width), 10))
        pygame.display.flip()
Пример #27
0
 def GetAssemblyForSpecific(self, el):
     ret = Assembly()
     ret.AppendLabel(Label(el.Name))
     ret.AppendInstruction(
         Instruction('DATA', [el.Init], el.Type.Name + ' ' + el.Name))
     return ret
Пример #28
0
    numLabelers = 25
    ground_truths = [choice(types) for i in range(5 * free * numLabelers)]

    Labelers = []

    for i in range(numLabelers):
        acc = uniform(.75, 1)
        style = sink_norm(abs(rand(n, n)), num_iter=100, iter_list=False)
        Labelers.append(Labeler(acc, style, n))

    for i in range(numLabelers):
        for j in range(len(ground_truths)):
            labeler = Labelers[i]
            gt = ground_truths[j]
            lbl = labeler.answerQuestion(gt)
            Labelers[i].labels.append(Label(j, i, lbl))

    numImages = len(ground_truths)
    numSampled = numImages / 2

    labels = []
    for sim in range(50):
        numLabels = numSampled * numLabelers
        fp = open("../../Simulation/Tests/SinkhornAnalysis/data/%d.txt" % sim,
                  'w')
        fp.write("%d %d %d %d\n" % (numLabels, numLabelers, numImages, n))

        # Write character set to file
        for c in types:
            fp.write("%s " % c)
        fp.write("\n")
Пример #29
0
 def get_label(self, name):
     assert isinstance(name, (str, unicode)), name
     headers, data = self._requester.requestAndCheck(
         "GET", self.url + "/labels/" + urllib.quote(name), None, None)
     return Label.Label(self._requester, data, completed=True)
Пример #30
0
 def __getLabels(self):
     labels = Label.Label()
     self.labelAlfa = labels.getLabels()