示例#1
0
 def stream(cam, stream, capture_fn):
     while readchar() != '\r':
             image = capture_fn(cam).to_greyscale()
             state.kernel.convolve_image(image).write(stream.stdin)
     stream_in.stdin.close()
     stream_in.wait()
     return
示例#2
0
def test_driving_functions(dt):
    print("w: Move Forward")
    print("a: Move Backward")
    print("s: Turn Left")
    print("d: Turn Right")
    print("k: Stop All Movement")
    print("o: Move piston out")
    print("l: Move piston in")
    input = ''
    while input != "\'x\'":
        input = repr(readchar.readchar())
        if input == "\'w\'":
            dt.drive_forward()
        elif input == "\'a\'":
            dt.turn_left()
        elif input == "\'s\'":
            dt.drive_backward()
        elif input == "\'d\'":
            dt.turn_right()
        elif input == "\'k\'":
            dt.stop_all()
        elif input == "\'o\'":
	    dt.piston_out()
        elif input == "\'l\'":
            print ("")
            dt.piston_in()
    dt.stop_all()
示例#3
0
文件: bot.py 项目: jksingh/sumobot
    def test(self):
        'Testing bot'
        try:
            self.start()

            print 'get config ([fine]:coarse):',
            config = raw_input()
            self.setConfig(config)
            print 'config set to ' + self.getConfig()

            ch = readchar.readchar()
            while(ch != 'Q'):
                self.move(ch)
                ch = readchar.readchar()
        finally:
            self.stop()
def test_driving_functions():
    print("w: Move Forward")
    print("a: Move Backward")
    print("s: Turn Left")
    print("d: Turn Right")
    print("k: Stop All Movement")
    print("l: Retract Piston")
    input = ''
    while input != "\'x\'":
	input = repr(readchar.readchar())
	if input == "\'w\'":
	    drive_forward()
	elif input == "\'a\'":
	    turn_left()
	elif input == "\'s\'":
	    drive_backward()
	elif input == "\'d\'":
	    turn_right()
	elif input == "\'k\'":
	    print("stopping all")
	    stop_all()
	elif input == "\'l\'":
	    print ("")
	    reset_piston()
    stop_all()
def recorder(mp3_ready_event, sigint_event, gpio_queues, thread_stop, playback_file):
    record = []

    while not mp3_ready_event.is_set():
        time.sleep(.001)

    start = datetime.now()

    while not thread_stop.is_set() and not sigint_event.is_set():
        c = readchar.readchar()
        if c == bytes('\x03'):
            sigint_event.set()
            exit()
        desired_state = -1
        index = 0
        if c in config['on_keys']:
            index = config['on_keys'].index(c)
            desired_state = 1
        if c in config['off_keys']:
            index = config['off_keys'].index(c)
            desired_state = 0
        if c in config['toggle_keys']:
            index = config['toggle_keys'].index(c)
            desired_state = 2

        if desired_state >= 0:
            gpio_queues[index].put(desired_state)
            record.append(((datetime.now()-start), index, desired_state))

    pickle.dump(record, open(playback_file, "wb"))
示例#6
0
	def run(self):
		print 'Starting keyboard manager.'
		myevent = False
		while not myevent:
			self.ch = readchar.readchar()
			decoded = self.decode(self.ch)
			print 'Keyboard: Got',self.ch, '. Decoded to:', decoded
#			self.logger.info('Keyboard: Got'+self.ch+'. Decoded to:'+decoded)
			if self.ch in matrix:
				self.command = True			
			if self.ch == 'n':
				self.next = True
			if self.ch == 's':
				self.stop = True
			if self.ch == 'p':
				self.prev = True
			if self.ch == 'v':
				self.volup = True
			if self.ch == 'w':
				self.voldown = True
			if self.ch == 'x':
				self.exit = True
				self.Event.set()
			while self.command:
				pass
			myevent = self.Event.wait(.5)	# wait for this timeout or the flag being set.
		print 'Keyboard manager exiting'
示例#7
0
    def run(self, script=None):
        self.display.set_wpm(60 / self.pusher.word_period)

        if script:
            for key in script:
                self.handle_key(key)

        while True:
            self.handle_key(readchar.readchar())
示例#8
0
文件: emojy.py 项目: pajowu/emojy
 def readchar(self):
     if self.pyinput:
         while len(self.input_cache) == 0:
             self.input_cache = list(str(input("\n:")))
         p = self.input_cache.pop(0)
         return p
     else:
         import readchar
         return readchar.readchar()
示例#9
0
def main():
    initialize_camera()
    while True:
      keyboard_input = readchar.readchar()
      if keyboard_input == 'q':
         break
      elif keyboard_input == 'i':
         zoom_in()
      elif keyboard_input == 'o':
         zoom_out()
示例#10
0
def ask_user(correction):
  import time
  escapekey = 'esc'
  print '>',
  correction = readchar()
  print correction
  time.sleep(10)
  if correction == escapekey:
    return False
  return True
示例#11
0
def test_gpio():
    input = ''
    pin = 228
    wiringpi.pinMode(pin, OUTPUT)

    while input != "\'x\'":
        input = repr(readchar.readchar())
        if input == "\'w\'":
	    print("Bring UP")
            wiringpi.digitalWrite(pin,HIGH)
        elif input == "\'s\'":
	    print("Brind down")
            wiringpi.digitalWrite(pin,LOW)
示例#12
0
def wait_for_input():
    """
    wait_for_input
    """
    try:
        print("started")
        c = ""
        while c != "q":
            c = readchar.readchar()

        print("set")
        G_EVENT.set()
    except:
        pass
