示例#1
0
def _send_specified_file(_ui: UserInput):
    """_send_specified_file()

    ui is a UserInput

    opens the controller, the commandreader, and
    sends each line to the controller.

    """

    _ui.open()
    _c: Controller = Controller(_ui)
    _cr = CommandReader(_ui)
    _cr.open()
    _c.open()
    try:
        while 1:
            line: str = _cr.get()
            if line == "":
                break  # exit when file read
            _c.sendcmd(line, echoit=_DEBUGGING)
    finally:
        _c.close()
        _cr.close()
        _ui.close()
示例#2
0
 def tearDownClass(cls):
     _ui = UserInput()
     _ui.request('com4')
     flex = Flex(_ui)
     flex.open()
     flex.restore_state(cls.initial_state)
     flex.close()
示例#3
0
 def setUpClass(cls):
     _ui = UserInput()
     _ui.request('com4')
     flex = Flex(_ui)
     flex.open()
     cls.initial_state = flex.save_current_state()
     flex.close()
示例#4
0
 def setUp(self):
     _ui = UserInput()
     _ui.request('com4')
     self.flex = Flex(_ui)
     self.flex.open()
     _ = self.flex.do_cmd_list(postproc.INITIALZE_FLEX)
     self.assertEqual(13, len(_))
示例#5
0
class Grid:
    DEAD = 0
    ALIVE = 1

    def __init__(self, configuration):
        pygame.init()
        self.display = Display(pygame, configuration)
        self.display.refresh()
        pygame.display.update()

        self.x_cell_number = configuration['x_cell_number']
        self.y_cell_number = configuration['y_cell_number']
        self.game_state = numpy.zeros((self.x_cell_number, self.y_cell_number))
        self.user_input = UserInput(self.x_cell_number, self.y_cell_number)

    def run(self):
        updatable_game_state = numpy.copy(self.game_state)

        while True:
            self.display.refresh()
            # pygame.display.update()
            time.sleep(0.1)

            self.user_input.update_state(pygame, updatable_game_state)

            if self.user_input.play:
                self._play(updatable_game_state)

            self.game_state = updatable_game_state

    def _play(self, updatable_game_state):
        for y in range(0, self.x_cell_number):
            for x in range(0, self.y_cell_number):
                neighbours = self._neighbours(x, y)

                if self.game_state[x, y] == self.DEAD and neighbours == 3:
                    updatable_game_state[x, y] = self.ALIVE

                elif self.game_state[x, y] == self.ALIVE and (neighbours < 2 or
                                                              neighbours > 3):
                    updatable_game_state[x, y] = self.DEAD

                if updatable_game_state[x, y] == self.DEAD:
                    self.display.draw_dead_cell(pygame, x, y)
                else:
                    self.display.draw_alive_cell(pygame, x, y)

        pygame.display.update()

    def _neighbours(self, x, y):
        return 0 + \
            self.game_state[(x - 1) % self.x_cell_number, (y - 1) % self.y_cell_number] + \
            self.game_state[(x)     % self.x_cell_number, (y - 1) % self.y_cell_number] + \
            self.game_state[(x + 1) % self.x_cell_number, (y - 1) % self.y_cell_number] + \
            self.game_state[(x - 1) % self.x_cell_number, (y)     % self.y_cell_number] + \
            self.game_state[(x + 1) % self.x_cell_number, (y)     % self.y_cell_number] + \
            self.game_state[(x - 1) % self.x_cell_number, (y + 1) % self.y_cell_number] + \
            self.game_state[(x)     % self.x_cell_number, (y + 1) % self.y_cell_number] + \
            self.game_state[(x + 1) % self.x_cell_number, (y + 1) % self.y_cell_number]
示例#6
0
    def test_set_size_with_valid_size_should_set_grid_properties(self):
        user_input = UserInput()
        size = '3, 4'

        user_input.set_size(size)

        self.assertEquals(user_input.grid.x, 3)
        self.assertEquals(user_input.grid.y, 4)
    def setUp(self):
        """setUp()

        """
        _ui = UserInput()
        _ui.request('com4')
        self.flex = Flex(_ui)
        self.flex.open()
        self.flex.do_cmd_list(postproc.INITIALZE_FLEX)
