Exemplo n.º 1
0
 def onMsgGameModified(self, payload):
     if not "modified" in payload:  #only process modifications of game object, not of its children
         log.debug("*******",
                   self.playerName,
                   function=self.onMsgGameModified,
                   args=payload)
         self.refresh()
Exemplo n.º 2
0
def tcp_rloop(sock, addr):
    log.debug("%r connected", addr)
    protocol = TCPProtocol(sock, addr)
    timeout = TimeoutMixin(settings.MAIN_TIMEOUT)
    timeout.start_timeout()
    def loop():
        _buf = ""
        while True:
            try:
                _buf = sock.recv(4)
                if not _buf:
                    continue
                len_, = struct.unpack(">I", _buf[:4])
                _buf = _buf[4:]
                while True:
                    _buf += sock.recv(512)
                    if len(_buf) >= len_:
                        break
                ctx = _buf[:len_]
                _buf = _buf[len_:]
                timeout.reset_timeout()
                protocol.data_received(ctx)
            except Timeout:
                log.warning("%r disconnect timeout", addr)
                sock.close()
                break
#             except Exception as e:
#                 log.error("%r disconnect error:%s", *(addr, repr(e)))
#                 sock.close()
#                 break
    loop()
Exemplo n.º 3
0
 def onTileRelease(self, pos, tileWidget):
     log.debug(function=self.onTileRelease, args=(pos, tileWidget.tile))
     tile = tileWidget.tile
     if tile.plate == self.player.getPlate():
         tileWidget.accept(self)
     else:
         tileWidget.reject()
Exemplo n.º 4
0
def path(searchString,cacheItems=[],cache=False):
    """
    a full file path to test for exists 
    """
    hits=False   
    if PLATFORM!='win':
        #no registy 
        hits=False
    
    else:
        if '\\' in searchString and searchString.split('\\')[0] in validHIVES:
            rootKey=searchString.split('\\')[0]
            subKey=searchString.split(rootKey)[1]
            rootKey=eval(rootKey)
            if type(rootKey)!= regobj.Key:
                debug("rootKey eval didn't result in a regobj.Key. Terminating check.")
                return hits
            
            if type(rootKey(subKey)) is regobj.Key:
                hits=True
                if cache:
                    cacheItems.append(searchString)
                       
        else: 
            debug("invalid registry key. Terminating check")
    return hits
Exemplo n.º 5
0
def verifyredditcodeposted(request):
    code = request.POST['code']
    sig = request.POST['sig']
    if code != tornado_cookies.validate_cookie('code', sig):
        log.error("verifyredditcodeposted signature failed with (code, sig)", code, sig)
        raise ValueError('Invalid signature')
    content = get_reddit_content()
    comments = content[1]['data']['children']
    comments_with_code = []
    for c in comments:
        try:
            if code in c['data']['body']:
                comments_with_code.append(c)
        except KeyError:
            log.debug("verifyredditcodeposted could not parse comment", c)
            continue
    if not comments_with_code:
        log.debug("verifyredditcodeposted found no comment with code", code)
        return dict(success=False)
    comments_with_code.sort(key=lambda x:x['data']['created_utc'])
    original_comment = comments_with_code[0]
    username = original_comment['data']['author']
    return dict(success=True, 
                username=username,
                usersig=tornado_cookies.generate_secure_cookie('username', username))
Exemplo n.º 6
0
	def __init__(self,variables):
		vv = {}
		for k,v in variables.items():
			vv[k] = v.getName()
		log.debug("phasestate", 6, variables=vv)
		object.__setattr__(self, "__variables", vv)
		object.__setattr__(self, "__dict", {})