def display_menu(pick_place):
    print('\n\n\n')
    print('*' * 40)
    print('*' * 40)
    print('**' + ' ' * 36 + '**')
    print('**' + ' ' * 36 + '**')
    print('**' + ' ' * 12 + 'RAS HACKATHON' + ' ' * 11 + '**')
    print('**' + ' ' * 36 + '**')
    print('**' + ' ' * 36 + '**')
    print('*' * 40)
    print('*' * 40)
    print('1. Show `Pick and Place` Demonstration')
    print('2. Reset robot to Home Position')
    print('3. Exit')
    print('What do you want to do?')
    try:
        choice = int(readchar.readchar())
    except:
        print('Only numbers allowed')

    while (choice > 5):
        print('Please choose one of the valid options [1-5]')
        try:
            choice = int(readchar.readchar())
        except:
            print('Only numbers allowed')

    if choice == 3:
        print('Closing an application')
        sys.exit()
    elif choice == 2:
        pick_place.move_to_home()
        display_menu(pick_place)
        pass
    elif choice == 1:
        pick_place.move_to_pose()
        display_menu(pick_place)
示例#14
0
def get_mode():
	"""Ask for mode to run the script"""
	mode_next_evaluation = '1- Preparar informe de desempeño individual'
	mode_auto_evaluation = '2- Preparar formulario de autoevaluación'
	mode_manager_evaluation = '3- Preparar formulario de evaluación para evaluador'
	mode_exchange_evaluation = '4- Preparar formulario de evaluación para intercambio'
	mode_first_evaluation = '5- Preparar informe de desempeño individual por primera vez'
	mode_rid_evaluation = '6- Preparar informe de RID'
	mode_update_feedback = '7- Actualizar feedback de una evaluación existente'
	while True:
		print('Ingresar modalidad de ejecución:')
		print(mode_next_evaluation)
		print(mode_auto_evaluation)
		print(mode_manager_evaluation)
		print(mode_exchange_evaluation)
		print(mode_first_evaluation)
		print(mode_rid_evaluation)
		print(mode_update_feedback)

		input_mode_number = input('Ingresar opción \'1-7\': ')
		mode = None
		mode = NEXT_EVALUATION if input_mode_number == '1' else mode
		mode = AUTO_EVALUATION if input_mode_number == '2' else mode
		mode = MANAGER_EVALUATION if input_mode_number == '3' else mode
		mode = EXCHANGE_EVALUATION if input_mode_number == '4' else mode
		mode = FIRST_EVALUATION if input_mode_number == '5' else mode
		mode = RID_EVALUATION if input_mode_number == '6' else mode
		mode = UPDATE_FEEDBACK if input_mode_number == '7' else mode

		if mode is None:
			print('El valor ingresado \'' + input_mode_number + '\' no es válido. Revisar y volver a intentar.')
			print('')
			continue

		input_mode = None
		input_mode = mode_next_evaluation if mode == NEXT_EVALUATION else input_mode
		input_mode = mode_auto_evaluation if mode == AUTO_EVALUATION else input_mode
		input_mode = mode_manager_evaluation if mode == MANAGER_EVALUATION else input_mode
		input_mode = mode_exchange_evaluation if mode == EXCHANGE_EVALUATION else input_mode
		input_mode = mode_first_evaluation if mode == FIRST_EVALUATION else input_mode
		input_mode = mode_rid_evaluation if mode == RID_EVALUATION else input_mode
		input_mode = mode_update_feedback if mode == UPDATE_FEEDBACK else input_mode

		print('Modalidad ingresada: \'' + input_mode[3:] + '\'')
		print('Es correcto? Presione \'s/n\'.')
		if readchar.readchar() == 's':
			print('Modalidad confirmada...')
			print('')
			return mode
示例#15
0
def main():
    """test_line()
    Typing test
    """

    # Parsing. 
    parser = argparse.ArgumentParser(description = "Definition of test mode")
    parser.add_argument('-utm', '--user_time_mode', action='store_true', help = 'If used, test will be time based.')
    parser.add_argument('-mv', '--max_value', help = 'Max number of secs for time mode or maximum number of inputs for number of inputs mode.', required=True)
    
    args = parser.parse_args()
    
    mode = args.user_time_mode
    maxi = int(args.max_value)
    
    print('-------------------------------------------------------------------')
    print('PARI typing test.')
    print('Francisco Power, Miguel Carvalhais, Rita Correia, October of 2020')
    print('-------------------------------------------------------------------\n')
    
    if mode:
        print('Your test will last ' + str(maxi) + ' seconds.')
    else:
        print('You will have to type ' + str(maxi) + ' charecters.')
    
    print("Press any key to start the test.\n")
    _ = readchar.readchar()
        
    now = datetime.now()
    start_time = now.strftime("%b %d %H:%M:%S %Y")
    start_time = week[now.weekday()] + ' ' + start_time
        
    if mode:
        main_results = time_mode(maxi)
    else:
        main_results = iter_mode(maxi)
    
    now = datetime.now()
    end_time = now.strftime("%b %d %H:%M:%S %Y")
    end_time = week[now.weekday()] + ' ' + end_time
    
    print(Fore.BLUE + '\nThe test ended.\n')

    #print the results of the statistic function with the parameters: main_results,start_time and end_time
    pprint(statistics(main_results, start_time, end_time))

    
    print('\nThanks for playing!')
    print('-------------------------------------------------------------------\n')
    def _read_user_input(self):

        # input mechanism via readchar
        user_press = b"" if self.platform == 'Windows' else ""
        start_dt = datetime.datetime.now()
        for _ in range(self.sequence_length):
            user_press += readchar.readchar()
        stop_dt = datetime.datetime.now()

        # convert byte string to utf-8 encoded string
        if self.platform == 'Windows':
            user_press = str(user_press, encoding="utf-8")
        time_taken = calculate_time_delta_ms(start_dt, stop_dt)

        return time_taken, user_press
示例#17
0
def listen_for_keychange():
    # propagate user input to game singleton
    # run in main thread (for input)
    while True:
        char = readchar.readchar()
        try:
            direction = SnakeGame.KEYS[char]
            game_state.last_key_press.put(direction)
        except KeyError:
            print 'Wrong key. Use {w, s, a, d}'
            if game_state.stop_flag:
                break
        except KeyboardInterrupt:
            game_state.stop_flag = True
            break
