コード例 #1
0
 def __init__(self, fileName):
     """fileName: xml spec file name""" 
     Parser.__init__(self, fileName)
     self.analyticsTools = {}
     self.analyticsToolTb = None
     self.colsDesc = None
     self.sqlFileHd = None
     self.cmdFileHd = None
コード例 #2
0
    def test_parser(self):
        parser = Parser(self.input_file)

        rooms, classes, students, class_map = parser.parse_input()

        for class_id in classes:
            students_in_class = classes[class_id]
            for student in students_in_class:
                self.assertTrue(class_id in students[student])
コード例 #3
0
 def __init__(self):
     self.online = {}
     self.modules = {}
     self.parser = Parser()
     self.rooms = Room(self)
     for item in modules:
         module = importlib.import_module(f"modules.{item}")
         class_ = getattr(module, module.class_name)
         self.modules[class_.prefix] = class_(self)
     self.clothes = self.parser.parse_clothes()
     self.furniture = self.parser.parse_furniture()
     self.game_items = self.parser.parse_game_items()
コード例 #4
0
ファイル: server.py プロジェクト: nasocksok/avacity-async
 def __init__(self, host="0.0.0.0", port=8123):
     self.online = {}
     self.slots = []
     self.rooms = {}
     self.inv = {}
     self.msgmeter = {}
     self.parser = Parser()
     self.conflicts = self.parser.parse_conflicts()
     self.achievements = self.parser.parse_achievements()
     self.trophies = self.parser.parse_trophies()
     self.game_items = self.parser.parse_game_items()
     self.appearance = self.parser.parse_appearance()
     self.modules = {}
     for item in modules:
         module = importlib.import_module(f"modules.{item}")
         class_ = getattr(module, module.class_name)
         self.modules[class_.prefix] = class_(self)
     self.kicked = []
コード例 #5
0
 def callback(self, commands):
     print "xgw: Dispatching commands"
     result = ["\n"]
     for cmd in Parser(commands).fragment:
         if isinstance(cmd, Element):
             print "xgw: Invoking ", cmd
             cmd_res = self._invoke(cmd)
             print "xgw: Outcome ", cmd_res.name  # print error or result
             result.append(cmd_res)
             result.append("\n")
     return str(Generator(result))
コード例 #6
0
    def __createToolsTb(self):
        """create the analytics tool table"""
        
        # drop table stmt
        stmt = "DROP TABLE IF EXISTS " + self.analyticsToolTb + " cascade;\n\n"
        self.sqlFileHd.write(stmt)

        analytics_tools = Parser.getNodeTag(self, self.xmlDoc, "analytics_tools")

        metadata = Parser.getNodeTag(self, analytics_tools, "metadata")
        colList = Parser.getNodeList(self, metadata, "column")

        for col in colList:
            colName = Parser.getNodeVal(self, col, "name")
            colType = Parser.getNodeVal(self, col, "type")
            self.colsDesc[colName] = colType

        # convert dict
        cols = self.dicToArray(self.colsDesc)

        # create table stmt
        stmt = "CREATE TABLE " + self.analyticsToolTb + "("
        stmt = stmt + ','.join(cols) + ");\n\n"
        self.sqlFileHd.write(stmt)
コード例 #7
0
ファイル: test_config.py プロジェクト: madlib/testsuite
    def testconfig(self):
        """Parse logger database connection to store result."""
        try:
            configuration       =   Parser.getNodeTag(self, self.xmlDoc, "configuration")
            metadatadb          =   Parser.getNodeTag(self, configuration, "metadatadb")        
            self.user                =   Parser.getNodeVal(self, metadatadb, "user")
            self.host                =   Parser.getNodeVal(self, metadatadb, "host")
            self.port                =   Parser.getNodeVal(self, metadatadb, "port")
            self.database            =   Parser.getNodeVal(self, metadatadb, "database")
            self.resultDBSchema      =   Parser.getNodeVal(self, metadatadb, "schema")

            self.resultDBconf = {'username':self.user, 'host':self.host, 'port':self.port, \
                       'database':self.database, 'schema':self.resultDBSchema, 'name':'resultDB'}
            self.dbmanager = dbManager.dbManager(self.resultDBconf)
 
        except Exception, exp:
            print str(exp)
            print "Error when parsing testConfig"
            sys.exit()
コード例 #8
0
ファイル: test_config.py プロジェクト: madlib/testsuite
 def __init__(self, fileName):
     Parser.__init__(self, fileName)
