Example #1
0
 def check_first_attacker(self):
     min_trump_card = None
     for player in self.__players:
         for card in player.hand:
             if card.colour == self.trump_card.colour:
                 if not min_trump_card:
                     min_trump_card = card
                     self.__player_turn = player
                 else:
                     if min_trump_card.rank > card.rank:
                         min_trump_card = card
                         self.__player_turn = player
     logger.info(
         f'Bot start hand: {[card.name for card in self.__players[-1].hand]}'
     )
     if self.__player_turn and min_trump_card:
         logger.info(
             f'Attack player: {self.__player_turn.name}, min trump card: {min_trump_card.name}'
         )
     else:
         logger.warning('Players don\'t have trump card!')
         # todo: fix me
         self.__player_turn = self.__players[-1]
         logger.info(
             f'Random choice attack player: {self.__player_turn.name}')
Example #2
0
 def add_cart(self, card):
     if self.len_hand >= MAX_COUNT_CARD_IN_ARM:
         logger.warning('Max count card in arm!')
         return
     if card:
         logger.info(f'To hand {self.name}, add card: {card.name}')
         card.change_scale(BASE_CARD_WIDTH, BASE_CARD_HEIGHT)
         self.__hand.add(card)
Example #3
0
    def add_sample(self, sample, L):
        """Add a sample to the film."""
        d_image_x = sample.image_x - 0.5
        d_image_y = sample.image_y - 0.5
        x0 = int(math.ceil(d_image_x - self.filter.x_width))
        x1 = int(d_image_x + self.filter.x_width)
        y0 = int(math.ceil(d_image_y - self.filter.y_width))
        y1 = int(d_image_y + self.filter.y_width)
        x0 = max(x0, self.x_pixel_start)
        x1 = min(x1, self.x_pixel_start + self.x_pixel_count - 1)
        y0 = max(y0, self.y_pixel_start)
        y1 = min(y1, self.y_pixel_start + self.y_pixel_count - 1)
        if ((x1 - x0) < 0) or ((y1 - y0) < 0):
            logger.warning("Sample outside the image extent. %d %d %d %d" %
                           (x0, x1, y0, y1))
            return

        # loop over filter support and add sample to pixel arrays
        L_x, L_y, L_z = L.to_xyz()

        # precompute x and y filter table offsets
        ifx = []
        for x in xrange(x0, x1 + 1):
            fx = abs(
                (x - d_image_x) * self.filter.inv_x_width * FILTER_TABLE_SIZE)
            ifx.append(min(int(fx), FILTER_TABLE_SIZE - 1))
        ify = []
        for y in xrange(y0, y1 + 1):
            fy = abs(
                (y - d_image_y) * self.filter.inv_y_width * FILTER_TABLE_SIZE)
            ify.append(min(int(fy), FILTER_TABLE_SIZE - 1))
        sync_needed = (self.filter.x_width > 0.5) or (self.filter.y_width >
                                                      0.5)
        for y in xrange(y0, y1 + 1):
            for x in xrange(x0, x1 + 1):
                # evaluate filter value at (x,y) pixel
                offset = ify[y - y0] * FILTER_TABLE_SIZE + ifx[x - x0]
                filter_weight = self.filter_table[offset]
                # update pixel values with filtered sample contribution

                if not sync_needed:
                    self.pixels[y * self.x_pixel_count * 8 +
                                x * 8] += filter_weight * L_x
                    self.pixels[y * self.x_pixel_count * 8 + x * 8 +
                                1] += filter_weight * L_y
                    self.pixels[y * self.x_pixel_count * 8 + x * 8 +
                                2] += filter_weight * L_z
                    self.pixels[y * self.x_pixel_count * 8 + x * 8 +
                                3] += filter_weight
                else:
                    self.pixels[y * self.x_pixel_count * 8 +
                                x * 8] += filter_weight * L_x
                    self.pixels[y * self.x_pixel_count * 8 + x * 8 +
                                1] += filter_weight * L_y
                    self.pixels[y * self.x_pixel_count * 8 + x * 8 +
                                2] += filter_weight * L_z
                    self.pixels[y * self.x_pixel_count * 8 + x * 8 +
                                3] += filter_weight
