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, 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 __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 __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 handle(self, memory, current_location): print("Checking if we can eat this plant.") response = Communicator.send_action('sense', []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message']) return result = response['result'] memory.update_squares(result) square = memory.get_square(current_location) if square['plant'] is None: print("No plant! No plant! Where is my delicious plant!") print("I have to plant another one :/") self._plant() return if not square['plant']['matured']: print("This plant is not matured, have to wait more.") return print("Eating this yummy plant!") response = Communicator.send_action('eat', []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message']) print("Planting another one here.") self._plant()
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 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 handle(self, memory): while True: response = Communicator.send_action("sense", []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message']) break # Updating the memory with these new data. result = response['result'] memory.update_squares(result) if memory.get_nearest_water() is not None: print("I found water on", memory.get_nearest_water()) return print("No water yet, moving on ", self._current_direction, "direction.") response = Communicator.send_action("move", [self._current_direction]) if response['status'] == 500: if response['error_code'] in ("InvalidLocationError", "LocationIsBlockedError"): self._current_direction = self._next_direction[ self._current_direction] print("Changing direction to", self._current_direction)
def run_til_die(self): '''Runs in a loop until the robot dies.''' # The algorithm: # 1) Find water. # 2) Take water and get back to the nearest soil. # 3) Plant three corps. # 4) Water corps. # 5) If honor is enough, give birth to another robot. # 6) Continue from 2 response = Communicator.send_action("info", []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message']) return self._memory.memorize_world_info(response['result']) print("I learned these about this world:", response['result']) print("Let's explore the world!") while True: # Checking the status. response = Communicator.send_action("status", []) if response['status'] == 500: # Error occured. if response['error_code'] == 'AuthenticationFailedError': print("Seems that I'm dead. Goodbye beautiful world.") break else: print("Unexpected error:", response['error_code'], ":", response['error_message']) break status = response['result'] print("My current status is:", status) if (status['location'] == self._memory.get_first_plant_location() or status['location'] == self._memory.get_second_plant_location()): # Trying to eat this plant. EatingHandler().handle(self._memory, status['location']) if status['honor'] >= self._memory.get_birth_required_honor(): print("Enough honor, let's giving birth to a child!") GiveBirthHandler().handle(self._memory) elif self._memory.get_nearest_water() is None: print("I still don't know any water. Let's find some!") WaterFindingHandler().handle(self._memory) elif not status['has_water']: print("No water on hand. Going to pick some.") WaterPickingHandler().handle(self._memory, status['location']) elif status['has_water'] and self._memory.get_first_plant_location() is None: print("I still didn't plant anything. Going to plant some corps.") PlantingHandler().handle(self._memory, status['location']) elif status['has_water'] and self._memory.get_first_plant_location() is not None: print("Going to water my plants.") WateringHandler().handle(self._memory, status['location'])
def send_invoice(modeladmin, request, queryset): for registration in queryset: communicator = Communicator(registration) try: if registration.billing_type == 'email': communicator.send_invoice_email() except RuntimeError: logging.error("Invalid statuscode. Is cloudvoice working. Email wasn't sent")
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 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 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()
class GUI: """ Designed to handle the GUI aspects (creating a window, buttons and pop-ups. Also initializes the communicator object. """ MESSAGE_DISPLAY_TIMEOUT = 250 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_message_to_action(self.__handle_message) self.__place_widgets() def __place_widgets(self): self.__button = t.Button( self._parent, text="YO", font=("Garamond", 20, "bold"), command=lambda: self.__communicator.send_message("YO")) self.__button.pack() self.__button.place(x=120, y=120) self.__label = t.Label(self._parent, text="", fg="red", font=("Garamond", 40, "bold")) self.__label.pack() self.__label.place(x=109, y=200) def __handle_message(self, text=None): """ Specifies the event handler for the message getting event in the communicator. Prints a message when invoked (and invoked by the communicator when a message is received). The message will automatically disappear after a fixed interval. :param text: the text to be printed. :return: None. """ if text: self.__label["text"] = text self._parent.after(self.MESSAGE_DISPLAY_TIMEOUT, self.__handle_message) else: self.__label["text"] = ""
def move(from_location, to_location): '''Moves the robot from the specified location to the specified location. Locations should be strings in form "x,y". ''' to_location_x, to_location_y = to_location.split(',') to_location_x = int(to_location_x) to_location_y = int(to_location_y) from_location_x, from_location_y = from_location.split(',') from_location_x = int(from_location_x) from_location_y = int(from_location_y) print("Current location:", from_location) print("Moving to location:", to_location_x, ",", to_location_y) while from_location_x != to_location_x or from_location_y != to_location_y: direction = "" # We also update the current location, so we don't need asking server and losing energy. if from_location_y < to_location_y: direction += "S" from_location_y += 1 if from_location_y > to_location_y: direction += "N" from_location_y -= 1 if from_location_x < to_location_x: direction += "E" from_location_x += 1 if from_location_x > to_location_x: direction += "W" from_location_x -= 1 print("Moving", direction) response = Communicator.send_action("move", [direction]) if response['status'] == 500: if response['error_code'] == "LocationIsBlockedError": while True: print( "The path is blocked! But I'm not smart enough to pass a blocked object :/" ) # Waiting a little, maybe there's a robot or something on the way. time.sleep(0.5) response = Communicator.send_action("move", [direction]) if not (response['status'] == 500 and response['error_code'] == "LocationIsBlockedError"): # Path cleared, or there's a new error. break else: print("Unexpected error:", response['error_code'], ":", response['error_message'])
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 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 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 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): SettingLoader.__init__(self) Communicator.__init__(self) self.space_subdivisions = 10 self.actions = None self.action_list = None self.states = None self.init_state = None self.ind2state = None self.state2ind = None self.alpha = 0 self.gamma = 0 self.episode_max = 300
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 __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 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 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 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 handle_communication(reg_model): communicator = Communicator(reg_model) try: communicator.send_customer_registration() communicator.send_invoice_registration() if reg_model.billing_type == 'email': communicator.send_invoice_email() else: communicator.send_notification_email() except RuntimeError: logging.error("Invalid statuscode. Is cloudvoice working. Email wasn't sent")
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 __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)
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 __init__(self): gui = Tk() gui.title("Pyctionary!") self.gui = gui self.last_pos = None canvas = Canvas(gui,width=500,height=500) canvas.pack() canvas.bind("<B1-Motion>", self.paint) canvas.bind("<Button-1>",self.paint) canvas.bind("<ButtonRelease-1>",self.unpaint) button = Button(gui,text="Generate Phrase",command=self.get_phrase) button.pack() #the drawing canvas that is the focus of our app self.canvas = canvas #This is the list of individual draw elements self.doodles = [] self.generator = PhraseGenerator self.communicator = Communicator(draw_callback=self.draw) menu = Menu(gui) file_menu = Menu(menu,tearoff=0) file_menu.add_command(label="Save",command=self.save) file_menu.add_command(label="Load",command=self.load) file_menu.add_command(label="Clear",command=self.clear) network_menu = Menu(menu,tearoff=0) network_menu.add_command(label="Host Session",command=self.host) network_menu.add_command(label="Connect to Session",command=self.query_server_address) menu.add_cascade(label="File",menu=file_menu) menu.add_cascade(label="Network",menu=network_menu) gui.config(menu=menu) #hook close event # gui.protocol("WM_DELETE_WINDOW", self.on_closing) mainloop()
def __init__(self, parent=None): super(MainWinGui, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.myName.setText(getStoredName() or "") self.ui.myName.textEdited.connect(self.nameChanged) self.communicator = Communicator(self) self.communicator.peersUpdated.connect(self.refreshPeers) self.communicator.fileReceived.connect(self.fileReceived) self.ui.refreshPeersButton.clicked.connect(self.discoverPeers) self.ui.peerList.itemClicked.connect(self.peerSelected) self.progressIndeterminate.connect(self.progressIndeterminateSlot) self.progressSet.connect(self.progressSetSlot) self.progressStop.connect(self.progressStopSlot) self.progressIndicator = QProgressBar(self.ui.statusbar) self.progressIndicator.setMinimumHeight(5) self.progressIndicator.setVisible(False) self.progressIndicator.setMaximum(0) self.progressIndicator.setMinimum(0) self.ui.statusbar.addWidget(self.progressIndicator)
def __init__(self, headless=True): SettingLoader.__init__(self) Communicator.__init__(self) # self.show_every_n_episodes = 10 self.headless = headless if not self.headless: super().__init__() self.jellys = {} self.p1_rl_model = None self.king_fish = None self.state2ind = None self.ind2state = None self.actions = None self.allowed_moves = None self.actions2ind = None # ? self.exploration = True self.policy = None self.episode_len_count = 0 self.episode_len = None self.game_over = False # Create class variables and set default values self.king_fish = None self.fishes = {} # Dictionary of fishes self._cnt_steps = 0 # Count of the number of steps taken so far self.move_x = [] # Next moves of the fishes in the x axis self.move_y = [] # Next moves of the fishes in the y axis self.action = "stay" # Actions received from player self.time = 0 # Seconds since start self.total_time = 60 # Total time of the game self.player = None self.time_board = None # Time board widget # PID of the player loop in order to be able to kill it when the game is over self.player_loop_pid = None self.models = None self.update_scheduled = None self.timer_scheduled = None self.space_subdivisions = 10 self.frames_per_action = 10 self.fishderby = None # Main widget of the game self.n_jelly = 0 if not self.headless: Builder.load_file('main.kv')
def move(from_location, to_location): '''Moves the robot from the specified location to the specified location. Locations should be strings in form "x,y". ''' to_location_x, to_location_y = to_location.split(',') to_location_x = int(to_location_x) to_location_y = int(to_location_y) from_location_x, from_location_y = from_location.split(',') from_location_x = int(from_location_x) from_location_y = int(from_location_y) print("Current location:", from_location) print("Moving to location:", to_location_x, ",", to_location_y) while from_location_x != to_location_x or from_location_y != to_location_y: direction = "" # We also update the current location, so we don't need asking server and losing energy. if from_location_y < to_location_y: direction += "S" from_location_y += 1 if from_location_y > to_location_y: direction += "N" from_location_y -= 1 if from_location_x < to_location_x: direction += "E" from_location_x += 1 if from_location_x > to_location_x: direction += "W" from_location_x -= 1 print("Moving", direction) response = Communicator.send_action("move", [direction]) if response['status'] == 500: if response['error_code'] == "LocationIsBlockedError": while True: print("The path is blocked! But I'm not smart enough to pass a blocked object :/") # Waiting a little, maybe there's a robot or something on the way. time.sleep(0.5) response = Communicator.send_action("move", [direction]) if not (response['status'] == 500 and response['error_code'] == "LocationIsBlockedError"): # Path cleared, or there's a new error. break else: print("Unexpected error:", response['error_code'], ":", response['error_message'])
def __init__(self, root, game, human_or_ai, port=None, 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.game = game self.ai = AI() self.root = root if human_or_ai: self.ai_on = False else: self.ai_on = True self.ip = ip self.port = port self.my_turn = True """The top image in the gui""" image_path = r"intro2cs.gif" photo = PhotoImage(file=image_path) label = Label(image=photo) label.image = photo # keep a reference label.grid(row=0, column=0, pady=10) self.canvas = Canvas( root, width=200, height=50, background=self.BACKGROUND_COLOR, highlightthickness=0, ) self.canvas.grid(row=2) self.current_player_var = StringVar(self.root, value="") self.currentPlayerLabel = Label(self.root, textvariable=self.current_player_var, anchor=W) self.currentPlayerLabel.grid(row=3) """when the user click on the canvas do action according to the _action_when_canvas_clicked function""" self.canvas.bind('<Button-1>', self._action_when_canvas_clicked) self.new_game() self.__communicator = Communicator(root, port, ip) self.__communicator.connect() self.__communicator.bind_action_to_message(self.__handle_message)
def __init__(self, device): if os.path.isfile(cfg.GUID_FILENAME): guidfile = open(cfg.GUID_FILENAME, "r") self.global_uid = guidfile.read() guidfile.close() else: guidfile = open(cfg.GUID_FILENAME, "w") self.global_uid = str(uuid.uuid4()).replace("-", "") guidfile.write(self.global_uid) guidfile.close() cfg.log(self.get_guid()) self.device = device self.communicator = Communicator(self.get_guid()) self.communicator.give_my_spec(device.get_num_of_chanels(), device.name, device.description) if isinstance(self.device, ThreadedDevice): self.device.set_callback(self.send_data_to_serv)
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(): if len(sys.argv) != 2: print('Usage: python3 simple_bot.py password') sys.exit(101) print("A simple robot for Beneath a Binary Sky.") print("Author: Aidin Gharibnavaz <*****@*****.**>") print("") Communicator.configure("127.0.0.1", 9537) print("Borning...") Communicator.born(sys.argv[1]) print("I'm borned!") Decider().run_til_die()
def handle(self, memory, current_location): print("Moving to the latest known water location.") helpers.move.move(current_location, memory.get_nearest_water()) print("I'm reached the water location. Picking some water.") response = Communicator.send_action("pick_water", []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message'])
def handle_request(request): try: validate_request(request) # Communicator is a singleton class. communicator = Communicator() communicator_result = communicator.execute_command(request["password"], request["command"], request["args"]) except BinarySkyException as error: return make_error_response(error) except Exception as error: # Logging exceptions that are not one of ours. Logger().error("System error: {0}\n{1}".format(error, traceback.format_exc())) return make_error_response(error) result = {'status': 200, 'result': communicator_result} return result
def handle(self, memory, current_location): print("Moving to the latest known soil.") helpers.move.move(current_location, memory.get_nearest_soil()) print("Checking current location.") response = Communicator.send_action("status", []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message']) status = response['result'] print("Now I'm at the", status['location'], "location. Planting something.") response = Communicator.send_action("plant", []) if response['status'] == 500: if response['error_code'] == 'AlreadyPlantError': print("Strange, but there's already a plant on", status['location']) memory.store_first_plant_location(status['location']) else: print("Unexpected error:", response['error_code'], ":", response['error_message']) else: memory.store_first_plant_location(status['location']) print("Trying to find other soils nearby, and planting on them too.") near_soil = self._find_nearby_soil(memory, status['location']) if near_soil is None: print("Couldn't find any other soils around.") return helpers.move.move(status['location'], near_soil) print("Planting on the founded soil.") response = Communicator.send_action("plant", []) if response['status'] == 500: if response['error_code'] == 'AlreadyPlantError': print("Strange, but there's already a plant on", status['location']) memory.store_second_plant_location(status['location']) else: print("Unexpected error:", response['error_code'], ":", response['error_message']) else: memory.store_second_plant_location(status['location'])
def handle(self, memory): while True: response = Communicator.send_action("sense", []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message']) break # Updating the memory with these new data. result = response['result'] memory.update_squares(result) if memory.get_nearest_water() is not None: print("I found water on", memory.get_nearest_water()) return print("No water yet, moving on ", self._current_direction, "direction.") response = Communicator.send_action("move", [self._current_direction]) if response['status'] == 500: if response['error_code'] in ("InvalidLocationError", "LocationIsBlockedError"): self._current_direction = self._next_direction[self._current_direction] print("Changing direction to", self._current_direction)
def handle(self, memory): response = Communicator.send_action("give_birth", []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message']) new_password = response['result'] print("Come, come, my little sweetie!") current_module_directory = os.path.abspath(os.path.dirname(sys.modules[__name__].__file__)) main_file = os.path.join(current_module_directory, '..', 'simple_bot.py') # Starting the child process. We set its stdout and stderr to ours, so the child can write # logs to terminal too. child_process = subprocess.Popen(["python3", main_file, new_password], stdout=sys.stdout, stderr=sys.stderr) print("My child came to life with PID", child_process.pid)
def handle(self, memory, current_location): if WateringHandler.LAST_WATERED == "first": plant_to_water = memory.get_second_plant_location() if plant_to_water is None: # There maybe no second plant. plant_to_water = memory.get_first_plant_location() WateringHandler.LAST_WATERED = "second" else: plant_to_water = memory.get_first_plant_location() print("Going to water", WateringHandler.LAST_WATERED, "plant.") helpers.move.move(current_location, plant_to_water) print("I reached the plant. Watering...") response = Communicator.send_action("water", []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message'])
class MainWinGui(QtGui.QMainWindow): progressIndeterminate = QtCore.pyqtSignal() progressSet = QtCore.pyqtSignal(int) progressStop = QtCore.pyqtSignal() def __init__(self, parent=None): super(MainWinGui, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.myName.setText(getStoredName() or "") self.ui.myName.textEdited.connect(self.nameChanged) self.communicator = Communicator(self) self.communicator.peersUpdated.connect(self.refreshPeers) self.communicator.fileReceived.connect(self.fileReceived) self.ui.refreshPeersButton.clicked.connect(self.discoverPeers) self.ui.peerList.itemClicked.connect(self.peerSelected) self.progressIndeterminate.connect(self.progressIndeterminateSlot) self.progressSet.connect(self.progressSetSlot) self.progressStop.connect(self.progressStopSlot) self.progressIndicator = QProgressBar(self.ui.statusbar) self.progressIndicator.setMinimumHeight(5) self.progressIndicator.setVisible(False) self.progressIndicator.setMaximum(0) self.progressIndicator.setMinimum(0) self.ui.statusbar.addWidget(self.progressIndicator) def nameChanged(self, newName): storeName(newName) self.communicator.updateName(newName) def progressStart(self): self.progressIndicator.setVisible(True) def progressSetSlot(self, value): self.progressStart() self.progressIndicator.setMaximum(100) self.progressIndicator.setValue(value) def progressIndeterminateSlot(self): self.progressStart() self.progressIndicator.setMaximum(0) def progressStopSlot(self): self.progressIndicator.setVisible(False) def show(self): super(MainWinGui, self).show() self.refreshPeers() self.discoverPeers() def discoverPeers(self): self.communicator.discoverPeers() def refreshPeers(self): self.ui.peerList.clear() for peer in self.communicator.peers: peer = self.communicator.peers[peer] peerName = QListWidgetItem(self.ui.peerList) peerName.peer = peer nameFont = QtGui.QFont() nameFont.setPointSize(14) peerDetails = QListWidgetItem(self.ui.peerList) peerDetails.peer = peer detailsFont = QtGui.QFont() detailsFont.setPointSize(10) name = peer.name details = "" if peer.publicKey is None: details += "Unpaired, " else: details += "Paired, " if peer.lastKnownIP is None: details += "unavailable" else: details += "available: " + peer.lastKnownIP peerName.setFont(nameFont) peerName.setText(name) peerDetails.setFont(detailsFont) peerDetails.setText(details) self.ui.peerList.addItem(peerName) self.ui.peerList.addItem(peerDetails) separatorItem = QListWidgetItem(self.ui.peerList) separatorItem.guid = peer.guid separatorItem.peer = None separatorItem.setFlags(QtCore.Qt.NoItemFlags) self.ui.peerList.addItem(separatorItem) def peerSelected(self, selectedItem): selectedItem.setSelected(False) if selectedItem.peer: PeerOptionsUi(self, selectedItem.peer, self.communicator).show() else: pass def sendFile(self, guid): fileName = QtGui.QFileDialog.getOpenFileName() if not fileName: return fileContents = open(fileName, "rb").read() basename = os.path.basename(fileName) self.communicator.sendFile(basename, fileContents, guid) def fileReceived(self, fileName, fileContents): fileName = QtGui.QFileDialog.getSaveFileName(directory=fileName) if not fileName: return with open(fileName, mode="wb") as file: file.write(fileContents)
def on_loginButton_pressed(self, *args): username = self.USERNAME_ENTRY.text() password = self.PASSWORD_ENTRY.text() Communicator.login(username,password)
def on_submitButton_clicked(self, *args): Communicator.write_chat_to_channel()
def channel_clicked(self,channel,flag): Communicator.switch_channel(channel)
def process_IN_CREATE(self, event): c = Communicator() c.add_mapping_for_file(event.pathname.split('/')[-1]) print('Added mapping via inotify')
class GUI(object): ''' The GUI Object contains a paintable canvas, a "get new words" button, and options to assist in connecting to other users ''' def __init__(self): gui = Tk() gui.title("Pyctionary!") self.gui = gui self.last_pos = None canvas = Canvas(gui,width=500,height=500) canvas.pack() canvas.bind("<B1-Motion>", self.paint) canvas.bind("<Button-1>",self.paint) canvas.bind("<ButtonRelease-1>",self.unpaint) button = Button(gui,text="Generate Phrase",command=self.get_phrase) button.pack() #the drawing canvas that is the focus of our app self.canvas = canvas #This is the list of individual draw elements self.doodles = [] self.generator = PhraseGenerator self.communicator = Communicator(draw_callback=self.draw) menu = Menu(gui) file_menu = Menu(menu,tearoff=0) file_menu.add_command(label="Save",command=self.save) file_menu.add_command(label="Load",command=self.load) file_menu.add_command(label="Clear",command=self.clear) network_menu = Menu(menu,tearoff=0) network_menu.add_command(label="Host Session",command=self.host) network_menu.add_command(label="Connect to Session",command=self.query_server_address) menu.add_cascade(label="File",menu=file_menu) menu.add_cascade(label="Network",menu=network_menu) gui.config(menu=menu) #hook close event # gui.protocol("WM_DELETE_WINDOW", self.on_closing) mainloop() #def on_closing(self): # cleanup # sys.exit(0) def host(self): ''' Begin hosting a new session :return: nothing ''' self.communicator.connect(host=True,remote_address="") def query_server_address(self): ''' Attempt to connect to a remote server :return: nothing ''' #pass callback to join server after getting IP InputDialog(self.gui,self.join_server) def join_server(self,address): print("Joining " + address) self.communicator.connect(host=False,remote_address=address) def get_phrase(self): phrase = self.generator.GetPhrase() tkMessageBox.showinfo("Your Phrase","Your Pyctionary Phrase is: " + phrase) def save(self): ''' Save a drawing to file :return: nothing ''' with open("doodles.txt","w") as f: for doodle in self.doodles: line = doodle.__str__() f.write(line +"\n") f.close() print(self.doodles) def load(self): ''' Load a drawing from file :return: Nothing ''' with open("doodles.txt","r") as f: lines = f.readlines() for line in lines: doodle = Doodle.parse(line) self.draw(doodle) #print(args) def clear(self): clear_doodle = Doodle(Doodle.CLEAR,0,0,0,0) self.draw(clear_doodle) def unpaint(self,event): ''' Stop painting. This tells the UI to not draw a line connecting the last point to the next drawn point. :param event: This contains the coordinates of the mouse release event. Not relevant to what we are doing :return: Nothing ''' self.last_pos = None def draw(self,doodle,store_local=True,retransmit=True): ''' Draw the specified doodle on the canvas :param doodle: The event to draw :param retransmit: if true, the doodle will be sent to networked users. :return: Nothing ''' if doodle is None: raise ValueError("No doodle passed to draw()") if(doodle.doodle_type == doodle.OVAL): self.canvas.create_oval( doodle.x-1, doodle.y-1, doodle.x+1, doodle.y+1,fill="black") elif(doodle.doodle_type == doodle.LINE): self.canvas.create_line(doodle.x,doodle.y,doodle.x2,doodle.y2) elif(doodle.doodle_type == doodle.CLEAR): self.canvas.delete("all") else: raise ValueError("Unknown doodle type passed to draw()") #if we are drawing locally, store this on the list of user actions for saving/transmitting if store_local is True: self.doodles.append(doodle) if retransmit is True: self.communicator.transmit_doodle(doodle) def paint(self,event): ''' Continue painting. If painting a continuous line, draw a line from the last known point to fill any "holes" :param event: This contains the coordinates of the mouse event that triggered the paint event (and where we should paint) :return: Nothing ''' #http://www.python-course.eu/tkinter_canvas.php provided insight on using ovals to draw freely #the ovals(circles, really) are radius "1" from the point clicked. doodle = Doodle(Doodle.OVAL,event.x,event.y,None,None) self.draw(doodle) #draw a line between this position and the last to ensure we have a continuous drawing line if self.last_pos and len(self.last_pos) == 2: #check for len 2 because moving mouse off canvas has weird effects line_doodle = Doodle(Doodle.LINE,event.x,event.y,self.last_pos[0],self.last_pos[1]) self.draw(line_doodle) #store last position to draw a line between any 'gaps' self.last_pos = (event.x,event.y)
def __init__(self, botdir): self.botdir = botdir self.bot_names = Communicator.read_bot_list(botdir) self.bots = [] self.load_bots()
def _plant(self): response = Communicator.send_action('plant', []) if response['status'] == 500: print("Unexpected error:", response['error_code'], ":", response['error_message'])
if(os.path.isfile(os.path.join(Communicator.doc_folder, file)) and file[0] != '.'): file_list.append(file) response_data['list'] = file_list return json.dumps(response_data) if __name__ == '__main__': # setUp(10) # Port 0 means to select an arbitrary unused port HOST, PORT = "0.0.0.0", 9876 server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler) ip, port = server.server_address # Start a thread with the server -- that thread will then start one # more thread for each request server_thread = threading.Thread(target=server.serve_forever) # Exit the server thread when the main thread terminates server_thread.daemon = True server_thread.start() print("Server loop running in thread:", server_thread.name) file_sync = ThreadFileSync() c = Communicator() c.register_user() app.run(debug=False, host='0.0.0.0') c.unregister_user() server.shutdown() server.server_close() file_sync.remove_watch() print('Server shutdown')
def main(): comm = Communicator() comm.start()
_host = 'localhost' return _host, _port, _team def check_return_values(val): return False if (val is None or val is False or val == '' or val == 'ko' or val == 'mort') else True def choose_an_id(team, id): result = 1 for i in range(0, len(team)): result *= ord(team[i]) * (i + 1) id *= result return str(id) if __name__ == "__main__": host, port, team = check_opt() com = Communicator() com.connect(host, port) id, map_size = com.join_team(team) com.id = choose_an_id(team, int(id)) print("MON ID EST %s" % com.id) routine_tab = misc.get_routine_tab(com) mode = 0 while com.alive(): routine_tab[com.mode]() if com.mode != mode: print("nouveau mode %d" % com.mode) mode = com.mode