示例#8
0
    def __init__(self, configuration):
        pygame.init()
        self.display = Display(pygame, configuration)
        self.display.refresh()
        pygame.display.update()

        self.x_cell_number = configuration['x_cell_number']
        self.y_cell_number = configuration['y_cell_number']
        self.game_state = numpy.zeros((self.x_cell_number, self.y_cell_number))
        self.user_input = UserInput(self.x_cell_number, self.y_cell_number)
    def setUpClass(cls):
        """setUpClass()

        """
        _ui = UserInput()
        _ui.request('com4')
        flex = Flex(_ui)
        flex.open()
        cls.initial_state = flex.save_current_state()
        flex.close()
        postproc.enable_bands(['10', '20'])
示例#10
0
    def test_set_size_with_invalid_size_should_raise_value_error(self):
        user_input = UserInput()
        exc = None
        size = '3,3'

        try:
            user_input.set_size(size)
        except ValueError as err:
            exc = err

        self.assertIsNotNone(exc)
        self.assertEquals(str(exc), "Invalid input! Size must be like 'x, y'.")
示例#11
0
def main(argv):

    print("init")
    qs.init()

    myIP = (get_ip_address())  #get the ip address of the current device
    argv.pop(
        0
    )  #remove first item from argv list which is the file name of this program
    argvString = ' '.join(
        argv
    )  #convert to string & remove brackets from string, sets argv to be same format as typed inputs during runtime
    uInput = UserInput(argvString, myIP)

    #Start threads
    #TODO manage threads in list
    #threads = []

    # thread for listening for incoming udp messages, then adding those messages to the message Queue
    listendThread = threading.Thread(target=listenUDP, args=(myIP, ))
    listendThread.setDaemon(True)
    listendThread.start()

    # thread for checking user keyboard input
    inputThread = threading.Thread(target=inputListener)
    inputThread.setDaemon(True)
    inputThread.start()

    # thread for sending outgoing messages
    sendThread = threading.Thread(target=sendThreadfnc)
    sendThread.setDaemon(True)
    sendThread.start()

    # thread for processing all the recieved messages
    udpProcessthread = threading.Thread(target=processUDPQueue)
    udpProcessthread.setDaemon(True)
    udpProcessthread.start()

    while (True):

        #TODO re-evaluate how to properly kill threads
        if (not qs.qLocalCmdEmpty()):
            cmd = qs.qLocalCmdGet()
            if ('quit' == cmd.messageType):
                print("breaking")
                break

        #this checks if a new user input has been added to input Queue
        #then runs the uInput.newInput function which parses the input and preps the message to be sent to the cameras / quits the program
        if (not qs.qInputEmpty()):
            input = qs.qInput.get()
            uInput.newInput(input)
示例#12
0
    def test01_instantiate(self):
        """test_instantiate()

        check if Flex instiantiates and has expected str and repr without flex being opened

        """
        _ui = UserInput()
        _ui.request('com4')
        flex = Flex(_ui)

        self.assertEqual('Flex cat: com4, opened: False', str(flex))
        self.assertEqual('[Flex] Flex cat: com4, opened: False', repr(flex))
        flex.close()
示例#13
0
    def test_set_wanted_with_invalid_wanted_should_raise_value_error(self):
        user_input = UserInput()
        exc = None
        wanted = '3,3,50'

        try:
            user_input.set_wanted(wanted)
        except ValueError as err:
            exc = err

        self.assertIsNotNone(exc)
        self.assertEquals(
            str(exc),
            "Invalid expected input it should be like: 'x, y, turns'.")
示例#14
0
def main():
    """main()

    """

    ui = UserInput()
    ui.request(port='com4')
    flex = None
    try:
        flex = Flex(ui)
        flex.open()
    finally:
        if flex:
            flex.close()
