示例#1
0
def grasp_ball():
    pygame.init()

    settings = Settings()

    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    pygame.display.set_caption(settings.screen_caption)
    stats = GameStats(settings)

    people = People(settings, screen)

    balls = Group()

    gbf.create_ball(settings, screen, balls)

    while True:
        gbf.check_events(people)

        if stats.game_active:
            gbf.update_ball(settings, stats, screen, people, balls)

        else:
            balls.empty()
            settings.people_image = './images/game_over.bmp'
            people = People(settings, screen)
            people.rect.centerx = screen.get_rect().centerx
            people.rect.centery = screen.get_rect().centery
            people.draw_people()

        gbf.update_screen(settings, screen, people, balls)
示例#2
0
def main(student_file, volunteer_file, output_file):

    workbook = xlsxwriter.Workbook(
        '/Users/Ingrid.Pacheco/Desktop/match-output.xlsx')
    worksheet = workbook.add_worksheet()
    headers = [
        'nome MENTOR', 'email MENTOR', 'numero MENTOR', 'graduacao MENTOR',
        'disciplinas MENTOR', 'idade MENTOR', 'estado MENTOR', 'nome ALUNO',
        'email ALUNO', 'numero ALUNO', 'graduacao ALUNO', 'disciplinas ALUNO',
        'idade ALUNO', 'estado ALUNO', 'dificuldades', 'interesse'
    ]
    worksheet = add_headers(worksheet, headers)
    matches = Match(worksheet, len(headers))
    students = People()
    mentors = People()
    with pd.ExcelFile(student_file) as firstxls:
        df1 = pd.read_excel(firstxls, 0)

        f1 = File(student_file, df1.columns, df1.values.tolist(), df1)
        f1.set_properties('student')

        with pd.ExcelFile(volunteer_file) as secondxls:
            df2 = pd.read_excel(secondxls, 0)

            f2 = File(volunteer_file, df2.columns, df2.values.tolist(), df2)
            f2.set_properties('mentor')

            hours = df2.get(
                'Quantas horas por semana você terá para dedicar para a mentoria (não esqueça de levar em consideração o tempo que você já dedica a outras atividades, e eventualmente outros projetos do ExplicaEnem que você é parte).  Dessa maneira, de acordo com sua disponibilidade, poderemos te conectar com a quantidade de mentorados.'
            ).tolist()
            for idx_mentor, val_mentor in enumerate(f2.get_values()):

                vital_properties = f2.get_properties(idx_mentor, 'mentor')
                mentor = Person(
                    f2.get_name(idx_mentor), f2.get_email(idx_mentor),
                    f2.get_phone(idx_mentor), vital_properties, val_mentor,
                    int(hours[idx_mentor].split('(')[1].split(' ')[0]))
                mentors.add_person(mentor)

                for idx_student, val_student in enumerate(f1.get_values()):

                    student_vital_properties = f1.get_properties(
                        idx_student, 'student')
                    student = Person(f1.get_name(idx_student),
                                     f1.get_email(idx_student),
                                     f1.get_phone(idx_student),
                                     student_vital_properties, val_student, 0,
                                     f1.get_additional_properties(idx_student))
                    students.add_person(student)

                    matches.get_match(student, mentor)

    find_matches(matches, students, mentors)
    workbook.close()
示例#3
0
def rungame():
	#初始化
	pygame.init()
	al_setting = Settings()
	#创建窗口
	screen = pygame.display.set_mode((al_setting.screen_width,
	al_setting.screen_height))
	pygame.display.set_caption("catch the ball")
	stats = Stats(al_setting)
	#创建角色
	people = People(al_setting,screen)
	#创建球组
	balls = Group()
	#创建角色组
	peoples = Group()
	peoples.add(people)
	while True:
		#鼠标键盘相应事件
		gf.check_event(people)
		if stats.game_active:	
			#更新角色位置
			people.update()
			#更新球的位置
			gf.ball_update(al_setting,screen,balls,peoples,stats)
			#刷新界面
		gf.screen_update(al_setting,screen,balls,people)
