def isSuicide(self, coordinates, colour): group = Group(colour, {coordinates}) potentialBoard = deepcopy(self) potentialBoard.addToGroups(group) #first we add any neighbouring allies to the group for neighbour in potentialBoard.neighbours(coordinates): if potentialBoard.getGroup(neighbour).colour == group.colour: group.mergeGroup(potentialBoard.getGroup(neighbour), potentialBoard) #now we check if the new stone captures anything, if so it's not suicide for neighbour in potentialBoard.neighbours(coordinates): if potentialBoard.getGroup(neighbour).colour != 'None' and \ potentialBoard.getGroup(neighbour) != colour: if potentialBoard.getGroup(neighbour).isCaptured( potentialBoard): return False #finally check to see if the stone will be captured itself return group.isCaptured(potentialBoard)
def get_observing_group_list(self): observing_group_list = [] for i in range(self.show_num): dummy_member = Member(0, "", [], False, 0, 0, 0, 0) dummy_group = Group(0, [], [dummy_member], [], 0, False, 0, 0, 0, 0, 0, "", "") observing_group_list.append(dummy_group) count = 0 for g in self.group_list: if g.group_name in self.observing_groups: observing_group_list[count] = g count += 1 if count >= self.show_num: break return observing_group_list
def initGroup(self): #格式{群id:[群成员id]}?? #grouplist格式为:列表[群id] self.my_groups = groupInfo = self.client.dealGetGroupList() for groupid in groupInfo: groupname, grouphead = self.client.dealGetGroupNameAndHead(groupid) groupmember = self.client.dealGetGroupMember(groupid) group = QListWidgetItem(self.groups) group.setSizeHint(QSize(self.groups.width(), 55)) groupdic = { 'group': group, 'groupid': groupid, 'groupname': groupname, 'grouphead': grouphead, 'groupmember': groupmember } g = Group(groupname, str(groupid), grouphead, groupmember) self.glist.append(groupdic) self.groups.setItemWidget(group, g)
def get_credits(game): out = Group() scr = game.scr out.append(Text(scr, "Credits", 500, 20, 70, WHITE)) out.append(Text(scr, "Wertpol - The OC", 50, 100, 40, WHITE)) out.append( Text(scr, "master1203 - Cat Stock Image", 50, 150, 40, WHITE)) out.append( Text_Button(scr, "Go Back", 500, 650, 50, BLACK, WHITE, resp=game.start, scale=1.3)) return out
def _set_default_value(self, record, fields=None): if record.value.get(self.name) is not None: return from group import Group parent_name = self.attrs.get('relation_field', '') fields = fields or {} context = record.expr_eval(self.attrs.get('context', {})) group = Group(self.attrs['relation'], fields, parent=record, parent_name=parent_name, child_name=self.name, context=context, parent_datetime_field=self.attrs.get('datetime_field')) if not fields and record.model_name == self.attrs['relation']: group.fields = record.group.fields record.value[self.name] = group self._connect_value(group)
def GetResultsFaceSearchCollection(self, jobId, idToNameMaps): maxResults = 10 paginationToken = '' finished = False groups = [] for idToNameMap in idToNameMaps: groups.append(Group(idToNameMap)) faceToGroupMap = {} for group in groups: for faceId in group.getMemberFaceIds(): if faceId not in faceToGroupMap: faceToGroupMap[faceId] = [] faceToGroupMap[faceId].append(group) while finished == False: response = self.client.get_face_search(JobId=jobId, MaxResults=maxResults, NextToken=paginationToken) for personMatch in response['Persons']: #print('Person Index: ' + str(personMatch['Person']['Index'])) #print('Timestamp: ' + str(personMatch['Timestamp'])) current = personMatch['Timestamp'] if ('FaceMatches' in personMatch): for faceMatch in personMatch['FaceMatches']: faceId = faceMatch['Face']['FaceId'] for group in faceToGroupMap[faceId]: group.faceAppear(faceId, current) #print('Face ID: ' + faceMatch['Face']['FaceId']) #print('Similarity: ' + str(faceMatch['Similarity'])) #print if 'NextToken' in response: paginationToken = response['NextToken'] else: finished = True group.printLastOccurance()
def update_event(self,location, date, time, explanation): self.place = location self.date = date self.time = time self.explanation = explanation with ConnectionPool() as cursor: cursor.execute('UPDATE event_table SET place = %s , date = %s, time = %s, explanation = %s WHERE event_id = %s' ,(location, date, time,explanation, self.event_id)) cursor.execute('SELECT username FROM user_table WHERE userid = %s' , (self.owner,)) username = cursor.fetchone()[0] if self.group_id is not None: group = Group(None,None,None,None,None,self.group_id,None) group.read_with_id() for participant in group.participants: new = New(None, username, participant, self.group_id, self.event_id, None, 'group' , 'updated event in', False, None,None ) new.save_to_db() else: for participant in self.participant_arr: new = New(None, username, participant, self.group_id, self.event_id, None, 'event' , 'updated', False,None,None ) new.save_to_db()
def load(self): """ Overwriting default load method. Load list does not contain node instances themselves, just network addresses. This method uses those network addresses to load node instances into nodes dictionary. :return: NA """ super(Groups, self).load() LOGGER.debug("Loading Groups") if self._db_file is not None: if len(self._main): self.main.clear() for group_name in self._main.values(): self.main[group_name] = Group(external_name(group_name), self._platform_name, self._nodes)
def test_HW_new_contact(self): wd = self.wd self.open_webpage(wd) self.login(wd, username="******", password="******") wd.find_element_by_xpath("//form[@id='LoginForm']/input[3]").click() self.link_to_group_page(wd) self.create_a_new_group(wd, Group(name="group.Chupakabra", header="group.Chupakabra Header", footer="group.Chupakabra footer")) self.group_verification(wd) self.new_contac_page(wd) self.contact_information(wd, Contact(firstname="Abra", middlename="Kadabra", lastname="Chupakabra", nickname="Chupakabra", title="My Title", company="Home", address="557 Mayfair Walk Ave, Las Vegas NV 89173", home="7023542185", mobile="6504655622", work="7023336669", fax="1234567890", email="*****@*****.**", email2="*****@*****.**", email3="test.mail.ru", homepage="yahoo.com", address2="123 new address test", phone2="123 home address", notes="my notes bla bla bla")) self.submit_cotact_information(wd) wd.find_element_by_link_text("Logout").click()
def set_lines(self, lines): gr = Group() self.lines = lines gr.set_group_by_lines(lines) if self.type in [0, 1]: self.group = gr.group.copy() elif self.type == 2: self.group = gr.group.copy() self.sums = gr.members.copy() elif self.type == 3: self.jigsaws = gr.members.copy() self.group = gr.group.copy() self.houses = self.rows + self.columns + self.jigsaws self.peers_jigsaw = [self.jigsaws[gr.group[i]] for i in range(81)] self.peers = [ {*i, *j, *k} for (i, j, k) in zip( self.peers_jigsaw, self.peers_column, self.peers_row ) ]
def get_HUD(scr, sprites, pull, buy_bg, save, load): money_bg = Image(scr, sprites["money_bg"], 5, -60) pulldown = Image_Button(scr, sprites["hud_pulldown"], 1150, 0, resp=pull) buy_bg = Image(scr, buy_bg, 0, -500) buy_buttons = Group() buy_buttons.append( Image_Button(scr, sprites["full_screen"], 1100, -450, resp=lambda: None)) buy_buttons.append( Image_Button(scr, sprites["save"], 1100, -300, resp=save)) buy_buttons.append( Image_Button(scr, sprites["load"], 1100, -150, resp=load)) return money_bg, pulldown, buy_bg, buy_buttons
def dealCreateGroupOk(self, gid, data): gname = data.decode('utf-8') for info in self.groupTemp: if gname == info[0]: ghead = info[1] newG = Group(gname, gid, ghead, [self.client.id]) item = QListWidgetItem(self.groups) item.setSizeHint(QSize(self.groups.width(), 61)) self.groups.setItemWidget(item, newG) self.groupTemp.remove(info) self.my_groups.append(gid) groupdic = { 'group': item, 'groupid': gid, 'groupname': gname, 'grouphead': ghead, 'groupmember': [self.client.id] } self.glist.append(groupdic) break
def read(): data = pd.read_csv("files/arquivo.csv") people = [] groups = [] for person in data.values: preferred_groups = person[1:] new_person = Person(person[0]) for person_group in preferred_groups: group_exists = False for group in groups: if group.theme == person_group: group.add_person(new_person) new_person.add_group(group) group_exists = True if not group_exists: new_group = Group(person_group) new_group.add_person(new_person) new_person.add_group(new_group) groups.append(new_group) people.append(new_person) return people, groups
def dealAddGroupOk(self, gid, data): if gid in self.addTemp: data = data.split('\n'.encode('utf-8'), 2) gname = data[0].decode('utf-8') gmembers = json.loads(data[1].decode('utf-8')) ghead = data[2] item = QListWidgetItem(self.groups) item.setSizeHint(QSize(self.groups.width(), 61)) newG = Group(gname, gid, ghead, gmembers) self.groups.setItemWidget(item, newG) self.addTemp.remove(gid) self.my_groups.append(gid) groupdic = { 'group': item, 'groupid': gid, 'groupname': gname, 'grouphead': ghead, 'groupmember': gmembers } self.glist.append(groupdic)
def instantiate_users(messages): usermap = {} num_messages = len(messages) latest_timestamp = messages[0]['created_at'] earliest_timestamp = messages[num_messages - 1]['created_at'] group = Group(earliest_timestamp, latest_timestamp) for i in range(len(messages) - 1, -1, -1): m = messages[i] uid = m['user_id'] username = m['name'] if uid not in usermap: user = User(uid) user.add_username(username) usermap[uid] = user else: usermap[uid].add_username(username) return (group, usermap)
def create_group(): posts = MyProfile(current_user.username) form = GroupForm() if request.method == 'POST': if form.validate_on_submit(): try: group = Group(form.name.data, form.isprivate.data, current_user.id, form.description.data, form.give_permission.data, None, form.max_number.data) group.save_to_db() except: flash('Group could not be created!') return redirect(url_for('create_group')) flash(f'Your group is created with name {form.name.data}!', 'success') return redirect(url_for('owned_groups')) return render_template("creategroup.html", title="Create", form=form, posts=posts)
def _updateGroups(self, response, request): self.logger.debug('Received groups list %s', response) # This XMPP client is not receiving this for some reason. groups = response.getGroups() for group in groups: room = group.getId() owner = group.getOwner() subjectOwner = group.getSubjectOwner() subject = group.getSubject() if room in self.groups: oroom = self.groups[room] oroom.owner = owner oroom.subjectOwner = subjectOwner oroom.subject = subject else: self.groups[room] = Group(room, owner, subject, subjectOwner) # A crude implemtation of groups that act like buddies self.backend.handleBuddyChanged(self.user, room, subject, [], protocol_pb2.STATUS_NONE)
def read_groups(dic, groups = dict(), parent = None): for name, value in dic.iteritems(): name = name.lower() group = Group(name, 0, parent) # If I'm not a leaf group then read my child groups if isinstance(value, dict): if name == "other": raise ValueError("Non-leaf groups named 'other' are not allowed.") groups = read_groups(value, groups, parent = group) # Else if I'm a leaf node elif isinstance(value, int): # Read number of servers if value > 0: group.servers = value else: raise ValueError("Group {} must have size greater than 0".format(group.name)) # Wait.. I'm not really a group.. if name == "other": if group.isRoot(): raise ValueError("Root groups named 'other' are not allowed.") else: # Deslike this, need to think about better solution.. group.name = "{}-{}".format(parent.name, "other") else: raise ValueError( "The value of group '{}' should be either an integer or a new group. Leaf groups should be in the form: \"group_name: nservers\"".format(name)) if group.name in groups: raise ValueError( "{}: Names of root groups and groups within each tree should be unique.".format(name)) groups[group.name] = group return groups
def test_initialize_possible_values(self): # Given 9 Entries with starting values entries = [ Entry(value=1, row=0, column=0), Entry(value=2, row=0, column=1), Entry(value=3, row=0, column=2), Entry(value=0, row=0, column=3), Entry(value=0, row=0, column=4), Entry(value=0, row=0, column=5), Entry(value=7, row=0, column=6), Entry(value=8, row=0, column=7), Entry(value=9, row=0, column=8), ] group = Group(GroupType.Row, group_number=0) group.entries = entries group.initialize_possible_values() for entry in group.entries: if entry.value: self.assertEqual(entry.possible_values[GroupType.Row], []) else: self.assertEqual(entry.possible_values[GroupType.Row], [4, 5, 6])
def __init__(self, *args, **traits): """ Creates a new menu manager. """ # Base class constructor. super(ActionManager, self).__init__(**traits) # The last group in every manager is the group with Id 'additions'. # # fixme: The side-effect of this is to ensure that the 'additions' # group has been created. Is the 'additions' group even a good idea? group = self._get_default_group() # Add all items to the manager. for arg in args: # We allow a group to be defined by simply specifying a string (its # Id). if isinstance(arg, basestring): # Create a group with the specified Id. arg = Group(id=arg) # If the item is a group then add it just before the default group # (ie. we always keep the default group as the last group in the # manager). if isinstance(arg, Group): self.insert(-1, arg) group = arg # Otherwise, the item is an action manager item so add it to the # current group. else: ## # If no group has been created then add one. This is only ## # relevant when using the 'shorthand' way to define menus. ## if group is None: ## group = Group(id='__first__') ## self.insert(-1, group) group.append(arg) return
def importTeamsFromFile(filename='teams.txt'): try: file = open(filename, 'r', encoding='utf-8') list_of_teams = file.read().splitlines() pool = Group('of Teams to be drawn') for team_line in list_of_teams: if team_line == '' or team_line.isspace() or team_line[0] == '#': list_of_teams.remove(team_line) else: team_details = [t.strip() for t in team_line.split(',')] team = Team(*team_details) pool.addToGroup(team) file.close() return pool except FileNotFoundError: print('Cannot read file from provided file path') return [] except: print('Error reading file') return []
def _start_battle_hand_animation(self): """手を出すアニメーションを開始 """ # self.actor_state_group.empty() total_frame = 60 group = Group() for actor in [self.actor1, self.actor2]: sprite = self.hand_sprites[actor][actor.hand] group.add(sprite) sprite.image.set_alpha(0) props = make_transform_properties(0, 0, 0, 0, 0, 1, total_frame=int(total_frame * 0.2)) self.transform_manager.add_transformer(sprite, props) self.timer_group.add_timer_sprite(group, timer=total_frame, on_delete_fnc=self._judge, debug_label="手を表示する")
def update_group_info(group): form = UpdateGroupInfoForm() posts = MyProfile(current_user.username) mygroup = Group(None, None, None, None, None, group, None) mygroup.read_with_id() if request.method == 'POST': if form.validate_on_submit(): try: mygroup.update_group(form.name.data, form.isprivate.data, form.description.data, form.give_permission.data, form.max_number.data) except: flash('Group information could not be updated!') return redirect(url_for('update_group_info', group=group)) flash(f'Your group information is updated successfully!', 'success') return redirect(url_for('group_info', group=group)) return render_template("update_group.html", title="Update Group", form=form, posts=posts, group=mygroup)
def new_group(): global groupname_to_group global username_to_user global current_user global current_group while True: print("Options: ") print(" 1. Create a group") print(" 2. Enter a group") print(" 3. Return to main page") choice = input("Enter an option: ") if choice == '1': while True: new_groupname = input('New Groupname:') if new_groupname == '':break elif new_groupname not in groupname_to_group: new_group = Group(new_groupname) new_group.add_user(current_user) groupname_to_group[new_groupname] = new_group return else: print('The groupname exists or is in valid, please try again or press Enter to return.') elif choice == '2': while True: e_groupname = input('Groupname:') if e_groupname == '': break elif e_groupname in groupname_to_group: current_user.enter_group(groupname_to_group[e_groupname]) return else: print('Please enter an existing groupname or press Enter to return.') elif choice == '3': return else: print('Please enter a valid option:') continue
def __add_groups(self, added_groups, min_distance): new_group = Group() new_group.name = self.__next_char() for group in self.__groups: if group not in added_groups: min_distance_temp = group.get_distance(added_groups[0]) for curr_group in added_groups: if group.get_distance(curr_group) < min_distance_temp: min_distance_temp = group.get_distance(curr_group) group.delete_distances(added_groups) group.distances.append(Distance(min_distance_temp, new_group)) new_group.distances.append(Distance(min_distance_temp, group)) for added_group in added_groups: if added_group.x == 0.0: added_group.x = self.__offset_x self.__offset_x += 1 new_group.sub_groups = added_groups sub_groups_points = [] for added_group in added_groups: sub_groups_points.append(Point(added_group.x, added_group.y)) try: self.__groups.remove(added_group) except ValueError: print('group has been deleted before') x = 0.0 for point in sub_groups_points: x += point.x new_group.x = x / len(sub_groups_points) new_group.y = min_distance self.__groups.append(new_group)
def get_top_posts(self) -> List[Post]: """ Gets the list of top Posts, one post from each Group and then sort them by its conversion :return: list of top Posts """ list_of_top_posts = [ Group(id, name, members_count, self.max_posts_per_group).top_posts for id, name, members_count in zip( self.group_ids, self.group_names, self.members_count) ] top_posts = [] for top_posts_of_group in list_of_top_posts: if top_posts_of_group is None: top_posts.append(top_posts_of_group) else: top_posts.extend(top_posts_of_group) bad_group_indexes = [ index for index, post in enumerate(list_of_top_posts) if post is None ] self.bad_groups = [(self.group_ids[index], self.group_names[index]) for index, post in enumerate(list_of_top_posts) if index in bad_group_indexes] top_posts = [ post for post in top_posts if post is not None and post.reposts > self.repost_border ] top_repost_posts = sorted(top_posts, key=lambda x: x.repost_conversion_pct) top_like_posts = sorted(top_posts, key=lambda x: x.like_conversion_pct) for post in top_posts: post.overall_rating = top_repost_posts.index( post) + top_like_posts.index(post) return sorted(top_posts, key=lambda x: x.overall_rating, reverse=True)
def loadWorkSpacefromConfig(self, work_space_file): try: if os.path.isfile(str(work_space_file)): self.server.clearGroups() work_space = json.load(open(str(work_space_file))) for g in work_space["groups"]: new_g = Group(self.server, g["group_name"]) new_g.group_info = g["group_info"] for d in g["duts"]: new_d = DUT(d["dut_name"], d["dut_ip"], None, self.server.server_config) new_d.setBranch(d["branch"]) new_d.setTestType(d["test_type"]) new_d.project_code = d["project_code"] new_d.platform = d["platform"] new_d.sub_platform = d["sub_platform"] for sce in d["scenarios"]: new_d.addTestScenario(sce["path"]) new_g.addDUT(new_d) self.server.addGroup(new_g) self._refreshUI() except: logger.LOGGER.error(traceback.format_exc()) self.server.work_space_file = str(work_space_file)
def test_p_anonymity_naive(): # create and print test group group_table = np.array([ [0, 1, 2, 3, 4], [-5, -3, -2, 0, 1], [-1, -3, -2, -10, -8], [10, 8, 9, 1, 3], # [1, 5, 6, 2, -4], # [10, 1, 3, -6, 0], [1, 10, 5, 6, -8] ]) ids = [ "A", "B", "C", "D", # "E", # "F", "G" ] group = Group(group_table, ids) for i, row in enumerate(group.group_table): print(ids[i] + ": " + str(row)) # p-anonymity leaves = p_anonymity_naive(group, 2, 5, 0) # print output for leaf in leaves: print() print(leaf.pr + " rows:") print(leaf.table) return
def main(): student1 = Student("Adam", "Nowak") student2 = Student(555, 888) student1.add_grades("UNIX", [4, 5]) student1.add_grades("UNIX", []) student1.add_grades("UNIX", [5]) student1.add_grades("Java", []) student1.add_grades("Java", [4, 5, 5, 5]) student1.add_grades("Java", [3]) student1.add_grades("Java", []) student1.add_grades("Java", [4]) print "Student's 1 partial grades:", student1.grades print "Student's 1 averages for each subject:", student1.get_averages() print "Student's 1 final average:", student1.get_total_average() group = Group() group.add_student(student1) group.add_student(student2) group.export_students("my_group.json")
def empty(shape, dtype=float): """ Return a new group of given shape and type, without initialising entries. :param tuple shape: Shape of the new group, e.g., ``(2, 3)`` or ``2``. :param dtype: The desired data-type for the group, e.g., `np.int8`. Default is `np.float64`. :return: Group with the given shape and dtype filled with zeros. **Notes** `empty`, unlike `zeros`, does not set the group values to zero, and may therefore be marginally faster. On the other hand, it requires the user to manually set all the values in the group, and should be used with caution. **Examples** >>> Group.empty((2,2)) Group([[6.94248367807e-310, 1.34841898023e-316], [1.34841977073e-316, 0.0]], dtype=[('f0', '<f8')]) **See also** * :meth:`dana.zeros` : Return a new group setting values to zero. * :meth:`dana.ones` : Return a new group setting values to one. * :meth:`dana.zeros_like` : Return a group of zeros with shape and type of input. * :meth:`dana.ones_like` : Return a group of ones with shape and type of input. * :meth:`dana.empty_like` : Return a empty group with shape and type of input. """ return Group(shape=shape, dtype=dtype, fill=None)