Example #4
0
def get_company_invert_partner(company_code):
    if not company_code:
        logger.warning({"isSuccess": False, "msg": "缺少必要参数"})
        response = {"isSuccess": False, "msg": "缺少必要参数"}
        return response
    data = get_invert_partner(company_code)
    if data.get('isSuccess'):
        response = data.get('data')
        return response
Example #5
0
 def set_trump_card(self):
     self.__trump_card = self.deck.get_card
     if RANK_INDEX_NAME[self.__trump_card.rank] == 'ace':
         logger.warning(f'Ace for trump card: {self.trump_card.name}')
         self.deck.return_card_in_deck(self.trump_card)
         # todo: fix me
         self.__trump_card = self.deck.get_card
         logger.warning(f'New trump card: {self.trump_card.name}')
     logger.info(f'Set trump card: {self.trump_card.name}')
     self.deck.return_card(self.__trump_card)
Example #6
0
    def initialize(self):

        self.create_indexes()
        for champ in ChampionshipUtil.list_championships():
            try:
                ChampionshipRepository(self.session).insert(champ)
                logger.debug('Championship created: ' + str(champ))
            except DuplicateKeyError as e:
                logger.warning(e)
                pass

            ChampionshipManager.create_dir(champ)
            logger.debug('Championship DIR created: ' + str(champ))
Example #7
0
 def splat(self, sample, L):
     if L.has_nan():
         logger.warning("ImageFilm ignoring splatted spectrum with NaN values")
         return
     L_x, L_y, L_z = L.to_xyz()
     x = int(sample.image_x)
     y = int(sample.image_y)
     if (x < self.x_pixel_start) or (x - self.x_pixel_start >= self.x_pixel_count) or (y < self.y_pixel_start) or (y - self.y_pixel_start >= self.y_pixel_count):
         return
     y = y - self.y_pixel_start
     x = x - self.x_pixel_start
     self.pixels[y*self.x_pixel_count*8+8*x+4] = L_x
     self.pixels[y*self.x_pixel_count*8+8*x+5] = L_y
     self.pixels[y*self.x_pixel_count*8+8*x+6] = L_z
Example #8
0
 def check_win(self):
     for player in self.__players:
         if player.len_hand >= MAX_COUNT_CARD_IN_ARM:
             logger.warning(f'Max count card in hand, {player.name}!')
             if player.name == 'Bot':
                 self.winner = self.client_player.name
             else:
                 self.winner = 'Bot'
     if self.deck.get_len_deck > 0:
         return
     if not self.bot.hand:
         self.winner = self.bot.name
         return True
     elif not self.__client_player.hand:
         self.winner = self.__client_player.name
         return True
Example #9
0
    def process_results(self, season):

        matches = SeasonRepository(self.session).get_matches(season)
        for match in matches:
            try:

                match[MatchNotation.RESULTS] = dict()

                MatchBusiness.set_result_money_line(match)
                MatchBusiness.set_result_both_teams_to_score(match)

                fields_to_update = {MatchNotation.RESULTS: match[MatchNotation.RESULTS]}
                MatchRepository(self.session).update(match, fields_to_update)

            except Exception as e:
                logger.warning(e)
                pass
