Example #1
0
 def command(self,command):
     """
     #执行命令模块
     """
     #print (command)
     stdin,stdout,stderr = self.s.exec_command(command)
     a = stderr.read().decode()
     if 'already exists' in a:
         ret = True
     else:
         ret = False
     if len(a) == 0 or ret:
         print (self.remote_host_address,':OK')
         out = stdout.read()
         try:
             print (out.decode())
         except UnicodeDecodeError:
             print (out.decode('gb2312'))
         msg = "[%s] exec command [%s] success" % (self.remote_host_address,command)
         logger.info(msg)
     else:
         print (self.remote_host_address,':')
         print (stderr.read().decode())
         logger.error(stderr.read().decode())
         print (a)
         print ('Somethings is Wrong,Please sure.')
     self.s.close()
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 login(uid):
    (session, login_uid) = wblogin(uid)
    if login_uid == uid:
        logger.info('uid [%s] login success!' % uid)
        return (session, True)
    else:
        logger.info('uid [%s] login failed!' % uid)
        return (session, False)
Example #4
0
 def first_bot_turn(self):
     logger.info(
         f'Bot move, his cards in hand: {self.__player_turn.cards_in_hand}')
     turn_card = self.bot_first_turn()
     self.add_card_in_game_deck(turn_card)
     self.__player_turn.remove_card(turn_card)
     self.__last_card = turn_card
     self.__player_turn.made_turn = True
Example #5
0
 def check_existance_optionals(self, name: str, value: str):
     logger.info("Checking the existance of ['%s']" % value)
     available = self.get_available(name)
     if value not in available:
         logger.error(
             "The {name} [{metric}] do not exist. The available one are [{metrics}]"
             .format(**locals()))
         return False
     return True
Example #6
0
def request_matches(replace=False):
    logger.info('request_matches() ')
    session = Database.get_session()

    seasons = SeasonController(session).list()
    args = [(s, replace) for s in seasons]

    pool = mp.Pool(mp.cpu_count())
    pool.map(_request_matches, args)
Example #7
0
def insert_metrics(conn: connection, metrics: List[dict]):
    if not metrics:
        return

    logger.info('Write messages ...')

    with conn.cursor() as cursor:
        extras.execute_batch(cursor, SQL_INSERT_METRICS, metrics)
        conn.commit()
Example #8
0
 def check_existance(self, name: str, value: str):
     logger.info("Checking the existance of ['%s']" % value)
     available = self.get_available(name)
     if value not in available:
         logger.error(
             "The {name} [{value}] do not exist. The available one are [{available}]"
             .format(**locals()))
         self.__del__()
         sys.exit(1)
Example #9
0
def request_seasons(replace=False):
    logger.info('request_seasons() ')
    session = Database.get_session()

    championships = ChampionshipController(session).list()

    args = [(c, replace) for c in championships]
    pool = mp.Pool(mp.cpu_count())
    pool.map(_request_season, args)
Example #10
0
def reset_database():

    logger.info('reset_database() ')

    session = Database.get_session()
    ChampionshipController(session).drop()
    SeasonController(session).drop()
    MatchController(session).drop()
    PerformanceController(session).drop()
Example #11
0
def _create_matches(season):

    logger.info('create_matches(): ' + str(season))
    session = Database.open_new_session()

    MatchController(session).create_matches(season)
    SeasonController(session).update_summary_fields(season)
    MatchController(session).process_results(season)
    MatchController(session).update_rounds(season)
Example #12
0
 def clear_game_deck(self):
     """
     Сбросить игровую колоду в отбой
     """
     for card in self.game_deck:
         self.__clear_cards.add(card)
     self.__game_deck = pygame.sprite.Group()
     self.check_cards_in_hands()
     logger.info('Drop game deck')
    def sendPacket(self, outPort, pkt):
        """Forward the packet to the its respective output 

        Args:
            outPort (int): the output port packet is being sent through
            pkt (Packet): the packet to be forwarded
        """
        logger.info(f"[Packet {pkt.pktId}] : Sent from Space Switch {self.spaceSwitchId}")
        outSwitch = self.network.stageThreeAWGRs[outPort]
        outSwitch.receive(self.spaceSwitchId, pkt)
Example #14
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 #15
0
def request_seasons(replace=False):

    logger.info('Service: request_seasons()')
    session = Database.get_session()

    champs = list(ChampionshipController(session).list())
    args = [(champs[idx], replace) for idx, item in enumerate(champs)]

    p = mp.Pool(mp.cpu_count())
    p.map(_requests_season, args)