Exemplo n.º 7
0
    def _init(self, etree, control, parent=None):
        self.etree = etree  # Element tree to parse
        self.control = control  # Control class (for callback connect)
        self.parent = parent  # Parent widget

        self.id = None  # ID of this widget (if specified)
        self.data = utils.Bunch()  # Metadata to append to object
        self.actions = []  # List of actions
        self.manifest = utils.Bunch()  # Dict of element ids
        self.bgimage = None  # Background image
        self.bgpos = (0, 0)  # Background position 'x,y' or 'center,top' etc..
        self.bgsize = 'fit'  # Background size 'x,y' or 'fit'
        self.bgfade = 0  # Fade bgimage when changed (0 to disable)
        self.bgopacity = 1.0  # Current bgopacity (used during transition)
        self.click_enabled = False  # Set True when click event enabled
        self.dblclick_enabled = False  # Set True when dblclick event enabled
        self.installEventFilter(self)  # Capture events for interactions
        self._init_attributes()  # Process all attributes (and actions)
        self.children = self._append_children()  # Build all Children

        # if init is too fast, widgets are not visible
        time.sleep(0.0001)
        if parent is not None:
            try:
                # log.debug("Init %s in %s", etree, parent.objectName())
                parent.layout().addWidget(self)
            except AttributeError as err:
                log.debug("Something terrible happened. %s", err)
            except Exception as ex:
                log.debug("Something terrible happened. %s", ex)
Exemplo n.º 8
0
def fit_model(io: IO, model: Sequential, preprocessed: List[Preprocessed]):
    epochs = io.get("epochs")
    model.reset_states()

    logline("splitting into training set and testing set ({}%)".format(
        io.get("split")))
    split = gen_split(preprocessed, io)

    log_dir = "logs/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    for i in range(epochs):
        logline("generating input and expected data for epoch {}/{}".format(
            i + 1, epochs))
        train_x, train_y = trim_params(gen_fit_params(split), io)

        logline("training epoch {}/{}".format(i + 1, epochs))
        callbacks = []
        if io.get("profile"):
            debug("profiling")
            callbacks.append(
                tf.keras.callbacks.TensorBoard(log_dir=log_dir,
                                               histogram_freq=1))

        model.fit(train_x,
                  train_y,
                  batch_size=io.get("batch_size"),
                  epochs=1,
                  shuffle=False,
                  callbacks=callbacks)
        model.reset_states()
Exemplo n.º 9
0
    def pushMessage(self, good, owner_income_show, uploader_income_show):
        '''
        author:arther
        '''
        log.debug('good:%s', good)

        def callback(response):
            log.info('Push:%s', response.body)
            self.finish()

        pushUrl = BaseConfig.pushUrl
        face = ClassHelper('Face').get(good['goods'])
        if face:
            if self.user['_id'] != face['assign']['user']:
                ##ownedBought 购买了我主页的照片 排除掉照片主人购买自身主页照片的情况
                ownedBoughtPushData = {
                    'userid': face['assign']['user'],
                    'action': 'ownedBought',
                    'otherid': self.user['_id'],
                    'extra': owner_income_show
                }
                client = tornado.httpclient.AsyncHTTPClient()
                client.fetch(pushUrl, callback=callback, method="POST", body=json.dumps(ownedBoughtPushData),
                             headers={'X-MeCloud-Debug': '1'})
            ##assignedBought 购买了我共享的照片
            assignedBoughtPushData = {
                'userid': face['assign']['assigner'],
                'action': 'assignedBought',
                'otherid': self.user['_id'],
                'extra': uploader_income_show
            }
            client = tornado.httpclient.AsyncHTTPClient()
            client.fetch(pushUrl, callback=callback, method="POST", body=json.dumps(assignedBoughtPushData),
                         headers={'X-MeCloud-Debug': '1'})
Exemplo n.º 10
0
 def get_all_orders_from_server(self):
     # assertion: the orders arrive in the right order (guaranteed by the server)
     s = self.main_server.read_line()
     if s is not None:
         debug("main server data for %s: %s", self.login, s)
         args = s.split()
         if args[0] == "all_orders":
             self.orders_digest.update(s) # used by the synchronization debugger
             players_orders = args[1:]
             for player_orders in players_orders:
                 player, orders = player_orders.split("/")
                 orders = orders.replace(NEWLINE_REPLACEMENT, "\n").replace(SPACE_REPLACEMENT, " ")
                 for order in orders.strip().split("\n"): # strip() to remove empty order at the end of the list
                     direct_player = self.get_client_by_login(player).player
                     if direct_player:
                         debug("player: %s  order: %s", player, order)
                         self.queue_command(direct_player, order)
                     if order != "update" and not order.startswith("control"):
                         self._all_orders += order.replace("order 0 0 ", "") + ";"
                         self._all_orders = self._all_orders[-100:]
         elif args[0] == "synchronization_error":
             try:
                 send_error_to_metaserver(self.get_sync_debug_msg_1())
                 send_error_to_metaserver(self.get_sync_debug_msg_2())
             except:
                 exception("error sending sync debug data")
         else:
             warning("ignored data from server: %s", s)