示例#18
0
def main():
    wavFilePath = "/home/valia/Desktop/megan.wav"
    mt_size, mt_step, st_win = 1, 0.1, 0.5
    newPath = StereoToMono(wavFilePath)
    print newPath
    mt_feats_norm = ExtractFeatures(newPath)
    print mt_feats_norm.shape
    #arr = np.asarray(F)
    k_means = KMeans(n_clusters=2)
    k_means.fit(mt_feats_norm.T)
    cls = k_means.labels_
    segs, c = flags2segs(cls, mt_step)  # convert flags to segment limits
    for sp in range(3):  # play each cluster's segment
        for i in range(len(c)):
            if c[i] == sp and segs[i, 1] - segs[i, 0] > 1:
                # play long segments of current speaker
                print(c[i], segs[i, 0], segs[i, 1])
                cmd = "ffmpeg -i {} -ss {} -t {} temp.wav " \
                          "-loglevel panic -y".format(newPath, segs[i, 0]+1,
                                                      segs[i, 1]-segs[i, 0]-1)
                os.system(cmd)
                #os.system("play temp.wav -q")
                playsound('temp.wav')
                readchar.readchar()
示例#19
0
def separateChar(stop_char):
    stop = ord(stop_char)
    numeric_inputs = []
    char_inputs = []
    while True:
        a = readchar.readchar()
        b = ord(a)
        if not b == stop:
            if isnumeric(b):
                numeric_inputs.append(a)
            else:
                char_inputs.append(a)
        else:
            break
    return numeric_inputs, char_inputs
示例#20
0
def write_thread(ser):
    global CONTINUE_RUNNING
    while CONTINUE_RUNNING:
        ch = readchar.readchar()  # blocking call
        try:
            send_str = ch.encode(
                "ASCII")  # convert python string to byte stream
            ser.write(
                send_str
            )  # send non-blocking due to "timeout=0" in serial.Serial(...)
        except:
            pass

        if ord(ch) == 17:  # CTRL+Q ends the program
            CONTINUE_RUNNING = False
示例#21
0
 def speak_a_line(self, role, line, role_to_speak=None):
     if role_to_speak is None:
         role_to_speak = role
     if self.clear:
         subprocess.call(["/usr/bin/clear"])
     if role_to_speak in self._voices:
         voice = self._voices[role_to_speak]
     else:
         voice = self._voices[None]
         line = "{} says: {}".format(role, line)
     sys.stdout.write("\n{}\n".format(role.upper()))
     if role == self.role and not self.mute:
         if self.display_role:
             sys.stdout.write("{}\n".format(
                 textwrap.fill(line, self._columns)))
         while True:
             sys.stdout.flush()
             say_it = readchar.readchar().lower()
             LOGGER.debug(">>>{}<<<".format(say_it))
             if say_it == "\x03":
                 raise KeyboardInterrupt
             elif say_it == "\x04":
                 raise EOFError
             elif say_it == "?":
                 sys.stdout.write(
                     "  Hit H for a hint, Y to read the whole line,\n"
                     "  Ctrl-C or Ctrl-D to exit, or any key to move on to the next line\n"
                 )
             elif say_it == "h":
                 if " " in line:
                     hint, line = re.split(r"\s+", line, 1)
                 else:
                     hint, line = line, None
                 if not self.display_role:
                     sys.stdout.write("{} ".format(hint))
                 self.vocalise(voice, hint, self.mute)
                 if line is None:
                     sys.stdout.write("\n")
                     return
             else:
                 break
     else:
         say_it = "y"
     if not (role == self.role and (self.mute or self.display_role)):
         sys.stdout.write("{}\n".format(textwrap.fill(line, self._columns)))
     if not say_it.lower().startswith("y"):
         return
     self.vocalise(voice, line, mute=(self.mute and role == self.role))
示例#22
0
def main():
    print('for exit press "q"')
    print('for move pess: "w" "a" "s" "d"')
    print('for shut pess: " "')
    print('for create personage press: "r"')
    print('for delete personage press: "t"')

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.settimeout(0.5)
    char = 0
    _id = 0
    print('connec to host:%s port:%s' % (UDP_IP, UDP_PORT))

    while char != 'q':
        try:
            char = readchar.readchar()
            if char == 'w':
                cmd = {'cmd': 'increase_speed', 'data': {'id': _id}}
                sock.sendto(json.dumps(cmd).encode(), (UDP_IP, UDP_PORT))
                sock.recv(128).decode()
            elif char == 's':
                cmd = {'cmd': 'reduce_speed', 'data': {'id': _id}}
                sock.sendto(json.dumps(cmd).encode(), (UDP_IP, UDP_PORT))
                sock.recv(128).decode()
            elif char == 'a':
                cmd = {'cmd': 'reduce_angle', 'data': {'id': _id}}
                sock.sendto(json.dumps(cmd).encode(), (UDP_IP, UDP_PORT))
                sock.recv(128).decode()
            elif char == 'd':
                cmd = {'cmd': 'increase_angle', 'data': {'id': _id}}
                sock.sendto(json.dumps(cmd).encode(), (UDP_IP, UDP_PORT))
                sock.recv(128).decode()
            elif char == ' ':
                cmd = {'cmd': 'create_bullet', 'data': {'id': _id}}
                sock.sendto(json.dumps(cmd).encode(), (UDP_IP, UDP_PORT))
                sock.recv(128).decode()
            elif char == 'r':
                cmd = {'cmd': 'create_personage', 'data': {'pos': [0, 0]}}
                sock.sendto(json.dumps(cmd).encode(), (UDP_IP, UDP_PORT))
                res = json.loads(sock.recv(128).decode())['data']
                _id = res['id']
            elif char == 't':
                cmd = {'cmd': 'delete_personage', 'data': {'id': _id}}
                sock.sendto(json.dumps(cmd).encode(), (UDP_IP, UDP_PORT))
                sock.recv(128).decode()
            # print('char:%s type:%s ' % (char, type(char)))
        except socket.timeout as e:
            LOG.warning('socket error:%s' % (e, ))