示例#4
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Pick the stars")

    people = People(ai_settings, screen)
    stars = Stars(ai_settings, screen)
    alien = Alien(ai_settings, screen)
    bullets = Group()
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    play_button = Button(ai_settings, screen, "Play")

    while True:
        gf.check_events(ai_settings, stats, sb, people, alien, bullets,
                        play_button)
        bullets.update()
        for bullet in bullets.copy():
            if bullet.rect.bottom >= ai_settings.screen_height:
                bullets.remove(bullet)
        if stats.game_active:
            people.update()
            gf.update_alien(alien)
            gf.update_stars(ai_settings, stats, sb, people, stars)
            if alien.rect.x % 120 == 0:
                gf.update_bullet(ai_settings, stats, screen, people, alien,
                                 bullets)

        gf.update_screen(ai_settings, stats, sb, screen, people, stars, alien,
                         bullets, play_button)
def get_faces():
    """
    This API searches an image for faces and returns the location of each face
    ---
    tags:
      - Image Analyzer
    consumes:
      - multipart/form-data
    produces: 
      -application/json
    parameters:
      - in: formData
        name: upfile
        type: file
        required: true
        description: Image file to analyse
    responses:
      500:
        description: Error, something went wrong!
      200:
        description: Detection success!
    """
    #logger=logging.getLogger(__name__)
    #logger.info("Calling prediction data for /people")
    response = None
    model = People()
    query_class = request.args.get('class')
    iFile = request.files.getlist('upfile')[0]
    img = load_image(iFile)
    img = rotate_image(img, iFile)
    img = limit_size_image(img)
    response = model.get_tags_coords(img, query_class)
    return jsonify(response)
示例#6
0
def create_people():
    """
    sample request body:{
                            "First":"Zhe",
                            "Last":"Chen",
                            "Age":"31",
                            "GithubAcct":"zchen1007",
                            "Date of 3rd Grade Graduation":"3/04/98"
                        }
    not recommending using id as one of the key in the json
    :return: json object response
    """
    input = request.json
    people = People(profile=input)
    is_valid, msg = people.is_data_valid()
    if not is_valid:
        return jsonify({"err": msg}), 400
    has_all_req, msg = people.contains_all_keys()
    if not has_all_req:
        return jsonify({"err": msg}), 400
    con_cur = Database.get_connection()
    if 'ID' in people.profile:
        app.logger.warning(
            "manually input ID has the risk of conflicting with existing, if conflicts records will be ignored"
        )
        people.insert_with_id(con_cur)
    else:
        people.insert_no_id(con_cur)
    con_cur.commit()
    con_cur.close()
    return getPeople()
示例#7
0
    def __init__(self, slug, api_key):
        super(NationBuilder, self).__init__()

        self.people = People(slug, api_key)
        self.tags = NBTags(slug, api_key)
        self.lists = Lists(slug, api_key)
        self.contacts = Contacts(slug, api_key)
示例#8
0
 def __init__(self, num, city, BROAD_RATE, PROTECTION_RATE, DEATH_RATE, EXPOSED_TIME, IMMUNED_TIME, \
   HOSPITAL_RECEIVE_TIME, CURE_TIME, SAFETY_DIST, u, FLUCTUATION, can_exposed_infect, recovered_included):
     # self.city = city
     self.num = num
     self.peoples = np.array([])
     self.BROAD_RATE = BROAD_RATE
     self.PROTECTION_RATE = PROTECTION_RATE
     self.DEATH_RATE = DEATH_RATE
     self.EXPOSED_TIME = EXPOSED_TIME
     self.HOSPITAL_RECEIVE_TIME = HOSPITAL_RECEIVE_TIME
     self.CURE_TIME = CURE_TIME
     self.IMMUNED_TIME = IMMUNED_TIME
     self.SAFETY_DIST = SAFETY_DIST
     self.FLUCTUATION = FLUCTUATION
     self.SCALE = 1000
     self.u = np.exp(u)
     self.can_exposed_infect = can_exposed_infect
     self.recovered_included = recovered_included
     self.Tg = []
     self.Te = []
     self.Ti = []
     self.in_touch = 0
     if can_exposed_infect == True:
         self.can_infect_status = [1, 2]
     else:
         self.can_infect_status = [2]
     for i in range(num):
         x = self.SCALE * np.random.normal(0, 1) + city.centerX
         y = self.SCALE * np.random.normal(0, 1) + city.centerY
         self.peoples = np.append(self.peoples, People(x, y))