Exemplo n.º 11
0
 def onMsgBoardModified(self, payload):
     if not "modified" in payload:  #only process modifications of board object, not of its children
         log.debug("*******",
                   function=self.onMsgBoardModified,
                   args=payload)
         self.rebuild()
         self.Refresh()
Exemplo n.º 12
0
 def pick(self):
     player = self.getCurrentPlayer()
     log.debug(function=self.pick, args=(self.getFullId(), player.getName()))
     if player:
         self.getPile().pickTile(player)
         self.board.cleanUp(False)
         self.nextTurn()
Exemplo n.º 13
0
 def addPlayer(self):
     log.debug(function=self.addPlayer, args=(self.getFullId(), len(self._players), self.__maxPlayers))
     if len(self._players) < self.__maxPlayers:
         player = Player(self)
         self._players.append(player)
         self.setModified()
         return player
Exemplo n.º 14
0
 def createTransaction(self, password, destList):
     """Create a new transaction and send it to the RelayNode
        destList is a list of tuples
        Each tuples is like : (str_address, value)
        The last transaction is the rest of the wallet send to the new user address
     """
     self.checkUpdate()
     newAddr = Address()
     newAddr.encryptPrivateKey(password)
     total = sum([i[1] for i in destList])
     if total <= self.count:
         destList.append((str(newAddr), (self.count - total)))
         transac = Transaction(self.addr.public(), destList)
         self.addr.decryptPrivateKey(password)
         transac.sign(self.addr)
         debug('valid: ' + ('True' if transac.is_signed() else 'False'))
         self.addr.encryptPrivateKey(password)
         if not self.relay.submit_transaction(transac):
             return False
         self.addrList.append(newAddr)
         self.addr = newAddr
         add_address(self.user_ID, self.addr, len(self.addrList) - 1)
         return True
     else:
         return False
Exemplo n.º 15
0
    def url(self, step, data, spec):
        log = getLogger('%s.url.%i' % (self.test_name, step))
        log.debug("Param data: " + data)
        log.debug("Param spec: " + spec)

        self.driver.get('https://gmail.com')
        Elements
Exemplo n.º 16
0
 def onMsgGameUpdated(self, payload):
     cg = self.getCurrentGame()
     cpName = cg.getCurrentPlayer().getName()
     gameId = cg.getId()
     log.debug(function=self.onMsgGameUpdated, args=(gameId, payload["id"], cpName, cg.getMoves(), payload["moves"]))
     if gameId != payload["id"] and cg.getGameNr() == payload["gamenr"]:
         self.loadGame(payload["game"])
Exemplo n.º 17
0
    def add_block(self, block):
        # check last hash
        if self.get_last_hash() != block.previous_hash:
            warning('last hash not matching')
            return False

        # check transactions validity
        if not block.is_valid(self):
            warning('block not valid')
            return False

        debug('accepted block')
        # add block, save THEN change last hash
        self.db.add_json_block(self.get_last_hash(), block.toJson())
        self.db.set_last_hash(block.get_hash())

        # reward sender
        self.update_addresses_amount([(block.miner_address, Blockchain.REWARD)
                                      ])

        # transactions are already checked within block
        for t in block.transactions:
            sender = t.senderAddress()
            self.db.set_address_spent(sender, True)
            self.update_addresses_amount(t.receivers)
        return True
def _check_solution(A, b, z):
    for z_l in z:
        assert z_l == z[0]
    log.debug("OK: All final vectors are equal!")
    for i in range(len(b)):
        assert b[i] == dot_product(A[i], z[0])
    log.debug("OK: final vector(s) are a solution of the system Ax=b!")
Exemplo n.º 19
0
 def _confirm_choice(self):
     if self._choice_exists() and self.choices[self.choice_index]:
         voice.confirmation(self.choices[self.choice_index][0][:1]) # repeat only the first part of the choice (not the help)
         self.choice_done = True
     else:
         debug("couldn't confirm choice (choices=%s, choice_index=%s)",
               self.choices, self.choice_index)
