def main(argv): if not check_args(argv): return client = False player_type = argv[PLAYER_TYPE_ARGUMENT] port = int(argv[PORT_ARGUMENT]) if len(argv) == 4: ip = argv[IP_ARGUMENT] client = True game = Game() root = Tk() if player_type == AI_ARGUMENT: ai = AI() if client: communicator = Communicator(root, port, ip) player = game.PLAYER_TWO else: communicator = Communicator(root, port) player = game.PLAYER_ONE if player_type == HUMAN_ARGUMENT: GUI(root, game, communicator, player) else: GUI(root, game, communicator, player, ai) communicator.connect() root.mainloop()
def setup_train(args, machine_is_host=False): # set_up_gpu(args) exp_root, exp_group, exp_name = args.experiment_root, args.experiment_group, args.experiment_name assert exp_name is not None local_export_root = os.path.join(exp_root, exp_group, exp_name) if machine_is_host: remote_export_root = None communicator = None if os.path.exists(local_export_root): if exp_group == 'test': print('Removing local test export root {}'.format( local_export_root)) shutil.rmtree(local_export_root) else: print('Local export root exists {}'.format(local_export_root)) exit(0) create_local_export_root(args, local_export_root) export_config(args, local_export_root) print('Export root', local_export_root) else: remote_export_root = os.path.join(REMOTE_ROOT, local_export_root) communicator = Communicator(HOST, PORT, USERNAME, PASSWORD) created = communicator.create_dir(remote_dir_path=remote_export_root) if not created: if os.path.exists(local_export_root): print('Local export root exists while checking status') exit(0) os.makedirs(local_export_root) local_status = os.path.join(local_export_root, 'status.txt') remote_status = os.path.join(remote_export_root, 'status.txt') try: communicator.sftp.get(remote_status, local_status) status = open(local_status).readline() except Exception: status = 'failed to download status' print('Checking status') if status == STATUS_RECOVERY: print('Status is recovery') with open(local_status, 'w') as f: f.write('running\n') print("Write 'running' on remote") communicator.sftp.put(local_status, remote_status) print('Downloading remote export root') communicator.download_dir(remote_export_root, local_export_root) args.resume_training = True else: print('Status is not recovery') shutil.rmtree(local_export_root) print('Remote export root {} exists. Existing'.format( remote_export_root)) exit(0) else: print( 'Created export_root={} in remote'.format(remote_export_root)) create_local_export_root(args, local_export_root) export_config(args, local_export_root) print('Export root', local_export_root) return local_export_root, remote_export_root, communicator
def __init__(self, root, port, player, ip=None, ai=None): self.root = root self.player = player self.game = Game() self.ai = ai self.__communicator = Communicator(root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message) self.pattern = tk.PhotoImage(file=PATTERN_IMAGE) self.red = tk.PhotoImage(file=RED_TOKEN_IMAGE) self.blue = tk.PhotoImage(file=BLUE_TOKEN_IMAGE) self.player_one = tk.PhotoImage(file=PLAYER_ONE_IMAGE) self.player_two = tk.PhotoImage(file=PLAYER_TWO_IMAGE) self.blue_win = tk.PhotoImage(file=BLUE_WIN_IMAGE) self.red_win = tk.PhotoImage(file=RED_WIN_IMAGE) self.no_win = tk.PhotoImage(file=NO_WINNER_IMAGE) self.illegal = tk.PhotoImage(file=ILLEGAL_ACTION_IMAGE) self.wait = tk.PhotoImage(file=WAIT_IMAGE) self.win_symbol = tk.PhotoImage(file=WIN_SYMBOL_IMAGE) self.canvas = tk.Canvas(self.root, width=CANVAS_WIDTH, height=CANVAS_HEIGHT) self.canvas.pack() self.canvas.create_image(0, 0, anchor=tk.NW, image=self.pattern) self.canvas.bind('<Button-1>', self.callback) if ip is None and self.ai: column = self.ai.find_legal_move(self.game, self.update) self.__communicator.send_message(column)
def create_communicator_from_configuration( communicator_configuration, meta_data_provider=None, connection=None, authenticator=None, marshaller=DefaultMarshaller.INSTANCE()): """ Creates a Communicator based on the configuration stored in the CommunicatorConfiguration argument """ # If an authenticator is not given, api_key_id and secret_api_key are # used to create a DefaultAuthenticator used to create the communicator. if connection is None: connection = DefaultConnection( connect_timeout=communicator_configuration.connect_timeout, socket_timeout=communicator_configuration.socket_timeout, max_connections=communicator_configuration.max_connections, proxy_configuration=communicator_configuration. proxy_configuration) if authenticator is None: authenticator = DefaultAuthenticator( api_key_id=communicator_configuration.api_key_id, secret_api_key=communicator_configuration.secret_api_key, authorization_type=communicator_configuration. authorization_type) if meta_data_provider is None: meta_data_provider = MetaDataProvider( integrator=communicator_configuration.integrator, shopping_cart_extension=communicator_configuration. shopping_cart_extension) return Communicator( api_endpoint=communicator_configuration.api_endpoint, authenticator=authenticator, connection=connection, meta_data_provider=meta_data_provider, marshaller=marshaller)
def record(host, port): positions = [] try: print('Start recording') com = Communicator(host, port) while True: position_data = com.get_position_data() x = position_data['Pose']['Position']['X'] y = position_data['Pose']['Position']['Y'] if len(positions) == 0: positions.append(position_data) else: last_position_data = positions[len(positions) - 1] last_x = last_position_data['Pose']['Position']['X'] last_y = last_position_data['Pose']['Position']['Y'] if distance_between_two_points(x, y, last_x, last_y) > 0.01: #m positions.append(position_data) except KeyboardInterrupt: print('Stopped recording') filename = 'Path-' + datetime.now().strftime( '%y.%m.%d-%M.%S') + '.json' with open(filename, 'w+') as f: json.dump(positions, f) print('Saved path to file: ' + filename)
def __init__(self, player, port, server, ip=None): """ a constructor of the graphics of the game :param player: either human of computer :param port: a number between 1000 and 65535 :param server: a boolean value that is True for the server and False for the client. :param ip: None for the server and an ip for the client """ self.game = Game() self.ai = ai.AI() self.root = tk.Tk() self.frame = tk.Frame(self.root, height=self.FRAME_HEIGHT, width=self.FRAME_WIDTH) self.game_board = tk.Canvas(self.frame, bg=self.CANVAS_BACKGROUND, height=self.BOARD_HEIGHT, width=self.BOARD_WIDTH) self.game_board.pack() self.game_board.place(x=200, y=50) self.__communicator = Communicator(self.root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.handle_message) self.player = player self.server = server
def __init__(self, locale='en_US', songs_in='test_songs', songs_out='songs_out'): self.name = 'music-sheet-maker' self.locale = self.set_locale(locale) self.communicator = Communicator(owner=self, locale=self.locale) self.song = None self.song_parser = None self.directory_base = os.path.normpath( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) self.song_dir_in = os.path.join(self.directory_base, songs_in) self.song_dir_out = os.path.join(self.directory_base, songs_out) self.css_path = os.path.normpath( os.path.join(self.directory_base, "css/main.css")) #TODO: move that into Renderer self.rel_css_path = os.path.relpath(self.css_path, start=self.song_dir_out) self.css_mode = CSSMode.EMBED #TODO: move that into Renderer self.render_modes_enabled = [mode for mode in RenderMode] # self.render_modes_disabled = [RenderMode.JIANPUASCII, RenderMode.DOREMIASCII] self.render_modes_disabled = [] self.render_modes_enabled = [ mode for mode in self.render_modes_enabled if mode not in self.render_modes_disabled ] self.botcog_render_modes = [RenderMode.PNG] self.website_render_modes = [RenderMode.HTML]
def main(): options = input(MENU_TEXT) c = Communicator() if options == "1": to_send = input("Type what you want to send\n> ") # turn input into dict to pass through request.post() as json # conversion between dict and json is automatic to_send = {"entry_string": to_send} c.send_recieve(to_send) elif options == "2": print("Type what you want to send. \nType 'q' to quit.") while True: to_send = input("\n> ") if to_send == "q": quit() # turn input into dict to pass through request.post() as json # conversion between dict and json is automatic to_send = {"entry_string": to_send} c.send_recieve(to_send) elif options == "3": c.read_last() elif options == "0": quit() else: print("Option not recognised. Try again.") main()
def __init__(self, root, ip, port, server, is_human): """ the game starts with a board (from class Game), creates canvas with all the images needed, and starts a communicator object :param root: the Tk 'parent' object :param ip: servers ip :param port: the game port :param server: True or False """ self.__board = Game() self.__root = root self.__is_human = is_human self.__coconut_img, self.__pineapple_img, self.__background_img, \ self.__winner_img, self.__illegal_img = self.create_images() self.__col_lst = [] # used for the indicator self.__indicator = self.OFF # a 'switch' for the indicator self.__illegal_sign = self.OFF # counter for illegal move sign self.__canvas, self.__title, self.__second_title = self.create_canvas( self.__background_img) self.__communicator = Communicator(root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message) self.__is_playing = server if self.__is_human == COMPUTER: self.__ai = AI() self.initialization()
def __init__(self, root, player, port, ip=None): """ Initialize GUI and connect the communicator :param root: The tkinter root :param player: An integer representing if the player is human or ai :param port: The port to connect to :param ip: The ip to connect to """ self.__root = root self.__game = Game() self.__bottoms = self.__game.get_board().get_bottoms() self.__communicator = Communicator(root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message) self.__top_frame = tk.Frame(self.__root) self.__top_frame.pack() self.__col_frames = [] self.__buttons = [] self.__player = GUI.P1 self.__opponent = GUI.P2 if ip is not None: self.__player, self.__opponent = self.__opponent, self.__player self.__msg_board = tk.Message(root, font=GUI.FONT, fg=GUI.MSG_COLOR) self.__msg_board.pack() self.__images = [] self.__load_images() self.__place_widgets() self.__ai = None if player == GUI.AI: self.__ai = AI() self.__start_game()
def create_communicator_from_configuration(communicator_configuration): """ Create a Communicator based on the configuration stored in the CommunicatorConfiguration argument """ session = Factory.create_session_from_configuration( communicator_configuration) return Communicator(session, DefaultMarshaller.INSTANCE())
def main(strategy_str: 'str', df: 'object'): # Read the level data from server. com = Communicator() com.ReadServerMessage() # Create a plan to solve the level. TimeTracker.startTimer("Planning") planner = Plan(com.starting_state, com.goal_state, strategy_str) # Solve the level (resolve the plan and get a path from initial state to goal state). commands = planner.resolve() TimeTracker.stopTimer("Planning") TimeTracker.printTimes() for command in commands: print(str(command.jointaction), file=sys.stderr, flush=True) # Write results in CSV file if needed if df is not None: df = df.append( { 'level': com.level_name, 'strategy': strategy_str, 'num_agents': len(planner.start_state.agents), 'num_boxes': len(planner.start_state.boxes), 'num_colors': len(set(planner.start_state.colors.values())), 'solved': 1, 'num_steps': len(commands), 'runtime': planner.strategy.time_spent(), 'explored': planner.strategy.explored_count(), 'frontier': planner.strategy.frontier_count(), 'generated': planner.strategy.explored_count() + planner.strategy.frontier_count(), 'mem': configuration.get_memory_usage() }, ignore_index=True) # Send actions to server. com.send_commands_to_server(commands) # Level completed! return df
def __init__(self): """ The constructor function of the main server. """ self.streamer_socket = socket.socket() self.online_users = {} # {socket: display resolution}. self.communicator = Communicator() self.screenshot = Screenshot() self.running = True
def init_communicator(self): port = self.ui.lineEdit_2.text() self.communicator = Communicator(int(port)) self.communicator.start_listen() self.communicator.generateRSAkey(port) self.ui.lineEdit_3.setText(self.communicator.IP) self.ui.lineEdit_3.setReadOnly(True) self.thread_update.start()
def __init__(self): """ the constructor function of the client. """ self.client_socket = socket.socket() # the socket of the client. self.communicator = Communicator() self.events_handler = EventsHandler(self.client_socket) self.running = True self.display_resolution = DEFAULT_DISPLAY_RESOLUTION self.screen = self.get_display()
def create_communicator_from_file(configuration_file_name, api_key_id, secret_api_key): """ Creates a Communicator based on the configuration values in configuration_file_name, api_key_id and secret_api_key. """ configuration = Factory.create_configuration(configuration_file_name, api_key_id, secret_api_key) session = Factory.create_session_from_configuration(configuration) return Communicator(session, DefaultMarshaller.INSTANCE())
def __init__(s, tag1, tag2): s.communicator = Communicator() s.__peers_in_shard = {} s.__nodes_peers = 2 s.__all_ids = s.communicator.comm.recv(source=0, tag=tag1) nodes_per_rank = s.communicator.comm.recv(source=0, tag=tag2) shard_nodes_ids = [] for i in range((s.communicator.rank - 1) * nodes_per_rank, s.communicator.rank * nodes_per_rank): shard_nodes_ids.append(s.__all_ids[i]) for node in shard_nodes_ids: s.__peers_in_shard[node] = sample((set(shard_nodes_ids)-{node}), s.__nodes_peers)
def test_getting_data(self): robot = Robot("13329.12900.12213", "123", name="HappyBot") robot.set_energy(124) robot.set_honor(7) robot.set_life(3) robot.set_has_water(True) plant = Plant() plant.set_age(64) plant.set_water_level(98) database = MemcachedDatabase() database.add_robot(robot, (6, 11)) square = database.get_square((5, 11), for_update=True) square.set_plant(plant) database.commit() expected_result = { "5,11": { "surface_type": MapSquareTypes.SOIL, "plant": { "water_level": 98, "matured": True, "age": 64 }, "robot": None }, "6,11": { "surface_type": MapSquareTypes.SOIL, "plant": None, "robot": { "name": "HappyBot", "has_water": True, "energy": 124, "life": 3, "honor": 7 } }, "6,2": { "surface_type": MapSquareTypes.ROCK, "robot": None, "plant": None } } communicator = Communicator() result = communicator.execute_command("NhdEr32Qcmp0Iue3", "map_data", expected_result.keys()) self.assertCountEqual(result, expected_result) for expected_key, expected_value in expected_result.items(): self.assertDictEqual(result[expected_key], expected_value)
def __init__(self, parent, port, is_ai, game, ip=None): """ constructor of Gui :param parent: root of the platform :param port: to conect :param is_ai: True if this player is the computer :param ip: of the server. """ # self.game = game self.best_ai_move = self.BEST_AI_DEFAULT self.ip = ip # server begins the game if not ip: self.__my_turn = True else: self.__my_turn = False # initial interface self._parent = parent self._canvas = tk.Canvas(parent, width=self.CANVAS_SIZE, height=self.CANVAS_SIZE, bg=self.BACKGROUND_COL) self._disc_places = [] self._prepeare_canvas() if is_ai: self.is_ai = True self.ai = AI() else: self.is_ai = False self._canvas.bind("<Button-1>", self.click_bind) self._canvas.pack() # communication: self.__communicator = Communicator(parent, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message) # if self is server and ai then responds immediately if is_ai and not ip: self.modify_my_turn(True) self.respond() if not is_ai: self.__put_labal()
def __init__(self, path_file_name, host="localhost", port="50000"): self._communicator = Communicator(host, port) self._time_for_new_carrot = 0 self._path = Path(path_file_name) self._path_tracker = PathTracker(self._path, self._communicator) self._TARGET_SPEED = 1 self._MAX_TURNING_SPEED = 2 self._turning_to_find_point = None self._TURNING_TO_FIND_POINT_TIME = 7 print('Starting robot on host {}:{}'.format(host, port))
def __init__(self, parent, player, port, ip=None): """Instructor of FourInARow object""" self._end_game = False self.__init_graphics__() self._game = Game() self._root = parent self._status = None self._player = player self.__init__ai_or_human() self.__init__ip_distinguisher(ip) self.__communicator = Communicator(self._root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message)
def main(): signal.signal(signal.SIGUSR1, handle_pdb) print(os.getpid()) comm = Communicator(num_processes=1) master = MasterProcess(comm, reload=False) slave = SlaveThread(comm, 0, reload=True) comm.start() comm.create_shm() slave.start() master.reproduce_loop() slave.join()
def downloadFile(): print(request.get_json()) response_data = {} filename = request.json['filename'] # At this point, we call the database and query against emoji_name for # the response_data parameters # For now, we use random values c = Communicator() if (not c.get_user_list(filename)): response_data['error'] = 'No users found' return json.dumps(response_data)
def main(): set_logging() bot = aiogram.Bot(BOT_TOKEN) dispatcher = aiogram.Dispatcher(bot) aggregator = Aggregator(rapidapi_key=RAPIDAPI_KEY) asyncio.run(aggregator.load_sources()) dispatcher.loop.create_task(aggregator.update_periodically()) communicator = Communicator(aggregator) register_handlers(communicator, dispatcher) run(dispatcher)
async def apply(host='localhost', port='5432'): # this should be simplified into a one line declaration of Store or # some subclass or composition, then pass the single arg to server store = Store() communicator = Communicator(store) interpreter = Interpreter(store) # this could probably be simplified by giving manager a default # value in Service server = Server(host, port, interpreter, communicator) manager = Manager() service = Service(manager, server) await service.run()
def run(self): print(SYS_INIT_ING) cmnct = Communicator(self.__is_ps, self.__ps_host) enum, eva = _module_init() if self.__is_ps: print(SYS_I_AM_PS) return self._ps_run(enum, eva, cmnct) else: print(SYS_I_AM_WORKER) self._worker_run(eva, cmnct) print(SYS_WORKER_DONE) return
def itemList(): response_data = {} c = Communicator() filelist = c.get_file_list() file_list_local = [] for file in os.listdir(Communicator.doc_folder): if (os.path.isfile(os.path.join(Communicator.doc_folder, file)) and file[0] != '.'): file_list_local.append(file) file_list_final = list(set(filelist) - set(file_list_local)) print("Sending list") response_data['list'] = file_list_final # print(response_data) return json.dumps(response_data)
def __init__(self, parent, port, ip=None): """ Initializes the GUI and connects the communicator. :param parent: the tkinter root. :param ip: the ip to connect to. :param port: the port to connect to. :param server: true if the communicator is a server, otherwise false. """ self._parent = parent self._canvas = t.Canvas(self._parent, width=300, height=300) self._canvas.pack() self.__communicator = Communicator(parent, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message) self.__place_widgets()
def main(): roll = SERVER ip = "127.0.0.1" port = 8000 gui = TkinterGui() communicator = Communicator(root=gui.root, ip=ip, port=port) if roll == SERVER: communication_handler = ServerCommunicationHandler(communicator) game_manager = GameServer(gui, communication_handler, Game()) else: communication_handler = ClientCommunicationHandler(communicator) game_manager = GameClient(gui, communication_handler) game_manager.run()
def __init__(self, parent, port, my_turn, ip=None, ai=None): """ Initiation function of the GUI Class :param parent: original board :param port: port for communication between computers :param my_turn: True if it's the turn of the relevant player :param ip: ip address for communication between computers """ self.__parent = parent self.__ai = ai self.__my_turn = my_turn self.__parent.resizable(width=False, height=False) self.__game = Game() # limits of the board self.__canvas = tki.Canvas(self.__parent, width=self.PICTURE_WIDTH, height=self.PICTURE_HEIGHT) self.__background = tki.PhotoImage(file=self.BOARD_IMAGE) self.__canvas.create_image(0, 0, anchor=tki.NW, image=self.__background) # Anchor NW will position the text so that the reference point # coincides with the northwest self.__canvas.grid() self.__canvas.bind('<Button-1>', self.__callback) self.__communicator = Communicator(parent, port, ip) self.__communicator.connect() # import message self.__communicator.bind_action_to_message(self.__handle_message) self.__blue_coin = tki.PhotoImage(file=self.BLUE_COIN_IMAGE) self.__red_coin = tki.PhotoImage(file=self.RED_COIN_IMAGE) self.__blue_coin_win = tki.PhotoImage(file=self.BLUE_WIN_COIN_IMAGE) self.__red_coin_win = tki.PhotoImage(file=self.RED_WIN_COIN_IMAGE) self.__tie_image = tki.PhotoImage(file=self.TIE_IMAGE) # We change a part of the background to indicate the player turn self.__player_one_no = tki.PhotoImage( file=self.PLAYER_ONE_NO_TURN_IMAGE) self.__one_no = None self.__player_two_yes = tki.PhotoImage(file=self.PLAYER_TWO_TURN_IMAGE) self.__two_yes = None if ip is None and self.__ai: column = self.__ai.find_legal_move(self.__game, self.__add_coin) self.__communicator.send_message(column)