示例#9
0
 def __init__(self, size, n_p):
     """
     :param size: int, size of the grid
     :param n_p: (4,) numpy array, [# of ppl of each status]
     """
     self.size = size
     self.all_p = []
     self.total_p = sum(
         n_p)  # sum of the n_p list, indicating total number of ppl
     self.steps = 1000  # this is the total number of steps you simulate
     for status, n in enumerate(n_p):
         gc = 0 if status == 0 else n_p[status - 1]
         cur_list = [
             People(i + gc,
                    np.random.randint(self.size, size=2),
                    size,
                    age=0,
                    status=status) for i in range(n)
         ]
         self.all_p.extend(cur_list)
     self.to_pos_array()
     self.stream = self.data_stream()
     # Setup the figure and axes...
     self.fig, self.ax = plt.subplots()
     # Then setup FuncAnimation.
     self.ani = anime.FuncAnimation(
         self.fig,
         self.update,
         interval=200,
         # interval it is the time between your snapshots in ms
         init_func=self.setup_plot,
         blit=True)
示例#10
0
 def getPeople(self):
     self.category = 'people'
     result_d = json.loads(
         SwapiService.getSwapi(self.category, self.getId()))
     self.people = People(result_d['name'], result_d['height'])
     print("Name: {} Height: {}cm".format(self.people.name,
                                          self.people.height))
def deal_data():
    for index, row in df.iterrows():
        new_person = People(row['age'], row['sex'], row['bmi'],
                            row['children'], row['smoker'], row['region'],
                            row['charges'])
        new_person.change_sex()
        new_person.change_smoker()
        new_person.change_region()
        list1.append(new_person)
    for index, row in rf.iterrows():
        new_person = People(row['age'], row['sex'], row['bmi'],
                            row['children'], row['smoker'], row['region'],
                            row['charges'])
        new_person.change_sex()
        new_person.change_smoker()
        new_person.change_region()
        list2.append(new_person)
示例#12
0
def run():
    """main function
    """
    file_data = None
    filename = ""
    validation_msgs = ValidationMessages()
    tags = Tags()
    peeps = People(validation_msgs)
    fam = Families(peeps, validation_msgs)
    peeps.set_families(fam)

    if len(sys.argv) < 2:
        sys.exit("Usage: " + sys.argv[0] + " path-to-gedom-file")
    filename = sys.argv[1]

    try:
        file_data = open(filename)
    except IOError:
        sys.exit("ERROR: file " + sys.argv[1] + "was not found!")

    for line in file_data:
        try:
            data = tags.processline(line)
            if data["valid"] == "Y":
                fam.process_line_data(data)
                peeps.process_line_data(data)

        except TagsError as err:
            sys.exit("ERROR: ", err)

    fam.validate()
    peeps.validate()

    if validation_msgs.get_messages():
        print("Validation Messages")
        validation_msgs.print_all()
        print("")

    print("Individuals")
    peeps.print_all()
    peeps.us29_print_deceased()
    peeps.us31_print_single()
    peeps.us35_print_recent_births()
    peeps.us36_print_recent_deaths()
    peeps.us_38_print_upcoming_birthdays()
    print("")

    print("Families")
    fam.print_all()
    fam.us30_print_married()
    fam.us32_print_multiple_births()
    fam.us33_print_orphans()
    fam.us34_print_big_age_diff()
    fam.us_39_print_upcoming_anniversaries()
    print("")
示例#13
0
文件: main.py 项目: jfxugithub/python
def app():

    laoLiu = People("老刘")
    laoWan = People("老王")
    laoLin = People("老林")

    peopleList = [laoLiu, laoWan, laoLin]
    nu = 1  # 记录回合数
    """随机获取一名要敌人"""
    def get_enemy(gunerName):
        while True:
            enemy = random.choice(peopleList)
            if enemy.name != gunerName:
                return enemy

    #每个人开一枪,看谁活到最后
    while True:
        print("=" * 10 + ("第%d回合" % nu) + "=" * 10)

        if laoWan.blood > 0:
            print("%s:" % laoWan.name)
            enemy = get_enemy(laoWan.name)
            if laoWan.shoot_enemy(enemy):
                peopleList.remove(enemy)

        if laoLiu.blood > 0:
            print("%s:" % laoLiu.name)
            enemy = get_enemy(laoLiu.name)
            if laoLiu.shoot_enemy(enemy):
                peopleList.remove(enemy)

        if laoLin.blood > 0:
            print("%s:" % laoLin.name)
            enemy = get_enemy(laoLin.name)
            if laoLin.shoot_enemy(enemy):
                peopleList.remove(enemy)

        if len(peopleList) == 1:
            print("最终的赢家是:", peopleList[0].name)
            break

        nu += 1
