コード例 #1
0
def main():
    # Load the circuit from database.
    circuit = load_circuit()

    # Create and run the command executor.
    command_executor = CommandExecutor(circuit)
    command_executor.run()
コード例 #2
0
 def __init__(self):
     self.timezone = pytz.timezone('Europe/Warsaw')
     self.capturer = Capturer()
     self.serial_reader = SerialReader()
     self.command_executor = CommandExecutor()
     self.route_sender = None
     self.started = False
     self.driving_started = False
コード例 #3
0
 def __init__(self, server_url, session_id):
     self._server_url = server_url.replace('http', 'ws')
     self._session_id = session_id
     self._command_id = -1
     cmd_params = {'sessionId': session_id}
     path = CommandExecutor.CreatePath(WebSocketCommands.CREATE_WEBSOCKET,
                                       cmd_params)
     self._websocket = websocket.create_connection(self._server_url + path)
コード例 #4
0
    def __init__(self, config):
        self._config = config
        self._db_man = DatabaseManager(config["Bot"]["DatabasePath"])
        if logger.getEffectiveLevel == logging.DEBUG:
            self._updater = Updater(config["Bot"]["Token"],
                                    workers=1, use_context=True)
        else:
            self._updater = Updater(config["Bot"]["Token"], use_context=True)
        self._captcha_manager = CaptchaManager(config, self._db_man)
        self._msg_broker = MessageBroker(self._updater,
                                         self._db_man,
                                         self._captcha_manager,
                                         self._config)
        self._cmd_executor = CommandExecutor(
            self._config,
            self._updater,
            self._db_man,
            self._msg_broker,
            self._captcha_manager)

        Role.init_roles_from_config(self._db_man, config)
        load_role_users_from_config_section(self._db_man, config)
コード例 #5
0
def init():    
    global comm
    
    global output

    global address

    global camera

    global config    

    global web_file_mappings
    
    global command_executor
    
    global distance_ev
    
    config = ConfigParser()
    config.read('config.ini')

    try:
        comm = Communicator(config.get('arduino', 'port'), config.getint('arduino', 'baud_rate'))
    except:
        sys.exit('Could not find Arduino on ' + config.get('arduino', 'port'))
  
    output = StreamingOutput()

    address = ('', config.getint('web_params', 'port'))
  
    camera = PiCamera(resolution = config.get('camera', 'resolution'), framerate = config.getint('camera', 'framerate'))
    camera.hflip = config.getboolean('camera', 'hflip')
    camera.vflip = config.getboolean('camera', 'vflip')   
    
    distance_ev = Event()
    
    command_executor = CommandExecutor()
コード例 #6
0
import sys
from command_executor import CommandExecutor

if len(sys.argv) < 2:
    print(r'Usage: C:\Python27\python -m BeforeCommand <command>')
    print('Commands:')
    print('    CreateOrder')
    print('    UpdateQuantity number')
    print('    ShipOrder')
    exit()

executor = CommandExecutor()
print('控制台参数列表: ' + ', '.join(sys.argv))
executor.execute_command(sys.argv[1:])
コード例 #7
0
import sys
from command_executor import CommandExecutor


if len(sys.argv) < 2:
    print 'Usage: C:\Python27\python -m BeforeCommand <command>'
    print 'Commands:'
    print '    CreateOrder'
    print '    UpdateQuantity number'
    print '    ShipOrder'
    exit()