示例#23
0
    def define_sex(self, df, idx):
        """Saves the sex of this person.

        Saves the sex of this person either by taking it from the the param df
        or by getting it from stdin
        """
        try:
            return df['sexes'][idx]
        except KeyError:
            print(f"Is {self.name} a man/Woman? (M/w) ")
            if readchar.readchar() is 'w':
                self.sex = 'w'
                return self.sex
            else:
                self.sex = 'm'
                return self.sex
示例#24
0
def charReader():
    global InChar

    print('charReader()')

    InChar = ''
    while True:
        InChar = readchar.readchar()
        print('InChar =', InChar, ord(InChar))

        if len(InChar) == 0:
            break
        if ord(InChar) <= 0x20:
            break

    print('charReader():end')
示例#25
0
def readvalue():
    while True:
        inp = repr(readchar.readchar())
        inp = inp.strip("'")
        inp = inp.replace("b\'", '')  # Windows Fix
        if inp == '\\x1b':
            print()
            exit()
        elif inp == ' ':
            return 0
        try:
            value = int(inp)
            return value

        except ValueError:
            continue
示例#26
0
def readchar_thread():
    global inChar
    
    myid = threading.get_ident()
    print('start readchar_thread()', myid)

    while True:
        ch = readchar.readchar()
        print(myid, '"'+ch+'"')

        cmd_Q.put(ch)

        if ch == ' ' or ord(ch) <= 20:
            break

    print(myid, 'end')
示例#27
0
def printAllCharsUpTo(stop_char):

    #key = readchar.readkey(c)
    num = ord(stop_char)                #Converte o caracter para decimal
    print('Stop Char: ' + stop_char)
    print('Type char: ')
    str=''
    while True:
        c= readchar.readchar()
        if c == stop_char:
            break
        else:
            print('Try again: ')
    for i in range(32,num+1):                #se começa no '' este cracter em ASCII corresponde ao nº32
            str=str + chr(i)                    #Converte para caracter
    print ('A resposta é:' + str)
 def loop(self):
     c = readchar.readchar()
     if c == 'z':
         self.target_position += 0.001
     elif c == 'x':
         self.target_position -= 0.001
     elif c == 'a':
         self.target_position += 0.01
     elif c == 's':
         self.target_position -= 0.01
     elif c == 'q':
         self.target_position += 0.1
     elif c == 'w':
         self.target_position -= 0.1
     self.target_position_pub.publish(self.target_position)
     print(self.target_position)
示例#29
0
def main():
    state = random_state(6, 10)
    key = ''
    while state and key != 'q':
        draw(state)
        key = readchar()
        if key == 'w':
            state = change_snake_direction(Directions.NORTH, state)
        elif key == 's':
            state = change_snake_direction(Directions.SOUTH, state)
        elif key == 'd':
            state = change_snake_direction(Directions.EAST, state)
        elif key == 'a':
            state = change_snake_direction(Directions.WEST, state)

        state = next_state(state)
示例#30
0
def get_input():
    # key = input("Enter a key: ")
    key = readchar.readchar()
    # key = key.decode('ascii')
    keyChar = key.decode('ascii')

    if (keyChar == ' '):
        return 10
    elif (keyChar < '0' or keyChar > '9'):
        return 11

    index = int(key.decode('ascii'))
    finger = hand_index_to_string[index]

    print("\nRead " + str(index) + " which is for " + finger)
    return index
示例#31
0
def Streak():
    MorseChars = list(CODE.keys())

    practice = input(
        "\nType the characters you wish to practice\n(non-alphanumeric characters will be ignored): "
    )
    practice = list(set(Filter(practice)))
    if ' ' in practice:
        practice.remove(' ')
    if len(practice) == 0:
        print("\nYou can't work with an empty set homie, try again/")
        Streak()

    print('characters being practiced:   ', ' '.join(practice))
    print('type what you hear')
    Countdown()
    tryagain = True
    while tryagain:
        start = time.perf_counter()
        total = 0
        Correct = True
        while Correct:
            rn = int(random() * len(practice))
            letter = practice[rn]
            p1 = Process(target=MorsePlay, args=(letter, ))
            p1.start()

            char = readchar.readchar()  #Crux was finding this capability
            if char == letter:
                total += 1
            else:
                Correct = False
            p1.join()
        end = time.perf_counter()

        print("\n\nTotal:           ", total)
        print("\n\nTime:            ", round((end - start), 2), "s")
        print("\n\nletters/sec:     ", round(total / (end - start), 2))

        print("\nSorry, last character was", letter, 'not', char)
        response = input("\nDo you want to try this same set again? <y/n> ")
        while response != 'y' and response != 'n':
            response = input("invalid response, try again: ")
        if response == 'n':
            tryagain = False

    Menu()
示例#32
0
def countNumberUPTO():
    total_number = 0
    total_other = 0

    inputs = [] # crio a list de imputs

    while True:
        print ("intreduza carater:")
        intVariavel = readchar.readchar()

        inputs.append(intVariavel)  # acrecenta varaiveis no input

        # retiri o isnumeric pois so dava para python3 e nao tinha conseguido fazer isso anteriormente

        intVariavel = ord(intVariavel)

        if intVariavel != 120:
            print ("intreduza o valor outra vez :")

        else:
            break

    # para destingir se e numero ou nao

    for input in inputs:  # vai correndo as variaveis que tenho nas listas



        if input.isdigit():
            total_other = total_number + 1
        else:
            total_number = total_number + 1

    print ("you entered " + str(total_number) + "numbers.")
    print ("you entered " + str(total_other) + "others.")


    # ex 5c

    dict_other={}

    for idx,input in enumerate(inputs): # o enumerate inumera as variavais para outra variavel que tinhamos
        if not input.isdigit():
            dict_other[idx]=input # add new key-value to dictianary


    print ('dint_other '+ str(dict_other))