示例#14
0
def write_arch(name, age, weight, height):
    last = 0
    people = People(name, int(age), float(weight), float(height))
    print(last_id())
    last += int(last_id())
    final_str = get_all()
    final_str += f"{(last)+1} - {people.get_name()}#{people.get_age()}#{people.get_weight():.2f}#{people.get_height():.2f}\n"
    with open(abs_file_path, 'w') as archive:
        archive.write(final_str)

    clear()
    print("Pessoa adicionada com sucesso")
示例#15
0
def test_get_all_people():
    response = requests.get("https://swapi.co/api/people/")
    next_is_available = True
    while (next_is_available):
        assert response.status_code == 200
        response_json = response.json()
        for response_person in response_json["results"]:
            person = People()
            person.set_fields(response_person)
            person.assert_people()
        if response_json["next"] is not None:
            response = requests.get(response_json["next"])
        else:
            next_is_available = False
示例#16
0
def load_main_file(filename, main_dic):

    wb = openpyxl.load_workbook(filename)
    sheet = wb.get_sheet_by_name(wb.sheetnames[0])
    line_number = len(sheet["A"])
    print "Filename: ", filename, "Lines: ", line_number

    racker_name_list = []
    contractor_name_list = []

    for row in range(9, line_number + 1):
        combi_name = sheet['A' + str(row)].value.encode(
            'ascii', 'ignore').lower().strip()
        status = sheet['C' + str(row)].value.encode('ascii',
                                                    'ignore').lower().strip()
        company = sheet['J' + str(row)].value.encode('ascii',
                                                     'ignore').lower().strip()
        time = sheet['D' + str(row)].value
        active_status = sheet['K' + str(row)].value.encode(
            'ascii', 'ignore').lower().strip()

        if status != "completed":
            status = "incompleted"
        if company != "contractor":
            company = "rackspace"

        if time > datetime.datetime(2017, 1, 1) and active_status == "active":
            if combi_name not in main_dic:
                people = People(combi_name)
                people.status = status
                people.company = company

                main_dic[combi_name] = people

            #name duplicate
            else:
                if status == "completed":
                    main_dic[combi_name].status = status

            last_name, first_name = combi_name.split(",")
            last_name = last_name.strip()
            first_name = first_name.strip()
            if company == "rackspace" and (first_name,
                                           last_name) not in racker_name_list:
                racker_name_list.append((first_name, last_name))
            if company != "rackspace" and (
                    first_name, last_name) not in contractor_name_list:
                contractor_name_list.append((first_name, last_name))

    print "Active registered in 2017: ", len(main_dic.keys())
示例#17
0
def generate_people(age_max, no_of_people, filename):
    """Reads a list of names from a file then selects a random number of them configured
    by no_of_people and assigns them ages up to age_max
    """
    try:
        people = []
        with open(filename) as myfile:
            for line in myfile:
                person = Person(line.rstrip('\n'), randint(1, age_max))
                people.append(person)
        people = random.sample(people, no_of_people)
        return People(people)
    except (FileNotFoundError, ValueError):
        raise
示例#18
0
	def __init__(self, num, city, BROAD_RATE, DEATH_RATE, SHADOW_TIME, \
			HOSPITAL_RECEIVE_TIME, CURE_TIME, SAFETY_DIST, u, FLUCTUATION):
		# self.city = city
		self.peoples = np.array([])
		self.BROAD_RATE = BROAD_RATE
		self.DEATH_RATE = DEATH_RATE
		self.SHADOW_TIME = SHADOW_TIME
		self.HOSPITAL_RECEIVE_TIME = HOSPITAL_RECEIVE_TIME
		self.CURE_TIME = CURE_TIME
		self.SAFETY_DIST = SAFETY_DIST
		self.FLUCTUATION = FLUCTUATION
		self.SCALE = 1000
		self.u = u
		for i in range(num):
			x = self.SCALE*np.random.normal(0, 1) + city.centerX
			y = self.SCALE*np.random.normal(0, 1) + city.centerY
			self.peoples = np.append(self.peoples, People(x, y))