executor = CommandExecutor()
executor.execute_command(sys.argv[1:])
コード例 #8
0
ファイル: application.py プロジェクト: ivanjermakov/txtype
class Application:
    DEFAULT_CONFIG_PATH = os.environ['HOME'] + '/.config/txtype/config.json'

    def __init__(self, config=None, create=None):
        config = config or self.DEFAULT_CONFIG_PATH
        create = create or False
        self.config_manager = ConfigurationManager(os.path.abspath(config),
                                                   create)
        self.executor = CommandExecutor(self.config_manager)

    def _init_text_win(self, h, w):
        # TODO: pad for really huge texts
        return curses.newwin(h - 1, w, 0, 0)

    def _init_input_win(self, h, w):
        return curses.newwin(1, w - 24, h - 1, 0)

    def _init_status_win(self, h, w):
        return curses.newwin(1, 24, h - 1, w - 24)

    def _init_command_win(self, h, w):
        return curses.newwin(1, w, h - 1, 0)

    def _init_result_win(self, h, w):
        return curses.newwin(1, w, h - 2, 0)

    def _paint_bar(self, input_win, status_win, color_pair):
        input_win.bkgd(' ', color_pair)
        status_win.bkgd(' ', color_pair)
        input_win.refresh()
        status_win.refresh()

    def _print_text_win(self, win, text):
        h, w = win.getmaxyx()

        win.erase()

        for i, word in enumerate(text.words):
            w_s = str(word)
            y, x = win.getyx()

            if w - 1 < x + len(w_s):
                win.addstr('\n')

            if i == text.current_word_index:
                win.addstr(w_s, curses.A_UNDERLINE)
            elif i >= text.current_word_index:
                win.addstr(w_s)
            else:
                if word.misspelled:
                    win.addstr(w_s, curses.color_pair(1))
                else:
                    win.addstr(w_s, curses.color_pair(2))

            if i != len(text.words) - 1:
                win.addstr(' ')

        win.refresh()

    def _print_input_win(self, win, status_win, text, input_text, key):
        h, w = win.getmaxyx()
        win.erase()

        if text.has_next():
            self._paint_bar(win, status_win, curses.color_pair(0))
            win.addstr(0, 0, input_text[-w + 1:])

            if input_text:
                if not text.words[text.current_word_index].word_str.startswith(
                        input_text):
                    self._paint_bar(win, status_win, curses.color_pair(3))
                    win.addstr(0, 0, input_text[-w + 1:])
            win.refresh()
        else:
            self._paint_bar(win, status_win, curses.color_pair(4))
            win.addstr('text complete')
            win.refresh()
            return key

    def _print_status_win(self, win, text):
        win.erase()

        # total number of cols is 6 x 4 = 24
        complete_str = (str(text.percent_complete) + '%c')[:5]
        accuracy_str = (str(text.percent_accuracy) + '%a')[:5]
        mistakes_str = (str(text.mistakes) + 'e')[:4]
        wpm_str = (str(text.wpm) + 'wpm')[:7]
        stat_str = ' '.join(
            [complete_str, accuracy_str, mistakes_str, wpm_str])
        win.insstr(stat_str)

        win.refresh()

    def _refresh_all(self, screen, text_win, input_win, status_win):
        screen.refresh()
        text_win.refresh()
        input_win.refresh()
        status_win.refresh()

    def _command_view(self, screen):
        h, w = screen.getmaxyx()

        command = ':'

        command_win = self._init_command_win(h, w)
        command_win.erase()
        command_win.addstr(command)
        command_win.refresh()

        result_win = self._init_result_win(h, w)
        result_win.refresh()

        while True:
            ch = screen.get_wch()

            if ch == curses.KEY_BACKSPACE:
                if len(command) > 1:
                    command = command[:-1]
                else:
                    command_win.erase()
                    command_win.refresh()
                    break
            elif ch == '\n':
                result = str(self.executor.execute(command[1:]))

                if result:
                    result_win.addstr(result)
                    result_win.refresh()

                command_win.erase()
                command_win.refresh()
                break
            if type(ch) == str:
                command += ch

            command_win.erase()
            command_win.addstr(command)
            command_win.refresh()

    def _welcome_view(self, screen):
        h, w = screen.getmaxyx()

        screen.erase()

        lines = [
            '          Welcome to TXTYPE!          ',
            '                                      ',
            '     Command line typing software     ',
            'https://github.com/ivanjermakov/txtype',
            '                                      ',
            'Help:                                 ',
            '     ctrl+z       force exit          ',
            '     q            exit                ',
            '     n            next text           ',
            '     w            welcome page        ',
            '     :            enter command       ',
        ]

        if h > 10 and w > 37:
            y = h // 2 - len(lines) // 2
            x = w // 2 - len(lines[0]) // 2

            for i, l in enumerate(lines):
                screen.insstr(y + i, x, l)

            # accents
            screen.addstr(y, x + 21, 'TXTYPE', curses.color_pair(2))
            screen.addstr(y + 6, x + 5, 'ctrl+z', curses.color_pair(2))
            screen.addstr(y + 7, x + 5, 'q', curses.color_pair(2))
            screen.addstr(y + 8, x + 5, 'n', curses.color_pair(2))
            screen.addstr(y + 9, x + 5, 'w', curses.color_pair(2))
            screen.addstr(y + 10, x + 5, ':', curses.color_pair(2))

        screen.refresh()

        while True:
            key = screen.get_wch()

            if key == curses.KEY_RESIZE:
                self._welcome_view(screen)
                return
            if key == 'n':
                self._text_view(screen)
                return
            if key == ':':
                self._command_view(screen)
            if key == 'q':
                return

    def _text_view(self, screen):
        h, w = screen.getmaxyx()

        text_win = self._init_text_win(h, w)
        input_win = self._init_input_win(h, w)
        status_win = self._init_status_win(h, w)

        words = text_generator.generate(
            self.config_manager.config.get_param('active_dictionary'),
            int(self.config_manager.config.get_param('text_words_count')))
        text = Text(words)
        self._print_text_win(text_win, text)
        self._print_status_win(status_win, text)

        self._refresh_all(screen, text_win, input_win, status_win)

        input_text = ''
        while True:
            key = screen.get_wch()

            # TODO: refactor
            if key == curses.KEY_RESIZE:
                h, w = screen.getmaxyx()
                screen.erase()
                text_win = self._init_text_win(h, w)
                input_win = self._init_input_win(h, w)
                status_win = self._init_status_win(h, w)
                self._print_text_win(text_win, text)
                self._print_input_win(input_win, status_win, text, input_text,
                                      key)
                self._refresh_all(screen, text_win, input_win, status_win)

            if text.current_word_index == 0 and len(input_text) == 0:
                text.start_typing()

            if key == '\n' or key == ' ':
                if text.has_next():
                    text.next(input_text)
                input_text = ''
            elif type(key) == str:
                if text.has_next():
                    current_word = text.words[text.current_word_index].word_str
                    if current_word.startswith(input_text) and \
                            not current_word.startswith(input_text + key):
                        text.mistakes += 1
                input_text += key
            elif int(key) == curses.KEY_BACKSPACE:
                input_text = input_text[:-1]

            self._print_text_win(text_win, text)
            self._print_status_win(status_win, text)

            key = self._print_input_win(input_win, status_win, text,
                                        input_text, key)

            if not key:
                continue

            if key == 'n':
                self._text_view(screen)
                return
            if key == 'w':
                self._welcome_view(screen)
                return
            if key == ':':
                self._command_view(screen)
                self._print_status_win(status_win, text)
                self._print_input_win(input_win, status_win, text, input_text,
                                      key)
            if key == 'q':
                return

    def main(self, screen):
        curses.mousemask(1)
        curses.curs_set(0)
        curses.use_default_colors()

        screen.idcok(False)
        screen.idlok(False)

        curses.init_pair(1, curses.COLOR_RED, -1)  # error
        curses.init_pair(2, curses.COLOR_GREEN, -1)  # correct
        curses.init_pair(3, -1, curses.COLOR_RED)  # input error
        curses.init_pair(4, -1, curses.COLOR_GREEN)  # text complete

        self._welcome_view(screen)

    def start(self):
        curses.wrapper(self.main)
