예제 #1
0
파일: word.py 프로젝트: 13guff13/scripts
    def test_unpack(self):
        "Тест на работу функции unpack"

        import datetime
        today = datetime.date.today().strftime("%Y.%m.%d")
        statistic_in = {
            str(en_to_ru_write): [2, 3, today, False, 30],
            str(ru_to_en_write): [2, 2, today, False, 40]
        }

        st0 = statistic.Statistic()
        st0.update(True, 50)
        st0.update(False, -10)
        st0.update(False, -10)
        st0.update(True, 10)
        st0.update(False, -10)

        st1 = statistic.Statistic()
        st1.update(True, 50)
        st1.update(False, -10)
        st1.update(True, 10)
        st1.update(False, -10)

        self.word.unpack(statistic_in)
        self.assertEqual(self.word.stat[en_to_ru_write], st0)
        self.assertEqual(self.word.stat[ru_to_en_write], st1)
예제 #2
0
파일: word.py 프로젝트: 13guff13/scripts
    def test_init(self):
        "Тест работы конструктора"

        self.assertEqual(self.word.en_word, u"")
        self.assertEqual(self.word.en_source, u"")
        self.assertEqual(self.word.en_word_list, [])
        self.assertEqual(self.word.transcription, u"")
        self.assertEqual(self.word.ru_word, u"")
        self.assertEqual(self.word.ru_word_list, [])
        self.assertEqual(self.word.rating, 0)
        self.assertEqual(len(self.word.stat), 2)
        self.assertEqual(self.word.stat[en_to_ru_write], statistic.Statistic())
        self.assertEqual(self.word.stat[ru_to_en_write], statistic.Statistic())
예제 #3
0
def run_bidirection_l3_perf():
    try:
        fg = flowgen.PktGen("config.json")
        fg.run_pktgen()
        l3 = l3fwd.L3Fwd("config.json")

        pps = statistic.Statistic("config.json")

        for pkt_len in pkt_len_list:
            for core_num in core_list:
                fg.set_pktgen_range(pkt_len)
                l3.run_l3fwd(core_num)
                fg.start_pktgen('all')
                # waiting to reach max pps
                time.sleep(5)
                pps.start_statistic(core_num, pkt_len)
                # time of testing duration
                fg.wait_test_period()
                pps.stop_statistic()
                fg.stop_pktgen('all')
                l3.stop_l3fwd()

        fg.quit_pktgen()
        file_name = os.path.splitext(__file__)[0]
        print(file_name)
        file_name_array = file_name.split("\\")
        print(file_name_array)
        print(file_name_array[-1])
        now = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
        file_name = 'bidirection_' + str(file_name_array[-1]) + '_mpps_' + now
        pps.save_to_csv(file_name)
    finally:
        fg.quit_pktgen()
        l3.stop_l3fwd()
def main():
    parser = argparse.ArgumentParser("Print the statistic result")
    parser.add_argument("cmd",
                        choices=["summary", "sample", "latex"],
                        help="summary: show summary data")
    parser.add_argument("--database", help="slqite database")
    parser.add_argument("--latexData",
                        default="../data/latexData/data.csv",
                        help="latex data generated from R")

    categoryList = [
        "accessibility", "blogging", "bygoogle", "communication", "fun",
        "news", "photos", "productivity", "searchTool", "shopping", "sports",
        "webDevelopment"
    ]
    try:
        args = parser.parse_args()
        if args.cmd == "summary":
            statistic.summary()
            statistic.category_stat()
        elif args.cmd == "sample":
            statistic.SqliteStat(args.database).createSamepleTables()
        elif args.cmd == "latex":
            format_str = "\\newcommand{{\\{0}}}{{{1}}}"
            with open(args.latexData, 'rb') as csvfile:
                spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
                for row in list(spamreader)[1:]:
                    print format_str.format(row[1], row[2])
            s = statistic.Statistic()
            srcDb = statistic.SqliteStat(args.database)
            with open("../data/latexData/TopRemoteDomain.csv") as csvfile:
                data = csv.reader(csvfile, delimiter=',', quotechar='"')
                data = [{"name": x[1], "c": x[3]} for x in data]
                print(
                    srcDb.latexTable(
                        data, "Top Hosts in Remote JavaScript Inclusion",
                        "top_hosts"))
            with open(
                    "../data/latexData/TopLibraryRemoteDomain.csv") as csvfile:
                data = csv.reader(csvfile, delimiter=',', quotechar='"')
                data = [{"name": x[1], "c": x[3]} for x in data]
                print(
                    srcDb.latexTable(
                        data,
                        "Top Hosts in Remote JavaScript Library Inclusion",
                        "top_hosts_library"))
            # print srcDb.latexCategoryTable
            # print srcDb.latexLanguageTable
            # print srcDb.JavaScriptNumberLatexTable

            # pprint(srcDb.IPSrcJS)
            # pprint(srcDb.extensionWithLocalhostJSInclusion)

            srcDb.cleanUp()
        else:
            print "unknow command"
    except Exception as e:
        print e
        sys.exit()