Exemplo n.º 20
0
def parse_messages(messages):
    debug("Parsing messages.")
    data = []
    for message in messages:
        # Ignore message if needed information is missing
        try:
            time = search(TIME_REGEXP, message).group()
            event = search(EVENT_REGEXP, message).group()
        except AttributeError:
            continue

        # Unix epoch
        dt = datetime.strptime(time, "%d/%m/%Y %H:%M")
        epoch_start = datetime(1970, 1, 1)
        epoch = int((dt - epoch_start) / timedelta(seconds=1))

        # Remove [] from [EVENT-lab_id-user_id] and split them to register
        args = event[1:-1].split("-")

        # Allow static events (no user_id or lab_id) e.g. opening the door
        _dict = {"epoch": epoch, "event": args[0]}
        n_args = len(args)
        if n_args > 1:
            _dict["user_id"] = args[1]
        if n_args == 3:
            _dict["lab_id"] = args[2]

        data += [_dict]

    debug("Messages parsed.")
    return data
Exemplo n.º 21
0
 def take_order(self,
                o,
                forget_previous=True,
                imperative=False,
                order_id=None):
     # an imperative "go" order on a unit is an "attack" order
     # note: this could be done by the user interface
     if imperative and o[0] == "go":
         target = self.player.get_object_by_id(o[1])
         if getattr(target, "player", None) is not None:
             o[0] = "attack"
     if self.is_inside:
         self.place.notify("order_impossible")
         return
     cls = ORDERS_DICT.get(o[0])
     if cls is None:
         warning("unknown order: %s", o)
         return
     if not cls.is_allowed(self, *o[1:]):
         self.notify("order_impossible")
         debug("wrong order to %s: %s", self.type_name, o)
         return
     if forget_previous and not cls.never_forget_previous:
         self.cancel_all_orders()
     order = cls(self, o[1:])
     order.id = order_id
     if imperative:
         order.is_imperative = imperative
     order.immediate_action()
Exemplo n.º 22
0
 def clone(self):
     log.debug(function=self.clone, args=self.getFullId())
     clonedGame = Game()
     data = self.serialize()
     clonedGame.deserialize(data)
     #log.debug("\n\noriginal = " + str(data) + "\n\nclone = " + str(clonedGame.serialize()))
     return clonedGame
Exemplo n.º 23
0
def calculate_total(stats_log):
    """Based on the logged stats calculate monthly totals."""
    buckets = []
    first_received = None
    first_sent = None
    for entry in stats_log:
        current_received = entry[1]
        current_sent = entry[2]

        # handle first entry for a new bucket
        if not first_received:
            first_received = current_received
            received = current_received
        if not first_sent:
            first_sent = current_sent
            sent = current_sent

        # handle integer overflows/restarts
        if current_received < received:
            buckets.append(received - first_received)
            first_received = current_received
        if current_sent < sent:
            buckets.append(sent - first_sent)
            first_sent = current_sent

        # store current values to last
        received = current_received
        sent = current_sent

    buckets.append(received - first_received)
    buckets.append(sent - first_sent)
    total = sum(buckets)
    debug('buckets:', buckets, 'total:', total)
    return total
Exemplo n.º 24
0
 def getPlayerByName(self, name):
     log.debug(function=self.getPlayerByName, args=(self.getFullId(), name, len(self._players)))
     player = None
     for p in self._players:
         if p.getName() == name:
             player = p
             break
     return player
Exemplo n.º 25
0
 def validateSets(self):
     invalid = 0
     for s in self.__sets:
         if not s.isEmpty():
             if not s.isValid():
                 invalid += 1
     log.debug(function = self.validateSets, returns=invalid)
     return invalid
Exemplo n.º 26
0
 def setTiles(self, tiles):
     log.debug(function=self.setTiles, args=(self.getFullId(), tiles))
     if tiles:
         for tId in tiles:
             if not tId in self.__tiles:
                 tile = Tile.getById(tId)
                 if tile.getContainer() != self:
                     tile.move(self)