コード例 #9
0
ファイル: server.py プロジェクト: nasocksok/avacity-async
class Server():
    def __init__(self, host="0.0.0.0", port=8123):
        self.online = {}
        self.slots = []
        self.rooms = {}
        self.inv = {}
        self.msgmeter = {}
        self.parser = Parser()
        self.conflicts = self.parser.parse_conflicts()
        self.achievements = self.parser.parse_achievements()
        self.trophies = self.parser.parse_trophies()
        self.game_items = self.parser.parse_game_items()
        self.appearance = self.parser.parse_appearance()
        self.modules = {}
        for item in modules:
            module = importlib.import_module(f"modules.{item}")
            class_ = getattr(module, module.class_name)
            self.modules[class_.prefix] = class_(self)
        self.kicked = []

    async def listen(self):
        self.redis = await aioredis.create_redis_pool("redis://localhost",
                                                      encoding="utf-8")
        loop = asyncio.get_event_loop()
        for prefix in self.modules:
            module = self.modules[prefix]
            if hasattr(module, "_background"):
                loop.create_task(module._background())
                print(f"{prefix} background")
        self.server = await asyncio.start_server(self.new_conn, "0.0.0.0",
                                                 8123)
        loop.create_task(self._background())
        await websockets.server.serve(self.handle_websocket, "localhost", 8765)
        logging.info("Сервер готов принимать соединения")

    async def stop(self):
        logging.info("Выключение...")
        for uid in self.online.copy():
            try:
                await self.online[uid].send([6, "Restart", {}], type_=2)
            except Exception:
                continue
        self.server.close()
        await self.server.wait_closed()

    async def handle_websocket(self, websocket, path):
        data = json.loads(await websocket.recv())
        if data["action"] == "get_online":
            await websocket.send(
                json.dumps({
                    "action": "online",
                    "online": len(self.online)
                }))

    async def new_conn(self, reader, writer):
        loop = asyncio.get_event_loop()
        loop.create_task(Client(self).handle(reader, writer))

    async def process_data(self, data, client):
        if not client.uid:
            if data["type"] != 1:
                return client.writer.close()
            return await self.auth(data["msg"], client)
        if data["type"] == 2:
            return client.writer.close()
        elif data["type"] == 17:
            await client.send([data["msg"][0], client.uid], type_=17)
            if data["msg"][0].split("_")[0] == "game":
                await self.modules["lg"].exit_game(data["msg"][0], client)
        elif data["type"] == 34:
            if data["msg"][1] == "clerr":
                return
            if client.uid in self.msgmeter:
                self.msgmeter[client.uid] += 1
                if self.msgmeter[client.uid] > 160:
                    if client.uid in self.kicked:
                        return client.writer.close()
                    self.kicked.append(client.uid)
                    logging.debug(f"Кик {client.uid} за превышение лимитов")
                    await client.send([
                        "cp.ms.rsm", {
                            "txt": "Вы были кикнуты "
                            "за превышение "
                            "лимитов"
                        }
                    ])
                    await client.send([5, "Limits kick", {}], type_=2)
                    return client.writer.close()
            else:
                self.msgmeter[client.uid] = 1
            client.last_msg = time.time()
            prefix = data["msg"][1].split(".")[0]
            if prefix not in self.modules:
                logging.warning(f"Command {data['msg'][1]} not found")
                return
            if not client.drop:
                if client.debug:
                    logging.debug(f"uid: {client.uid}, {data}")
                await self.modules[prefix].on_message(data["msg"], client)
            # asyncio.create_task(self.modules[prefix].on_message(data["msg"],
            #                                                    client))

    async def auth(self, msg, client):
        uid = await self.redis.get(f"auth:{msg[2]}")
        if not uid:
            await client.send([5, "Key is invalid", {}], type_=2)
            client.writer.close()
            return
        cfghash = msg[3]["cfghsh"]
        if not os.path.exists(f"files/data/config_all_ru_{cfghash}.zip"):
            print(f"КОНФИГ ЛЕВЫЙ - {uid}")
            banned = await self.redis.get(f"uid:{uid}:banned")
            if not banned and uid != "38046":
                await self.redis.set(f"uid:{uid}:banned", 0)
                await self.redis.set(f"uid:{uid}:ban_time", int(time.time()))
                await self.redis.set(f"uid:{uid}:ban_end", 0)
                await self.redis.set(f"uid:{uid}:ban_reason", "Читы")
                message = f"{uid} получил автобан\nПричина: читы"
                await self.modules["cp"].send_tg(message)
        banned = await self.redis.get(f"uid:{uid}:banned")
        if banned:
            ban_time = int(await self.redis.get(f"uid:{uid}:ban_time"))
            ban_end = int(await self.redis.get(f"uid:{uid}:ban_end"))
            reason = await self.redis.get(f"uid:{uid}:ban_reason")
            if not reason:
                reason = ""
            category = await self.redis.get(f"uid:{uid}:ban_category")
            if category:
                category = int(category)
            else:
                category = 4
            if ban_end == 0:
                time_left = 0
            else:
                time_left = ban_end - int(time.time() * 1000)
            if time_left < 0 and ban_end != 0:
                await self.redis.delete(f"uid:{uid}:banned")
                await self.redis.delete(f"uid:{uid}:ban_time")
                await self.redis.delete(f"uid:{uid}:ban_end")
                await self.redis.delete(f"uid:{uid}:ban_reason")
            else:
                await client.send([
                    10, "User is banned", {
                        "duration": 999999,
                        "banTime": ban_time,
                        "notes": reason,
                        "reviewerId": banned,
                        "reasonId": category,
                        "unbanType": "none",
                        "leftTime": time_left,
                        "id": None,
                        "reviewState": 1,
                        "userId": uid,
                        "moderatorId": banned
                    }
                ],
                                  type_=2)
                client.writer.close()
                return
        if uid in self.online:
            try:
                await self.online[uid].send([6, {}], type_=3)
                self.online[uid].writer.close()
            except OSError:
                pass
        user_data = await self.get_user_data(uid)
        if not user_data:
            pipe = self.redis.pipeline()
            pipe.set(f"uid:{uid}:slvr", 1000)
            pipe.set(f"uid:{uid}:gld", 6)
            pipe.set(f"uid:{uid}:enrg", 100)
            pipe.set(f"uid:{uid}:exp", 493500)
            pipe.set(f"uid:{uid}:emd", 0)
            pipe.set(f"uid:{uid}:lvt", 0)
            await pipe.execute()
            user_data = await self.get_user_data(uid)
        role = user_data["role"]
        if len(self.slots) >= 1700 and uid not in self.slots and not role and \
           not user_data["premium"]:
            await client.send([
                10, "User is banned", {
                    "duration":
                    999999,
                    "banTime":
                    1,
                    "notes":
                    "Сервер переполнен, пожалуйста, "
                    "попытайтесь войти чуть позже. "
                    "Игроки купившие премиум могут "
                    "входить на переполненный сервер "
                    "без ограничений!",
                    "reviewerId":
                    "1",
                    "reasonId":
                    4,
                    "unbanType":
                    "none",
                    "leftTime":
                    0,
                    "id":
                    None,
                    "reviewState":
                    1,
                    "userId":
                    uid,
                    "moderatorId":
                    "1"
                }
            ],
                              type_=2)
            client.writer.close()
            return
        if uid not in self.slots:
            self.slots.append(uid)
        client.uid = uid
        client.user_data["id"] = uid
        email = await self.redis.get(f"uid:{uid}:email")
        if email:
            client.user_data["email"] = email
        self.online[uid] = client
        await self.redis.set(f"uid:{uid}:lvt", int(time.time()))
        await self.check_new_act(client, user_data["lvt"])
        await self.redis.set(f"uid:{uid}:ip", client.addr)
        if uid not in self.inv:
            self.inv[uid] = Inventory(self, uid)
            await self.inv[uid]._get_inventory()
        else:
            self.inv[uid].expire = 0
        if user_data["prem_time"] != 0 and \
           time.time() - user_data["prem_time"] > 0:
            await self.remove_premium(uid)
        await client.send([client.uid, "", True, False, False], type_=1)
        client.checksummed = True

    async def check_new_act(self, client, lvt):
        now = datetime.now()
        old = datetime.fromtimestamp(lvt)
        give = False
        if now.day - old.day == 1:
            give = True
        else:
            delta = now - old
            if now.day != old.day:
                if delta.days <= 1:
                    give = True
                else:
                    await self.redis.delete(f"uid:{client.uid}:days")
        if give:
            strik = await self.redis.get(f"uid:{client.uid}:days")
            if not strik:
                strik = 1
            else:
                strik = int(strik)
                if strik >= 5:
                    user_data = await self.get_user_data(client.uid)
                    if user_data["premium"] and strik < 8:
                        strik += 1
                else:
                    strik += 1
            await self.redis.incrby(f"uid:{client.uid}:act", strik)
            await self.redis.set(f"uid:{client.uid}:days", strik)

    async def remove_premium(self, uid):
        clothes = self.modules["a"].clothes_list
        apprnc = await self.redis.lindex(f"uid:{uid}:appearance", 2)
        if not apprnc:
            return
        if apprnc == "1":
            gender = "boy"
        else:
            gender = "girl"
        items = await self.redis.smembers(f"uid:{uid}:items")
        crt = int(await self.redis.get(f"uid:{uid}:crt"))
        for category in clothes[gender]:
            for item in clothes[gender][category]:
                if not clothes[gender][category][item]["vipOnly"]:
                    continue
                for tmp in items:
                    if item not in tmp:
                        continue
                    await self.inv[uid].take_item(item)
                    crt -= clothes[gender][category][item]["rating"]
                    for ctp in [
                            "casual", "club", "official", "swimwear",
                            "underdress"
                    ]:
                        await self.redis.srem(f"uid:{uid}:{ctp}", item)
                    break
        await self.redis.set(f"uid:{uid}:crt", crt)
        await self.redis.set(f"uid:{uid}:wearing", "casual")
        for item in const.PREMIUM_BUBBLES:
            await self.inv[uid].take_item(item)
        await self.redis.delete(f"uid:{uid}:trid")
        await self.redis.delete(f"uid:{uid}:bubble")
        await self.redis.delete(f"uid:{uid}:premium")

    async def get_user_data(self, uid):
        pipe = self.redis.pipeline()
        pipe.get(f"uid:{uid}:slvr")
        pipe.get(f"uid:{uid}:enrg")
        pipe.get(f"uid:{uid}:gld")
        pipe.get(f"uid:{uid}:exp")
        pipe.get(f"uid:{uid}:emd")
        pipe.get(f"uid:{uid}:lvt")
        pipe.get(f"uid:{uid}:trid")
        pipe.get(f"uid:{uid}:crt")
        pipe.get(f"uid:{uid}:hrt")
        pipe.get(f"uid:{uid}:act")
        pipe.get(f"uid:{uid}:role")
        pipe.get(f"uid:{uid}:premium")
        result = await pipe.execute()
        if not result[0]:
            return None
        if result[5]:
            lvt = int(result[5])
        else:
            lvt = 0
        if result[7]:
            crt = int(result[7])
        else:
            crt = await self.modules["a"].update_crt(uid)
        if result[8]:
            hrt = int(result[8])
        else:
            hrt = await self.modules["frn"].update_hrt(uid)
        if result[9]:
            act = int(result[9])
        else:
            act = 0
        if result[10]:
            role = int(result[10])
        else:
            role = 0
        premium = False
        if result[11]:
            prem_time = int(result[11])
            if prem_time == 0 or prem_time - time.time() > 0:
                premium = True
        else:
            prem_time = 0
        return {
            "uid": uid,
            "slvr": int(result[0]),
            "enrg": int(result[1]),
            "gld": int(result[2]),
            "exp": int(result[3]),
            "emd": int(result[4]),
            "lvt": lvt,
            "crt": crt,
            "act": act,
            "hrt": hrt,
            "trid": result[6],
            "role": role,
            "premium": premium,
            "prem_time": prem_time
        }

    async def get_appearance(self, uid):
        apprnc = await self.redis.lrange(f"uid:{uid}:appearance", 0, -1)
        if not apprnc:
            return False
        return {
            "n": apprnc[0],
            "nct": int(apprnc[1]),
            "g": int(apprnc[2]),
            "sc": int(apprnc[3]),
            "ht": int(apprnc[4]),
            "hc": int(apprnc[5]),
            "brt": int(apprnc[6]),
            "brc": int(apprnc[7]),
            "et": int(apprnc[8]),
            "ec": int(apprnc[9]),
            "fft": int(apprnc[10]),
            "fat": int(apprnc[11]),
            "fac": int(apprnc[12]),
            "ss": int(apprnc[13]),
            "ssc": int(apprnc[14]),
            "mt": int(apprnc[15]),
            "mc": int(apprnc[16]),
            "sh": int(apprnc[17]),
            "shc": int(apprnc[18]),
            "rg": int(apprnc[19]),
            "rc": int(apprnc[20]),
            "pt": int(apprnc[21]),
            "pc": int(apprnc[22]),
            "bt": int(apprnc[23]),
            "bc": int(apprnc[24])
        }

    async def get_clothes(self, uid, type_):
        clothes = []
        cur_ctp = await self.redis.get(f"uid:{uid}:wearing")
        for item in await self.redis.smembers(f"uid:{uid}:{cur_ctp}"):
            if "_" in item:
                id_, clid = item.split("_")
                clothes.append({"id": id_, "clid": clid})
            else:
                clothes.append({"id": item, "clid": ""})
        if type_ == 1:
            ctps = ["casual", "club", "official", "swimwear", "underdress"]
            clths = {"cc": cur_ctp, "ccltns": {}}
            clths["ccltns"][cur_ctp] = {"cct": [], "cn": "", "ctp": cur_ctp}
            for item in clothes:
                if item["clid"]:
                    clths["ccltns"][cur_ctp]["cct"].append(f"{item['id']}:"
                                                           f"{item['clid']}")
                else:
                    clths["ccltns"][cur_ctp]["cct"].append(item["id"])
            ctps.remove(cur_ctp)
            for ctp in ctps:
                clths["ccltns"][ctp] = {"cct": [], "cn": "", "ctp": ctp}
                clothes = []
                for item in await self.redis.smembers(f"uid:{uid}:{ctp}"):
                    if "_" in item:
                        id_, clid = item.split("_")
                        clothes.append({"id": id_, "clid": clid})
                    else:
                        clothes.append({"id": item, "clid": ""})
                for item in clothes:
                    if item["clid"]:
                        clths["ccltns"][ctp]["cct"].append(f"{item['id']}:"
                                                           f"{item['clid']}")
                    else:
                        clths["ccltns"][ctp]["cct"].append(item["id"])
        elif type_ == 2:
            clths = {"clths": []}
            for item in clothes:
                clths["clths"].append({
                    "tpid": item["id"],
                    "clid": item["clid"]
                })
        elif type_ == 3:
            clths = {"cct": [], "cn": "", "ctp": cur_ctp}
            for item in clothes:
                if item["clid"]:
                    clths["cct"].append(f"{item['id']}:{item['clid']}")
                else:
                    clths["cct"].append(item["id"])
        return clths

    async def get_room_items(self, uid, room):
        if "_" in room:
            raise exceptions.WrongRoom()
        names = []
        pipe = self.redis.pipeline()
        spipe = self.redis.pipeline()
        for name in await self.redis.smembers(f"rooms:{uid}:{room}:items"):
            pipe.lrange(f"rooms:{uid}:{room}:items:{name}", 0, -1)
            spipe.smembers(f"rooms:{uid}:{room}:items:{name}:options")
            names.append(name)
        result = await pipe.execute()
        options = await spipe.execute()
        i = 0
        items = []
        for name in names:
            name, lid = name.split("_")
            item = result[i]
            option = options[i]
            try:
                tmp = {
                    "tpid": name,
                    "x": float(item[0]),
                    "y": float(item[1]),
                    "z": float(item[2]),
                    "d": int(item[3]),
                    "lid": int(lid)
                }
            except IndexError:
                await self.redis.srem(f"rooms:{uid}:{room}:items",
                                      f"{name}_{lid}")
                await self.redis.delete(f"rooms:{uid}:{room}:items:"
                                        f"{name}_{lid}")
                continue
            for kek in option:
                if kek == "clrs":
                    item = await self.redis.smembers(f"rooms:{uid}:{room}:"
                                                     f"items:{name}_{lid}:"
                                                     f"{kek}")
                else:
                    item = await self.redis.get(f"rooms:{uid}:{room}:items:"
                                                f"{name}_{lid}:{kek}")
                tmp[kek] = item
            items.append(tmp)
            i += 1
        return items

    async def _background(self):
        while True:
            logging.info(f"Игроков онлайн: {len(self.online)}")
            logging.info(f"Кикнуто за превышение лимитов: {len(self.kicked)}")
            self.msgmeter = {}
            self.kicked = []
            for uid in self.inv.copy():
                inv = self.inv[uid]
                if uid not in self.online and time.time() - inv.expire > 0:
                    del self.inv[uid]
            for uid in self.slots.copy():
                if uid not in self.online:
                    self.slots.remove(uid)
            for uid in self.online.copy():
                if uid not in self.online:
                    continue
                if time.time() - self.online[uid].last_msg > 420:
                    client = self.online[uid]
                    user_data = await self.get_user_data(uid)
                    if user_data["role"] or user_data["premium"]:
                        continue
                    # logging.debug(f"Кик {client.uid} за афк")
                    await client.send(
                        ["cp.ms.rsm", {
                            "txt": "Вы были кикнуты "
                            "за афк"
                        }])
                    await client.send([3, {}], type_=3)
                    client.writer.close()
                    if uid in self.slots:
                        self.slots.remove(uid)
            await asyncio.sleep(60)
