Beispiel #1
0
	def __init__(self):
		#Lets define interfaces
		self.interface_a = interface(int_select = 1)
		self.interface_b = interface(int_select = 2)
	
		#lets initizlize interface A and B into mpsse mode
		self.interface_b.reset()
		self.interface_a.reset_uart()


		#lets define gpio's
		self.led_user = gpio(self.interface_b.port_h, 7, 1, 0)

		if(self.uart_mode == False):
			self.gpio_1 = gpio(self.interface_a.port_l, 4, 1, 0)
			self.gpio_2 = gpio(self.interface_a.port_l, 5, 1, 0)

		self.gpio_mclr = gpio(self.interface_b.port_h, 0, 1, 1)
		self.gpio_boot_en = gpio(self.interface_b.port_h, 1, 1, 1)
		self.gpio_5 = gpio(self.interface_b.port_h, 2, 1, 1)
		self.gpio_6 = gpio(self.interface_b.port_h, 3, 1, 1)
		self.gpio_7 = gpio(self.interface_b.port_h, 4, 1, 1)
		self.gpio_8 = gpio(self.interface_b.port_h, 5, 1, 1)
		self.gpio_9 = gpio(self.interface_b.port_h, 6, 1, 1)

		self.sel_spi_jtag = gpio(self.interface_b.port_l, 4, 1, 0)
		self.sel_spi_uart = gpio(self.interface_b.port_l, 5, 1, 0)
Beispiel #2
0
def passage_couche(angle_incidence, n1, n2, n3, n):
    _, _, a_t1, _ = interface(angle_incidence, n1, n2)
    t23, r23, a_t2, _ = interface(a_t1, n2, n3)
    _, r21, _, _ = interface(a_t1, n2, n1)

    transmission = t23 * ((1 - (r23 * r21)**n) / (1 - (r23 * r21)))
    angle_interne = a_t1
    return transmission, angle_interne
Beispiel #3
0
def users_interface():
	print("Добро пожаловать в наш VCS.")
	while 1:
		username=si.login()
		print("Вы авторизировались как </"+username+"/>.")
		uc.check_users_requests(username)
		intf.interface(username)
		if input("Вы хотите сменить пользователя?(д/н)\n>> ").lower() in ["yes","да","y","д"]:
			continue
		elif input("Вы хотите выйти из системы?(д/н)\n>> ").lower() in ["yes","да","y","д"]:
			sys.exit()
 def __init__(self):
     '''
     Constructor
     '''
     list_empty = Set([])
     self.interface_principal = interface.interface(list_empty,"researchers.txt","archivo.bib")
     self.interface_principal.ini_listas()
     
     self.list_c = self.interface_principal.list_citation #objetos
     self.list_r = self.interface_principal.list_reference #objetos
     
     self.interface_citation = interface.interface(self.list_c,"researchers.txt","archivo.bib")
     self.interface_reference = interface.interface(self.list_r,"researchers.txt","archivo.bib")
     self.interface_citation.ini_listas()
     self.interface_reference.ini_listas()
Beispiel #5
0
    def __init__(self):
        self.lcd = None
        self.num_lcd_rows = 2
        self.ben_line = ["Starting", "Ben"]
        self.imu_line = ["Starting", "IMU"]
        self.rpm_line = ["Starting", "Speed m/s"]
        self.loop_timer = 0
        self.last_button_pressed = 2
        self.rpm = 0
        self.timer_interval = 0.001
        self.current_menu = 0
        self.last_string_length = 0
        self.ben_identifier = None
        self.cv_depth_image = None
        self.cv_rgb_image = None
        self.rgb_get = False
        self.depth_get = False

        self.text_xpos = 1050
        self.text_ypos = 350
        self.text_pos_multiplier = 40
        self.font_size = 30

        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber("/camera/rgb/image_raw", Image, self.rgbCallback)
        self.depth_sub = rospy.Subscriber("/camera/depth/image_raw", Image, self.depthCallback)

        self.imu_values = rospy.Subscriber('/imu', Imu, self.imuCallback)
        self.odom_values = rospy.Subscriber('/odom', Odometry, self.rpmCallback)

        self.music_subscriber = rospy.Subscriber('/play_melody', Int8, self.musicCallback)
        self.button_publisher = rospy.Publisher('/pushed', Int8, queue_size=1)

        self.main_interface = interface.interface()
Beispiel #6
0
    def SendDhcpPacket(self, request, response):
        giaddr = ".".join(map(str, request.GetOption("giaddr")))
        ciaddr = ".".join(map(str, request.GetOption("ciaddr")))
        yiaddr = ".".join(map(str, response.GetOption("yiaddr")))
        chaddr = struct.pack(6 * "B", *request.GetOption("chaddr")[0:6])
        broadcast = request.GetOption("flags")[0] != 0

        if (giaddr != "0.0.0.0"):
            self.SendDhcpPacketTo(response, giaddr, self.listen_port)
        elif (response.IsDhcpNackPacket()):
            self.SendDhcpPacketTo(response, "255.255.255.255", self.emit_port)
        elif (ciaddr != "0.0.0.0"):
            self.SendDhcpPacketTo(response, ciaddr, self.emit_port)
        elif (broadcast):
            self.SendDhcpPacketTo(response, "255.255.255.255", self.emit_port)
        else:  # unicast to yiaddr
            ifconfig = interface.interface()
            ifindex = ifconfig.getIndex(self.ifname)
            ifaddr = ifconfig.getAddr(self.ifname)
            if (ifaddr is None):
                ifaddr = "0.0.0.0"
            _rawsocket.udp_send_packet(response.EncodePacket(),
                                       type_ipv4.ipv4(ifaddr).int(),
                                       self.listen_port,
                                       type_ipv4.ipv4(yiaddr).int(),
                                       self.emit_port, chaddr, ifindex)