Exemplo n.º 27
0
 def addChild(self, childObject):
     log.debug(function=self.addChild, args=childObject.getFullId())
     assert isinstance(childObject, ModelObject)
     self.__children__[childObject.getId()] = childObject
     assert self.isValidChild(childObject) == True
     self.dispatch("msg_new_child", {"object": self, "child": childObject})
     childObject.subscribe(self, "msg_object_modified", self.onMsgChildObjectModified)
     self.setModified()
Exemplo n.º 28
0
 def _get_weak_user_id(self):
     # truncated hash of various parameters
     # used to approximate the number of users, not more
     thing_to_hash = self._get_volume_serial_number()
     user_id = "%s" % abs(hash(thing_to_hash))
     user_id = user_id[:4]  # collisions are probable
     debug("user id = %s" % user_id)
     return user_id
Exemplo n.º 29
0
 def destroyDragPanel(self):
     """
     Destroys the temporary drag panel if it is active.
     """
     log.debug(function=self.destroyDragPanel, args=self.GetName())
     if self.__dragPlane__:
         self.__dragPlane__.Destroy()
         del self.__dragPlane__
Exemplo n.º 30
0
 def _get_weak_user_id(self):
     # truncated hash of various parameters
     # used to approximate the number of users, not more
     thing_to_hash = self._get_volume_serial_number()
     user_id = "%s" % abs(hash(thing_to_hash))
     user_id = user_id[:4] # collisions are probable
     debug("user id = %s" % user_id)
     return user_id
Exemplo n.º 31
0
 def _create_with_crossover(self, genome_a, genome_b):
     self.data = copy.deepcopy(genome_a.data)
     genome_size = len(genome_a.data) if len(genome_a.data) < len(genome_b.data) else len(genome_b.data)
     crossover_object_count = int(math.ceil(genome_size * config.config['ga']['crossoverObjectCountMultiplier']))
     log.debug('%s crossover: objects=%d' % (self.serial, crossover_object_count))
     if crossover_object_count < genome_size:
         for i in random.sample(xrange(0, genome_size), crossover_object_count):
             self.data[i] = copy.deepcopy(genome_b.data[i])
Exemplo n.º 32
0
 def queue_command(self, player, s):
     if player not in self.player.world.players:
         debug("didn't send the order for player %s: %s", player, s)
         return
     if self.game_session.record_replay:
         player_index = self.player.world.players.index(player)
         self.game_session.replay_write(str(player_index) + " " + s)
     self.player.world.queue_command(player, s)
Exemplo n.º 33
0
	def __setattr__(self,name,value):
		log.debug("phasestate", 6, name=name,value=value)
		thevars = object.__getattribute__(self,"__variables")
		log.debug("phasestate",7, thevars=thevars)
		if not name in thevars.values():
			raise KeyError("%s not a variable for this phase")
		thedict = object.__getattribute__(self,"__dict")
		thedict[name] = value
Exemplo n.º 34
0
 def handle_BROADCAST(self, data):
     """广播消息
     - 如果消息含有媒体文件,同上,下同
     """
     message = data["message"]
     log.debug("broadcast:%s", message)
     for cli in id2cli.values():
         cli.send(message)
Exemplo n.º 35
0
 def loadGame(self, data):
     log.trace(function=self.loadGame)
     log.debug(function=self.loadGame, args=data)
     if self.currentGame:
         del self.currentGame
     self.currentGame = Game()
     self.currentGame.deserialize(data)
     self.rememberState(data)
     self.dispatch("msg_game_loaded", {"game": self.currentGame})
Exemplo n.º 36
0
 def onMsgPlayerModified(self, payload):
     #        if not "modified" in payload: #only process modifications of player object, not of its children
     if True:
         log.debug(function=self.onMsgPlayerModified, args=payload)
         player = payload["object"]
         if player:
             assert isinstance(player, model.Player)
             if self.getGame().getCurrentPlayer() == player:
                 self.refresh()
Exemplo n.º 37
0
 def reject(self, restore=False):
     """
     This method is called by a drop target when it does not accept this instance when it is dropped.
     Parameters: 
     - restore: indicates whether this instance should be moved back to the position it was dragged from (default is False)
     """
     log.debug(function=self.reject, args=self.GetName())
     if restore:
         self.restorePositionBeforeDrag()