Example #10
0
    def add_sample(self, sample, L):
        """Add a sample to the film."""
        d_image_x = sample.image_x - 0.5
        d_image_y = sample.image_y - 0.5
        x0 = int(math.ceil(d_image_x - self.filter.x_width))
        x1 = int(d_image_x + self.filter.x_width)
        y0 = int(math.ceil(d_image_y - self.filter.y_width))
        y1 = int(d_image_y + self.filter.y_width)
        x0 = max(x0, self.x_pixel_start)
        x1 = min(x1, self.x_pixel_start + self.x_pixel_count - 1)
        y0 = max(y0, self.y_pixel_start)
        y1 = min(y1, self.y_pixel_start + self.y_pixel_count - 1)
        if ((x1-x0)<0) or ((y1-y0)<0):
            logger.warning("Sample outside the image extent. %d %d %d %d" % (x0, x1, y0, y1))
            return

        # loop over filter support and add sample to pixel arrays
        L_x, L_y, L_z = L.to_xyz()

        # precompute x and y filter table offsets
        ifx = []
        for x in xrange(x0, x1+1):
            fx = abs((x - d_image_x) * self.filter.inv_x_width * FILTER_TABLE_SIZE)
            ifx.append(min(int(fx), FILTER_TABLE_SIZE-1))
        ify = []
        for y in xrange(y0, y1+1):
            fy = abs((y - d_image_y) * self.filter.inv_y_width * FILTER_TABLE_SIZE)
            ify.append(min(int(fy), FILTER_TABLE_SIZE-1))
        sync_needed = (self.filter.x_width > 0.5) or (self.filter.y_width > 0.5)
        for y in xrange(y0, y1+1):
            for x in xrange(x0, x1+1):
                # evaluate filter value at (x,y) pixel
                offset = ify[y-y0]*FILTER_TABLE_SIZE + ifx[x-x0]
                filter_weight = self.filter_table[offset]
                # update pixel values with filtered sample contribution

                if not sync_needed:
                    self.pixels[y*self.x_pixel_count*8+x*8] += filter_weight * L_x
                    self.pixels[y*self.x_pixel_count*8+x*8+1] += filter_weight * L_y
                    self.pixels[y*self.x_pixel_count*8+x*8+2] += filter_weight * L_z
                    self.pixels[y*self.x_pixel_count*8+x*8+3] += filter_weight
                else:
                    self.pixels[y*self.x_pixel_count*8+x*8] += filter_weight * L_x
                    self.pixels[y*self.x_pixel_count*8+x*8+1] += filter_weight * L_y
                    self.pixels[y*self.x_pixel_count*8+x*8+2] += filter_weight * L_z
                    self.pixels[y*self.x_pixel_count*8+x*8+3] += filter_weight
Example #11
0
 def splat(self, sample, L):
     if L.has_nan():
         logger.warning(
             "ImageFilm ignoring splatted spectrum with NaN values")
         return
     L_x, L_y, L_z = L.to_xyz()
     x = int(sample.image_x)
     y = int(sample.image_y)
     if (x < self.x_pixel_start) or (
             x - self.x_pixel_start >= self.x_pixel_count) or (
                 y < self.y_pixel_start) or (y - self.y_pixel_start >=
                                             self.y_pixel_count):
         return
     y = y - self.y_pixel_start
     x = x - self.x_pixel_start
     self.pixels[y * self.x_pixel_count * 8 + 8 * x + 4] = L_x
     self.pixels[y * self.x_pixel_count * 8 + 8 * x + 5] = L_y
     self.pixels[y * self.x_pixel_count * 8 + 8 * x + 6] = L_z
Example #12
0
    def initialize(self, initial_year, final_year):
        """ Creates seasons """
        self.create_indexes()

        for champ in ChampionshipRepository(self.session).list():

            for year in range(initial_year, final_year):

                season = SeasonBusiness.create(champ,year)

                try:
                    SeasonRepository(self.session).insert(season)
                    logger.debug('Season created: ' + str(season))
                except DuplicateKeyError as e:
                    logger.warning(e)
                    pass

                SeasonManager.create_dir(season)
                logger.debug('Season DIR created: ' + str(season))
Example #13
0
 async def broadcaster(self) -> None:
     while True:
         logger.debug(f"Start mailer for chats: {self.ACTIVE_CHATS}")
         if not self.GAME_NEWS_SOURCE:
             logger.warning(
                 "Empty game sources, setup a game sources by adding @Mailer.add_news_source() decorator"
             )
         informers = [informer() for informer in self.GAME_NEWS_SOURCE]
         for sheduled_informer in asyncio.as_completed(informers):
             updates = await sheduled_informer
             for update in updates:
                 senders = [
                     self.send_safe_message(chat, update)
                     for chat in self.ACTIVE_CHATS
                 ]
                 await asyncio.gather(*senders)
         logger.debug(
             f"Mailer successfully ended for chats: {self.ACTIVE_CHATS}")
         await asyncio.sleep(self.update_frequency)