Beispiel #7
0
 def __init__(self, screen, display):
     self.screen = screen
     self.background = pygame.Surface((800, 600))
     self.background.fill(constants.background_color)
     self.terrain = pygame.Surface((800, 600))
     
     self.camera_x = 0
     self.camera_y = 0
     
     self.tile_draw_dimensions = (45, 33)
     self.tile_odd_offset = 22.5
     
     self.model = None #intialized manually
     self.display = display
     
     self.centered_actor = None
     self.chunk_offset = (0, 0)
     self.tile_offset = (0, 0)
     self.tile_offset_end = (0, 0)
     self.centered_actor_offset = (0, 0) #tuple of actor landscape coordinates
     
     #image caches
     self.actor_images = actor_images.actor_images()
     self.terrain_images = terrain_images.terrain_images()
     
     #render groups
     self.actor_sprite_group = pygame.sprite.Group()
     self.effect_sprite_group = pygame.sprite.Group()
     self.gui_group = pygame.sprite.Group()
     self.text_group = pygame.sprite.RenderUpdates()
     
     self.interface = interface.interface()
def main():
    interf = interface.interface()
    for i in range(4):
        print("RFID!!!!!!")
        interf.get_i()
        uid=interf.get_UID()
        print(uid)
Beispiel #9
0
    def SendDhcpPacket(self, request, response):
        giaddr = ".".join(map(str, request.GetOption("giaddr")))
        ciaddr = ".".join(map(str, request.GetOption("ciaddr")))
        yiaddr = ".".join(map(str, response.GetOption("yiaddr")))
        chaddr = struct.pack(6*"B", *request.GetOption("chaddr")[0:6])
        broadcast = request.GetOption("flags")[0] != 0

        if (giaddr != "0.0.0.0"):
            self.SendDhcpPacketTo(response, giaddr, self.listen_port)
        elif (ciaddr != "0.0.0.0"):
            self.SendDhcpPacketTo(response, ciaddr, self.emit_port)
        elif (broadcast):
            self.SendDhcpPacketTo(response, "255.255.255.255", self.emit_port)
        else:
            ifconfig = interface.interface()
            ifindex  = ifconfig.getIndex(self.ifname)
            ifaddr   = ifconfig.getAddr(self.ifname)
            _rawsocket.udp_send_packet( response.EncodePacket(),
                                        type_ipv4.ipv4(ifaddr).int(),
                                        self.listen_port,
                                        type_ipv4.ipv4(yiaddr).int(),
                                        self.emit_port,
                                        chaddr,
                                        ifindex
                                      )
Beispiel #10
0
async def on_message(message):
    """
    Handles all messages. Only command hardcoded here is !reload, which'll reload all subplugins.
    Passes everything else through.
    """
    global plugin
    if message.author == client.user:
        return
    try:
        print("#{} - {}: {}".format(message.channel.name, str(message.author),
                                    message.content))
    except UnicodeEncodeError:
        print("#{} - {}: [UNENCODEABLE]".format(message.channel.name,
                                                str(message.author)))
    except Exception as exception:
        await handleException(message, exception)
    if message.content.split(" ")[0].lower() == "!reload":
        accesslevel = getAccessLevel(message.author)
        if accesslevel >= 4:
            try:
                await plugin.beforeReload()
                importlib.reload(interface)
                plugin = interface.interface()
                await plugin.reload(client)
                await sendMessage(message, "Reloaded!")
            except Exception as exception:
                await handleException(message, exception)
        else:
            await sendMessage(
                message, "You don't have access to !reload, {}.".format(
                    message.author.mention))
    try:
        await plugin.action(message)
    except Exception as exception:
        await handleException(message, exception)
Beispiel #11
0
def interface_n1_smaller(angle_incidence, angle_1, angle_2):
    indice_ch_39 = 1.5
    indice_BI = 1.35
    transmission, reflexion, angle_transmit, angle_reflechi = interface(angle_incidence, angle_1, angle_2)
    assert transmission + reflexion - 1 < 0.01
    assert reflexion == 0.7
    assert angle_transmit.deg() < 45
    assert angle_transmit.deg() > 0
    assert angle_reflechi == -angle_incidence
Beispiel #12
0
 def __init__(self, ifname, listen_address="0.0.0.0", listen_port=67, emit_port=68):
     netifo = interface.interface()
     self.ifname         = ifname
     self.listen_port    = int(listen_port)
     self.emit_port      = int(emit_port)
     self.listen_address = listen_address
     self.so_reuseaddr   = False
     self.so_broadcast   = True
     self.dhcp_socket    = None