コード例 #10
0
class ConfigurationsManager:
    """Manages all the configuration settings.

     Examples:
    >>> config_manager = ConfigurationsManager()


    # make a directory
    >>> config_manager.make_directory('test_directory') # doctest: +ELLIPSIS
    ...\\test_directory
    
    # load specified component settings as a dictionary object from XML configuration file
    >>> launcher_settings = config_manager.get_configuration_settings('launcher_configurations', CONFIG_FILE)
    >>> print(launcher_settings)
    {'foo': {'bar': None}, 'test_type': 'cluster'}

    >>> print(type(launcher_settings))
    <class 'dict'>

    # configure and load logger
    >>> myLogger = ConfigurationsManager().load_log_configurations(__name__)
    >>> myLogger.info("configured") # doctest: +ELLIPSIS
    20...INFO configurationsmanager... configured
    """

    __directories_manager = DirectoriesManager()
    __parser = Parser()
    __configuration_file = CONFIG_FILE

    def make_directory(self, directory):
        """Wrapper for making directories"""
        return self.__directories_manager.make_directory(directory)

    def get_directory(self, directory):
        """Wrapper for retrieving directories"""
        return self.__directories_manager.get_directory(directory)

    def load_xml(self, configuration_file, component):
        """Wrapper for loading an xml file"""
        # loads the xml configuration file as an xml.etree.ElementTree
        global_configurations_xml_tree = self.__parser.load_xml(configuration_file)
        root = global_configurations_xml_tree.getroot()
        # get the xml configuration settings for the desired component
        component_configurations_xml = root.find(component)
        if component_configurations_xml is None:
            # TODO: a better exception handling
            raise LookupError("configuration settings not found!", component)
        return component_configurations_xml

    def convert_xml_to_dictionary(self, xml):
        """Wrapper for converting xml to dictionary"""
        return self.__parser.convert_xml2dict(xml)

    def get_configuration_settings(self, component, configuration_file=None):
        """Returns the specified component_configuration settings from
         the ``configuration_file``.
        """
        if configuration_file is None:
            configuration_file = self.__configuration_file
        component_configurations_xml = self.load_xml(configuration_file, component)
        component_configurations_dict = self.convert_xml_to_dictionary(component_configurations_xml)
        return component_configurations_dict

    def load_log_configurations(self, name, directory=None,
                                configuration_settings=None):
        """Creates a logger with the specified name and configuration settings.

        Parameters
        ----------
        name : str
            Logger name

        directory: str
            target directory for the log file

        configuration_settings: dict
            configuration settings for the logger

        Returns
        ------
        Return a logger
        """
        if directory is None:
            # Case: if no directory is specified,
            # set the default directory for the logs
            target_directory = self.get_directory(directory='logs')
        else:
            # Case: make specified directory for the logs
            target_directory = self.make_directory(directory)
        if configuration_settings is None:
            log_configurations = self.get_configuration_settings(
                                                    'log_configurations')
        logger = ConfigLogger()
        return logger.initialize_logger(name, target_directory,
                                        configurations=log_configurations)