示例#33
0
文件: prompt.py 项目: lainiwa/buglog
def user_read_character(*args: str) -> str:
    """Read single character.

    Prompt user with the lines passed as parameters,
    and then wait for a valid keypress. The possible
    keypresses are searched in between of ``[]`` brackets.

    If the letter in brackets is UPPERCASE, then it is treated as
    a default choice and corrsponds to pressing Enter.

    Example:
        >>> user_read_character("Install?", "[Y]es/[n]ope")  # doctest: +SKIP

    Parameters:
        args: Lines to be printed as a prompt.

    Returns:
        The letter the user have chosen; lowercase.
    """
    # Construct prompt message from provided arguments
    prompt = "\n".join(args)
    # All letters the user specified to accept
    letters = "".join(re.findall(r"\[(.)\]", prompt))
    # The big letter (if present) or empty string
    big_letter = "".join(ch for ch in letters if ch.isupper()).lower()
    # Accepted characters with Enter as a default choice
    chars = letters.lower() + "\r" if big_letter else letters.lower()

    while True:
        # Print prompt message and wait for user input
        print(prompt, end="", flush=True)
        char = readchar.readchar().lower()
        # If user typed a valid choice - echo the typed letter and return it
        # Enter is echoed as the default choice letter
        if char in chars:
            if char == "\r":
                char = big_letter
            print(char.upper())
            return char
        # otherwise just echo the letter
        print(char.upper())

        # Print message with available choices
        char_list_str = ", ".join(f"'{let}'" for let in letters.upper()[:-1])
        last_char_str = letters[-1].upper()
        print(f"Type either {char_list_str} or '{last_char_str}'")
        print()
示例#34
0
def keyCheck():
    global ACTIVE
    global ALLFIN
    global LEN
    soloFlag = False

    print "\n"

    while ALLFIN is False:
        for i in range(LEN):
            if (ACTIVE[i] == 1):
                print "[%d] " % ((i + 1) % MAX_CHANNEL),
            else:
                print "[ ] ",
        if (soloFlag is True):
            print "Solo",
        else:
            print "    ",
        print "\r",

        key = readchar.readchar()
        key = ord(key)
        if (ord('0') <= key and key < MAX_CHANNEL + ord('0')):
            if (key == ord('0')):
                cnt = MAX_CHANNEL
            else:
                cnt = key - ord('0')
            if (cnt <= LEN):
                if (soloFlag is True):
                    for i in range(LEN):
                        ACTIVE[i] = 0
                ACTIVE[cnt - 1] = 1 - ACTIVE[cnt - 1]

        elif (key == ord('a')):
            for i in range(LEN):
                ACTIVE[i] = 1

        elif (key == ord('r')):
            for i in range(LEN):
                ACTIVE[i] = 1 - ACTIVE[i]

        elif (key == ord('s')):
            soloFlag = not soloFlag

        elif (key == ord('q')):
            print "\nQuit."
            ALLFIN = True
示例#35
0
def get_digits(size=9):
    """
  accept digits from user to fill puzzle array.
  """
    print acceptable_digits
    puzzle = []
    for xarg in range(size):
        line = []
        for yarg in range(size):
            userchar = 99
            while userchar not in acceptable_digits:
                userchar = readchar()
            line += userchar
            print ' ' + userchar,
        puzzle.append(line)
        print  # carriage return, line feed
    return puzzle
示例#36
0
def run_manual_loop(game, lookahead_fn=None):
    game.render_board()
    key_to_moves = {
        "w": game.UP,
        "A": game.UP,
        "d": game.RIGHT,
        "C": game.RIGHT,
        "s": game.DOWN,
        "B": game.DOWN,
        "a": game.LEFT,
        "D": game.LEFT,
    }
    moves_to_str = {
        game.UP: "Up",
        game.RIGHT: "Right",
        game.DOWN: "Down",
        game.LEFT: "Left",
    }
    should_print = True
    while True:
        if should_print:
            if lookahead_fn:
                suggested_action = lookahead_fn(game.board[:])
            print(f"Score: {game.score}")
            print("Move (w=UP, d=RIGHT, s=DOWN, a=LEFT, or arrows)?")
            if lookahead_fn:
                action_str = moves_to_str[suggested_action]
                print(f"Suggested move (spacebar to accept): {action_str}")
            should_print = False
        move = readchar.readchar()
        if move in ["\x03", "\x04", "\x1a"]:
            print("Exiting...")
            break
        if move == "\x20" and lookahead_fn:
            move_items = key_to_moves.items()
            move = [k for k, v in move_items if v == suggested_action][0]
        if move not in key_to_moves:
            continue
        print(f"Move: {moves_to_str[key_to_moves[move]]}")
        should_print = True
        _, _, done, _ = game.step(key_to_moves[move])
        print()
        game.render_board()
        if done:
            print("Game over!")
            break
示例#37
0
    def japanese(self, gametime):
        self.game_t = gametime
        kana = word_house.kana()
        word_list = self.select_word(2)
        num = len(word_list)

        stime = time.time()

        self.miss_count = []
        self.word_count = []
        self.word_num = []

        while time.time() - stime < gametime:
            for i in range(num):
                if time.time() - stime > gametime:
                    break
                else:
                    pass
                word_single_list = list(word_list[i])
                print("===========")
                print(word_list[i])
                print("===========")
                num2 = len(word_single_list)
                self.word_num.append(num2)

                for ii in range(num2):
                    word = word_single_list[ii]
                    word_kana = kana[word]
                    now_list = word_single_list[:ii]
                    now_word = "".join(now_list)
                    print(now_word)

                    for i in list(word_kana):
                        while True:
                            word2 = readchar.readchar()
                            if word2 == word:
                                break
                            else:
                                print("\007")
                                self.miss_count.append(1)
                                continue
                continue
                #print("go to next word")
        print("======= Game End =====")
        print("======= RESULT =======")
        self.check_result()