Example #16
0
    def onPacketArrival(self, pkt):
        """Communicate with the controller and schedule the packet

        Args:
            pkt (Packet): the incoming packet
        """
        logger.info(
            f"[Packet {pkt.pktId}] : Arrived at Transmitter {self.transmitterId}"
        )
        self.network.controller.enqueue_scheduler(pkt)
Example #17
0
def request_matches(replace=False):

    logger.info('Service: request_matches()')
    session = Database.get_session()

    seasons = list(SeasonController(session).list())
    args = [(seasons[i], replace) for i, item_a in enumerate(seasons)]

    p = mp.Pool(mp.cpu_count())
    p.map(_request_matches, args)
Example #18
0
def create_odds(replace=False):
    logger.info('Service: extract_odds()')

    session = Database.SESSION
    seasons = list(SeasonController(session).list())

    if replace:
        OddsController(session).reset()

    p = mp.Pool(mp.cpu_count())
    p.map(_create_odds, seasons)
Example #19
0
 def check_cards_in_hands(self):
     """
     Добавляем карты в руку если их меньше константы.
     :return:
     """
     for player in self.__players:
         if player.len_hand < COUNT_START_CARD:
             logger.info(
                 f'Player: {player.name} have {player.len_hand} in hand')
             for i in range(COUNT_START_CARD - player.len_hand):
                 player.add_cart(self.deck.get_card)
Example #20
0
def downloadAndForwardAttachable(bill_dict, bill_in_qb):
    attachableName = bill_dict.get('BILL PDF') if len(bill_dict.get(
        'BILL PDF')) else bill_in_qb.get('Bill').get('DocNumber') + ".pdf"
    downloadFileFromLink(attachableName, bill_dict.get('BILL PDF LINK'))
    s3AttachableName = "bill_attachments/" + attachableName
    s3_link = upload_file(s3AttachableName, file_root_path + attachableName,
                          True)
    attachNoteToEntity(s3_link, bill_in_qb.get('Bill').get('Id'), 'Bill')
    deleteAttachemnt(attachableName)
    logger.info(
        'downloadAndForwardAttachable | pushed to s3 | bill: {0}'.format(
            bill_dict))
Example #21
0
def create_matches(replace=False):
    logger.info('create_matches() ')
    session = Database.get_session()
    MatchController(session).initialize()

    if replace:
        MatchController(session).drop()

    seasons = SeasonController(session).list()

    pool = mp.Pool(mp.cpu_count())
    pool.map(_create_matches, seasons)
    def receive(self, inPort, pkt):
        """Receive scheduled packets from the Stage One AWGRs and pass them to 
        Stage Three AWGRs

        Args:
            inPort (int): the port on which packet is being received
            pkt (Packet): the packet to be received
        """
        logger.info(f"[Packet {pkt.pktId}] : Reached Space Switch {self.spaceSwitchId}")
        slotData = self.getSlotData(pkt.dispatchSlot)
        outPort = slotData.finalState[inPort]
        self.sendPacket(outPort, pkt)
Example #23
0
def create_matches(replace=False):

    logger.info('Service: create_matches()')
    session = Database.SESSION

    if replace:
        MatchController(session).drop()

    MatchController(session).initialize()
    seasons = list(SeasonController(session).list())

    p = mp.Pool(mp.cpu_count())
    p.map(_create_matches, seasons)
Example #24
0
def qbwebhook(request):
    if request.method == 'POST':
        try:
            body_unicode = request.body.decode('utf-8')
            signature = request.headers.get('Intuit-Signature')
            verifier_token = settings.QBO_WEBHOOK_VERIFIER
            logger.info("QB webhook received: {0}, {1}".format(
                body_unicode, signature))
            process_qb_webhook.delay(signature, body_unicode, verifier_token)
            return HttpResponse(
                "Hello, world. You're at the quickbooks webhook.")
        except Exception as e:
            print('qbwebhook error')  # TODO:get stacktrace log
            return HttpResponseBadRequest(e)
Example #25
0
 def get(self,rpath,lpath):
     """
     #下载文件目录,调用get_dirs
     """
     self.get_dirs(rpath,lpath)
     print (self.remote_host_address)
     error_num = self.error_count(-1)
     msg_ok = 'Get Total files number: %s' % self.sucess_count(-1)
     msg_error = 'Get Error files number: %s' % error_num
     logger.info('%s %s %s' % (self.remote_host_address,rpath,msg_ok))
     if error_num > 0:
         logger.error('%s %s %s' % (self.remote_host_address,rpath,msg_error))
     print (msg_ok)
     print (msg_error)