예제 #5
0
파일: word.py 프로젝트: 13guff13/scripts
 def __init__(self):
     # Английское слово, которое будет отображаться пользователю
     self.en_word = ""
     # Исходное английское слово, без преобразований
     self.en_source = ""
     # Распарсенное английское слово
     self.en_word_list = []
     # Транскрипция
     self.transcription = ""
     # Массив русских слов, без преобразований
     self.ru_source = []
     # Русское слово, которое будет отображаться пользователю
     self.ru_word = ""
     # Распарсенное русское слово
     self.ru_word_list = []
     # Рейтинг слова, влияет на вероятность появления его в упражнении
     self.rating = 0
     # Ссылка на статистику по слову
     self.stat = {
         en_to_ru_write: statistic.Statistic(),
         ru_to_en_write: statistic.Statistic()
     }
예제 #6
0
 def reflect_ball_by_platform(self):
     if self.ball.right < self.platform.LEFT_COORD or \
             self.ball.left > self.platform.RIGHT_COORD:
         self.multiplier = 1.0
         if not self.ball_cant_drop:
             self.eps = 1.0
             self.score -= int(self.score // 5)
             self.life -= 1
             if self.life == 0:
                 pygame.mixer.music.stop()
                 if not self.custom:
                     stats = statistic.Statistic(
                         str(self.current_level_index - 1), self.score)
                     stats.draw_stats()
                 menu.Menu()
             else:
                 self.ball.reincarnate()
         else:
             self.ball.speed[1] = -self.ball.speed[1]
         return
     self.score += int(10 * self.multiplier)
     self.multiplier = 1.0
     if self.ball.x < self.platform.LEFT_COORD:
         self.ball.speed[0] = -self.ball.basic_speed
         self.ball.speed[1] = -self.ball.basic_speed
     elif self.ball.x > self.platform.RIGHT_COORD:
         self.ball.speed[0] = self.ball.basic_speed
         self.ball.speed[1] = -self.ball.basic_speed
     else:
         middle = self.platform.WIDTH // 2
         pos = self.ball.x - self.platform.LEFT_COORD
         if pos < middle:
             angle = -1 + (pos / middle)
             self.ball.speed[0] = angle
         else:
             angle = (pos / middle) - 1
             self.ball.speed[0] = angle
         self.ball.speed[1] = \
             -math.sqrt(2 - math.pow(self.ball.speed[0], 2))
     print(self.ball.speed)
예제 #7
0
def main():
    """ Definování všech parametrů pro spouštění různých částí programu"""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest="command")
    parser_graph = subparsers.add_parser('graph')
    parser_graph.add_argument("draw_graph", type=str, nargs=2, default=0,
                              help="Give two charges results file, if you have not it, you can used CALCULATION")
    parser_calculate = subparsers.add_parser('calculation')
    parser_calculate.add_argument('calculate', type=str, nargs="?", default=0,
                                  help="Give one file with molecules (.sdf) for mgcm and "
                                       "one file with parameters for EEM (.xml)")
    parser_calculate.add_argument('--eem', action="store_true",
                                  help="Give this argument, if you want calculate with EEM")
    parser_calculate.add_argument('--mgc', action="store_true",
                                  help="Give this argument, if you want calculate with MGC")
    parser_calculate.add_argument('--ogc', action="store_true",
                                  help="Give this argument, if you want calculate with OGC")
    parser_calculate.add_argument('--parameters', type=str, help="Give this argument for parameters,"
                                                                 " if you want calculate with EEM")
    parser_calculate.add_argument('--output', type=str, help="Give a name file, for output calculate")
    parser_structure = subparsers.add_parser('structure')
    parser_structure.add_argument('--parameters', type=str, help="Give a file with parameters (EEM) (.xml)")
    parser_structure.add_argument('--molecules', type=str, help="Give a file with molecules (.sdf)")
    parser_structure.add_argument('--nobond', action="store_false",
                                  help="Give this argument, if you want not type bond.")
    args = parser.parse_args()
    try:
        if args.calculate:  # počítaní
            mset = classes.MoleculesSet()
            """eem.py"""
            if args.eem:
                set_file, para_file = args.calculate, args.parameters
                mset.load_parameters(para_file)  # načtení parametrů
                mset.load_from_sdf(set_file, args.eem, args.mgc, args.ogc)  # načtení molekuly
                cal = eem.Calculate(mset.molecules, mset.parameters)  # výpočet pomocí EEM
                """
                Parametry --eem, --mgc,  --ogc jsou boolean parametry
                """
            else:
                set_file = args.calculate
                mset.load_from_sdf(set_file, args.eem, args.mgc, args.ogc)  # načtení molekuly
            """mgcm.py"""
            if args.mgc:
                cal = mgcm.Calculate(mset.molecules, mset.periodic_table)  # výpočet pomocí MGC
            """ogcm.py"""
            if args.ogc:
                cal = ogcm.Calculate(mset.molecules)  # výpočet pomocí OGC
            if args.output:  # pro zadání uložení do souboru --output
                charge = cal
                charge.save_charges(args.output)
    except AttributeError:
        pass
    try:
        """statistic.py """
        if args.molecules:  # vypsání struktury molekul
            stat = statistic.Statistic()
            mset = classes.MoleculesSet()
            mset.load_from_sdf(args.molecules, True, False, False, args.nobond)  # True aby se chovalo jako při --eem
            stat.get_statistic_from_set(args.molecules, mset.molecules, args.nobond)  # vypsání struktury
        if args.parameters:  # vypsání struktury parametrů
            mset = classes.MoleculesSet()
            mset.load_parameters(args.parameters)  # načtení parametrů
            stat = statistic.Statistic()
            stat.get_statistic_from_parameters(args.parameters, mset.parameters)  # vypsání struktury
    except AttributeError:
        pass
    try:
        """graph.py"""
        if args.draw_graph:  # vytvoření grafu a statistických výpočtů
            graph.Graph(args.draw_graph)
    except AttributeError:
        pass