Example #14
0
    def __init__(self, x_res, y_res, filter, crop_window, filename,
                 open_window):
        """Default constructor for ImageFilm."""
        super(ImageFilm, self).__init__(x_res, y_res)
        self.filter = filter
        self.crop_window = list(crop_window)
        self.filename = filename

        # compute film image extent
        self.x_pixel_start = int(
            math.ceil(self.x_resolution * self.crop_window[0]))
        self.x_pixel_count = max(
            1,
            int(
                math.ceil(self.x_resolution * crop_window[1]) -
                self.x_pixel_start))
        self.y_pixel_start = int(
            math.ceil(self.y_resolution * self.crop_window[2]))
        self.y_pixel_count = max(
            1,
            int(
                math.ceil(self.y_resolution * crop_window[3]) -
                self.y_pixel_start))

        if self.x_pixel_count > self.x_resolution:
            logger.warning("ImageFilm.x_pixel_count is incorrect: %d" %
                           self.x_pixel_count)

        if self.y_pixel_count > self.y_resolution:
            logger.warning("ImageFilm.y_pixel_count is incorrect: %d" %
                           self.y_pixel_count)

        # allocate film image storage
        self.pixels = [0.0] * (self.x_pixel_count * self.y_pixel_count * 8)

        # precompute filter weight table
        self.filter_table = [0.0] * (FILTER_TABLE_SIZE * FILTER_TABLE_SIZE)
        for y in xrange(FILTER_TABLE_SIZE):
            fy = (float(y) +
                  0.5) * self.filter.y_width / float(FILTER_TABLE_SIZE)
            for x in xrange(FILTER_TABLE_SIZE):
                fx = (float(x) +
                      0.5) * self.filter.x_width / float(FILTER_TABLE_SIZE)
                self.filter_table[y * FILTER_TABLE_SIZE + x] = \
                                    self.filter.evaluate(fx, fy)

        # possibly open window for image display
        if open_window:  # or pbrt_options.open_window:
            logger.warning(
                "Support for opening image display window not available in this build."
            )
Example #15
0
def get_company_map():
    try:
        data = request.get_json()
        if not data:
            '''
            content-type:
            '''
            logger.warning({
                "isSuccess": False,
                "msg": "请使用 application/json 传递参数"
            })
            response = Response(json.dumps({
                "isSuccess": False,
                "msg": "请使用 application/json 传递参数"
            }),
                                mimetype='application/json')
            return response
    except BadRequest:
        logger.warning({"isSuccess": False, "msg": "JSON 格式错误"})
        response = Response(json.dumps({
            "isSuccess": False,
            "msg": "JSON 格式错误"
        }),
                            mimetype='application/json')
        return response

    if not data.get('company_name'):
        logger.warning({"isSuccess": False, "msg": "缺少必要参数"})
        response = Response(json.dumps({
            "isSuccess": False,
            "msg": "缺少必要参数"
        }),
                            mimetype='application/json')
        return response

    company_name = data.get('company_name')

    data = get_company_base_info(company_name)
    if data.get('isSuccess'):
        company_map = EnterpriseGenealogy()
        logger.info('正在构建 {} 企业族谱.'.format(company_name))
        genealogy = company_map.make_company_map(data)
        remove_company_code(genealogy)
        response = make_response(genealogy)
    else:
        response = make_response(data)

    logger.info(data)
    return response
Example #16
0
    def __init__(self, x_res, y_res, filter, crop_window, filename, open_window):
        """Default constructor for ImageFilm."""
        super(ImageFilm, self).__init__(x_res, y_res)
        self.filter = filter
        self.crop_window = list(crop_window)
        self.filename = filename

        # compute film image extent
        self.x_pixel_start = int(math.ceil(
            self.x_resolution * self.crop_window[0]))
        self.x_pixel_count = max(1, int(math.ceil(
            self.x_resolution * crop_window[1]) - self.x_pixel_start))
        self.y_pixel_start = int(math.ceil(
            self.y_resolution * self.crop_window[2]))
        self.y_pixel_count = max(1, int(math.ceil(
            self.y_resolution * crop_window[3]) - self.y_pixel_start))

        if self.x_pixel_count>self.x_resolution:
            logger.warning("ImageFilm.x_pixel_count is incorrect: %d" %
                           self.x_pixel_count)

        if self.y_pixel_count>self.y_resolution:
            logger.warning("ImageFilm.y_pixel_count is incorrect: %d" %
                           self.y_pixel_count)

        # allocate film image storage
        self.pixels = [0.0] * (self.x_pixel_count * self.y_pixel_count * 8)

        # precompute filter weight table
        self.filter_table = [0.0] * (FILTER_TABLE_SIZE * FILTER_TABLE_SIZE)
        for y in xrange(FILTER_TABLE_SIZE):
            fy = (float(y) + 0.5) * self.filter.y_width / float(FILTER_TABLE_SIZE)
            for x in xrange(FILTER_TABLE_SIZE):
                fx = (float(x) + 0.5) * self.filter.x_width / float(FILTER_TABLE_SIZE)
                self.filter_table[y * FILTER_TABLE_SIZE + x] = \
                                    self.filter.evaluate(fx, fy)

        # possibly open window for image display
        if open_window: # or pbrt_options.open_window:
            logger.warning("Support for opening image display window not available in this build.")