コード例 #11
0
def preform_genetic_algorithm(input_file, fitness_threshold, round_limit):
    parser = Parser(input_file)

    room_information_dict, course_students_dict, student_courses_dict, _ = parser.parse_input(
    )

    room_ids = list(room_information_dict.keys())

    population = seed_population(POPULATION_SIZE, course_students_dict,
                                 room_ids)

    fitness_calculator = FitnessCalculator(room_information_dict,
                                           course_students_dict,
                                           student_courses_dict,
                                           fitness_threshold)

    rounds = 1
    min_fitness = float('inf')

    while rounds <= round_limit or round_limit == 0:
        print("Beginning new selection")
        population = selector.selection(population, fitness_calculator)

        # print('population after selection:')
        # for individual in population:
        #     print(individual)
        #     print('***')
        # print('end population')

        population = crossover.population_crossover(population)

        # print('population after crossover:')
        # for individual in population:
        #     print(individual)
        #     print('***')
        # print('end population')

        population = mutator.mutate_population(population, room_ids)

        # print('population after mutation:')
        # for individual in population:
        #     print(individual)
        #     print('***')
        # print('end population')

        fit_chromosomes = fitness_calculator.get_fit_chromosomes(population)

        # distinct_individuals = []
        # for individual in population:
        #     if individual not in distinct_individuals:
        #         distinct_individuals.append(individual)
        # print('Num distinct individuals after mutation: {}'.format(len(distinct_individuals)))

        if fit_chromosomes:
            print('Num fit chromosomes: {}'.format(len(fit_chromosomes)))

        for chromosome, fitness, validity in fit_chromosomes:
            min_fitness = min(min_fitness, fitness)

            if validity == True:
                return chromosome, fitness, rounds, course_students_dict

        rounds += 1

    print('Failed. Min fitness found: {}'.format(min_fitness))
    return None