示例#15
0
    def test_set_wanted_with_out_of_bounds_should_raise_value_error(self):
        user_input = UserInput()
        user_input.grid.x = 2
        user_input.grid.y = 2
        wanted = '2, 2, 50'
        exc = None

        try:
            user_input.set_wanted(wanted)
        except ValueError as err:
            exc = err

        self.assertIsNotNone(exc)
        self.assertEquals(
            str(exc),
            "Invalid expected input it should be like: 'x, y, turns'.")
    def create_daily_status_report(self):
        try:
            report_file = config.FILE_PATH + "\\" + config.FILE_NAME
            field_names = (
                'Topics',
                'Content',
                'Start Date',
                'End Date',
                'Progress (Completed, In progress)',
                'Confidence Level 1.High – Ready to work on deliverables 2.Medium – Understood but have some queries 3.Low – No confidence',
                'Team Member',
                'Comments',
            )

            with open(report_file, 'a', encoding='utf-8') as csv_file:

                writer = csv.writer(csv_file, delimiter=config.DELIMETER)

                if os.stat(report_file).st_size == 0:
                    writer.writerow(field_names)

                record = UserInput.user_input()
                writer.writerow(record)

                email_body = {'field_names': field_names, 'record': record}
                EmailSend.send(email_body)
                print(
                    "\n********Daily Status Report Created Successfully*******\n"
                )
        except Exception as e:
            print(e)
示例#17
0
def send_users_cmds(_ui: UserInput) -> bool:
    """sendUsersCmds()

    Opens the ui and controller,
    runs the command loop
    closes the controller and the ui.

    """

    _ui.open()
    _c = Controller(_ui)
    _c.open()
    try:
        _cmdloop(_c)
    finally:
        _c.close()
        _ui.close()
    return True
示例#18
0
def do_utility_cmds(_ui: UserInput) -> bool:
    """doUtilityCmds(ui)

    Asks for the log file name, opens the ui, and the controller.
    Calls the util processor loop,
    Closes the controller and the ui on exit
    """

    _ui.inputfn = input("input log file name.txt>")
    _ui.open()
    _c: Controller = Controller(_ui)
    _c.open()
    try:
        _utils: Utils = Utils(_ui, _c)
        _utils.process_loop()
    finally:
        _c.close()
        _ui.close()
    return True
示例#19
0
def main():
    """main()

    """
    # bandrd = Bandreadings(
    # ['14000000', '14073400', '14100000', '14200000'], None)
    #bd = bandrd.bandid
    ui: UserInput = UserInput()
    ui.request(port='com4')
    flexr: Flex = Flex(ui)
    initial_state = None
    try:
        if not flexr.open():
            raise (RuntimeError('Flex not connected to serial serial port'))

        print('saving current flex state')
        initial_state = flexr.save_current_state()
        print('initializing dbg flex state')
        flexr.do_cmd_list(postproc.INITIALZE_FLEX)
        bandr = Bandreadings('20', flexr)
        print('start scanning for noise')
        bss: SMeterAvg = bandr.doit()
        if False:

            with open('banddata.json', 'w') as jso:  # jsonpickle.encode
                _ = jsonpickle.encode(bss)
                jso.write(_)

            with open('banddata.json', 'r') as jsi:
                aa = jsi.readline()
                cpybss = jsonpickle.decode(aa)

            if str(bss) != str(cpybss):
                print('bss <> cpybss')

        print('end scanning for noise')
        print(f'band noise is {bandr.band_signal_strength}')

    except RuntimeError as re:
        raise
    except Exception as e:
        #a = 0
        print(e)
        raise e

    finally:
        print('restore flex prior state')
        flexr.restore_state(initial_state)
        flexr.close()
示例#20
0
    def test_set_wanted_with_valid_input_should_set_userinput_properties(self):
        user_input = UserInput()
        user_input.set_size('4, 4')
        wanted = '2, 3, 30'

        user_input.set_wanted(wanted)

        self.assertEquals(user_input.wanted_x, 2)
        self.assertEquals(user_input.wanted_y, 3)
        self.assertEquals(user_input.turns, 30)
示例#21
0
def send_file(_ui: UserInput) -> bool:
    """send_file()

    asks for a file name and invokes _send_specified_file
    """
    while 1:

        try:
            _ui.inputfn = input("file name to send to repeater?>")
            _send_specified_file(_ui)
            return True

        except OSError:
            print(f"{_ui.inputfn} not found")  # .format(_ui.inputfn))
            if input("Abort sendfile Y/N").lower().strip()[0:1] == 'y':
                return False
            def doita(
            ):  # the program to be run by _thread_template the return 0 says that no work need be done when stopping
                try:

                    UI: UserInput = UserInput()
                    UI.request(port='com4')
                    flexr: Flex = Flex(UI)
                    nf: Noisefloor = Noisefloor(flexr,
                                                arg.qs[QK.dQ],
                                                arg.stope,
                                                run_till_stopped=True)
                    nf.open()
                    nf.doit(loops=0, runtime=0, interval=100, dups=True)
                except StopEventException as see:
                    nf.close()
                    raise see