def initialize():

    main_interface = interface.interface()
    main_interface.start_screen()
    main_interface.init_joystick()
    joystick_count = main_interface.get_joystick_count()
    main_interface.create_menu()
    bus = can.interface.Bus(bustype='socketcan', channel='can1', bitrate=1000000)

    return (main_interface, joystick_count, bus)
Beispiel #14
0
def main():
    os.system('cls' if os.name == 'nt' else 'clear')
    print("Starting the interface...")

    loop = asyncio.get_event_loop()

    task = loop.create_task(interface(loop))

    loop.run_until_complete(task)
    loop.close()
Beispiel #15
0
def main():

    parser = argparse.ArgumentParser(description="Sort image in folders")
    parser.add_argument("-s", "--source")
    parser.add_argument("-d", "--destination")
    parser.add_argument("-x", "--delete", action="store_true")
    parser.add_argument("-p", "--prefix")
    parser.add_argument("-y", "--year")
    parser.add_argument("-m", "--month")
    parser.add_argument("-r", "--rename", action="store_true")
    parser.add_argument("-c",
                        "--count",
                        action="store_true",
                        help="Print number of copied/moved jpg files")
    parser.add_argument("-g", "--gui", action="store_true")
    args = parser.parse_args()

    if (args.gui != 0):
        if ((args.source != None) and (args.destination != None)):
            parameters = {
                'delete': args.delete,
                'rename': args.rename,
            }

            if (args.prefix == None):
                parameters['prefix'] = ""

            if (args.year == None):
                parameters['year'] = ""

            if (args.month == None):
                parameters['month'] = ""

            (numberCp, numberRm) = core.sortImgs(args.source, args.destination,
                                                 parameters)

            if (args.count != None):
                print("Number of copied files: %d" % numberCp)
                print("Number of removed files: %d" % numberRm)
        else:
            print('Error, args -s and -d are required')
    else:
        interface.interface()