예제 #8
0
    def __init__(self,
                 mode_hiders,
                 mode_seekers,
                 num_hiders,
                 num_seekers,
                 map_id,
                 input_file,
                 output_file,
                 conf_options,
                 log_flag,
                 vis_flag,
                 total_step_times,
                 sim_turn,
                 max_steps=1000,
                 window_width=640,
                 window_height=360):
        assert (mode_hiders in Simulator.mode_type_hiders)
        assert (mode_seekers in Simulator.mode_type_seekers)

        self.__mode_hiders = mode_hiders
        self.__mode_seekers = mode_seekers
        self.__num_hiders = num_hiders
        self.__num_seekers = num_seekers
        self.__map_id = map_id
        self.__input_file = input_file
        self.__output_file = output_file

        self.__conf_options = conf_options
        self.__fps = self.__conf_options.get_fps()
        self.__velocity = self.__conf_options.get_velocity()
        self.__fixed_time_quanta = self.__conf_options.get_fixed_time_quanta()
        self.__verbose = self.__conf_options.get_verbose()
        self.__num_rays = self.__conf_options.get_num_rays()
        self.__visibility_angle = self.__conf_options.get_visibility_angle()
        self.__show_fellows = self.__conf_options.get_show_fellows()
        self.__show_opponent = self.__conf_options.get_show_opponent()

        self.__sim_turn = sim_turn
        self.__stats = statistic.Statistic(num_hiders, num_seekers,
                                           self.__map_id, self.__sim_turn)
        self.__max_steps = max_steps
        self.__steps = 0
        self.__polygon_map = gamemap.PolygonMap(map_id)

        self.__log_flag = log_flag
        self.__vis_flag = vis_flag
        self.__replay_output_file = None

        self._total_step_times = total_step_times

        if log_flag:
            print('Logging initiated:', output_file)
            self.__replay_output_file = open(output_file, 'w')
            self.__replay_output_file.write('map_id:' + str(map_id) + '\n')
            self.__replay_output_file.write('num_hiders:' + str(num_hiders) +
                                            '\n')
            self.__replay_output_file.write('num_seekers:' + str(num_seekers) +
                                            '\n')
            self.__replay_output_file.write('simulation:' + '\n')

        hider_map_copy = gamemap.PolygonMap(map_id)
        seeker_map_copy = gamemap.PolygonMap(map_id)

        # AI setup
        if mode_hiders == 'random':
            self.__hider_team = team.RandomTeam(agent.AgentType.Hider,
                                                num_hiders, hider_map_copy,
                                                self.__fps, self.__velocity,
                                                self.__fixed_time_quanta)
        elif mode_hiders == 'bayesian':
            self.__hider_team = team.BayesianTeam(agent.AgentType.Hider,
                                                  num_hiders, hider_map_copy,
                                                  self.__fps, self.__velocity,
                                                  self.__fixed_time_quanta)
        elif mode_hiders == 'sbandit':
            self.__hider_team = team.UCBPassiveTeam(
                agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps,
                self.__velocity, self.__fixed_time_quanta, self.__num_rays,
                self.__visibility_angle, False, False)
        elif mode_hiders == 'hm_sbandit':
            self.__hider_team = team.UCBPassiveTeam(
                agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps,
                self.__velocity, self.__fixed_time_quanta, self.__num_rays,
                self.__visibility_angle, True, False)
        elif mode_hiders == 'hv_sbandit':
            self.__hider_team = team.UCBPassiveTeam(
                agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps,
                self.__velocity, self.__fixed_time_quanta, self.__num_rays,
                self.__visibility_angle, False, True)
        elif mode_hiders == 'hmv_sbandit':
            self.__hider_team = team.UCBPassiveTeam(
                agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps,
                self.__velocity, self.__fixed_time_quanta, self.__num_rays,
                self.__visibility_angle, True, True)
        elif mode_hiders == 'human':
            self.__hider_team = team.HumanRandomTeam(
                agent.AgentType.Hider, num_hiders, hider_map_copy, self.__fps,
                self.__velocity, self.__fixed_time_quanta)
        elif mode_hiders == 'offset':
            self.__hider_team = team.OffsetTeam(agent.AgentType.Hider,
                                                num_hiders, hider_map_copy,
                                                self.__fps, self.__velocity,
                                                self.__fixed_time_quanta)

        if mode_seekers == 'random':
            self.__seeker_team = team.RandomTeam(agent.AgentType.Seeker,
                                                 num_seekers, seeker_map_copy,
                                                 self.__fps, self.__velocity,
                                                 self.__fixed_time_quanta)
        elif mode_seekers == 'sbandit':
            self.__seeker_team = team.UCBAggressiveTeam(
                agent.AgentType.Seeker, num_seekers, seeker_map_copy,
                self.__fps, self.__velocity, self.__fixed_time_quanta,
                self.__num_rays, self.__visibility_angle)
        elif mode_seekers == 'coverage':
            self.__seeker_team = team.UCBCoverageTeam(
                agent.AgentType.Seeker, num_seekers, seeker_map_copy,
                self.__fps, self.__velocity, self.__fixed_time_quanta,
                self.__num_rays, self.__visibility_angle)
        elif mode_seekers == 'cc':
            self.__seeker_team = team.UCBCoverageCommunicationTeam(
                agent.AgentType.Seeker, num_seekers, seeker_map_copy,
                self.__fps, self.__velocity, self.__fixed_time_quanta,
                self.__num_rays, self.__visibility_angle)
        elif mode_seekers == 'human':
            self.__seeker_team = team.HumanRandomTeam(
                agent.AgentType.Seeker, num_seekers, seeker_map_copy,
                self.__fps, self.__velocity, self.__fixed_time_quanta)
        elif mode_seekers == 'wave':
            self.__seeker_team = team.WaveTeam(agent.AgentType.Seeker,
                                               num_seekers, seeker_map_copy,
                                               self.__fps, self.__velocity,
                                               self.__fixed_time_quanta,
                                               self.__num_rays,
                                               self.__visibility_angle)
        elif mode_seekers == 'trap':
            self.__seeker_team = team.TrapTeam(agent.AgentType.Seeker,
                                               num_seekers, seeker_map_copy,
                                               self.__fps, self.__velocity,
                                               self.__fixed_time_quanta,
                                               self.__num_rays,
                                               self.__visibility_angle)

        # Graphics setup
        self.__window_width = self.__polygon_map.get_map_width()
        self.__window_height = self.__polygon_map.get_map_height()
        self.__texture_flag = self.__conf_options.get_texture_flag()
        dynamic_batching_flag = True
        show_hiders_flag = True
        show_seekers_flag = True
        if mode_hiders == 'human':
            dynamic_batching_flag = False
            show_seekers_flag = self.__show_opponent
        if mode_seekers == 'human':
            dynamic_batching_flag = False
            show_hiders_flag = self.__show_opponent
        if self.__vis_flag:
            self.__window = graphics.Graphics(
                self.__window_width, self.__window_height, num_hiders,
                num_seekers, self.__polygon_map, self.__conf_options,
                dynamic_batching_flag, show_hiders_flag, show_seekers_flag,
                self.__texture_flag)
        else:
            self.__window = None

        # Movers setup
        self.__hiders = [
            Mover(self.__polygon_map, 0, 0, 0, self.__fps, self.__velocity,
                  self.__fixed_time_quanta, self.__num_rays,
                  self.__visibility_angle) for i in range(num_hiders)
        ]
        self.__seekers = [
            Mover(self.__polygon_map, 0, 0, 0, self.__fps, self.__velocity,
                  self.__fixed_time_quanta, self.__num_rays,
                  self.__visibility_angle) for i in range(num_seekers)
        ]

        # Mover active list
        self.__hiders_active = [True for i in range(num_hiders)]
        self.__seekers_active = [True for i in range(num_seekers)]

        # Mapping AI agents and Graphics players for interchange of percepts and
        # actions
        self.__hiders_agent2player = {}
        self.__hiders_player2agent = [None for i in range(self.__num_hiders)]
        counter = 0
        for i in range(self.__hider_team.get_ranks()):
            for j in range(self.__hider_team.get_num_rankers(i)):
                rank, ai_idx = i, j
                graphics_idx = counter
                self.__hiders_agent2player[(rank, ai_idx)] = graphics_idx
                self.__hiders_player2agent[graphics_idx] = (rank, ai_idx)
                counter += 1

        self.__seekers_agent2player = {}
        self.__seekers_player2agent = [None for i in range(self.__num_seekers)]
        counter = 0
        for i in range(self.__seeker_team.get_ranks()):
            for j in range(self.__seeker_team.get_num_rankers(i)):
                rank, ai_idx = i, j
                graphics_idx = counter
                self.__seekers_agent2player[(rank, ai_idx)] = graphics_idx
                self.__seekers_player2agent[graphics_idx] = (rank, ai_idx)
                counter += 1

        # Initializing the caught list by setting all hiders as NOT CAUGHT
        # self.__caught = [[False for j in range(self.__hider_team.get_num_rankers(i))] for i in range(self.__hider_team.get_ranks())]
        self.__num_caught = 0
        self.__total_time = 0