Exemplo n.º 38
0
	def __getattribute__(self,name):
		thedict = object.__getattribute__(self,"__dict")
		if not thedict.has_key(name):
			raise KeyError("%s not a variable for this phase"%name)
		r = thedict[name]
		if r is None:
			r = 0
		log.debug("phasestate", 6, name=name, value=r)
		return r
Exemplo n.º 39
0
    def calculate(self, genome):
        with Timer('render time %f'):
            self.renderer.render_to_file(genome)

        with Timer('qualify time %f'):
            fitness = self.qualifier.calculate(self.target, genome.pngPath)

        log.debug('calculated fitness for %s: %s' % (genome.serial, fitness))
        return fitness
Exemplo n.º 40
0
 def _confirm_choice(self):
     if self._choice_exists() and self.choices[self.choice_index]:
         voice.confirmation(
             self.choices[self.choice_index][0][:1]
         )  # repeat only the first part of the choice (not the help)
         self.choice_done = True
     else:
         debug("couldn't confirm choice (choices=%s, choice_index=%s)",
               self.choices, self.choice_index)
Exemplo n.º 41
0
 def handle_C2CS(self, data):
     """群发,非广播
     """
     message = data["message"]
     userids = data["clients"]
     log.debug("c2cs:%s", message)
     clis = [id2cli.get(userid) for userid in userids]
     for cli in clis:
         cli.send(message)
Exemplo n.º 42
0
 def quit_game(self):
     debug("quit_game %s", self.name)
     self.push("quit")
     if self in self.world.true_players():
         self.broadcast_to_others_only([self.name, 4261])
     for u in self.units[:]:
         u.delete()
     self.world.players.remove(self)
     self.world.ex_players.append(self)
Exemplo n.º 43
0
def parseRegString(searchString):
    if '\\' in searchString and searchString.split('\\')[0] in validHIVES:
        rootKey=searchString.split('\\')[0]
        subKey=searchString.split(rootKey)[1]
        rootKey=eval(rootKey)
        if type(rootKey)!= regobj.Key:
            debug("rootKey eval didn't result in a regobj.Key. Terminating check.")
            return None,None
        else:
            return rootKey,subKey
Exemplo n.º 44
0
    def on_message_receive(self, message):
        _, topic, message_str = message
        log.info("MQTT: Message received")
        log.debug("MQTT: Topic: {} - Message: {}".format(topic, message_str))

        if self.callback is not None:
            self.callback({
                "action": remove_prefix(topic, self.base_path),
                "data": json.loads(message_str)
            })
Exemplo n.º 45
0
def load_config():
    """定时重新加载配置文件
    """
    for module in settings.CONFIG_MODULES:
        try:
            module = sys.modules[module]
        except:
            continue
        reload(module)
        log.debug(u"加载配置文件")
Exemplo n.º 46
0
def value(searchString,cacheItems=[],cache=False):
    hits=False
    debug("value values %s %s"%(searchString,str(cacheItems)))
    for akey in cacheItems:
        rootKey,subKey=parseRegString(akey)
        subKeyValues=[str(k.data) for k in rootKey(subKey).values()]
        debug('SubKeyValues are %s'%(str(subKeyValues)))
        if searchString in subKeyValues:
            hits=True
    return hits
Exemplo n.º 47
0
 def _process_server_event(self, s):
     debug("server event: %s", s)
     cmd_args = s.strip().split(" ")
     cmd = "srv_" + cmd_args[0]
     args = cmd_args[1:]
     if hasattr(self, cmd):
         return getattr(self, cmd)(args)
     elif cmd == "srv_all_orders":
         debug("ignored by ServerMenu: %s", s)
     elif cmd != "srv_":
         warning("not recognized by ServerMenu: %s", s)
Exemplo n.º 48
0
 def dispatch_event(self, event):
     """
     Dispatch an instance of Event class
     """
     # Dispatch the event to all the associated listeners 
     if event.type in self._events.keys():
         listeners = self._events[event.type]
         if len(listeners)>0:
             log.debug('dispatch event "%s" to %d listener(s)' % (event.type, len(listeners)))
         for listener in listeners:
             listener(event)
Exemplo n.º 49
0
def iter_stream(stream_url, params=None):
    url = prepare_request(stream_url, params)
    log.debug('Connecting to %s', url)
    resp = requests.get(url, stream=True)
    for line in resp.iter_lines():
        if line.strip():
            try:
                message = json.loads(line)
            except json.JSONDecodeError, e:
                log.error('Invalid JSON: %s: %r', e, line)
            else:
                yield message