Example #26
0
def predict_time_left(x : np.ndarray, y : np.ndarray, name : str, mode : str = "BAYESIAN") -> int:
    functions = {
        "OLS":OLS,
        "RANSAC":RANSAC,
        "BAYESIAN":BAYESIAN
    }

    # Reshape the array as a single feature array for the predictors
    x = x.reshape(-1, 1)

    if mode in functions.keys():
        logger.info("Predicting using the mode [%s]"%mode)
        with Timer("The prediction took {time}s"):
            m, q, p =  functions[mode](x, y)
            logger.info("The coefficents predicted are m [{m}] q[{q}]".format(**locals()))
        if m <= 0:
            logger.info("The predicted line is not growing so it will never reach the max")
            return "inf", p
        time_predicted = (1 - q)/m
        delta = time_predicted - x[-1]
        if delta > MAX_TIME:
            logger.info(f"The predicted time [{delta}] is over [{MAX_TIME}] so it's casted to [inf]")
            return "inf", p
        return delta[0], p
    logger.error("Mode [%s] not found, the available ones are %s"%(mode, functions.keys()))
    return None, 0
Example #27
0
def deleteBillFromQB(tv_bill_id):
    bill = BillExpenseReference().getBillExpenseReferanceByTvId(
        bill_id=tv_bill_id)
    if not bill:
        logger.error(
            "deleteBillFromQB: No bill found for {0}".format(tv_bill_id))
        return

    deleteBillInQB(bill.qb_id)

    bill.delete()
    bill.save()

    logger.info('deleted bill from qb: {0}'.format(bill.qb_id))
Example #28
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 #29
0
    def onSchedule(self, pkt):
        """Recieve scheduled packets from the Controller and do further 
        processing

        Args:
            pkt (Packet): the incoming packet
        """
        logger.info(
            f"[Packet {pkt.pktId}] : Scheduled for dispatch from Transmitter {self.transmitterId}"
        )
        if pkt.dispatchSlot in self.transmissions.keys():
            self.transmissions[pkt.dispatchSlot] += 1
        else:
            self.transmissions[pkt.dispatchSlot] = 1
        self.sendPacket(pkt)
Example #30
0
def tvwebhook(request):
    if request.method == 'GET':
        try:
            table_id = request.GET.get('tableId')
            view_id = request.GET.get('viewId')
            record_id = request.GET.get('recordId')
            event_type = request.GET.get('eventType')
            logger.info("TV webhook received: {0}, {1}, {2}, {3}".format(
                table_id, view_id, record_id, event_type))
            process_tv_webhook.delay(table_id, view_id, record_id, event_type)
            return HttpResponse(
                "Hello, world. You're at the trackvia integrations.")
        except Exception as e:
            print('tvwebhook error')  # TODO:get stacktrace
            return HttpResponseBadRequest(e)
Example #31
0
def set_theme(theme):
    ''' Set theme '''
    global color_light_ground, color_light_wall, \
        color_dark_wall, color_dark_ground, \
        color_wall_highlight, color_ground_highlight, \
        color_accent

    # Setting colors to the absence of colors is kind of hard. Let's not do that.
    if theme is not None:
        logger.info('Theme set: ' + theme)

        # Set all the colors here
        # Yes, I know. It goes over the proper line wrapping length.
        # The other way is 10x less readable, so I am not wrapping it.
        try:
            color_light_ground     = get_color(color_data[theme]['ground']['light'])
            color_dark_ground      = get_color(color_data[theme]['ground']['dark'])
            color_light_wall       = get_color(color_data[theme]['wall']['light'])
            color_dark_wall        = get_color(color_data[theme]['wall']['dark'])
            color_wall_highlight   = get_color(color_data[theme]['highlight']['wall'])
            color_ground_highlight = get_color(color_data[theme]['highlight']['ground'])
            color_accent           = get_color(color_data[theme]['accent']['light'])
        except KeyError as e:
            logger.severe("KeyError({0}): {1}".format(e.errno, e.strerror))
            default_colors()
            logger.write('----- STACK TRACE: -----')
            logger.write(traceback.extract_stack())
            logger.write('------------------------')

        # Simple assertion testing to make sure all the colors loaded properly
        try:
            assert color_light_ground     is not None
            assert color_dark_ground      is not None
            assert color_light_wall       is not None
            assert color_dark_wall        is not None
            assert color_wall_highlight   is not None
            assert color_ground_highlight is not None
            assert color_accent           is not None
        except AssertionError as e:
            logger.severe("AssertionError ({0}): {1}".format(e.errno, e.strerror))
            default_colors()
            logger.write('----- STACK TRACE: -----')
            logger.write(traceback.extract_stack())
            logger.write('------------------------')
    else:
        logger.warn('No theme passed to set_theme()!')
        logger.info('Defaulting theme...')
        default_colors()