def main():
    interf = interface.interface()
    interf.send_dir(dir[0])
    interf.get_p()
    interf.send_dir(dir[1])
    interf.get_p()
    interf.send_dir(dir[2])
    interf.get_i()
    uid = interf.get_UID()
    print(uid)
    '''
Beispiel #17
0
def main():
    # point = score.Scoreboard("data/UID.csv", "team_3")
    thread = threading.Thread(target=start_socket)
    thread.start()
    interf = interface.interface()
    for i in range(12):
        interf.get_i()
        uid = interf.get_UID()
        print(uid)
        point.add_UID(uid)
        print(point.getCurrentScore())
Beispiel #18
0
def interface_show(cmd, *args, **argv):
    """
    """

    context = argv["context"]
    """
    from _interface_auxiliary import interface as __interface
    interface_date = __interface()
    from _prettytable import PrettyTable
    interface_t = PrettyTable(["Interface", "Status", "Zone", "IP", "MAC"])
    for interface_l in interface_date:
    	if interface_l[3]  == []:
            interface_l[3] = ["-"]
        for ip in interface_l[3]:
            interface_t.add_row([interface_l[0], interface_l[1], interface_l[2], ip, interface_l[4]])
    context.write("%s" % interface_t)
    """

    from interface import interface
    interface("interface", context=context)
Beispiel #19
0
    def __init__(self):
        com_port = "/dev/ttyACM0"
        #com_port = "COM8"
        
        self.multiwii = interface.interface()
        self.multiwii.init_serial(com_port)
        self.multiwii.get_variables("")

        self.fow_scale = 100.0
        self.turn_scale = 100.0
        self.skew_scale = 100.0
def main():
    maze = mz.Maze("data/small_maze.csv")
    point = score.Scoreboard("data/UID.csv", "team_NTUEE")
    interf = interface.interface()
    # TODO : Initialize necessary variables

    if (sys.argv[1] == '0'):
        print("Mode 0: for treasure-hunting")
        # TODO : for treasure-hunting, which encourages you to hunt as many scores as possible

    elif (sys.argv[1] == '1'):
        print("Mode 1: Self-testing mode.")
Beispiel #21
0
 def __init__(self,
              ifname,
              listen_address="0.0.0.0",
              listen_port=67,
              emit_port=68):
     netifo = interface.interface()
     self.ifname = ifname
     self.listen_port = int(listen_port)
     self.emit_port = int(emit_port)
     self.listen_address = listen_address
     self.so_reuseaddr = False
     self.so_broadcast = True
     self.dhcp_socket = None
def transmission(angle, delta_n, angle_interface):
    n1 = 1  # indice de l'air
    n2 = 1.5  # indice du CH 39
    n3 = 1.55  # indice HI
    n4 = 1.35  # indice BI
    n5 = 1.5  # indice CR39

    nb_iterations = 100000
    T1, _, angle1, _ = interface(angle, n1, n2)
    T2, angle2 = passage_couche(angle1, n2, n3, n4, nb_iterations)
    T3, _, angle3, _ = interface(
        DegreeAngle(90 - angle_interface.deg() - angle2.deg()), n3,
        n3 + delta_n)
    T4, angle4 = passage_couche(
        DegreeAngle(angle_interface.deg() - angle3.deg()), n3 + delta_n, n4,
        n5, nb_iterations)
    T5, _ = passage_couche(angle4, n4, n5, n1, nb_iterations)
    transmission = T1 * T2 * T3 * T4 * T5

    # Transmission_progressive = [T1, T1 * T2, T1 * T2 * T3, T1 * T2 * T3 * T4, T1 * T2 * T3 * T4 * T5];
    # plt.plot(Transmission_progressive)
    return transmission
Beispiel #23
0
    def __init__(self):
        self.config = config;
        self.console = interface.interface();
        self.engine = opencv2.opencv2;
        self.input = control.control;

        self.serverChoose_module = server_choose.server_choose(self.engine);

        self.console.printLogo();
        self.clientInit();
        self.userInit();
        self.login();
        self.startSCA();
def animed_over(screen):
    inter = interface.interface(screen)
    ani_over = pygame.image.load("img/comando.png")

    while not False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                fechar_janela()
        screen.blit(ani_over, (0, 0))

        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_RETURN]:
            inter.menu(screen)


        pygame.display.flip()
Beispiel #25
0
def main():
    maze = mz.Maze("data/maze_test.csv")
    point = score.Scoreboard("data/UID.csv")
    interf = interface.interface()         # the part of calling interface.py was commented out.
    # TODO : Initialize necessary variables

    if (sys.argv[1] == '0'):
        print("Mode 0: for treasure-hunting with rule 1")
        # TODO : for treasure-hunting with rule 1, which encourages you to hunt as many scores as possible

    elif (sys.argv[1] == '1'):
        print("Mode 1: for treasure-hunting with rule 2")
        # TODO : for treasure-hunting with rule 2, which requires you to hunt as many specified treasures as possible

    elif (sys.argv[1] == '2'):
        print("Mode 2: Self-testing mode.")
def main():
    point = score.Scoreboard("data/UID.csv", "team_NTUEE")
    interf = interface.interface()
    # TODO : Initializ1e necessary variables

    print("Mode 0: for checkpoint")
    direction = 2 #input("Enter the initial direction:(1,2,3,4)")
    in_node = 1
    interf.send_action(mz.Action(1))
    while(in_node < 13):
        command = interf.get_command()
        if command == "n":
            if in_node == 1 or in_node == 2 or in_node == 3:
                interf.send_action(mz.Action(1))
                in_node += 1
            elif in_node == 4:
                interf.send_action(mz.Action(3))
                in_node += 1
            elif in_node == 5:
                interf.send_action(mz.Action(2))
                in_node += 1
            elif in_node == 6:
                interf.send_action(mz.Action(1))
                in_node += 1
            elif in_node == 7:
                interf.send_action(mz.Action(3))
                in_node += 1
            elif in_node == 8:
                interf.send_action(mz.Action(4))
                in_node += 1
            elif in_node == 9:
                interf.send_action(mz.Action(3))
                in_node += 1  
            elif in_node == 10:
                interf.send_action(mz.Action(2))
                in_node += 1
            elif in_node == 11:
                interf.send_action(mz.Action(1))
                in_node += 1
            elif in_node == 12:
                interf.send_action(mz.Action(5))
                in_node += 1      
            print(in_node)
        # TODO : for treasure-hunting, which encourages you to hunt as many scores as possible
        

    interf.end_process()
Beispiel #27
0
    def collect_selfplay_data(self, n_games = 1):
        for i in range(n_games):
            inter = interface(self.board_length)
            current_board = copy.deepcopy(self.chess)
            current_real_mcts = real_mcts(current_board,
                                          self.policy_value_net.policy_value,
                                          self.cpuct,
                                          self.real_mcts_simulation_times,
                                          self.temperature,
                                          self.num_history,
                                          True)
            play_data = inter.start_self_play(player = current_real_mcts)
# =============================================================================
#             play_data = start_self_play(player = current_real_mcts)
# =============================================================================
            play_data = list(play_data)[:]
            self.episode_len = len(play_data)
            play_data = self.get_equi_data(play_data)
            self.data_buffer.extend(play_data)
Beispiel #28
0
 def __init__(self, buildingID, SwitchID):
     print("Starting Logical Layer")
     self.buildingID = buildingID
     self.SwitchID = SwitchID
     self.building_config = switch_board_building(self.buildingID)
     self.intf = interface(self.building_config, self.SwitchID)
     cfg = configuration_reader(self.intf)
     self.comms = communicator_physical_layer()
     self.translator = name_translator()
     self.busy_busbars = {}
     self.work_q = Queue()
     self.work_pauser = Queue()
     self.logic = logic(self.comms, self.work_q, self.work_pauser,
                        self.translator, self.intf)
     #self.logic.switchboard_initialization(self.intf)
     self.online_reader = Process(target=cfg.run,
                                  args=(self.work_q, self.work_pauser))
     self.online_reader.daemon = True
     self.online_reader.start()
Beispiel #29
0
 def __init__(self):
     ans = raw_input("Use new input? y/N ").strip().lower()
     if ans == 'y':
         self.mode = 'setup'
         self.inter = interface.interface(self, 10, 10)
         self.inter.startup(
         )  #this call doesn't return until the window is closed, nothing will be run after it
         #print "done!"
         #self.inter.set_text('Enter the setup number')
         #print "New input is not yet coded"
         #self.interface_setup()
         #return
     else:
         ans = raw_input("Enter setup number: ").strip()
         if ans.isdigit() == False:
             ans = 0
         else:
             ans = int(ans)
         self.game = game(ans)
         self.mainloop()
Beispiel #30
0
def game_over(screen, score):
    inter = interface.interface(screen)
    game_over = pygame.image.load(FIM)
    trofeu = pygame.image.load(TROFEU)
    ultimo_recorde = open(ARQUIVO_SALVA_SCORE, "r").read()

    efeitos_sonoros("Game_Over")
    intro(1)
    while not False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        screen.blit(game_over, (0, 0))
        if score >= int(ultimo_recorde):
            imprime_texto(screen, "NOVO  RECORDE", (197, 210), FONTE_PIXEL,
                          BRANCO)
            imprime_texto(screen, score, (255, 240), FONTE_DG, BRANCO)
            screen.blit(trofeu, (230, 280))
        else:
            imprime_texto(screen, "seu score", (77, 210), FONTE_PIXEL, BRANCO)
            imprime_texto(screen, score, (133, 240), FONTE_DG, BRANCO)
            imprime_texto(screen, "maior score", (277, 210), FONTE_PIXEL,
                          BRANCO)
            imprime_texto(screen, ultimo_recorde, (356, 240), FONTE_DG, BRANCO)

        imprime_texto(screen, "TENTE NOVAMENTE...", (152, 388), FONTE_DG,
                      BRANCO)
        imprime_texto(screen, "PRESSIONE   ENTER", (90, 540), FONTE_PIXEL2,
                      PRETO)

        pressed = pygame.key.get_pressed()

        if pressed[pygame.K_RETURN]:
            inter.menu(screen)

        pygame.display.flip()
Beispiel #31
0
 def policy_evaluate(self, n_games=10):
     win_cnt = defaultdict(int)
     
     for i in range(n_games):
         inter = interface(self.board_length)
         current_board = copy.deepcopy(self.chess)
         current_real_mcts = real_mcts(current_board,
                             self.policy_value_net.policy_value,
                             self.cpuct,
                             1000,
                             self.temperature,
                             self.num_history,
                             False)
         current_pure_mcts = pure_mcts(current_board,
                                       self.pure_mcts_simulation_times)
         winner = inter.start_play(current_real_mcts,
                                   current_pure_mcts,
                                   start_player=i % 2)
         win_cnt[winner] += 1
         print('winner', winner)
     win_ratio = 1.0 * (win_cnt[1] + 0.5 * win_cnt[0]) / n_games
     print("num_simulation_times:{}, win: {}, lose: {}, tie:{}".format(self.pure_mcts_simulation_times,win_cnt[1], win_cnt[2], win_cnt[0]))
     return win_ratio
Beispiel #32
0
def main():
    maze = mz.Maze("data/mid_map.csv")
    point = score.Scoreboard("data/UID.csv", "team_puipui")

    #start_point="1.0" #正式競賽由這個取代下兩行 車車放在1的位置面向北邊
    #car_d="3"
    start_point = input("input the start point: ")
    car_d = input("input the car direction (N1 E2 S3 W4):  ")

    car_direction = Direction(int(car_d))
    sequence = maze.BFS(start_point)  #list of type:str
    interf = interface.interface()
    for i in range(0, len(sequence) - 1):
        a = maze.getAction(car_direction, sequence[i], sequence[i + 1])
        interf.send_action(a)
        print(a)
        car_direction = maze.update_cardirc(sequence[i], sequence[i + 1])
    interf.send_action("e")
    while True:
        point.add_UID(interf.read())

    # TODO : Initialize necessary variables
    '''