コード例 #12
0
class Server:
    def __init__(self):
        self.online = {}
        self.modules = {}
        self.parser = Parser()
        self.rooms = Room(self)
        for item in modules:
            module = importlib.import_module(f"modules.{item}")
            class_ = getattr(module, module.class_name)
            self.modules[class_.prefix] = class_(self)
        self.clothes = self.parser.parse_clothes()
        self.furniture = self.parser.parse_furniture()
        self.game_items = self.parser.parse_game_items()

    async def open_connections(self):
        self.logging("Server is ready to accept connections!")
        self.redis = await aioredis.create_redis_pool("redis://localhost",
                                                      encoding="utf-8")
        self.server = await asyncio.start_server(self.new_connection,
                                                 "127.0.0.1", 8123)
        asyncio.create_task(self._background())

    async def check_outside_get_room(self, client):
        element = 0
        old_type = client.old_type
        while element < 5:
            if old_type == client.old_type:
                element += 1
            else:
                return False
            await asyncio.sleep(0.5)
        client.old_type = 0
        await client.send(
            {
                'secretKey': None,
                'zoneId': client.zoneId,
                'user': {
                    'roomIds': [],
                    'name': None,
                    'zoneId': client.zoneId,
                    'userId': client.uid
                },
                'userId': client.uid
            },
            type_=1)

    async def process_data(self, msg, client):
        client.old_type = msg['type']
        if msg['type'] == 1:
            if client.uid is None:
                if 'login' not in msg['msg']:
                    return self.logging(f"Ошибка авторизации!")
                return await self.auth(msg['msg'], client)
            return await self.auth(msg['msg'], client)
        elif msg['type'] == 2 or msg['type'] == 17:
            return asyncio.create_task(self.check_outside_get_room(client))
        elif msg['type'] == 32:
            if msg['msg']['text'].startswith('!'):
                await self.chat_command(msg['msg']['text'], client)
                if 'recipients' in msg['msg']:
                    del msg['msg']['recipients']
                msg['msg']['text'] = "Ввёл команду."
            return await self.chat(msg['msg'], client)
        elif msg['type'] == 34:
            prefix = msg['msg']['command'].split(".")[0]
            if prefix not in self.modules:
                return self.logging(
                    f"Command {msg['msg']['command']} not found.")
            if msg['msg']['command'] == 'crt.bcp':
                if 'avacoin' not in msg['msg']['data']['pk'].lower():
                    return await self.modules['b'].buy_gold(msg['msg'], client)
                return await self.modules['b'].buy_coint(msg['msg'], client)
            return await self.modules[prefix].get_message(msg['msg'], client)
        return self.logging(f"Type error: {msg['type']}")

    async def chat_command(self, msg, client):
        subcommand = msg[1:]
        if " " in msg:
            subcommand = msg.split()[0][1:]
        if subcommand == 'команда':
            return await self.send_system_message(subcommand, msg, client)
        elif subcommand == 'бан':
            return await self.user_ban(subcommand, msg, client)
        elif subcommand == 'уровень':
            return await self.change_avatar_level(subcommand, msg, client)

    async def change_avatar_level(self, subcommand, msg, client):
        level = msg.split(subcommand)[1].strip()
        if not level.isdigit():
            return await self.error(type_=1, client=client)
        premium = await self.redis.get(f"uid:{client.uid}:premium")
        premium = False if not premium else True
        if not premium and int(level) > 69 or int(level) < 10:
            return await self.error(type_=2, client=client)
        elif premium and int(level) > 998 or int(level) < 10:
            level = 998
        await self.redis.set(f"uid:{client.uid}:exp", get_exp(int(level)))
        await Location(self, client).refresh_avatar()
        await Location(self, client).ntf_ci()
        return await client.send(
            {
                'broadcast': False,
                'text': f'Ваш уровень изменился на {level}.'
            },
            type_=36)

    async def error(self, type_=1, client=None):
        message = ""
        if type_ == 1:
            message = "Ошибка в команде"
        elif type_ == 2:
            message = "Вам доступна смена уровня от 10 до 69. Купите премиум на avaland.xyz"
        return await client.send({
            'broadcast': False,
            'text': message
        },
                                 type_=36)

    async def user_ban(self, subcommand, msg, client):
        gen_plr = await Location(self, client).gen_plr()
        if gen_plr['usrinf']['rl'] != const.BAN_PRIVILEGIES:
            return
        try:
            uid = msg.split("uid=")[1].split("&")[0]
            reason = msg.split("reason=")[1].split("&")[0]
            minutes = msg.split("minutes=")[1].split("&")[0]
        except IndexError:
            return
        if uid and reason and minutes:
            await self.redis.set(f'uid:{uid}:banned', client.uid)
            await self.redis.set(f'uid:{uid}:reason_ban', reason)
            await self.redis.set(f'uid:{uid}:time_ban', minutes)
            await self.redis.set(f'uid:{uid}:times', int(time.time()))
            await self.redis.set(f'uid:{uid}:left_ban',
                                 int(time.time()) + int(minutes) * 60)
        if uid in self.online:
            tmp = self.online[uid]
            await tmp.send(
                {
                    'zoneId': tmp.zoneId,
                    'error': {
                        'code': 10,
                        'data': {
                            'duration': int(minutes),
                            'reason': reason,
                            'banTime': int(time.time()),
                            'reasonId': 4,
                            'unbanType': 'admin panel',
                            'leftTime': int(time.time()) * 1000,
                            'userId': tmp.uid,
                            'moderatorId': client.uid
                        },
                        'message': 'User is banned'
                    }
                },
                type_=2)
        return await client.send(
            {
                'broadcast': False,
                'text': f"{uid} получил бан"
            }, type_=36)

    async def send_system_message(self, subcommand, msg, client):
        gen_plr = await Location(self, client).gen_plr()
        if gen_plr['usrinf']['rl'] != const.SEND_SYSTEM_MESSAGE:
            return
        message = msg.split(subcommand)[1].strip()
        for user in self.online:
            tmp = self.online[user]
            await tmp.send({'broadcast': False, 'text': message}, type_=36)

    async def chat(self, msg, client):
        apprnc = await self.get_appearance(client.uid)
        if not apprnc or not apprnc['n']:
            return
        broadcast = True
        if 'recipients' in msg:
            broadcast, uidS = False, msg['recipients'][0]
        for uid in self.online:
            if not broadcast and\
                    uid not in [uidS, client.uid]:
                continue
            tmp = self.online[uid]
            if tmp.room == client.room:
                await tmp.send(
                    {
                        'broadcast': broadcast,
                        'sender': {
                            'roomIds': [client.room],
                            'name': apprnc['n'],
                            'zoneId': client.zoneId,
                            'userId': client.uid
                        },
                        'text': msg['text']
                    },
                    type_=32)

    async def technical_working(self, client):
        return await client.send(
            {
                'zoneId': 'house',
                'error': {
                    'code': 10,
                    'data': {
                        'duration': 999999999,
                        'reason': "тест серверов avatarlife.",
                        'banTime': int(time.time()),
                        'reasonId': 4,
                        'unbanType': 'admin panel',
                        'leftTime': 0,
                        'userId': None,
                        'moderatorId': "1"
                    },
                    'message': 'User is banned'
                }
            },
            type_=2)

    async def auth(self, msg, client):
        if not await self.redis.get(f"login:{msg['login']}"):
            uid, password = await self._new_account(msg['login'])
        else:
            uid = await self.redis.get(f"login:{msg['login']}")
            password = await self.redis.get(f"uid:{uid}:password")
        role = await self.redis.get(f'uid:{uid}:rl')
        if const.TECHNICAL_WORKING and not role:
            return await self.technical_working(client)
        if client.uid:
            apprnc = await self.get_appearance(client.uid)
            await client.send(
                {
                    'reason': 2,
                    'data': {},
                    'zoneId': client.zoneId,
                    'user': {
                        'roomIds': [],
                        'name': apprnc['n'],
                        'userId': client.uid
                    }
                },
                type_=3)
        if not client.uid:
            banned = await self.redis.get(f'uid:{uid}:banned')
            if banned:
                times = await self.redis.get(f'uid:{uid}:times')
                reason = await self.redis.get(f'uid:{uid}:reason_ban')
                time_ban = await self.redis.get(f'uid:{uid}:time_ban')
                left_ban = await self.redis.get(f'uid:{uid}:left_ban')
                if int(time.time()) - int(left_ban) > 0:
                    for banType in [
                            'banned', 'times', 'reason_ban', 'time_ban',
                            'left_ban'
                    ]:
                        await self.redis.delete(f'uid:{uid}:{banType}')
                    banned = False
                if banned:
                    return await client.send(
                        {
                            'zoneId': msg['zoneId'],
                            'error': {
                                'code': 10,
                                'data': {
                                    'duration': int(time_ban),
                                    'reason': reason,
                                    'banTime': int(times),
                                    'reasonId': 4,
                                    'unbanType': 'admin panel',
                                    'leftTime': int(times) * 1000,
                                    'userId': uid,
                                    'moderatorId': banned
                                },
                                'message': 'User is banned'
                            }
                        },
                        type_=2)
            if uid in self.online:
                tmp = self.online[uid]
                await tmp.writer.close()
                del self.online[uid]
            client.uid = str(uid)
        if client.uid not in self.online:
            self.online[client.uid] = client
        client.zoneId = msg['zoneId']
        client.step_to_activate = False
        await self.check_new_act(client)
        return await client.send(
            {
                'secretKey': password,
                'zoneId': msg['zoneId'],
                'user': {
                    'roomIds': [],
                    'name': None,
                    'zoneId': msg['zoneId'],
                    'userId': client.uid
                },
                'userId': client.uid
            },
            type_=1)

    async def check_new_act(self, client):
        premium = await self.redis.get(f"uid:{client.uid}:premium")
        if not premium:
            return
        if int(time.time()) - int(premium) > 0:
            self.redis.delete(f"uid:{client.uid}:dr")
            self.redis.delete(f"uid:{client.uid}:premium")

    async def get_appearance(self, uid):
        apprnc = await self.redis.lrange(f"uid:{uid}:appearance", 0, -1)
        if not apprnc:
            return False
        return {
            "n": apprnc[0],
            "g": int(apprnc[1]),
            "hc": int(apprnc[2]),
            "ec": int(apprnc[3]),
            "bc": int(apprnc[4]),
            "sc": int(apprnc[5]),
            "bt": int(apprnc[6]),
            "rg": int(apprnc[7]),
            "et": int(apprnc[8]),
            "brc": int(apprnc[9]),
            "ht": int(apprnc[10]),
            "sh": int(apprnc[11]),
            "ss": int(apprnc[12]),
            "mc": int(apprnc[13]),
            "brt": int(apprnc[14]),
            "rc": int(apprnc[15]),
            "shc": int(apprnc[16]),
            "mt": int(apprnc[17])
        }

    async def add_item(self, uid, name, type_, amount=1):
        redis = self.redis
        item = await redis.lrange(f"uid:{uid}:items:{name}", 0, -1)
        if item:
            if type_ == "cls":
                return
            await redis.lset(f"uid:{uid}:items:{name}", 1,
                             int(item[1]) + amount)
        else:
            await redis.sadd(f"uid:{uid}:items", name)
            await redis.rpush(f"uid:{uid}:items:{name}", type_, amount)

    async def take_item(self, item, uid, amount=1):
        redis = self.redis
        items = await redis.smembers(f"uid:{uid}:items")
        if item not in items:
            return False
        tmp = await redis.lrange(f"uid:{uid}:items:{item}", 0, -1)
        if not tmp:
            await redis.srem(f"uid:{uid}:items", item)
            return False
        type_ = tmp[0]
        have = int(tmp[1])
        if have < amount:
            return False
        if have > amount:
            await redis.lset(f"uid:{uid}:items:{item}", 1, have - amount)
        else:
            await redis.delete(f"uid:{uid}:items:{item}")
            await redis.srem(f"uid:{uid}:items", item)
        return True

    async def errors(self, type_=0, client=None):
        message = "Произошла какая-то ошибка."
        if type_ == 1:
            message = "Превышен лимит предметов."
        elif type_ == 2:
            message = "Произошла ошибка при поиске мебели."
        return await client.send({
            'broadcast': False,
            'text': message
        },
                                 type_=36)

    async def _new_account(self, login, pswdlnght=20):
        uid = await self.redis.incr("uids")
        passwd = "".join(random.choice(string) for i in range(pswdlnght))
        await self.redis.set(f"login:{login}", uid)
        await self.redis.set(f"uid:{uid}:login", login)
        await self.redis.set(f"uid:{uid}:password", passwd)
        return uid, passwd

    async def stop(self):
        self.server.close()
        await self.server.wait_closed()

    async def new_connection(self, reader, writer):
        loop = asyncio.get_event_loop()
        loop.create_task(Client(self).listen_server(reader, writer))

    def logging(self, message):
        return print(f"INFO [{time.strftime('%X')}] {message}")

    async def _background(self):
        while True:
            self.logging(f"Players online: {len(self.online)}")
            self.logging(
                f"Players registrations: {await self.redis.get('uids')}")
            await asyncio.sleep(60)
        return self.logging("Произошла ошибка, перезапустите сервер!")