示例#19
0
def test_get_person():
    response = requests.get("https://swapi.co/api/people/1/")
    expected_json = {
        "name":
        "Luke Skywalker",
        "height":
        "172",
        "mass":
        "77",
        "hair_color":
        "blond",
        "skin_color":
        "fair",
        "eye_color":
        "blue",
        "birth_year":
        "19BBY",
        "gender":
        "male",
        "homeworld":
        "https://swapi.co/api/planets/1/",
        "films": [
            "https://swapi.co/api/films/2/", "https://swapi.co/api/films/6/",
            "https://swapi.co/api/films/3/", "https://swapi.co/api/films/1/",
            "https://swapi.co/api/films/7/"
        ],
        "species": ["https://swapi.co/api/species/1/"],
        "vehicles": [
            "https://swapi.co/api/vehicles/14/",
            "https://swapi.co/api/vehicles/30/"
        ],
        "starships": [
            "https://swapi.co/api/starships/12/",
            "https://swapi.co/api/starships/22/"
        ],
        "created":
        "2014-12-09T13:50:51.644000Z",
        "edited":
        "2014-12-20T21:17:56.891000Z",
        "url":
        "https://swapi.co/api/people/1/"
    }
    assert response.status_code == 200
    person = People()
    person.set_fields(response.json())
    person.assert_json_equal(expected_json)
 def initPeople(self, n):
     global MAX_LIKE_LEVEL
     #(self,id,egoMax,initMax,sex):
     ncore = 10  # n/10
     for i in range(0, n):
         p = People(i, r.randint(0, self.egoMax),
                    r.randint(0, self.initMax), r.randint(0, 1))
         p.initLike0(n)
         if (len(self.people) > 0):
             for j in range(0, min(ncore, len(self.people))):
                 lover = r.randint(0, len(self.people) - 1)
                 p.like[lover] = r.randint(
                     MAX_LIKE_LEVEL - MAX_LIKE_LEVEL / 20, MAX_LIKE_LEVEL)
                 self.people[
                     lover].nice = self.people[lover].nice + p.like[lover]
         p.initUndefinedLike()
         self.people.append(p)
示例#21
0
def ini():
    # create a bunch of particles
    num_people = 40
    vec_v = np.array([0, 0])
    r = 0.25  # in meters
    #random initial position and check overlap
    overlap= False 
    p_list=[]
    while len(p_list)<num_people:
        P=People(np.random.rand(2) * 10, vec_v, r,np.random.rand(2),screen)
        for p_j in p_list:
            if p_j.overlap(P):
                overlap= True 
                break
            overlap= False 
        if overlap== False:
            p_list.append(P)
    return p_list
示例#22
0
def run_game():
    #初始化一个游戏并创建一个屏幕对象
    pygame.init()
    ai_settings=Settings()
    screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    #创建一艘飞船
    ship=Ship(screen)
    people=People(screen)

    #开始游戏的主循环
    while True:

        #监视屏幕和鼠标和键盘事件
        gf.check_events(ship)
        ship.update()
        #更新屏幕上的图像,并切换到新图像
        gf.update_screen(ai_settings,screen,ship,people)