Exemplo n.º 50
0
 def handle_error(self):
     try:
         debug("Server.handle_error %s", sys.exc_info()[0])
     except:
         pass
     if sys.exc_info()[0] in [SystemExit, KeyboardInterrupt]:
         sys.exit()
     else:
         try:
             exception("Server.handle_error")
         except:
             pass
Exemplo n.º 51
0
 def handle_C2C(self, data):
     """客户端发给客户端的消息
     """
     dst_id = data["dst"]
     dst_cli = id2cli.get(dst_id)
     message = data["message"]
     log.debug("c2c:%s", message)
     if dst_cli:
         dst_cli.send(message)
     else:
         # TODO: 对方不在线,存库
         pass
Exemplo n.º 52
0
 def _select_next_choice(self):
     if self.choices:
         if self.choice_index == None:
             self.choice_index = self.default_choice_index
         else:
             self.choice_index += 1
             if not self._choice_exists():
                 self.choice_index = 0
         self._say_choice()
         debug("select_next_choice %s", self.choice_index)
     else:
         debug("select_next_choice did nothing because choices=%s", self.choices)
Exemplo n.º 53
0
 def add(self, game_type, duration):
     try:
         if duration >= 60:
             stats = self._read_file()
             if stats.has_key(game_type):
                 stats[game_type][0] += 1
                 stats[game_type][1] += duration
             else:
                 stats[game_type] = [1, duration]
             self._write_file(stats)
     except:
         debug("error adding stats")
Exemplo n.º 54
0
 def _read_file(self):
     if os.path.exists(self.filepath):
         lines = open(self.filepath).readlines()
     else:
         lines = []
     stats = {}
     for line in lines:
         try:
             game_type, nb_games, total_duration = line.split()
             stats[game_type] = [int(nb_games), int(total_duration)]
         except:
             debug("stat ignored: %s", line)
     return stats
Exemplo n.º 55
0
 def _dispatch_orders_if_needed(self):
     debug("dispatch orders if needed")
     while self._orders_are_ready():
         log_this = False
         debug(">> orders are ready")
         self._process_check_strings()
         # remove orders from the queue and pack them
         _all_orders = []
         for player, queue in self.all_orders.items():
             orders = queue.pop(0)[0]
             if SPACE_REPLACEMENT in orders:
                 log_this = True
             _all_orders.append("%s/%s" % (player.login, orders))
         all_orders = " ".join(_all_orders)
         # send orders
         for p in self.human_players:
             if not p.is_disconnected:
                 debug("send all_orders to %s", p.login)
                 p.push("all_orders %s\n" % all_orders)
             else:
                 debug("don't send all_orders to %s", p.login)
         if log_this and config.record_games:
             self.f.write("%s: all_orders %s\n" % (self.time, all_orders.replace(NEWLINE_REPLACEMENT, ";").replace(SPACE_REPLACEMENT, ",").replace("update;", "")))
         self.time += 1
         self._timeout_reference = None