示例#38
0
def write_thread(ser):
    global CONTINUE_RUNNING
    while CONTINUE_RUNNING:
        ch = readchar.readchar()  # blocking call
        print(ch, end="")  # echo all typed characters
        sys.stdout.flush()  # see the characters instantly
        try:
            send_str = ch.encode(
                "ASCII")  # convert python string to byte stream
            ser.write(
                send_str
            )  # send non-blocking due to "timeout=0" in serial.Serial(...)
        except:
            pass

        if ord(ch) == 17:  # CTRL+Q ends the program
            CONTINUE_RUNNING = False
示例#39
0
 def artist(self, artist):
     '''get user input for each top-level directory'''
     artist_path = os.path.join(self.rootdir, artist)
     if os.path.isfile(artist_path):
         return
     os.system('clear')
     print artist
     album_list = []
     for album in os.listdir(artist_path):
         if os.path.isfile(os.path.join(artist_path, album)):
             continue
         album_list.append(album)
         print '  ' + album
     print
     genredic = { k: self.genre_lst.count(k) for k in set(self.genre_lst) }
     topten = sorted(genredic, key=genredic.get, reverse=True)[:10]
     for entry in enumerate(topten):
         print entry[0], '    ', entry[1]
     print "\nEnter  Input a common genre for the artist"
     print "L      Input a genre for each album"
     print "Space  Skip directory"
     print "Q      Quit loop"
     genre = False
     choice = readchar.readchar()
     if choice == ' ':
         return
     elif choice == 'q':
         sys.exit()
     elif choice.isdigit():
         try:
             genre = topten[int(choice)]
             self.genre_lst.append(genre)
             self.harmonize_dir(artist_path, genre)
         except IndexError:
             pass
     print
     if choice == '\r':
         genre = raw_input("Enter artist genre: ")
         self.genre_lst.append(genre)
         self.harmonize_dir(artist_path, genre)
     elif choice == 'l':
         for album in album_list:
             print '   ' + album
             genre = raw_input("   Enter album genre: ")
             self.genre_lst.append(genre)
             self.harmonize_dir(os.path.join(artist_path, album), genre)
示例#40
0
文件: test.py 项目: yusuftrl/mina
 def prompt(self, msg, default):
     if self.force_yes:
         return True
     elif self.non_interactive:
         return default
     else:
         while True:
             sys.stdout.write('%s [y/n] ' % msg)
             sys.stdout.flush()
             c = readchar()
             print()
             if c == 'y' or c == 'Y':
                 return True
             elif c == 'n' or c == 'N':
                 return False
             else:
                 print('  invalid input')
示例#41
0
def get_digits(size=9):
  """
  accept digits from user to fill puzzle array.
  """
  print acceptable_digits
  puzzle = []
  for xarg in range(size):
    line = []
    for yarg in range(size):
      userchar = 99
      while userchar not in acceptable_digits:
        userchar = readchar()
      line += userchar
      print ' ' + userchar,
    puzzle.append(line)
    print # carriage return, line feed
  return puzzle
示例#42
0
 def speak_a_line(self, role, line, role_to_speak=None):
     if role_to_speak is None:
         role_to_speak = role
     if self.clear:
         subprocess.call(['/usr/bin/clear'])
     if role_to_speak in self._voices:
         voice = self._voices[role_to_speak]
     else:
         voice = self._voices[None]
         line = '{} says: {}'.format(role, line)
     sys.stdout.write('\n{}\n'.format(role.upper()))
     if role == self.role and not self.mute:
         if self.display_role:
             sys.stdout.write('{}\n'.format(textwrap.fill(line, self._columns)))
         while True:
             sys.stdout.flush()
             say_it = readchar.readchar().lower()
             LOGGER.debug(">>>{}<<<".format(say_it))
             if say_it == '\x03':
                 raise KeyboardInterrupt
             elif say_it == '\x04':
                 raise EOFError
             elif say_it == '?':
                 sys.stdout.write('  Hit H for a hint, Y to read the whole line,\n'
                                  '  Ctrl-C or Ctrl-D to exit, or any key to move on to the next line\n')
             elif say_it == 'h':
                 if ' ' in line:
                     hint, line = re.split(r'\s+', line, 1)
                 else:
                     hint, line = line, None
                 if not self.display_role:
                     sys.stdout.write('{} '.format(hint))
                 self.vocalise(voice, hint, self.mute)
                 if line is None:
                     sys.stdout.write('\n')
                     return
             else:
                 break
     else:
         say_it = 'y'
     if not (role == self.role and (self.mute or self.display_role)):
         sys.stdout.write('{}\n'.format(textwrap.fill(line, self._columns)))
     if not say_it.lower().startswith('y'):
         return
     self.vocalise(voice, line, mute=(self.mute and role == self.role))
示例#43
0
def main(basename):
    print('> ', basename)
    runs_filename = 'runs_' + basename + '.json'
    runs = runs_from_json_file(runs_filename)
    audio = AudioSegment.from_wav('filtered_' + basename + '.wav')

    for i, run in enumerate(runs.runs):
        padded_start = max(0, run.start - run_padding)
        padded_end = min(len(audio), run.start + run_padding)
        chunk = audio[padded_start:padded_end]

        print(
            '{}/{} [e]mergency, [w]ind, [j]ake brake, [h]orn, [g]ate, [r]eplay, [O]ther: '
            .format(i + 1, len(runs.runs)),
            end='')
        playback.play(chunk)

        tag = None
        while tag is None:
            tag = readchar()
            if tag == 'r':
                playback.play(chunk)
                tag = None
            elif tag == 'q':
                exit()
            elif tag == '\r':
                tag = ''
            elif tag == 'h':
                tag = 'horn'
            elif tag == 'w':
                tag = 'wind'
            elif tag == 'e':
                tag = 'emergency'
            elif tag == 'j':
                tag = 'jake brake'
            elif tag == 'g':
                tag = 'gate'
            else:
                tag = None

        if tag != '': run.add_tag(tag)
        print('\n   ', repr(run))

    with open(runs_filename, 'w') as f:
        json.dump(runs.to_dict(), f)