Example #17
0
def get_company_url(company_name):
    logger.info(
        'GET https://m.tianyancha.com/search?key={}'.format(company_name))
    logger.info('正在尝试获取代理...')
    proxy = get_proxy()
    if proxy.get('isSuccess'):
        logger.info('当前代理地址 {}'.format(proxy.get("data").get('http')))
        logger.info('正在使用代理搜索公司.')
        try:
            print(proxy.get('data'))
            response = requests.get(
                'https://m.tianyancha.com/search?key={}'.format(company_name),
                proxies=proxy.get("data"),
                headers=headers)
        except Exception as e:
            logger.warning(e)
            logger.info('天眼查异常,本次搜索无效.')
            return {'isSuccess': False, 'msg': '第三方服务异常,请稍后重试'}
        logger.info('移动站搜索已完成.')
        if '立即登录' in response.text or '登录/注册即表示同意' in response.text:
            logger.info('移动站需要登录,正在使用PC站搜索.')
            response = request.spider.get_normal_response(
                'https://www.tianyancha.com/search?key={}'.format(
                    company_name))
            if response.get('isSuccess'):
                text_html = response.get('data')
                HTML = etree.HTML(text_html)
                url = HTML.xpath(
                    "/html[1]/body[1]/div[2]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[3]/div[1]/a[1]/@href"
                )
                url2 = HTML.xpath(
                    "/html[1]/body[1]/div[2]/div[1]/div[1]/div[2]/div[3]/div[1]/div[1]/div[3]/div[1]/a[1]/@href"
                )
                if url:
                    logger.info('当前公司 URL {}'.format(url[0]))
                    return {
                        'isSuccess': True,
                        'msg': '获取企业URL成功',
                        "URL": url[0]
                    }
                elif url2:
                    logger.info('当前公司 URL {}'.format(url2[0]))
                    return {
                        'isSuccess': True,
                        'msg': '获取企业URL成功',
                        "URL": url2[0]
                    }
                else:
                    return {'isSuccess': False, 'msg': '未查到企业信息'}
            else:
                return {'isSuccess': False, 'msg': '内部错误,PC站搜索失败'}

        else:
            # print(response.text)
            html = etree.HTML(response.text)
            a_list = html.xpath("//div[@class='col-10 search-name']/a/@href")
            if a_list:
                return {
                    'isSuccess': True,
                    'msg': '获取企业URL成功',
                    "URL": mobile_url_2_computer_url(a_list[0])
                }
            else:
                return {'isSuccess': False, 'msg': '内部错误,企业URL获取失败'}
    else:
        return {"isSuccess": False, 'msg': "代理获取失败"}