示例#23
0
def main():
    """main()

    Identifies the avilable ports, gets user input, sends the specified file (if exists) to
    the controller on a port.

    Prints the command list and processes the user selected command(s)

    """

    _available_ports = GetPorts().get()
    print(f"Available serial ports are: {_available_ports}")

    _ui: UserInput = UserInput()
    _ui.request()
    try:
        _ui.open()
        _send_specified_file(_ui)

        def _nodop(ignore: Any) -> bool:
            # pylint: disable=W0613
            return False

        def _errmsg(ignore: Any) -> bool:
            # pylint: disable=W0613
            print("only type one of Q, M, U, or F")
            return True

        cmddisptch = {
            'q': _nodop,
            'm': send_users_cmds,
            'u': do_utility_cmds,
            'f': send_file,
        }

        _loop_ctl: bool = True
        while _loop_ctl:
            _response = input("Type 'Q' to quit\n"
                              "Type 'M' for manual commands\n"
                              "type 'U' for Utility operations\n"
                              "Type 'F' for file transfer (Q/F/M/U)?>").strip().lower()[0:1]
            _loop_ctl = cmddisptch.get(_response, _errmsg)(_ui)
    finally:
        _ui.close()
def __main():
    """__main()

    gets user input, opens port to the repeater, sends the contents of the specified file
    to the repeater controller, closes down
    """
    if not os.path.isdir(LOG_DIR):
        os.mkdir(LOG_DIR)
    _LF_HANDLER = logging.handlers.RotatingFileHandler(
        ''.join([LOG_DIR, LOG_FILE, ]),
        maxBytes=10000,
        backupCount=5,
    )
    _LF_HANDLER.setLevel(logging.DEBUG)
    _LC_HANDLER = logging.StreamHandler()
    _LC_HANDLER.setLevel(logging.DEBUG)  # (logging.ERROR)
    _LF_FORMATTER = logging.Formatter(
        '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
    _LC_FORMATTER = logging.Formatter(
        '%(name)s: %(levelname)s - %(message)s')
    _LC_HANDLER.setFormatter(_LC_FORMATTER)
    _LF_HANDLER.setFormatter(_LF_FORMATTER)
    _THE_LOGGER = logging.getLogger()
    _THE_LOGGER.setLevel(logging.DEBUG)
    _THE_LOGGER.addHandler(_LF_HANDLER)
    _THE_LOGGER.addHandler(_LC_HANDLER)
    _THE_LOGGER.info('commandreader executed as main')
    # LOGGER.setLevel(logging.DEBUG)
    _ui: UserInput = UserInput()
    _ui.request()
    _ui.open(detect_br=False)
    _cr = CommandReader(_ui)
    try:
        _cr.open()
        while True:
            _line = _cr.get()
            if not _line:
                break
            _jj = _line.split('\n')
            print(_jj[0])
    finally:
        _cr.close()
        _ui.close()
示例#25
0
# import usersettings
import usersettings

# create settings object
session_folder = os.getcwd()
settings_folder = currentdir  #os.path.join(currentdir.split('experiments')[0],"tasks","confidentiality_task_training_simple")
global settings_obj
settings_obj = TrialParameterHandler(usersettings, settings_folder,
                                     session_folder)

# create bpod object 'COM6' '/dev/cu.usbmodem62917601'
bpod = Bpod()
#bpod= Bpod('/dev/cu.usbmodem62917601') #TODO:
#create tkinter userinput dialoge window
window = UserInput(settings_obj)
window.draw_window_bevore_conf(stage="habituation_complex")
window.show_window()

# create multiprocessing variabls
# flags
display_stim_event = threading.Event()
still_show_event = threading.Event()
display_stim_event.clear()
still_show_event.clear()

#settings_obj.run_session = True #TODO:

# run session
if settings_obj.run_session:
    settings_obj.update_userinput_file_conf()
示例#26
0
from helperfunctions import *
from stimulus_conf import Stimulus

# import usersettings
import usersettings

# create settings object
session_folder = os.getcwd()
settings_folder = currentdir  # os.path.join(currentdir.split('experiments')[0],"tasks","confidentiality_task_training_simple")
settings_obj = TrialParameterHandler(usersettings, settings_folder, session_folder)

# create bpod object 'COM6' '/dev/cu.usbmodem65305701' bpod '/dev/cu.usbmodem62917601'
bpod = Bpod()

# create tkinter userinput dialoge window
window = UserInput(settings_obj)
window.draw_window_bevore_conf(stage="training")
window.show_window()


# create multiprocessing variabls
# flags
display_stim_event = threading.Event()
still_show_event = threading.Event()
display_stim_event.clear()
still_show_event.clear()
# set functions

# run session
if settings_obj.run_session:
    settings_obj.update_userinput_file_conf()
示例#27
0
        maxBytes=10000,
        backupCount=5,
    )
    LF_HANDLER.setLevel(logging.DEBUG)
    LC_HANDLER = logging.StreamHandler()
    LC_HANDLER.setLevel(logging.DEBUG)  # (logging.ERROR)
    LF_FORMATTER = logging.Formatter(
        '%(asctime)s - %(name)s - %(funcName)s - %(levelname)s - %(message)s')
    LC_FORMATTER = logging.Formatter('%(name)s: %(levelname)s - %(message)s')
    LC_HANDLER.setFormatter(LC_FORMATTER)
    LF_HANDLER.setFormatter(LF_FORMATTER)
    THE_LOGGER = logging.getLogger()
    THE_LOGGER.setLevel(logging.DEBUG)
    THE_LOGGER.addHandler(LF_HANDLER)
    THE_LOGGER.addHandler(LC_HANDLER)
    THE_LOGGER.info('userinput executed as main')
    # LOGGER.setLevel(logging.DEBUG)
    MS = MySerial()
    MS.open()
    from userinput import UserInput
    _UI = UserInput()
    try:
        _UI.request()
        _UI.open()
        print("Requested Port can be opened")
        _UI.close()

    except(Exception, KeyboardInterrupt) as exc:
        _UI.close()
        sys.exit(str(exc))