Beispiel #33
0
def main():
    maze = mz.Maze("data/medium_maze.csv")
    point = score.Scoreboard("data/UID.csv", "team_4")
    interf = interface.interface()  # it will send "s" to arduino
    # TODO : Initialize necessary variables

    if (sys.argv[1] == '0'):
        print("Mode 0: for treasure-hunting")
        # TODO : for treasure-hunting, which encourages you to hunt as many scores as possible
        shortest_path = maze.ShortestPath(int(float(str(maze.getStartPoint()))))
        print("THE PATH:", shortest_path, "\n")
        end_node = maze.FindEndNode()
        end_node.pop(0)
        
        i = 0
        while i < len(shortest_path) - 1:
            if interf.ser.SerialReadString() == "1":
                nd_from = maze.nd_dict[shortest_path[i]]
                nd_to = maze.nd_dict[shortest_path[i + 1]]
                print(f"arrive at Node{shortest_path[i]}")
                interf.ser.SerialWrite(f"{maze.getAction(nd_from, nd_to)}")
                if shortest_path[i] in end_node :
                    UID = interf.ser.SerialReadByte()
                    while UID == "0" or UID == "31":
                        UID = interf.ser.SerialReadByte()
                    UID = str(hex(int(UID)))
                    print("讀到的:", UID)
                    point.add_UID(UID)
                i += 1
        if interf.ser.SerialReadString() == "1":
            interf.ser.SerialWrite("2")
            UID = interf.ser.SerialReadByte()
            while UID == "0" or  UID == "31":
                UID = interf.ser.SerialReadByte()
            UID = str(hex(int(UID)))
            point.add_UID(UID)
            interf.end_process()