Example #18
0
def get_company_map2():
    resp_type = 0
    if request.method == 'POST':
        try:
            data = request.get_json()
            if not data:
                logger.warning({
                    "isSuccess": False,
                    "msg": "请使用 application/json 传递参数"
                })
                response = Response(json.dumps({
                    "isSuccess":
                    False,
                    "msg":
                    "请使用 application/json 传递参数"
                }),
                                    mimetype='application/json')
                return response
        except BadRequest:
            logger.warning({"isSuccess": False, "msg": "JSON 格式错误"})
            response = Response(json.dumps({
                "isSuccess": False,
                "msg": "JSON 格式错误"
            }),
                                mimetype='application/json')
            return response

        if not data.get('company_name'):
            logger.warning({"isSuccess": False, "msg": "缺少必要参数"})
            response = Response(json.dumps({
                "isSuccess": False,
                "msg": "缺少必要参数"
            }),
                                mimetype='application/json')
            return response
        company_name = data.get('company_name')
        p2p_name = data.get('name')
    else:
        company_name = request.args.get('company_name')
        p2p_name = request.args.get('name')
        resp_type = request.args.get('type')
    data = get_company_base_info2(company_name)
    if data.get('isSuccess'):
        company_map = EnterpriseGenealogy()
        logger.info('正在构建 {} 企业族谱.'.format(company_name))
        genealogy = company_map.make_company_map2(data)
        logger.info(data)
    else:
        response = make_response(data)
        return response
    logger.info('企业族谱响应成功')
    # 请求携带参数,为1时响应最新的简化的csv
    if resp_type == '1':
        genealogy_new = []
        # 添加股东和对外投资
        for row in genealogy:
            c0 = '被查主体'
            c1 = '项目'
            c2 = '内容'
            genealogy_new.append({
                c0: company_name,
                c1: row['0'],
                c2: row['1']
            })
        # 添加主要人员
        for i in data['main_person']:
            genealogy_new.append({
                c0: company_name,
                c1: i['2'] + '(当前)',
                c2: i['1']
            })
        # 添加变更记录
        from setting import change_address, change_person, change_name
        names = []  # 存放所有变更中出现过的名字
        for i in data['change_record']:
            # 如果变更前变更后信息一致,直接continue掉
            if i['3'] == i['4']:
                continue
            if i['2'] in change_address:
                genealogy_new.append({
                    c0: company_name,
                    c1: '地址',
                    c2: i['4'].replace(' ', '')
                })
                genealogy_new.append({
                    c0: company_name,
                    c1: '地址变更',
                    c2: i['3'].replace(' ', '')
                })
            if i['2'] in change_name:
                genealogy_new.append({
                    c0: company_name,
                    c1: '名称变更',
                    c2: i['3'].replace(' ', '')
                })
            if i['2'] in change_person:
                result1 = clean(i['3'])
                if result1:
                    names = names + result1
                result2 = clean(i['4'])
                if result2:
                    names = names + result2
        print(names)
        names = set(names)
        if names:
            for name in names:
                if name != '':
                    genealogy_new.append({
                        c0: company_name,
                        c1: '历史角色',
                        c2: name
                    })
        return send_csv(genealogy_new, "{}.csv".format(company_name),
                        [c0, c1, c2])
    genealogy.append({'0': '', '1': '', '2': '', '3': ''})
    genealogy.insert(0, {
        '0': '层级',
        '1': '名称',
        '2': '股东类型',
        '3': '投资金额',
        '4': '投资占比',
        '5': '关联公司'
    })
    genealogy.insert(
        0, {
            '0': '平台名称:' + str(p2p_name),
            '1': "企业名称:" + data['company_name'],
            '2': '法人:' + data['contact'],
            '3': '电话:' + data['tel'],
            '4': '员工人数:' + data['staff_num'],
            '5': '注册时间:' + data['found_date']
        })
    genealogy.insert(
        1, {
            '0': '邮箱:' + data['mail'],
            '1': "企业类型:" + data['company_type'],
            '2': '统一信用代码:' + data['credit_code'],
            '3': '组织机构码:' + data['org_code'],
            '4': '地址:' + data['address'],
            '5': '状态:' + data['business_status']
        })
    genealogy.append({'0': '', '1': '', '2': '', '3': ''})
    genealogy.append({'0': '主要人员'})
    genealogy.append({'0': '序号', '1': '姓名', '2': '职位'})
    genealogy = genealogy + data['main_person']
    if data['change_record']:
        genealogy.append({'0': '', '1': '', '2': '', '3': ''})
        genealogy.append({'0': '变更记录'})
        genealogy.append({
            '0': '序号',
            '1': '变更日期',
            '2': '变更项目',
            '3': '变更前',
            '4': '变更后'
        })
        genealogy = genealogy + data['change_record']
    genealogy.append({'0': '分支机构'})
    for branch in data.get('branch'):
        genealogy.append({'0': branch})
    return send_csv(genealogy, "{}.csv".format(company_name),
                    ['0', '1', '2', '3', '4', '5'])