示例#28
0
文件: rummi.py 项目: rjweis/Rummi
from card import Card
from carddeck import CardDeck
from cardset import CardSet
from discardpile import DiscardPile
from player import Player
from table import Table
from typing import List, Tuple
import userinput
from userinput import UserInput
import logo
# TODO: add the player method .swap_card() to the game
# TODO: make move invalid if player empties their hand -- they must have at least one card remaining

ui = UserInput()


class Rummi:
    def __init__(self, player_names):
        print("Let's start the game!\n")
        self.deck = CardDeck()
        self.discard_pile = DiscardPile(self.deck)
        self.table = Table()
        self.players = [Player(name, self.deck) for name in player_names]
        self.turn_counter = 0

    def print_score_board(self):
        print('Here is the scoreboard:\n')
        for player in self.players:
            print('{}: {} points'.format(player.name, player.points))

    def draw(self, player: object):
from helperfunctions import *

# import usersettings
import usersettings

# create settings object
session_folder = os.getcwd()
settings_folder = currentdir  # os.path.join(session_folder.split('experiments')[0],"tasks","gamble_task_recording")
settings_obj = TrialParameterHandler(usersettings, settings_folder,
                                     session_folder)

# create bpod object
bpod = Bpod()

# create tkinter userinput dialoge window
window = UserInput(settings_obj)
window.draw_window_bevore_gamble()
window.show_window()
window.update_settings()

# create multiprocessing variabls
# flags
display_stim_event = threading.Event()
start_open_loop_event = threading.Event()
still_show_event = threading.Event()
display_stim_event.clear()
start_open_loop_event.clear()
still_show_event.clear()

# run session
if settings_obj.run_session:
示例#30
0
import argparse

from stocks import Stock
from userinput import CSVInput, UserInput

parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument('csv_file', nargs='?', default=None, help="CSV file path")
args = parser.parse_args()

csv_file = args.csv_file

if __name__ == "__main__":
    all_stock_data = CSVInput().read(csv_file)
    user_input = UserInput(list(all_stock_data.keys()))()
    stock_records = all_stock_data[user_input['name']]
    stock = Stock(stock_records, user_input['start_date'],
                  user_input['end_date'])
    stock.print_all_data()