Example #32
0
    def event_trigger(self, ev):
        """ Response function to handle special trigger events. Initiates the proper
        response depending on the event.

        Args:
            ev(Event): the special trigger event
        """
        if ev.category == "timeslot-end":
            logger.info(f"[Timeslot {ev.slot_no}] : Timeslot ENDING....")
            self.fault_tracking(self.current_slot)
            self.allotSlots(ev.slot_no)
            logger.info(
                f"[Timeslot {ev.slot_no}] : Timeslot ENDED, Next Timeslot STARTING..."
            )
        elif ev.category == "eventset-end":
            self.clearQueue(self.current_slot)
Example #33
0
 def get_available(self, name: str):
     """For a field it returns all the distinct values once the filter is applied
      to the previous fields in order of insertion in the dictionary"""
     # If it's measuremnets it's a special case because it's a different kind of query
     if name == "measurement":
         return self.get_measurements()
     # Selectors must be valid and they have an order
     elif name in self.query["selectors"].keys():
         index = list(self.query["selectors"].keys()).index(name)
         selectors_before_name = dict(
             list(self.query["selectors"].items())[:index])
         return self.get_distinct_values(name, selectors_before_name)
     # Optionals do not have an order and only need the selectors on the WHERE
     elif name in self.query["optionals"].keys():
         return self.get_distinct_values(name, self.query["selectors"])
     else:
         logger.info("%s not found" % name)
Example #34
0
def default_colors():
    ''' Sets the values used in the main file to hard-coded defaults
    Should be used as a fallback in case something goes wrong and we cannot
    load the colors from our theme file
    '''
    global color_light_ground, color_light_wall, \
        color_dark_wall, color_dark_ground, \
        color_wall_highlight, color_ground_highlight, \
        color_accent

    logger.info('Setting to default color scheme...')

    color_light_ground     = libtcod.Color(110, 109, 91)
    color_light_wall       = libtcod.Color(128, 127, 98)
    color_dark_wall        = libtcod.Color(51, 51, 51)
    color_dark_ground      = libtcod.Color(33, 33, 33)
    color_wall_highlight   = libtcod.Color(130, 110, 50)
    color_ground_highlight = libtcod.Color(200, 180, 50)
    color_accent           = libtcod.Color(255, 255, 255)
Example #35
0
def hex_to_color(inp):
    ''' Converts a hex string into a libtcod Color object '''
    # Format the string for use
    fhex = inp.replace('#', '').strip()

    try:
        # Get string slices for each hex bit and convert them to numbers
        # NOTE: String slices are in base 16
        red_bit   = int(fhex[0:2], 16)
        green_bit = int(fhex[2:4], 16)
        blue_bit  = int(fhex[4:6], 16)

        logger.info('Color: (' + str(red_bit) + ', ' + str(green_bit) + ', ' + \
            str(blue_bit) + ')')

        return libtcod.Color(red_bit, green_bit, blue_bit);

    # If the color sting is mal-formatted
    except ValueError as e:
        logger.error('Problem converting hex to color! Is it `rrggbb` formatted?')
        return None
Example #36
0
 def put(self,lpath,rpath=None):
     if not rpath:
         print ('Please input remote file or dir')
     else:
         if os.path.isfile(lpath):
             self.put_file(lpath,rpath)
         else:
             if re.match(r'd',str(self.sftp.stat(rpath))):
                 for l,r in self.put_dir(lpath, rpath):
                     self.put_file(l,r)
             else:
                 print ('Remote path must be a dirname')
             self.s.close()
     print (self.remote_host_address)
     error_num = self.error_count(-1)
     msg_ok = 'Put Total files number: %s' % self.sucess_count(-1)
     msg_error = 'Put Error files number: %s' % error_num
     logger.info('%s %s %s' % (self.remote_host_address,rpath,msg_ok))
     if error_num > 0:
         logger.error('%s %s %s' % (self.remote_host_address,rpath,msg_error))
     print (msg_ok)
     print (msg_error)