예제 #9
0
    def __init__(self, id=1, score=0, life=3, f=None, map=None):
        self.custom = False
        if map is not None:
            self.current_level_index = "Custom.{0}".format(map)
            self.custom = True
            self.life = life
            self.score = score
            self.multiplier = 1.0
            self.map = m.Map(map)
            self.current_level = self.map.map
            self.field_width = len(self.current_level[0]) * 20 - 20
            self.win_width = self.field_width + 150
            self.win_height = len(self.current_level) * 20
            self.blocks = self.map.blocks
            self.platform = pl.Platform(self.field_width)
            self.ball = b.Ball(self.field_width, self.win_height)
        elif f is not None:
            args = f.split(";")
            if args[0][:6] == "Custom":
                self.custom = True
            if not self.custom:
                self.current_level_index = int(args[0])
                try:
                    self.map = m.Map("Levels/level" +
                                     str(self.current_level_index) + ".txt")
                except:
                    stat = statistic.Statistic(
                        "{0}".format(self.current_level_index), self.score)
                    stat.draw_stats()
            else:
                self.map = m.Map(args[0][7:])
            self.score = int(args[1])
            self.life = int(args[2])
            self.multiplier = float(args[3])

            self.current_level = self.map.map
            self.field_width = len(self.current_level[0]) * 20 - 20
            self.win_width = self.field_width + 150
            self.win_height = len(self.current_level) * 20
            self.platform = pl.Platform(self.win_width, float(args[4]),
                                        float(args[5]))
            b_args = args[6].split(',')
            self.ball = b.Ball(self.field_width, self.win_height,
                               float(b_args[0]), float(b_args[1]),
                               float(b_args[2]), float(b_args[3]),
                               float(self.win_height - 50), float(b_args[4]))
            self.blocks = []
            for i in range(7, len(args)):
                if args[i] == '':
                    break
                block_args = args[i].split(',')
                self.blocks.append(
                    bl.Block(int(block_args[0]), int(block_args[1]),
                             int(block_args[2])))
        else:
            self.current_level_index = id
            self.life = life
            self.score = score
            self.multiplier = 1.0
            try:
                self.map = m.Map("Levels/level" +
                                 str(self.current_level_index) + ".txt")
            except:
                stat = statistic.Statistic(
                    "{0}".format(self.current_level_index - 1), self.score)
                stat.draw_stats()
            self.current_level = self.map.map
            self.field_width = len(self.current_level[0]) * 20 - 20
            self.win_width = self.field_width + 150
            self.win_height = len(self.current_level) * 20
            self.blocks = self.map.blocks
            self.platform = pl.Platform(self.field_width)
            self.ball = b.Ball(self.field_width, self.win_height)
        self.active_bonuses = []
        self.display = (self.win_width, self.win_height)
        self.background_color = "#001a82"
        self.border_color = "#000e47"
        self.on_pause = False
        self.lose = False
        self.screen = pygame.display.set_mode(self.display)
        self.bg = pygame.Surface(self.display)
        self.timer = pygame.time.Clock()
        self.ctrl_pressed = False
        self.ball_cant_drop = False
예제 #10
0
파일: word.py 프로젝트: 13guff13/scripts
 def unpack(self, statistic):
     for it in statistic:
         it_int = int(it)
         if it_int not in self.stat.keys():
             self.stat[it_int] = statistic.Statistic()
         self.stat[it_int].unpack(statistic[it])