Beispiel #34
0
milisecond = 1000
	
## END CONFIGURATION
#########################


# == GENERATED CONFIG VALUES  == 

half_width = screen_width/2
half_height = screen_height/2

# == END GENERATED  == 

random.seed()

iface = interface(screen_width=screen_width, screen_height=screen_height, border=border, point_rad=point_rad)
slider_control = None

# utility function
def is_number(s):
    try:
        float(s)
        return True or s.isdigit()
    except ValueError:
        return False

# help dialogue
def help_dia():
	#	+ "\n\t-w <file>\toutput file (used with -s) (NYI)"	\
	#	+ "\n\t-p \tread from input pipe (NYI)"	\
	#	+ "\n\t-s \tspoof other vehicles on this same path (NYI)"	\
Beispiel #35
0
def main():

    wine_list = pickle.load( open("train/training_cellar.p", "rb") ) 
    interface.interface(wine_list)

    growHarvestPress.dictionarizeTerms( wine_list )
Beispiel #36
0
localeHelper = LocaleHelper()
lang = localeHelper.getLocale()

t=gettext.translation('google2ubuntu',os.path.dirname(os.path.abspath(__file__))+'/i18n/',languages=[lang])
t.install()


# pause media player if necessary
config = expanduser('~')+'/.config/google2ubuntu/google2ubuntu.conf'
paused = False
try:
    with open(config,"r") as f:
        for line in f.readlines():
            line = line.strip('\n')
            field = line.split('=')
            if field[0] == 'pause' and field[1].replace('"','') != '':
                os.system(field[1].replace('"','')+' &')
                paused = True
            elif field[0] == 'play':
                play_command = field[1].replace('"','')
except Exception:
    print 'Error reading google2ubuntu.conf file'

# launch the recognition                    
g2u = interface()

# restore media player state
print paused
if paused:
    os.system(play_command+' &')
Beispiel #37
0
def main():
	print("hello world!")
	current_user = sign.login()
	interface.interface(current_user)
from create_grid import create_grid
from grid_2048 import init_game
from interface import interface
from grid_add_new_tile import grid_add_new_tile
from read_player_command import read_player_command
from movement import movement
from whether_gameover import whether_the_game_is_over

import time

game_continue=0
while game_continue==0:
    game_grid=init_game(4)
    interface(game_grid)
    game_continue=whether_the_game_is_over(game_grid)
    while game_continue==1:
        game_continue=whether_the_game_is_over(game_grid)
        if game_continue==0:
            break
        move= read_player_command()
        grid = create_grid(4)
        for i in range(0,4):
            for j in range(0,4):
                grid[i][j]=game_grid[i][j]
        movement(game_grid,move)
        game_grid=grid_add_new_tile(game_grid)
        while grid==game_grid:
            print("UNABLE TO MOVE THIS WAY")
            move= read_player_command()
            movement(game_grid,move)
        interface(game_grid)
    global terrain, terrain_complet, cases_vues, pos_mines

    # On récupère les nouveaux paramètres
    largeur = iu.sc_largeur.get()
    hauteur = iu.sc_hauteur.get()
    nb_mines = iu.sc_mines.get()

    # On prépare les éléments pour pouvoir finir la partie
    ordi.reset(hauteur, largeur, nb_mines)

    # On remet à zéro les positions vues
    cases_vues = []

    # On génère un terrain et on récupère le terrain et les positions des mines
    terrain, pos_mines = jeu.genere_terrain(largeur, hauteur, nb_mines)

    # On sauvegarde le terrain non-modifié
    terrain_complet = tuple(deepcopy(terrain))

    # On génère le plateau
    iu.canvas_plateau(iu.fenetre, largeur, hauteur)

    iu.lb_chrono.stop_chrono()
    iu.lb_chrono.lance_chrono()


# Exemples en console, toutes les valeurs ici sont des valeurs de test
if __name__ == "__main__":

    iu.interface(NOM_APP, LARGEUR_MIN, HAUTEUR_MIN)
Beispiel #40
0
import interface
from scraper import locate_url, rank_movies, scrape_IMDB, scrape_rt
import movie_page
from movie_summary import get_movie_summary
from similarity_analyzer import find3MostSim
import summary_page

from tkinter import *

if __name__ == "__main__":

    # call interface.py

    window = Tk()
    interface = interface.interface(window)
    window.mainloop()
    user_inputs = []  # obtain user selections
    for i in interface.result:
        user_inputs.append(interface.emotions[i])

    # apply self-built crawler

    user_emotion = user_inputs
    url_lst = locate_url(user_emotion)
    movie_dict = {}

    for url in url_lst:
        if "www.imdb.com" in url:
            if len(user_emotion) == 1:
                movie_dict.update(scrape_IMDB(url, 12))
            elif len(user_emotion) == 2:
Beispiel #41
0
# pause media player if necessary
config = expanduser('~')+'/.config/google2ubuntu/google2ubuntu.conf'
paused = False
haskey = False
key = ''