Exemplo n.º 56
0
def walkIndicatorItems(ind):
    global level,iocEvalString, cacheItems
    cache=False

    lastii=ind.findall("./*[local-name()='IndicatorItem']")[-1]

    #if we are to look for a filename/registry, then attributes of the hit, save the hit.
    searches=walksearches(ind)
    if ('FileItem/' in str(searches)) or ('RegistryItem/' in str(searches)):
        cache=True
        
    for i in ind.findall("./*[local-name()='IndicatorItem']"):        
        #do we know how to handle this IOC?
        #split it into category/attribute
        itemTarget=i.Context.attrib.get("search")        
        iocMajorCategory=itemTarget.split('/')[0]
        iocAttribute=itemTarget.split('/')[-1]
        #some ioc attributes are all lower, 1 upper, then lower, camel case, etc..normalize to lower case.
        iocAttribute=iocAttribute.lower()
        #optimistic result default. change if you are pessimistic ;-]
        iocResult= False        
        #let python tell us what functions we support by eval'ing our include iocItems modules.
        if iocMajorCategory in dir(iocItems):
            if iocAttribute in dir(eval(iocMajorCategory)):
                #tell the function about items we've cached? 
                if 'cacheItems' in eval(iocMajorCategory + '.' + iocAttribute + '.func_code.co_varnames'):
                    #iocResult=eval(iocMajorCategory + '.' + iocAttribute + '("' + str(i.Content) + '")')
                    if cache:
                        iocResult=eval("%s.%s(r'%s',cacheItems,True)" %(iocMajorCategory,iocAttribute,i.Content))
                        debug('cache items: %s' %(str(cacheItems)))
                    else:
                        iocResult=eval("%s.%s(r'%s',[],False)" %(iocMajorCategory,iocAttribute,i.Content))

                else:
                    #iocResult=eval(iocMajorCategory + '.' + iocAttribute + '("' + str(i.Content) + '")')
                    iocResult=eval("%s.%s(r'%s')" %(iocMajorCategory,iocAttribute,i.Content))
            else:
                debug('cannot evaluate %s'%( (iocMajorCategory + '.' + iocAttribute + '("' + str(i.Content) + '")')))
        else:
            debug('cannot evaluate %s'%( (iocMajorCategory + '.' + iocAttribute + '("' + str(i.Content) + '")')))

        logicOperator=str(i.getparent().attrib.get("operator")).lower()        
        if i == lastii:
            debug('\t'*level + str(iocResult))
            info('\t'*level + i.Context.attrib.get("search") + ' ' + i.attrib.get("condition") + ' ' + str(i.Content))            
            iocEvalString+=' ' + str(iocResult)
        else:
            debug('\t'*level + str(iocResult) +' ' + str(logicOperator))
            info('\t'*level + i.Context.attrib.get("search") + ' ' + i.attrib.get("condition") + ' ' + str(i.Content) + ' ' + str(logicOperator))            
            iocEvalString+=' ' + str(iocResult) + ' ' + str(logicOperator)
Exemplo n.º 57
0
 def build_or_train_or_upgradeto(self, t, nb=1):
     if t.__class__ == str:
         t = self.world.unit_class(t)
     type = t.__name__
     if self.gather(t.cost, t.food_cost) and \
        self._get(1, self.world.get_makers(type)) and \
        self._get_requirements(t):
         # XXX why choose the first maker type? (problem if several creation paths are possible (train and upgradeto for example))
         if type in self.world.unit_class(self.world.get_makers(type)[0]).can_upgrade_to:
             # upgrade to
             if self.nb(self.world.get_makers(type)[0]) >= nb:
                 # If we have the correct number of archers,
                 # We upgrade then here.
                 self.order(nb, self.world.get_makers(type)[0], ["upgrade_to", type])
                 self.AI_timer = 100 # XXX: compute value # don't use ai too often # TODO: use events, not this timer
             else:
                 # If not, we recruit then
                 self._get(nb, self.world.get_makers(type)[0])
         elif type in self.world.unit_class(self.world.get_makers(type)[0]).can_build:
             # build
             if self.nb(BuildingSite) > 0:
                 self.send_some_peasants_to_building_site()
                 return
             if t.storable_resource_types:
                 meadow = self.choose(Meadow, resource_type=t.storable_resource_types[0])
                 # if no place to build and already enough building, forget this
                 if meadow is None:
                     if self.nb(t) > 0:
                         return True
                     else:
                         meadow = self.choose(Meadow)
             else:
                 meadow = self.choose(Meadow, nearest_for_builders=True)
             if meadow:
                 self.order(8, self.world.get_makers(type), ["build", type, meadow.id], True)
             else:
                 self.AI_timer = 10
                 return
         elif type in self.world.unit_class(self.world.get_makers(type)[0]).can_train:
             # train
             if self.nb(Worker) and \
                nb > self.nb(self.world.get_makers(type)[0]) * 3 and \
                self.potential(t.cost) > \
                self.nb(self.world.get_makers(type)[0]) * 100:
                 # additional production sites
                 self.build_or_train_or_upgradeto(self.world.get_makers(type)[0])
             self.order(nb, self.world.get_makers(type), ["train", type])
     else:
         self.AI_timer = 100 # XXX: compute value # don't use ai too often # TODO: use events, not this timer
         debug("not enough")