コード例 #13
0
class ConfigurationsManager:
    """Mediator to manage the configuration settings."""

    __directories_manager = DirectoriesManager()
    __parser = Parser()

    def setup_default_directories(self, directory) -> None:
        """Wrapper for setting up default directories"""
        return self.__directories_manager.setup_default_directories(directory)

    def make_directory(self, directory, directory_path=None):
        """Wrapper for making directories"""
        if directory_path is None:
            directory_path = self.get_default_directory(DefaultDirectories.OUTPUT)
        return self.__directories_manager.make_directory(directory, directory_path)

    def get_directory(self, directory):
        """Wrapper for retrieving directories"""
        return self.__directories_manager.get_directory(directory)

    def convert_xml_to_dictionary(self, xml):
        """Wrapper for converting xml to dictionary"""
        return self.__parser.convert_xml2dict(xml)

    def get_configuration_settings(self, component, configuration_file) -> dict:
        """Returns the configuration settings for the target component from
         the configuration_file.

        Parameters
        ----------
        component : str
            target component

        configuration_file: str
            configuration file which contains the target component's settings

        Returns
        ------
        component_configurations_dict: dict
            configuration settings for the target component
        """
        # load xml settings for the target component
        component_configurations_xml = self.__load_xml(component,
                                                       configuration_file)
        component_configurations_dict = self.convert_xml_to_dictionary(
            component_configurations_xml)
        return component_configurations_dict

    def __load_xml(self, component, configuration_file):
        """helper function for getting configuration settings of a component"""
        # loads the xml configuration file as an xml.etree.ElementTree
        global_configurations_xml_tree = self.__parser.load_xml(configuration_file)
        # get root element
        root = global_configurations_xml_tree.getroot()
        # find the xml configuration settings for the desired component
        component_configurations_xml = root.find(component)
        if component_configurations_xml is None:
            raise LookupError("configuration settings not found!", component)
        return component_configurations_xml

    def load_log_configurations(self, name, log_configurations,
                                directory=None, directory_path=None) -> Logger:
        """Creates a logger with the specified name and configuration settings.
        The default location will be set for the logs if either directory or
        directory path is not specified.

        Parameters
        ----------
        name : str
            Logger name

        log_configurations: dict
            configuration settings for the logger

        directory: str
            target directory for the logs

        directory_path: str
            target location for the logs directory

        Returns
        ------
        Return a logger
        """
        if directory and directory_path is not None:
            # Case: make directory at the target location for the logs
            target_directory = self.make_directory(directory, directory_path)
        else:
            # Case: if no directory or the directory path is specified,
            # set the default directory for the logs
            target_directory = self.get_directory(directory=DefaultDirectories.LOGS)
        logger = ConfigLogger()
        return logger.initialize_logger(name, target_directory,
                                        configurations=log_configurations)