示例#23
0
def Cellular_Automata(Total_People):

    UI = GUI()

    # Total_People = 200
    P = People(Total_People, myMap)

    UI.Show_People(P.list)

    Time_Start = time.time()
    Eva_Number = 0
    Time_Pass = 0
    Time_Step = 1
    while Eva_Number < Total_People:
        Eva_Number = P.run()

        UI.Update_People(P.list)

        # time.sleep(random.uniform(0.015, 0.025))

        UI.canvas.update()
        UI.root.update()

        Time_Pass += Time_Step
        UI.label_time['text'] = "Time = " + "%.2f" % Time_Pass + "s"
        UI.label_evac['text'] = "Evacution People: " + str(Eva_Number)
        # print("%.2fs" % (Time_Pass) + " 已疏散人数:" +str(Eva_Number))

    # Time_Pass = time.time()-Time_Start
    UI.label_time['text'] = "Time = " + "%.2f" % Time_Pass + "s"
    UI.label_evac['text'] = "Evacution People: " + str(Eva_Number)

    # 热力图
    sns.heatmap(P.thmap.T, cmap='Reds')
    # for i in range(0, 100):
    # 	for j in range(0, 60):
    # 		if P.thmap[i][j] != 0:
    # 			print(P.thmap[i][j])
    plt.axis('equal')
    plt.show()

    UI.root.mainloop()
示例#24
0
    def check_map(self):
        # 用于把门周围的地面变成人们更趋近的区域
        res = np.where(self.map == Block.GATE.value)
        gates = list(zip(res[0], res[1]))  # y, X
        for gate in gates:
            self.gate_log.add_gate(gate[0], gate[1])
            man_in_gate = People(gate[1], gate[0], 0)
            envs = self.get_env(GATE_AREA, man_in_gate)
            envs[0][envs[0] == 0] = Block.EMPTY_NEAR_GATE.value

        # 找到地图中的传送门
        res = np.where(self.map == Block.GATE_MAN_OUT.value)
        gates = list(zip(res[0], res[1]))  # y, X
        for gate in gates:
            num = input(str(gate[0]) + " " + str(gate[1]) + ": ")
            g_o = Gate_People_Out(gate[0], gate[1], int(num))
            env = self.get_env(4, g_o)
            g_o.set_env(env[0])
            self.gate_man_out.append(g_o)
        self.draw_map()
示例#25
0
    def gen_people(self, num):
        self.total_man = num
        res = np.where(self.map == Block.GATE.value)
        gates = list(zip(res[0], res[1]))  # y, X
        #  随机放入游客在空白的地图中
        while (num != 0):
            x = random.randint(1, self.map.shape[1] - 1)
            y = random.randint(1, self.map.shape[0] - 1)
            if (self.map[y, x] == Block.EMPTY.value
                    or self.map[y, x] == Block.EMPTY_NEAR_GATE.value):
                d = []
                # 计算到门的距离
                for gate in gates:
                    d.append(sqrt((gate[0] - y)**2 + (gate[1] - x)**2))
                # 计算出最小值
                self.mans.append(People(x, y, min(d)))

                num = num - 1
                self.map[y, x] = Block.MAN.value
        # 应该按照距离排序
        self.mans.sort(key=lambda x: x.distance_to_gate, reverse=False)
def get_face_id(repo):
    """
    This API searches an image for faces and returns the person face grouop the name of a face group in the DB for a repo.
    ---
    paths:
      /people/{repo}
    tags:
      - Image Analyzer
    consumes:
      - multipart/form-data
    produces: 
      -application/json
    parameters:
      - in: formData
        name: upfile
        type: file
        required: true
        description: Image file to analyse
      - in: path
        name: repo
        schema:
          type: integer
        required: true
    responses:
      500:
        description: Error, something went wrong!
      200:
        description: Detection success!
    """
    #logger=logging.getLogger(__name__)
    #logger.info("Calling prediction data for /faces")
    response = None
    model = People(repo)
    query_class = request.args.get('class')
    iFile = request.files.getlist('upfile')[0]
    img = load_image(iFile)
    img = rotate_image(img, iFile)
    img = limit_size_image(img)
    response = model.get_tags_face(img, query_class)
    return jsonify(response)
def set_person_name(repo, personid, name):
    """
    This API allows you to set the name of a person group in the DB for a repo
    ---
    paths:
      /people/{repo}/{personid}/{name}
    tags:
      - Image Analyzer
    consumes:
      - multipart/form-data
    produces: 
      -application/json
    parameters:
      - in: path
        name: repo
        schema:
          type: integer
        required: true
      - in: path
        name: personid 
        schema:
          type: integer
        required: true
      - in: path
        name: name 
        schema:
          type: string
        required: true
    responses:
      500:
        description: Error, something went wrong!
      200:
        description: Detection success!
    """
    logger = logging.getLogger(__name__)
    logger.info("Calling prediction data for /people/<repo>/<personid>/<name>")
    model = People(repo)
    query_class = request.args.get('class')
    response = model.set_name(repo, personid, name)
    return jsonify(response)