コード例 #9
0
ファイル: application.py プロジェクト: ivanjermakov/txtype
 def __init__(self, config=None, create=None):
     config = config or self.DEFAULT_CONFIG_PATH
     create = create or False
     self.config_manager = ConfigurationManager(os.path.abspath(config),
                                                create)
     self.executor = CommandExecutor(self.config_manager)
コード例 #10
0
ファイル: pipeline.py プロジェクト: trunkclub/ontology_etl
    def connect_components(self):
        for data_source in self.data_sources:
            print 'connecting data sources:'
            data_source > self.alligator
        (self.alligator > self.logic_validator > command_generator >
         self.dependency_checker > self.command_executor)


if __name__ == '__main__':
    etl_pipeline = ETLPipeline()
    ontology.instantiate_data_sources()
    alligator = Alligator()
    logic_validator = LogicValidator()
    dependency_checker = DependencyChecker()
    command_generator = CommandGenerator()
    command_executor = CommandExecutor()

    data_stores_dict = get_data_stores_dict()

    etl_pipeline.add(alligator)
    etl_pipeline.add(logic_validator)
    etl_pipeline.add(dependency_checker)
    etl_pipeline.add(command_generator)
    etl_pipeline.add(command_executor)
    etl_pipeline.add(alligator)
    for data_source in ontology.SOURCES_STORE.itervalues():
        etl_pipeline.add(data_source)
    for data_store in data_stores_dict.itervalues():
        etl_pipeline.add(data_store)

    etl_pipeline.connect_components()