示例#44
0
    def english(self, gametime):
        self.game_t = gametime
        word_list = self.select_word(1)
        num = len(word_list)

        stime = time.time()

        self.miss_count = []
        self.word_count = []
        self.word_num = []

        while time.time() - stime < gametime:
            for i in range(num):
                if time.time() - stime > gametime:
                    break
                else:
                    pass
                word_single_list = list(word_list[i])
                print("===========")
                print(word_list[i])
                print("===========")
                num2 = len(word_single_list)
                self.word_num.append(num2)
                self.word_count.append(0.3)

                for ii in range(num2):
                    word = word_single_list[ii]

                    now_list = word_single_list[:ii]
                    now_word = "".join(now_list)
                    print("\r" + now_word, end="")
                    while True:
                        word2 = readchar.readchar()
                        if word == word2:
                            break
                        else:
                            print("\007", end="")
                            self.miss_count.append(1)
                            continue
                print("\n")
                continue
                #print("go to next word")
        print("======= Game End =====")
        print("======= RESULT =======")
        self.check_result()
示例#45
0
def start():
    l_volumes, r_volumes = np.array([1, 0, 0, 0, 0]), np.array([0, 0, 0, 1, 0])
    shared_music_l_volumes, shared_music_r_volumes = Array("f",
                                                           l_volumes), Array(
                                                               "f", r_volumes)
    # デバックモード
    direction = Value('i', 0)

    music_process = Process(
        target=play_music,
        args=[shared_music_l_volumes, shared_music_r_volumes])
    speaker_process = Process(
        target=assign_speaker,
        args=[shared_music_l_volumes, shared_music_r_volumes, direction])
    music_process.start()
    speaker_process.start()

    while (True):
        kb = readchar.readchar()
        if kb == 'q':
            direction.value = -1
        elif kb == 's':
            direction.value = 0
        elif kb == 'a':
            direction.value = 9
        elif kb == '1':
            direction.value = 1
        elif kb == '2':
            direction.value = 2
        elif kb == '3':
            direction.value = 3
        elif kb == '4':
            direction.value = 4
        elif kb == '5':
            direction.value = 5
        elif kb == 'z':
            direction.value = 6
        elif kb == 'x':
            direction.value = 7
        elif kb == 'c':
            direction.value = 8
        elif kb == 'v':
            direction.value = -2
        elif kb == 'b':
            direction.value = -3
示例#46
0
 def start(self, topic):
   self.cards = topic.getCardsToTrain()[:]
   while self.cards:
     card = self.cards.pop()
     print(card.side[0])
     usrInput = input()
     if card.side[0] in self.result:
       self.result[card.side[0]] += int(usrInput == card.side[1]) + 1
     else:
       self.result[card.side[0]] = int(usrInput == card.side[1]) + 1
     if usrInput != card.side[1]:
       self.cards.insert(0,card)
       print(usrInput + " == " + card.side[0] + " = " + str(usrInput == card.side[1]))
       print("Continue by pressing a key")
       key = readchar.readchar();
       if key == '\x03' or key == '\x04' or key == '\x1A':
         sys.exit()
       print(repr(key))
   print(self.result)
   topic.saveTrainingResult(self.result)
示例#47
0
def keyInput(cat, ans, amnt):
	#win = curses.initscr()
	#key = win.getch()
	print("Enter Key: ")
	#key = raw_input("Enter Key: ")
	#print("Enter Key: ")
	is_key = False
	while is_key == False:
		key = readchar.readchar()
		if key == 'a':
			is_key = True
		elif key == 'l':
			is_key = True

	if key == 'a':
		#player1
		player1_turn(cat, ans, amnt)
	elif key == 'l':
		#player2
		player2_turn(cat, ans, amnt)
示例#48
0
def controller(zone):
    """Control currently playing track."""
    keep_polling = True
    while keep_polling:
        if _FINISH:
            # catch the abort signal to avoid deadlock
            break
        device_state = zone.get_current_transport_info()['current_transport_state']
        control_input = readchar.readchar()
        if control_input.lower() == 's':
            # stop track
            zone.stop()
            print '\tSTOPPED'
            keep_polling = False
            continue
        elif control_input.lower() == 'p' and device_state == 'PAUSED_PLAYBACK':
            # unpause
            print '\t{}'.format(device_state)
            zone.play()
            print '\tRESUME'
        elif control_input.lower() == 'p' and device_state in ['PLAYING', 'RESUME', 'TRANSITIONING']:
            # pause
            print '\t{}'.format(device_state)
            zone.pause()
            print '\tPAUSED'
        elif control_input.lower() == 'u':
            # volume up
            zone.volume += 1
            print '\tVOLUME ({}) +'.format(zone.volume)
        elif control_input.lower() == 'd':
            # volume down
            zone.volume -= 1
            print '\tVOLUME ({}) -'.format(zone.volume)
        elif control_input.lower() == 'q':
            # quit
            zone.stop()
            print '\tEXITING'
            os.kill(os.getpid(), signal.SIGKILL)
        time.sleep(0.1)
    return None
 def __get_ascii(self):
     ch = readchar.readchar()
     self.MEMORY[self.memory_pointer] = ord(ch)
示例#50
0
# motors = [motor1, motor2, motor3, motor4]


def initialize():
    for pin in pins:
        motors.append(Motor(pin))

    """time.sleep(5)
    for motor in motors:
        call(["pigs", "s", str(motor.pin), "1270"])

    time.sleep(5)
    for motor in motors:
        call(["pigs", "s", str(motor.pin), "0"])"""