try:
    with open(config,"r") as f:
        for line in f.readlines():
            line = line.strip('\n')
            field = line.split('=')
            if field[0] == 'pause' and field[1].replace('"','') != '':
                os.system(field[1].replace('"','')+' &')
                paused = True
            elif field[0] == 'play':
                play_command = field[1].replace('"','')
            elif field[0] == 'key' and field[1].replace('"','') != '':
                key = field[1].replace('"','')
                haskey = True
                
except Exception:
    print 'Error reading google2ubuntu.conf file'

if haskey == True:
    # launch the recognition                    
    g2u = interface(key)

    # restore media player state
    if paused:
        os.system(play_command+' &')
Beispiel #42
0
# Name:        noha-alert.py
# Purpose:     Simple script that connects to NoHa and alerts via XML-RPC
#
# Author:      Rune "TheFlyingCorpse" Darrud
#
# Created:     22.01.2012
# Copyright:   (c) Rune "TheFlyingCorpse" Darrud 2012
# Licence:     GPL 2
#-------------------------------------------------------------------------------

import sys, getopt, xmlrpclib, yaml
import interface
import logging

# Make it shorter
i = interface.interface()

debug = False
verbose = False

# Read the config, so it doesnt have to be loaded for every call (downside to reading and parsing for every notifiction)
(temp_result, YamlConfig) = i.load_yaml_config(None)
if temp_result:
    # Set up alert_logger.before anything else! (Ugly?)
    LoggingEnabled = YamlConfig['app_properties']['alert_logging_properties']['logging_enabled']

    # Use the config (if found) to be the guiding star.
    if LoggingEnabled:
        LogFile = YamlConfig['app_properties']['alert_logging_properties']['logfile']
        LogLevel = YamlConfig['app_properties']['alert_logging_properties']['loglevel']
    else:
Beispiel #43
0
#
# Created:     21.01.2012
# Copyright:   (c) Rune "TheFlyingCorpse" Darrud 2012
# Licence:     GPL 2
#-------------------------------------------------------------------------------

import sys, getopt, xmlrpclib, daemon, time
from SimpleXMLRPCServer import SimpleXMLRPCServer
import threading, logging
from threading import Thread
from ruleeval import ruleeval
from interface import interface

# Make it shorter:
r = ruleeval()
i = interface()

# Puproses which need no explainin
debug = False
verbose = False

# Read the config, so it doesnt have to be loaded for every call (downside to reading and parsing for every notifiction)
(temp_result, YamlConfig) = i.load_yaml_config(None)
if temp_result:
	# Set up logging before anything else! (Ugly?)
	LoggingEnabled = YamlConfig['app_properties']['daemon_logging_properties']['logging_enabled']

	# Use the config (if found) to be the guiding star.
	if LoggingEnabled:
		LogFile = YamlConfig['app_properties']['daemon_logging_properties']['logfile']
		LogLevel = YamlConfig['app_properties']['daemon_logging_properties']['loglevel']
Beispiel #44
0
def main():
    maze = mz.Maze("data/final_map.csv")
    interf = interface.interface()
    point = score2.Scoreboard("data/medium_maze_UID.csv", "Lily小粉絲與他的快樂夥伴",
                              sys.argv[1])

    # TODO : Initialize necessary variables
    nownode = 1
    path = []
    sequence = []

    preUID = ""

    if (sys.argv[1] == '0'):
        print("Mode 0: for treasure-hunting with rule 1")
        # TODO : for treasure-hunting with rule 1, which encourages you to hunt as many scores as possible
        maze.setStartDirection(1)

        path = maze.strategy(nownode)
        if len(path) == 1:
            interf.end_process()
            print('end')
        else:
            print(path)
            while (len(path) >= 2):
                nd_to = path[1]
                nd_from = path.pop(0)
                nowdirection = maze.getNowDirection()
                action = maze.getAction(nowdirection, nd_from, nd_to)
                interf.send_action(str(int(action)))
                print(action)
                nownode = nd_to

        while (True):
            if preUID != "":
                point.add_UID(preUID)
                print(preUID)
                preUID = ""

            path = maze.strategy(nownode)
            if len(path) == 1:
                break

            interf.send_action('5')
            print('Action.HALT')

            print(path)
            while (len(path) >= 2):
                nd_to = path[1]
                nd_from = path.pop(0)
                nowdirection = maze.getNowDirection()
                action = maze.getAction(nowdirection, nd_from, nd_to)
                interf.send_action(str(int(action)))
                print(action)
                nownode = nd_to

            # RFID
            while (True):
                UID = interf.get_string()
                if UID != "":
                    print(UID)
                    preUID = UID
                    break

        #RFID
        interf.send_action('5')
        print('Action.HALT')
        while (True):
            UID = interf.get_string()
            if UID != "":
                print(UID)
                point.add_UID(UID)
                break
        interf.end_process()
        print('end')

    elif (sys.argv[1] == '1'):
        print("Mode 1: for treasure-hunting with rule 2")
        # TODO : for treasure-hunting with rule 2, which requires you to hunt as many specified treasures as possible
        sequence = [1, 8, 24, 44, 41, 36]
        # 1, 7, 10, 9, 12
        # 1, 8, 24, 44, 41, 36
        print(sequence)
        maze.setStartDirection(sequence[0])
        print(maze.getNowDirection())

        if len(sequence) == 1:
            interf.end_process()
            print("end")
        else:
            ND_TO = sequence[1]
            ND_FROM = sequence.pop(0)
            path = maze.strategy_2(ND_FROM, ND_TO)
            print(path)
            while (len(path) >= 2):
                nd_to = path[1]
                nd_from = path.pop(0)
                nowdirection = maze.getNowDirection()
                action = maze.getAction(nowdirection, nd_from, nd_to)
                interf.send_action(str(int(action)))
                print(action)
                nownode = nd_to

        while (True):

            if preUID != "":
                point.add_UID(preUID)
                print(preUID)
                preUID = ""

            if len(sequence) == 1:
                break

            interf.send_action('5')
            print('Action.HALT')

            ND_TO = sequence[1]
            ND_FROM = sequence.pop(0)
            path = maze.strategy_2(ND_FROM, ND_TO)
            print(path)
            while (len(path) >= 2):
                nd_to = path[1]
                nd_from = path.pop(0)
                nowdirection = maze.getNowDirection()
                action = maze.getAction(nowdirection, nd_from, nd_to)
                interf.send_action(str(int(action)))
                print(action)
                nownode = nd_to

            #RFID
            while (True):
                UID = interf.get_string()
                if UID != "":
                    print(UID)
                    preUID = UID
                    break
        #RFID
        interf.send_action('5')
        print('Action.HALT')
        while (True):
            UID = interf.get_string()
            if UID != "":
                print(UID)
                point.add_UID(UID)
                break

    elif (sys.argv[1] == '2'):
        # print("Mode 2: Self-testing mode.")
        # TODO: You can write your code to test specific function.

        # interf.send_action('2')
        # interf.send_action(input())
        for i in range(0, 4):
            for j in range(2):
                interf.send_action('3')
                interf.send_action('3')
                interf.send_action('2')
            for j in range(2):
                interf.send_action('4')
                interf.send_action('4')
                interf.send_action('2')