コード例 #14
0
    def parseTools(self):
        """parse the xml file and generate sql file""" 
        try:
            analytics_tools = Parser.getNodeTag(self, self.xmlDoc, "analytics_tools")
            atList = Parser.getNodeList(self, analytics_tools, "analytics_tool")

            for at in atList:
                atDic = {}
                name = Parser.getNodeVal(self, at, "name")
                kind = Parser.getNodeVal(self, at, "kind")
               
                if kind.lower() in( "greenplum", "postgres"):
                    atDic["name"]           =   Parser.getNodeVal(self, at, "name")
                    atDic["kind"]           =   Parser.getNodeVal(self, at, "kind")
                    atDic["host"]           =   Parser.getNodeVal(self, at, "host")
                    atDic["port"]           =   Parser.getNodeVal(self, at, "port")
                    atDic["superuser"]  =   Parser.getNodeVal(self, at, "superuser")
                    atDic["database"]       =   Parser.getNodeVal(self, at, "database")
                    atDic["username"]       =   Parser.getNodeVal(self, at, "user")
                    atDic["master_dir"]     =   Parser.getNodeVal(self, at, "master_dir")
                    atDic["env"]    =   Parser.getNodeVal(self, at, "env")
                self.analyticsTools[name] = atDic

        except Exception, exp:
            print str(exp)
            print "Error when parsing analyticsTools"
            sys.exit()
コード例 #15
0
ファイル: xml_test.py プロジェクト: elizarov/xgw
"""Tests for XML modules"""

from xml_generator import Generator
from xml_element import Element
from xml_parser import Parser

print Generator([Element("test", dict(a='1', b='2'), [12345])])
assert "<test a='1' b='2'>12345</test>" == str(
    Generator([Element("test", dict(a='1', b='2'), [12345])]))

print Parser(
    "<send dest='FIO1'>!RR\\r\\n</send><recv src='FIO1' wait='1'/>").fragment
assert "<send dest='FIO1'>!RR\\r\\n</send><recv src='FIO1' wait='1'/>" == str(
    Parser("<send dest='FIO1'>!RR\\r\\n</send><recv src='FIO1' wait='1'/>").
    fragment)

print Parser("<send dest='FIO1'>!RR\\r\\n</send>   <recv src='FIO1' wait='1'/>"
             ).fragment
for a in Parser(
        "<send dest='FIO1'>!RR\\r\\n</send>   <recv src='FIO1' wait='1'/>"
).fragment:
    print a.__class__, len(a), str(a)