if __name__ == "__main__":
    initialize()
    print "w > increase | s > decrease | q > quit"
    while True:
        print throttle
        choice = readchar.readchar()
        if choice == "w":
            throttleUp()
        if choice == "s":
            throttleDown()
        if choice == "q":
            switchOff()
            exit()
示例#51
0
    return distance

def calculate_velocity(d0,d1,old_d0,old_d1,last_read):
    v0 = (d0-old_d0)/(last_read-lastTime)
    v1 = (d1-old_d1)/(last_read-lastTime)
    return (v0+v1)/2
    


while True:
    lcd.enable_display(True)
    users = get_Users()
    while not userFlag:
        lcd.clear()
        lcd.message("Please enter your user ID: " + user_id)
        ui = readchar.readchar()
        now = time()
        while now - lastTime < REFRESH_TIME:
            sleep(.5)
            now = time()
        if ui != "\n":
            user_id += ui
        else:
            if user_id in users:
                userFlag = 1
            else:
                lcd.clear()
                lcd.message("Incorrect User ID")
                user_id = ""
    lcd.clear()
    lcd.message("Hello " + users[user_id])
示例#52
0
  # close serial port
  print "close serial port"
  s.close()



# ============= main application starts here ==================

# init serial port
s = serial.Serial(port = '/dev/ttyACM0', baudrate = 115200) #SensorTag


# start read_loop in a separate thread
read_data = True
t1 = threading.Thread(target=read_loop, args=())
t1.start()

# send loop for serial port
while True:
  try:
    #for command in ['0' , '1', '2', 'a', 'i', 't']:
      command=readchar.readchar()
      s.write(command)
      time.sleep(1)
  except KeyboardInterrupt:
    print "Shutdown"
    break

read_data = False

    elif key == ' ':
        num = 84
    elif key == '\x07': # bell character, ctrl-g
        num = 60
    elif 'A' <= key <= 'Z':
        num = ord(key.lower()) - ord('a') + 30
    elif key == '+': # caps
        num = 86
    elif key == '=': # shift
        num = 87
    return num

num = 0;
print("Please start typing! (ctrl-c or ctrl-d to quit, ctrl-g for bell)")
while True:    
    key = readchar.readchar()
    if (key == '\r'):
        print()
    else:
        if key != '\x07': # ignore bell for terminal
            sys.stdout.write(key)
            sys.stdout.flush()
    if key == '\x03' or key == '\x04': # ctrl-c or ctrl-d
        break

    num = charToTypewriter(key)
    
    if key in uppercase:
        # caps lock
        output.send(mido.Message('note_on',note=86,velocity=64))
示例#54
0
文件: next.py 项目: zhangkaka/supercp
        for output in outputs:
            # colortext += "{t.normal}" + output.strip() + '{t.red}' + "{t.bold}" + keyword.strip() + "{t.normal}".strip()
            colortext += "{t.normal}" + output + "{t.red}" + "{t.bold}" + keyword + "{t.normal}"
        print colortext[0 : -len(keyword + "{t.normal}")].strip().format(t=t)

        if line == "" and p.poll() != None:
            break


genhostlist()
os.system("clear")
os.system("cat %s" % (hostlist))
limit = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890_-:*.|\/\\"
keyword = ""
while True:
    key = repr(readchar.readchar())
    if not (key[1] in limit):
        os.system("clear")
        os.system("cat %s" % (hostlist))
        print use_style("Warnning!! Invalide Char %s!" % (key[1]), mode="bold", fore="red")
        print keyword
        continue
    elif key[1] == "*":
        keyword = keyword[0:-1]
        if len(keyword) == 0:
            os.system("clear")
            os.system("cat %s" % (hostlist))
            print use_style("Warnning!!!NO char to delete!", mode="bold", fore="red")
            continue
    elif key == _ENTER:
        if len(keyword) == 0:
示例#55
0
def char_generator_from_repl():
    while True:
        x = readchar.readchar()
        yield x
 def execute(self, node):
   node.value = ord(readchar.readchar())
   return (self.next, node)
示例#57
0
print("Type x to exit!!!")

# Both motors rotate clockwise (looking into the shaft) with +ve values
# 1 is left motor 
speed1=0
# 2 is right motor
speed2=0


try:
    print("")

    count = 0
    while True:
        count += 1
        c = readchar.readchar()
        if c == 'x':
            exit()
        # quickly reset motors using o or r
        if c == 'r':
            speed1 =0
            speed2 =0
        if c == 'o':
            speed1 =0
            speed2 =0
        # debugging keys using qa and ed
        if c == 'q':
            speed1 +=20
        if c == 'a':
            speed1 -=20
        if c == 'e':
示例#58
0
# how to install readchar, pip install readchar
import readchar

print("Reading a char:")
print(repr(readchar.readchar()))
print("Reading a key:")
print(repr(readchar.readkey()))

atexit.register(turnOffMotors)

lr_motor = mh.getMotor(4)
shoulder_motor = mh.getMotor(3)
elbow_motor = mh.getMotor(1)
wrist_motor = mh.getMotor(2)

import readchar

print "Press q to quit"
username = ""

while True:
    c = repr(readchar.readchar()).replace("'", "")
    if c == "q":
        exit(0)
    elif c == "a":
        print username, "Left"
        lr_motor.setSpeed(255)
        lr_motor.run(Adafruit_MotorHAT.BACKWARD)
        time.sleep(0.1)
        lr_motor.run(Adafruit_MotorHAT.RELEASE)
    elif c == "d":
        print username, "Right"
        lr_motor.setSpeed(255)
        lr_motor.run(Adafruit_MotorHAT.FORWARD)
        time.sleep(0.1)
        lr_motor.run(Adafruit_MotorHAT.RELEASE)
    elif c == "w":
示例#60
0
def getChar():
    global look
    look = readchar.readchar()