Beispiel #45
0
    def __init__(self, role = constants.get('default.role'),                   \
                 group = constants.get('default.group')):

        # invoke the constructor of the threading superclass
        super(ThunderRPC, self).__init__()

        # check the role of the service to determine the proper configuration
        if (role == 'PUBLISHER'):
            iface = constants.get('server.interface')
            port = SERVER_PORT
        elif (role == 'SUBSCRIBER'):
            iface = constants.get('default.interface')
            port = constants.get('default.port')
        else:
            print('Invalid role identifer.  Must be either ' +                  \
                  '"PUBLISHER" or "SUBSCRIBER"')
            sys.exit(-1)

        # set the interface variable, which is the interface that we want to
        # bind the service to
        self._interface = iface

        # set the role ('PUBLISHER' | 'SUBSCRIBER')
        self._role = role
 
        # set the default nonce value.  this is autogenerated, so the initial
        # value does not matter.
        self._nonce = 'DEADBEEF'

        iface_tool = interface()
        # get the IP address of the system
        self._IP = iface_tool.getAddr(iface)

        # create a TCP server, and bind it to the address of the desired
        # interface
        self._server = self.rpc.ThunderRPCServer((self._IP, port),             \
                                                 self.rpc.RequestHandler)
        self._server._ThunderRPCInstance = self
        self._server.daemon = True

        # workaround for getting the port number for auto-assigned ports
        # (default behavior for clients)
        self._port = self._server.server_address[1]

        # create a dictionary mapping an event name to a function
        self._events = Dictionary()

        # create a dictionary mapping group name to an array of tuples (IP,Port)
        # these tuples represent the clients that are connecting to this service
        # if the role of this service is SUBSCRIBER then this dictionary should
        # always be empty.
        self._clients = Dictionary()

        print('Starting ThunderRPC Service (role = %s)' % role)
        print('-------------------------------------------------')
        print('Binding to IP address - %s:%s' % (self._IP, self._port))

        # register some builtin events for metadata aggregation
        self.registerEvent('UTILIZATION', builtinEvents.utilization)
        self.registerEvent('SYSINFO', builtinEvents.sysInfo)

        # associate with a group
        self._group = group

        # give this node an arbitrary name
        self._name = getMAC(getnode())
 
        # set the default publisher to None
        self._publisher = None

        if (role == 'PUBLISHER'):
            # startup a multicasting thread to respond to multicast messages
            self.mcastThread = threading.Thread(target = self.multicastThread)
            self.mcastThread.start()
            if (self.clients.contains(self.group)): 
               c = self.clients.get(self.group)
               c.append((self.addr[0], int(self.addr[1])))
            else:
               self.clients.append((self.group, [(self.addr[0],                \
                                   int(self.addr[1]))]))
               myConnector = mysql(self.addr[0], 3306)
               myConnector.connect()
               myConnector.insertNode(self.name, self.addr[0] + ':' +          \
                                      str(self.addr[1]), self.group)
               myConnector.disconnect()
            # recreate preseeding files from template
            generatePreseed(self._IP)

        # start the thread
        self.start()

        return