示例#28
0
def convert(file_path_read, file_path_write):
    gorbFile = open(file_path + file_path_read, 'r', encoding='utf-8')
    resultFile = open(file_path + 'result.txt', 'r', encoding='utf-8')
    gorbPlusResult = open(file_path + file_path_write, 'a+', encoding='utf-8')

    resList = []
    listOfResult = []

    print('Start writting {}'.format(file_path_read))

    next(resultFile)  #пропускаю первую строку
    for line in resultFile:  #сплит резалта
        resList = line.split()  #загоняю резалт в лис
        People(resList[0] + ' ' + resList[1] + ' ' + resList[2], resList[3],
               resList[12])

    gorbPlusResult.writelines(
        'file;N;-2;-1;0;1;2;p-2;p-1;p0;p1;p2;TypeExperiment;Target;N_Type_Target;N_Type;Type_Target;N_Target;Hit;'
        + '\n')
    next(gorbFile)  #пропускаю первую строку
    for line in gorbFile:  #сплит горба
        resList = line.split(';')

        gorbList = re.search('[а-яА-ЯёЁ]+\s+[а-яА-ЯёЁ]+\s+[а-яА-ЯёЁ]+',
                             resList[0])
        name = gorbList[0]
        gorbList = re.search('[-+]?\d+', resList[0])
        id = gorbList[0]
        for obj in People.nameList:
            if name == obj.getFIO() and id == obj.getNumOfExperiment():
                gorbPlusResult.write(line.replace('\n', ''))
                gorbPlusResult.write(obj.getResult() + '\n')
                break

    print('Writting completed {}'.format(file_path_write))

    gorbFile.close()
    resultFile.close()
    gorbPlusResult.close()
示例#29
0
    def run(self):
        import dlib
        from people import People
        from gender_recognizer_tf import GenderRecognizer
        from face_recognizer import FaceRecognizer
        self.gender_recognizer = GenderRecognizer()
        self.p = People("./known_people")
        self.face_recognizer = FaceRecognizer(
            self.p.people
        )  #this is not ok , we should pass onlu self.p as object
        self.predictor = dlib.shape_predictor(
            "shape_predictor_68_face_landmarks.dat")
        self.fa = FaceAligner(self.predictor, desiredFaceWidth=160)
        self.state = IdleState()
        while True:
            label, data = self.recv()
            if label == 'video_feed':
                frame = data[0]
                face = None
                aligned_image, face, rect_nums, XY = self.face_extractor(frame)
                if face is None:
                    continue

                face_locations, face_names, percent = self.face_recognizer.recognize(
                    face)
                in_the_frame = self.__update_state(self.p.people, percent)

                if (self.state.__class__ == MatchState):
                    path, gender, age = self.gender_recognizer.recognize(
                        aligned_image, face, rect_nums, XY)
                    self.broadcast(["Match", face, in_the_frame, gender, age])
                else:
                    path, gender, age = self.gender_recognizer.recognize(
                        aligned_image, face, rect_nums, XY)
                    if path is None:
                        continue
                    print("FaceFinder path = " + path)
                    self.broadcast(["NoMatch", path])
示例#30
0
文件: window.py 项目: Veigal/avl-tree
    def search_archive(self):
        root.filename = filedialog.askopenfilename(
            initialdir="/",
            title="Select file",
            filetypes=(("csv files", "*.csv"), ("all files", "*.*")))

        people_file = open(root.filename, 'r')

        self.t_birth = Tree("birth")
        self.t_name = Tree("name")
        self.t_cpf = Tree("cpf")

        b_date = []

        for line in people_file:
            columns = line.split(";")
            b_date = columns[3].split("/")
            columns[3] = b_date[2] + b_date[1] + b_date[0]
            people = People(columns[0], columns[1], columns[2], columns[3],
                            columns[4])
            self.t_birth.insert_node(people)
            self.t_name.insert_node(people)
            self.t_cpf.insert_node(people)