コード例 #11
0
class CarServer(object):
    def directory_for_session(self):
        directory = "session-%s" % self.timestamp()
        images = "%s/images" % directory
        os.makedirs(images)
        return directory

    def __init__(self):
        self.timezone = pytz.timezone('Europe/Warsaw')
        self.capturer = Capturer()
        self.serial_reader = SerialReader()
        self.command_executor = CommandExecutor()
        self.route_sender = None
        self.started = False
        self.driving_started = False

    @cherrypy.expose
    def idle(self):
        self.command_executor.change_status(Status.IDLE)

    @cherrypy.expose
    def remote(self):
        self.command_executor.change_status(Status.REMOTE)

    @cherrypy.expose
    def learning(self):
        self.command_executor.change_status(Status.LEARNING)

    def autonomous(self):
        self.command_executor.change_status(Status.AUTONOMOUS)

    @cherrypy.expose
    def speed(self, value):
        self.command_executor.set_speed(int(value))

    @cherrypy.expose
    def turn(self, angle):
        self.command_executor.make_turn(int(angle))

    @cherrypy.expose
    def replay(self, directory):
        self.driving_started = True
        directions = ReplayDirectionsProvider(directory)
        self.route_sender = RouteSender(self.command_executor, directions)
        self.autonomous()

    @cherrypy.expose
    @cherrypy.tools.json_out()
    def sessions(self):
        sessions_provider = SessionsProvider(os.getcwd())
        return sessions_provider.get_sessions()

    @cherrypy.expose
    def drive(self):
        self.driving_started = True
        directions = CameraDirectionsProvider()
        initialized_queue = Queue()
        self.route_sender = RouteSender(self.command_executor, directions,
                                        initialized_queue)
        print("Waiting for initialization")
        if initialized_queue.get():
            print("Initialization completed")
            self.autonomous()

    @cherrypy.expose
    def start(self):
        if self.started:
            cherrypy.response.status = 400
            return "WARNING: Session already started"
        if self.driving_started:
            cherrypy.response.status = 400
            return "WARNING: Driving in progress"

        directory = self.directory_for_session()
        self.started = True
        self.capturer.start(directory)
        self.serial_reader.start_saving(directory)
        self.remote()

        return "INFO: Session %s has been started" % directory

    @cherrypy.expose
    def stop(self):
        if not self.started and not self.driving_started:
            cherrypy.response.status = 400
            return "WARNING: Neither session nor driving started"
        self.idle()
        if self.started:
            self.cleanup()
            return "INFO: Session ended successfully"
        else:
            self.stop_driving()
            return "INFO: Driving ended successfully"

    def stop_driving(self):
        self.driving_started = False
        self.route_sender.terminate()
        self.route_sender = None

    def terminate(self):
        self.cleanup()
        self.capturer.terminate()
        self.serial_reader.terminate()

    def cleanup(self):
        if not self.started:
            return

        self.capturer.stop()
        self.serial_reader.stop_saving()
        self.started = False

    def timestamp(self):
        utc_dt = datetime.datetime.now(pytz.utc)
        loc_dt = utc_dt.astimezone(self.timezone)
        return loc_dt.strftime("%Y%m%d%H%M%S")