Beispiel #1
0
def animate(canvas, fn, delay=1./24, *args, **kwargs):
    """Animation automatition function

    :param canvas: :class:`Canvas` object
    :param fn: Callable. Frame coord generator
    :param delay: Float. Delay between frames.
    :param *args, **kwargs: optional fn parameters
    """

    # python2 unicode curses fix
    if not IS_PY3:
        import locale
        locale.setlocale(locale.LC_ALL, "")

    def animation(stdscr):

        for frame in fn(*args, **kwargs):
            for x,y in frame:
                canvas.set(x,y)

            f = canvas.frame()
            stdscr.addstr(0, 0, '{0}\n'.format(f))
            stdscr.refresh()
            if delay:
                sleep(delay)
            canvas.clear()

    curses.wrapper(animation)
Beispiel #2
0
def main():

    parser = argparse.ArgumentParser(description='Maze game for the Euskal Encounter XXI.')
    parser.add_argument('--width', dest='width', default=4, help="Maze width", type=int)
    parser.add_argument('--height', dest='height', default=4, help="Maze height", type=int)
    parser.add_argument('--server', dest='server', action="store_true", default=False, help="Start a maze server")
    parser.add_argument('--server-port', dest='server_port', default=8123, help="Server port", type=int)
    parser.add_argument('--connect', dest='server_address', help="Server host:port")
    args = parser.parse_args()

    if args.width < 2:
        parser.error("width can't be smaller than 2.")

    if args.height < 2:
        parser.error("height can't be smaller than 2.")

    try:
        curses.wrapper(partial(run_game, width=args.width,
                                         height=args.height,
                                         is_server=args.server,
                                         server_port=args.server_port,
                                         server_address=args.server_address))
    except curses.error:
        print "ERROR: It looks like your terminal is not big enough for this maze."
        sys.exit(-1)
    except MazeException, exc:
        print exc.args[0]
        sys.exit(-2)
Beispiel #3
0
def main():
    try:
        targetFilePath = sys.argv[1]
    except:
        sys.stderr.write('usage: %s targetFilePath\n' % sys.argv[0])
        sys.exit(1)

    values = os.popen('tail -1 ' + targetFilePath).read().split(', ')
    invoiceNo = values[0]
    period = values[2]
    rate = values[3]

    endDate = dateutil.parser.parse(period.split(' -- ')[1])
    firstMonday = next(date for date in (endDate + datetime.timedelta(days=delta) for delta in range(1, 6)) if date.strftime('%w') is '1')

    fieldStartDate[1] = mutateDate(0, firstMonday.strftime(dateFormat))
    secondFriday = firstMonday + datetime.timedelta(days=11)
    fieldEndDate[1] = mutateDate(0, secondFriday.strftime(dateFormat))

    curses.wrapper(gui)

    # New invoice
    invoiceNo = str(int(invoiceNo) + 1)
    invoiceDate = time.strftime(dateFormat)
    period = fieldStartDate[1].split()[0] + ' -- ' + fieldEndDate[1].split()[0]
    rate = rate
    hours = fieldHours[1]
    total = '%.2f' % (int(hours) * float(rate))
    currency = 'AUD'
    notes = fieldNotes[1]

    open(targetFilePath, 'at').write(', '.join([invoiceNo, invoiceDate, period, rate, hours, total, currency, notes]) + '\n')
    sys.exit(0)
	def init(self, radio):
		self.model.setRadios(self.jamendo.getRadios())

		if radio:
			# Interfaz colorama (se envía una radio)

			# Capturar CTRL-c para terminar la aplicación
			signal.signal(signal.SIGINT, self.__signalHandler)

			# Inicializar la vista
			self.model.view = ColoramaView(self)

			# Dibujado inicial de la vista
			self.model.view.render(self.model)

			# Buscar la radio
			x = None
			for i, r in enumerate(self.model.radios):
				if int(radio) == r['id']:
					x = self.jamendo.getRadio(self.model.getRadioName1(r))
					break

			# Reproducir la radio
			self.player.play(x)
		else:
			# Interfaz curses
			curses.wrapper(self.curses)
Beispiel #5
0
 def run(self):
     # Get the locale encoding
     locale.setlocale(locale.LC_ALL, '')
     self._code = locale.getpreferredencoding()
     
     # Start the curses main loop
     curses.wrapper(self._curses_main)
Beispiel #6
0
def main():
    """
    Actually run the search interface.
    """
    try:
        try:
            optlist, args = getopt.getopt(sys.argv[1:], 'hc:v', ['help', 'confdir=', 'verbose'])
        except getopt.GetoptError:
            usage()
            sys.exit(2)

        confdir = None
        verbose = False

        for opt, arg in optlist:
            if opt in ('-h', '--help'):
                usage()
                sys.exit()
            if opt in ('-c', '--confdir'):
                confdir = arg
            if opt in ('-v', '--verbose'):
                verbose = True
                            
        conf = woodpecker.Config(confdir)
        query_string = ' '.join(args)
        qs = QueryState(conf, query_string, verbose)
        qs.set_my_addresses(['*****@*****.**'])

        curses.wrapper(lambda x: qs.interface(x))
    except woodpecker.WoodpeckerError, e:
        sys.stdout.write(str(e))
        sys.stdout.write("\n")
        print e.aux
Beispiel #7
0
def main():
    """ Main entry point for IRC Client"""
    parser = argparse.ArgumentParser(description="IRC Client")
    parser.add_argument('--hostname', help="Hostname", default="localhost")
    parser.add_argument('--port', type=int, help="Port", default=50000)
    parser.add_argument('--gui', action='store_true')
    parser.add_argument('--log', default=None)

    args = parser.parse_args()

    if args.log != None:
        logging.basicConfig(
            filename=args.log,
            filemode='w',
            level=logging.DEBUG
        )

    client = IRCClient(args.hostname, args.port)
    if client.connect():
        if args.gui:
            #keep the client running even if the GUI needs to redraw
            while client.isRunning():
                curses.wrapper(client.guirun)
        else:
            client.run()
Beispiel #8
0
def run():
    if sys.version_info[:2] < (3, 3):
        raise RuntimeError('kaa requires Python 3.3 or later')

    if not getattr(__builtins__, 'kaa_freeze', False):
        try:
            setproctitle = __import__('setproctitle')
            setproctitle.setproctitle('kaa')
        except:
            pass

    signal.signal(signal.SIGTERM, handle_term)

    parser = options.build_parser()

    global opt
    opt = parser.parse_args()

    if opt.show_version:
        print(version.version_info())
        return

    if not os.environ.get('ESCDELAY'):
        os.environ['ESCDELAY'] = CURSES_ESCDELAY

    _init_term()
    curses.wrapper(main)
Beispiel #9
0
 def __init__(self, players):
     self.players = [cls(self, n+1) for n, cls in enumerate(players)]
     self.err = None
     curses.wrapper(self.run)
     if self.err:
         e,x,c = self.err
         raise e,x,c
Beispiel #10
0
def start():

    parser = ArgumentParser(description="Create the matrix falling text.",
                            formatter_class=ArgumentDefaultsHelpFormatter)

    parser.add_argument("-b", "--background", default="black",
            help="The colour of the falling text.")
    parser.add_argument("-c", "--clear", action="store_true",
            help="Use stdscr.clear() instead of stdscr.erase().")
    parser.add_argument("-f", "--foreground", default="green",
            help="The colour of the falling text.")
    parser.add_argument("-l", "--letters", type=int, default=2,
            help="The number of letters produced per update.")
    parser.add_argument("-p", "--probability", type=int, default=5,
            help="1/p probability of a dispense point deactivating.")
    parser.add_argument("-u", "--ups", type=int, default=15,
            help="The number of updates to perform per second.")
    args = parser.parse_args()

    global BG, CLEAR, FG, LETTERS_PER_UPDATE, PROBABILITY, UPDATES_PER_SECOND
    CLEAR = args.clear
    FG = COLORS.get(args.foreground.upper(), curses.COLOR_GREEN)
    BG = COLORS.get(args.background.upper(), curses.COLOR_BLACK)
    LETTERS_PER_UPDATE = abs(args.letters)
    PROBABILITY = args.probability - 1
    UPDATES_PER_SECOND = abs(args.ups)

    try:
        while 1:
            curses.wrapper(main)
    except (EOFError, KeyboardInterrupt):
        sys.exit(0)
Beispiel #11
0
    def __init__(self):
      
        # Variables for game
        self.time = 0

        # Variables for menu

        self.optionRange = 0
        self.deltaOptions = 0
        
        #up down variables
        self.topLineNum = 0
        self.highlightLineNum = 0
        self.bottomLineNum = 0

        #left right variables
        self.focusedPanelNum = 0
        self.horozontalLineNum = 0
        self.maxPanels = 2

        self.planetViewOptions = []
        self.panelStack = {} 
 
        self.Test_DATA = Test_DATA()
        self.loadData()
        curses.wrapper(self.mainMenu)
Beispiel #12
0
def app_wrapper(func, args):
    global NCURSES
    base_dir = GLOBALS.get("scratch_dir", GLOBALS["basedir"])
    lock_file = pjoin(base_dir, "alive")

    if not args.enable_ui:
        NCURSES = False
    
    if not pexist(lock_file) or args.clearall:
        open(lock_file, "w").write(time.ctime())
    else:
        clear_env()
        print >>sys.stderr, '\nThe same process seems to be running. Use --clearall or remove the lock file "alive" within the output dir'
        sys.exit(-1)
        
    try:
        if NCURSES:
            curses.wrapper(main, func, args)
        else:
            main(None, func, args)
    except ConfigError, e:
        if GLOBALS.get('_background_scheduler', None):
            GLOBALS['_background_scheduler'].terminate()

        print >>sys.stderr, "\nConfiguration Error:", e
        clear_env()
        sys.exit(-1)
Beispiel #13
0
 def start(self):
     """ Start the monitor """
     if CURSES_SUPPORTED:
         curses.wrapper(self.run)
     else:
         six.print_("Your system does not have curses installed. "
                    "Cannot use 'watch'")
Beispiel #14
0
def start_gui(process):
    """
    A function that takes care of starting the GUI and stops the Scrapy crawler process when exited from program.

    :param CrawlerProcess process: The scrapy crawler process that is used to scrape the web. The instance is used for stopping the process.
    """

    def create_ui(screen):
        """
        A function passes to curses wrapper for safe execution of terminal GUI.

        :param screen: The screen parameter to run the GUI. Sent from the curses wrapper.
        """

        GUI.screen = screen  # All the statis variables of the GUI class is initialized
        GUI.strings = []  # the list of songs is empty initially
        GUI.init_display()  # init the variables required for GUI
        GUI.update_on_key()  # Starts a loop that waits for key input and acts accordingly

        curses.nocbreak()
        curses.echo()
        curses.endwin()
        GUI.gui_stopped = True

    curses.wrapper(create_ui)
    process.stop()  # Stopping the scrapy crawler process
def display_xor_components(components):
    components = tuple(components) # buffer
    if os.name == 'nt':
        display_xor_components_with_shell_clear(components)
    else:
        import curses
        curses.wrapper(display_xor_components_curses, components)
Beispiel #16
0
    def run(self):
        try:
            # parse configuration
            self.config = Configuration(self.config_file_name)
        except FileNotFoundError as e:
            print("[Error] File not found: {}".format(e.filename))
            exit(1)

        #variables = self.config.get_variables()
        #pprint(variables)

        #tasks = self.config.get_tasks()
        #pprint(tasks)

        # change to low priority
        process = psutil.Process()
        if os.name is "nt":
            process.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS)
        else:
            process.nice(10)  # should about be the same as BELOW_NORMAL_PRIORITY_CLASS

        self.runner = Runner(self.max_workers)
        self.runner.add_tasks(self.config.get_tasks())

        if self.interactive_mode:
            import curses  # http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses

            curses.wrapper(self.interactive_screen)
        else:
            self.runner.run()
Beispiel #17
0
def run_interactive(launchfiles):
    import curses

    signal.signal(signal.SIGTERM, exit_gracefully)

    menu_items = []

    def wrap_run(group):
        return lambda: run_script(group)

    for file in os.listdir(launchfiles):
        if not file.endswith(".spark"):
            continue
        try:
            group = ProgramGroup(os.path.join(launchfiles, file))
            menu_items.append((group.description, wrap_run(group)))
        finally:
            pass

    def run_terminal():
        call(["sudo", "-u", "manus", "bash"])
        return False

    def run_upgrade_reload():
        run_upgrade()
        os.execv(sys.executable, [sys.executable, sys.argv[0]])
        return True

    menu_items.append(('Upgrade system', run_upgrade_reload))
    menu_items.append(('Exit to terminal', run_terminal))
    menu_items.append(('Shutdown', run_shutdown))

    menu = Menu(menu_items)
    curses.wrapper(lambda scr: menu.display(scr))
Beispiel #18
0
def _main():
    parser = argparse.ArgumentParser(
        description='''A terminal-based GUI client for Git.''')
    parser.add_argument(
        '-v', '--version', action='version', version=__version_text__)
    parser.parse_args()
    curses.wrapper(main)
Beispiel #19
0
def main():
    parser = optparse.OptionParser(usage=USAGE, version='iotop ' + VERSION)
    parser.add_option('-o', '--only', action='store_true',
                      dest='only', default=False,
                      help='only show processes or threads actually doing I/O')
    parser.add_option('-b', '--batch', action='store_true', dest='batch',
                      help='non-interactive mode')
    parser.add_option('-n', '--iter', type='int', dest='iterations',
                      metavar='NUM',
                      help='number of iterations before ending [infinite]')
    parser.add_option('-d', '--delay', type='float', dest='delay_seconds',
                      help='delay between iterations [1 second]',
                      metavar='SEC', default=1)
    parser.add_option('-p', '--pid', type='int', dest='pids', action='append',
                      help='processes to monitor [all]', metavar='PID')
    parser.add_option('-u', '--user', type='str', dest='users', action='append',
                      help='users to monitor [all]', metavar='USER')
    parser.add_option('-P', '--processes', action='store_true',
                      dest='processes',
                      help='only show processes, not all threads')
    options, args = parser.parse_args()
    if args:
        parser.error('Unexpected arguments: ' + ' '.join(args))
    find_uids(options)
    options.pids = options.pids or []
    if options.batch:
        run_iotop(None, options)
    else:
        curses.wrapper(run_iotop, options)
Beispiel #20
0
    def __init__(self):
        self.display_flag  = True
        self.display_count = None

        # This is the most portable way (across POSIX systems) to get
        # our screen size that I can find, so, screw windows. Yeah.
        wrapper(self.__setmaxyx)
Beispiel #21
0
def start(function, transparent_background = False, cursor = True):
  """
  Starts a curses interface, delegating to the given function.

  :param funtion: function to invoke when curses starts
  :param bool transparent_background: allows background transparency
  :param bool cursor: makes cursor visible
  """

  def _wrapper(stdscr):
    global CURSES_SCREEN

    CURSES_SCREEN = stdscr

    if transparent_background:
      try:
        curses.use_default_colors()
      except curses.error:
        pass

    if not cursor:
      try:
        curses.curs_set(0)
      except curses.error:
        pass

    function()

  curses.wrapper(_wrapper)
Beispiel #22
0
    def __init__(self, username=None, password=None, filename=None, debug=False):
        UAClient.__init__(self, username=username, password=password, filename=filename, debug=debug)

        self.set_options()

        self.start_time = datetime.now()
        curses.wrapper(self.startcurses)
Beispiel #23
0
    def start_experiment(self):
        # start configuration commands
        for vnf_name, cmd_list in self.configuration_commands.items():
            for cmd in cmd_list:
                self.emu.docker_exec(vnf_name=vnf_name, cmd=cmd)

        # start overload detection
        self.overload_monitor.start(self.emu)

        # start the profling loop
        self.profiling_thread.start()

        if self.no_display == False:
            # nicely print values
            rows, columns = os.popen('stty size', 'r').read().split()
            # Set the Terminal window size larger than its default
            # to make sure the profiling results are fitting
            if int(rows) < 40 or int(columns) < 120:
                sys.stdout.write("\x1b[8;{rows};{cols}t".format(rows=40, cols=120))
            # print something to reset terminal
            print("")
            n = os.system("clear")
            # Add a delay to allow settings to settle...
            time.sleep(1)
            curses.wrapper(self.display_loop)


        # stop overload detection
        self.overload_monitor.stop(self.emu)
Beispiel #24
0
  def main(self):
    #load up our bots and start processing them.
    self.log.info("Started up, loading bot list.")
    
    try:
      bots = self.api.listBots()
      if (bots['status'] == 'success'):
        for row in bots['data']:
          if (self.isOurBot(row)):
            #create our thread and start it.
            parent_conn, child_conn = multiprocessing.Pipe()
            p = multiprocessing.Process(target=self.loadbot, args=(child_conn,row,))
            p.start()
            
            #link = 'process' : p, 'pipe' : parent_conn }
            link = hive.Object()
            link.bot = row
            link.process = p
            link.pipe = parent_conn
            link.job = None
            self.workers.append(link)
          else:
            self.log.info("Skipping unknown bot %s" % row['name'])
      else:
        self.log.error("Bot list failure: %s" % bots['error'])

      curses.wrapper(self.mainMenu)

      for link in self.workers:
        link.process.join()
    except KeyboardInterrupt as e:
      pass
Beispiel #25
0
    def __init__(self, options, title='Select', arrow="-->",
                 footer="Space = toggle, Enter = accept, q = cancel",
                 more="...", border="||--++++", c_selected="[X]", c_empty="[ ]", checked="[ ]"):
        self.title = title
        self.arrow = arrow
        self.footer = footer
        self.more = more
        self.border = border
        self.c_selected = c_selected
        self.c_empty = c_empty

        self.all_options = []

        for option in options:
            self.all_options.append({
                "label": option,
                "selected": True if (option in checked) else False
            })
            self.length = len(self.all_options)

        self.curses_start()

        signal.signal(signal.SIGWINCH, self.sigwinch_handler)
        curses.wrapper( self.curses_loop )
        self.curses_stop()
Beispiel #26
0
def main(args=None):
  args = argparser.parse_args(args)

  global DEBUG_LOG
  DEBUG_LOG = args.debug

  global MENU_COMMANDS
  for cmd in args.command:
    MENU_COMMANDS[cmd] = 'command-line argument'

  # Recalculate globals based on command-line options.
  global PREFIX_ON
  global PREFIX_OFF
  global PREFIX_LEN
  global MIN_HDR_WIDTH
  global MIN_STATUS_WIDTH
  global MIN_WIDTH

  MIN_STATUS_WIDTH = min(len(s) for s in MENU_COMMANDS.values())

  on_len = len(args.on)
  off_len = len(args.off)
  if on_len > off_len:
    args.off = args.off.ljust(on_len, ' ')
    PREFIX_LEN = on_len
  else:
    args.on = args.on.ljust(off_len, ' ')
    PREFIX_LEN = off_len
  PREFIX_ON = args.on
  PREFIX_OFF = args.off
  MIN_WIDTH = min(MIN_HDR_WIDTH, MIN_STATUS_WIDTH) + PREFIX_LEN + HELP_MSG_LEN + 1

  curses.wrapper(curses_main, args)
Beispiel #27
0
def main():
    args = parse_arguments()

    if args.teams > 4 or args.teams < 2:
        die(u'Number of teams must be between 2 and 4.\n')

    restore_file = '/tmp/pyctionary_{}.pickle'.format(
        datetime.datetime.now().strftime('%Y%m%d-%H%M%S'))

    cards = load_cards(args.cards)
    categories = cards[0]
    cards = cards[1:]

    try:
        curses.wrapper(start_game, categories, cards, args.teams, 
            args.restore, restore_file)
    except ScreenTooSmall as e:
        if e.saved:
            sys.stderr.write(u'Game saved as {}\n'.format(restore_file))
        die(u'Minimum term size 104x32, aborting.\n')
    except GameTerminated as e:
        if e.saved:
            sys.stderr.write(u'Game saved as {}\n'.format(restore_file))
    except pickle.UnpicklingError:
        sys.stderr.write(u'Malformed restore file provided, aborting\n')
Beispiel #28
0
    def __init__(self,target):
        self.target=target
        self.running=1
        curses.wrapper(self.setStdScr)
	self.console = []
        self.consoleHeight = 7
        threading.Thread.__init__(self)
Beispiel #29
0
def shell():
    parser = ArgumentParser(description="Console radio player")
    parser.add_argument("--stations", "-s", default=DEFAULT_FILE,help="Path on stations csv file.")
    parser.add_argument("--play", "-p", nargs='?', default=False,help="Start and play. " "The value is num station or empty for random.")
    parser.add_argument("--add", "-a", action='store_true',help="Add station to list.")
    parser.add_argument("--list", "-l", action='store_true',help="List of added stations.")
    args = parser.parse_args()

    # No need to parse the file if we add station
    if args.add:
        params = input("Enter the name: "), input("Enter the url: ")
        with open(args.stations, 'a') as cfgfile:
            writter = csv.writer(cfgfile)
            writter.writerow(params)
            sys.exit()

    with open(args.stations, 'r') as cfgfile:
        stations = []
        for row in csv.reader(cfgfile, skipinitialspace=True):
            if row[0].startswith('#'):
                continue
            name, url = [s.strip() for s in row]
            stations.append((name, url))

    if args.list:
        for name, url in stations:
            print(('{0:50s} {1:s}'.format(name, url)))
        sys.exit()

    pyradio = PyRadio(stations, play=args.play)
    curses.wrapper(pyradio.setup)
Beispiel #30
0
def command():
    if getpass.getuser() != 'root':
        sys.stderr.write("Err. Sorry you need root permissions for using iptables.\n")
        sys.exit(2)
    args = parser.parse_args()
    offset = 0
    if args.ntp_server:
        offset = get_ntp_offset(args.ntp_server)
    mount_info = utils.get_mount_info()
    port = get_cmd_port(args, mount_info, get_defaults(args.user))-2
    main2 = functools.partial(main, reset=args.reset, offset=offset, port=port)
    if not args.log:
        stdscr = curses.initscr()
        curses.curs_set(0)
        try:
            curses.wrapper(main2)
        except KeyboardInterrupt:
            i = 0
            line = stdscr.instr(i, 0)
            while line:
                sys.stdout.write(line.decode()+'\n')
                i += 1
                line = stdscr.instr(i, 0)
    else:
        main2()
Beispiel #31
0
#     ''' get the size of the console '''
#     WIDTH = scr.getmaxyx()[1] - 2
#     HEIGHT = scr.getmaxyx()[0] - 2
#     return WIDTH, HEIGHT
#
# WIDTH, HEIGHT = wrapper(main)
WIDTH, HEIGHT = 36, 20

Map = level.Map(HEIGHT, WIDTH)
keybinds = {}  # y  x
keybinds["KEY_UP"] = [-1, 0]
keybinds["KEY_DOWN"] = [1, 0]
keybinds["KEY_LEFT"] = [0, -1]
keybinds["KEY_RIGHT"] = [0, 1]
keybinds[("k")] = [-1, 0]
keybinds[("j")] = [1, 0]
keybinds[("h")] = [0, -1]
keybinds[("l")] = [0, 1]
keybinds[("y")] = [-1, -1]
keybinds[("u")] = [-1, 1]
keybinds[("b")] = [1, -1]
keybinds[("n")] = [1, 1]
keybinds[(".")] = [0, 0]
keybinds[("m")] = [0, 0, "m"]
keybinds[("t")] = [0, 0, "t"]
keybinds[("?")] = [0, 0, "?"]

foo = Display(WIDTH, HEIGHT, keybinds, Map)

wrapper(foo.main)
Beispiel #32
0
 def run(self):
     curses.wrapper(self._wrapped_run)
Beispiel #33
0
        if input_key == 'c':
            status = clear_status(len(status), len(status[0]))
        if input_key == 'r':
            status[curse_position[0]][curse_position[1]] = 0


GPIO.add_event_detect(button_1, GPIO.BOTH, callback=updateCanvas)
GPIO.add_event_detect(button_2, GPIO.BOTH, callback=updateCanvas)
GPIO.add_event_detect(button_3, GPIO.BOTH, callback=updateCanvas)
GPIO.add_event_detect(button_4, GPIO.BOTH, callback=updateCanvas)
GPIO.add_event_detect(button_5, GPIO.BOTH, callback=updateCanvas)
GPIO.add_event_detect(button_6, GPIO.BOTH, callback=updateCanvas)
GPIO.add_event_detect(button_7, GPIO.BOTH, callback=updateCanvas)


def main(stdscr):
    stdscr.clear()

    win = curses.newwin(HEIGHT, WIDTH, BEGIN_Y, BEGIN_X)
    win.keypad(True)
    win.addstr(
        0, 0,
        'Etch-a-Sketch\n Movements: Keys UP & DOWN,\n                 LEFT &  RIGHT\n Key SPACE - draw\n c - clear\n r - erase\n q - exit '
    )
    while (1):
        draw(win, status, curse_position)
        time.sleep(1.0 / 20)


curses.wrapper(main)
Beispiel #34
0
import model.plots as pl

import controller.settingloader as sl
import controller.keycontrols as kc
import controller.viewcontrols as vc
__author__ = 'Kellan Childers'


def app(stdscr):
    vc.create_color_schemes()
    vc.init(stdscr)
    vc.setup.draw_background(stdscr)
    """
    board = pl.Plot(4, 4)
    for x in range(4):
        for y in range(4):
            board[x][y] = pl.Tile(2, str(2))
    board[0][0] += pl.Tile(2, str(2))

    stdscr.addstr(0, 0, str(board))
    stdscr.refresh()
    """
    vc.setup.do_commands(stdscr, kc.execute_command)


if __name__ == "__main__":
    os.chdir(sl.get_main_directory())

    crs.wrapper(app)
Beispiel #35
0
    std_pp("")
    text = "Solution curve has been plotted! Would you like to create more " \
           "visualizations?"
    std_pp(text)
    std_pp("")
    user_choice = input("\033[35;1mMore visualizations? [y/N] \033[0m")
    global next_screen
    if user_choice != 'n' and user_choice != 'N':
        next_screen = 8
        return
    else:
        next_screen = 11
        return


def Anim3D():
   global next_screen
   next_screen = -1


screens = {0: Intro, 1: Visualize, 2: PlotCurves, 3: Anim3D}

if __name__ == '__main__':
    sys.stdout.write("\x1b[2J\x1b[H")
    curses.wrapper(get_size)
    while 0 <= current_screen:
        screens[current_screen]()
        visited[current_screen] = 1
        current_screen = next_screen
    sys.stdout.write("\x1b[2J\x1b[H")
Beispiel #36
0
            snake[0][1] + (key == KEY_RIGHT and 1) + (key == KEY_LEFT and -1)
        ])

        # encouter border
        if snake[0][0] in [0, height - 1] or snake[0][1] in [0, width - 1]:
            break

        # encouter food
        if snake[0] == food:
            win.addch(food[0], food[1], '#')
            food = []
            #score += 1
            while food == []:
                food = [randint(1, height - 2), randint(1, width - 2)]
                if food in snake: food = []
            win.addch(food[0], food[1], '*')
        else:
            last = snake.pop()
            win.addch(last[0], last[1], ' ')
            win.addch(snake[0][0], snake[0][1], '#')

        # self-colliding
        if snake[0] in snake[1:]:
            break

    curses.endwin()
    print(f"\nLength - {len(snake)}")


wrapper(main)
Beispiel #37
0
        if not DEBUG_MODE:
            key = stdscr.getkey()
        else:
            key = input()
        if key == 'q':
            sys.exit(0)
        else:
            try:
                key_as_int = int(key)
                if key_as_int in (1, 2, 3, 4, 5, 6) and mancala_board.board[key_as_int - 1] != 0:
                    mancala_board.make_move(key_as_int - 1)
                    print_screen(stdscr, mancala_board)
                    while not mancala_board.player0_turn and not mancala_board.game_finished():
                        next_move = decide_next_move(mancala_board, 50000)
                        mancala_board.make_move(next_move)
                        print_screen(stdscr, mancala_board)

            except:
                pass

    print_screen(stdscr, mancala_board)
    if not DEBUG_MODE:
        key = stdscr.getkey()


if __name__ == "__main__":
    if not DEBUG_MODE:
        curses.wrapper(start_game)
    else:
        start_game(None)
Beispiel #38
0
        print(now_str)
        time.sleep(SLEEP)


def init_arr():
    now_arr = np.zeros((H, W), dtype=np.uint8)
    for x in rangeH:
        for y in rangeW:
            if int(random.random() + 0.1):
                now_arr[x][y] = 1

    return now_arr


if __name__ == '__main__':
    curses.wrapper(pbar)
    # print2terminal()

# warn algorithm
'''
import time
import curses
import random
import copy

H = 40
W = 120
RANDOM_LIVE = 0.01
EPOCH = 100
SLEEP = 1
Beispiel #39
0
                if self.stripspaces and x > stop:
                    break
                result = result + chr(curses.ascii.ascii(self.win.inch(y, x)))
            if self.maxy > 0:
                result = result + "\n"
        return result

    def edit(self):
        "Edit in the widget window and collect the results."
        while 1:
            ch = self.win.getch()
            if not ch:
                continue
            if not self.do_command(ch):
                break
            self.win.refresh()
        return self.gather()

if __name__ == '__main__':
    def test_editbox(stdscr):
        ncols, nlines = 140, 30
        uly, ulx = 2, 1
        stdscr.addstr(uly-2, ulx, "Use Ctrl-G to end editing.")
        win = curses.newwin(nlines, ncols, uly, ulx)
        rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols)
        stdscr.refresh()
        return Textbox(win).edit()

    str = curses.wrapper(test_editbox)
    print('Contents of text box:', repr(str))
Beispiel #40
0
            if c < size[1] - 1:
                nc = c + 1
        elif userkey == curses.KEY_LEFT:
            if c > 0:
                nc = c - 1
        elif userkey == curses.KEY_DOWN:
            if r < size[0] - 1:
                nr = r + 1
        elif userkey == curses.KEY_UP:
            if r > 0:
                nr = r - 1
        elif userkey == 100:
            digcell(field[r][c])
        elif userkey == 102:
            # f 102
            flagcell(field[r][c])
        elif userkey == 32:
            # 32 is the white space key
            opensurrounding(stdscr, field, r, c, colors)

        # paint the current cell normally
        paintcell(stdscr, field[r][c], colors)
        # the new cell reverse.
        paintcell(stdscr, field[nr][nc], colors, True)
        # reset current cell's index.
        r = nr
        c = nc


curses.wrapper(sweeper)
Beispiel #41
0
 def __init__(self, type="curses", menudata=None):
     if type == "curses":
         self.menu = curses.wrapper(CursesMenu, menudata=menudata)
def main(dataset, outpath):
    stdscr = curses.initscr()
    imgs = []
    obj_points = []
    img_points = []
    pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
    pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
    pattern_points *= square_size
    def curses_main(stdscr):
        k = ""
        status_found = False
        status = None
#        stdscr.nodelay(1)
        curses.halfdelay(1)
        curses.noecho()
        for im0 in dataset:
            stdscr.clear()
            stdscr.addstr("Press \"j\" to use detected values\n")
            stdscr.addstr("Press \"q\" to end\n")
            stdscr.addstr("Found chessboard: {0}\n".format(str(status_found)))
            if isinstance(k, int) and k != -1:
                stdscr.addstr("Detected key: {0}\n".format(chr(k)))
            else:
                stdscr.addstr("Detected key: None\n")
            print("finding chessboardcorners\n")

            img_gray = cv2.cvtColor(im0, cv2.COLOR_RGB2GRAY)
            if gray_images: im0 = img_gray
            found, corners = cv2.findChessboardCorners(img_gray,
                                                       pattern_size,
                                                       flags=cv2.CALIB_CB_ADAPTIVE_THRESH)
            if found:
                status_found = True
                term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
                cv2.cornerSubPix(img_gray, corners, (5, 5), (-1, -1), term)
                cv2.drawChessboardCorners(im0, pattern_size, corners, found)
                add_corners = corners.reshape(-1,2)
            else:
                status_found = False

            cv2.imshow("Camera Display", im0)

            if k == ord('q'):
                break
            elif k == ord('j'):
                img_points.append(add_corners)
                obj_points.append(pattern_points)
                imgs.append(im0)
            k = stdscr.getch()

    curses.wrapper(curses_main)

    assert len(img_points) != 0, "No Chessboard Corners Added"
    h, w = imgs[0].shape[:2] 
    rms, camera_matrix, dist_coefs, _rvecs, _tvecs = cv2.calibrateCamera(obj_points,
                                                                         img_points,
                                                                         (w, h),
                                                                         None,
                                                                         None)
    with open('{0}.npy'.format(cparams_fn), 'wb') as f:
        np.save(f, rms)
        np.save(f, camera_matrix)
        np.save(f, dist_coefs)
        print('camera intrinsic parameters saved to {0}.npy'.format(cparams_fn))
    undistort_img(imgs, outpath, rms, camera_matrix, dist_coefs, crop_dist)
Beispiel #43
0
def main():
    curses.wrapper(draw)
Beispiel #44
0
        await utils.sleep(ticks_in_year)
        year += 1


async def show_year_window(canvas, rows_number, columns_number):
    """Show window with year and year phrase at the bottom of canvas."""

    start_row = rows_number - BORDER_WIDTH * 2 - DERIVED_WINDOW_HEIGHT
    start_column = 0
    notify_window = canvas.derwin(start_row, start_column)
    text_offset = 2
    while True:
        try:
            phrase = game_scenario.PHRASES[year]
        except KeyError:
            # Do not delete the previous phrase, as it is difficult
            # to read it in a "year"
            pass
        # Add offset to the text using spaces, so there will be no other
        # objects in offset (like when we add offset in window.addstr(...))
        text = f'{" "*text_offset}{year}: {phrase}'.ljust(
            columns_number - BORDER_WIDTH * 2, ' ')
        notify_window.border()
        notify_window.addstr(1, BORDER_WIDTH, text)
        await asyncio.sleep(0)


if __name__ == '__main__':
    curses.update_lines_cols()
    curses.wrapper(draw)
Beispiel #45
0
    keys = [
        "KEY_UP", "KEY_DOWN", "KEY_LEFT", "KEY_RIGHT", "\n", "q", "r", "o",
        "x", "c"
    ]
    info.clear()
    info.addstr("Instructions:\n")
    info.addstr("Use the ArrowKeys to select a box\n")
    info.addstr("Press return to place an " + ("X" if object.isUserX else "O"))
    info.addstr("\nMake three in a row to win!\n\n")
    info.addstr("Can you beat the computer?\n\n")
    info.addstr("Use the '" + ("O" if object.isUserX else "X") +
                "' key to change token\n")
    info.addstr("Use the 'R' key to reset\n")
    info.addstr("Use the 'Q' key to quit\n")
    stdscr.refresh()
    info.refresh()
    key = stdscr.getkey()
    while str(key) != "q":
        key, object, pause, hScore = gameLoop(stdscr, info, key, keys, object,
                                              pause, hScore)


wrapper(
    main
)  #wrapper catches exceptions, closes curses and then prints exceptions

curses.nocbreak()  #terminate curses commands
stdscr.keypad(False)
curses.echo()
curses.endwin()
Beispiel #46
0
                if self.blockViewOffset < self.keylen - self.charsPerBlock:
                    self.blockViewOffset += 1
                else:
                    self.printInfo("reached end of block.")

            self.refresh()


if __name__ == "__main__":
    # display help
    if len(sys.argv) == 2 and sys.argv[1] == "-h":
        print "Usage: otp_pwn.py [encrypted file] [key length]"
        sys.exit()

    if len(sys.argv) < 2:
        filename = raw_input("Encrypted file: ")
    else:
        filename = sys.argv[1]

    if len(sys.argv) < 3:
        keylen = int(raw_input("Length of the key: "))
    else:
        keylen = int(sys.argv[2])

    with open(filename, "r") as f:
        # size of file
        f.seek(0, 2)
        filesize = f.tell()
        otpPwn = OTPPwn(f, keylen, filesize)
        curses.wrapper(otpPwn.run)
Beispiel #47
0
def sendrecvTestLauncher():
    curses.wrapper(sendrecvTest)
Beispiel #48
0
        print('Punctuation Key %r (%r)' % (event.keysym, event.char))
    else:
        # f1 to f12, shift keys, caps lock, Home, End, Delete ...
        print('Special Key %r' % event.keysym)


if __name__ == "__main__":

    # initialize Serial monitor
    ser = serial.Serial(port='\\\\.\\COM6',
                        baudrate=115200,
                        parity=serial.PARITY_ODD,
                        stopbits=serial.STOPBITS_ONE,
                        bytesize=serial.EIGHTBITS)

    # for debugging:
    # ser = None
    # update_board_state([[3,5], [3,4], [3,3]] , [5,5])

    # welcome message
    render_text("Welcome To Snake!", ser)

    # game main
    try:
        wrapper(curses_main(ser))
    except:
        render_text("Come back again!", ser)
        pass
    # exit message
    render_text("Come back again!", ser)
Beispiel #49
0
def play(stdscr):
    """
    Play function
    """

    stdscr.clear()

    # Get window height & width
    height, width = stdscr.getmaxyx()

    title = "Answer the problems to beat your opponent to the finish!"

    # get various x,y coordinates according to user's window size
    start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2)
    start_y_title = int((height // 4) - 2)

    start_x_problem = int((width // 2) - 4)
    start_y_problem = int((3 * height // 4))

    enemy_x = int(width // 8)
    enemy_y = int((height // 2) - 1)

    x = int(width // 8)
    y = int((height // 2) + 1)

    x_finish = int((width // 8) * 7)

    finished = False

    winner = False

    while (finished == False):  # iterate until user finishes game

        stdscr.addstr(start_y_title, start_x_title, title)

        stdscr.addstr(enemy_y + -2, x_finish - 3, 'Finish')
        stdscr.addstr(enemy_y + -1, x_finish, '|')
        stdscr.addstr(enemy_y, x_finish, '|')
        stdscr.addstr(enemy_y + 1, x_finish, '|')
        stdscr.addstr(enemy_y + 2, x_finish, '|')
        stdscr.addstr(enemy_y + 3, x_finish, '|')

        # get initial equation
        problem, actual_answer = get_equation()

        stdscr.addstr(start_y_problem, start_x_problem, problem)

        counter = 1

        stdscr.nodelay(True)  # make sure it doesnt stop to get a character

        user_answer = ""

        while (enemy_x < x_finish - 4 and x < x_finish - 4):

            key = stdscr.getch()

            stdscr.addstr(enemy_y, enemy_x, '>[~~]>')

            stdscr.addstr(y, x, '>[~~]>')

            # how often the enemy moves forward - it's faster when the difficulty is harder
            if counter % 10000 == 0:
                enemy_x = enemy_x + 1

            counter = counter + 1

            stdscr.refresh()

            if key == 10:  # user presses enter
                if user_answer == str(actual_answer):  # correct answer
                    stdscr.addstr(y, x, '>>>>>>>>>>>')
                    x = x + 10
                    stdscr.addstr(y, x, '>[~~]>')  # moves user forward

                    problem, actual_answer = get_equation()  # get new equation
                    stdscr.addstr(start_y_problem, start_x_problem,
                                  "          ")
                    stdscr.addstr(start_y_problem, start_x_problem,
                                  problem)  # overwrite old equation
                    stdscr.addstr(start_y_problem, start_x_problem + 10,
                                  "          ")
                    user_answer = ""

                else:  # incorrect answer
                    user_answer = ""
                    stdscr.addstr(start_y_problem, start_x_problem + 10,
                                  "          ")

            elif key == 127:  # user presses backspace
                user_answer = user_answer[:-1]
                stdscr.addstr(start_y_problem, start_x_problem + 10,
                              "          ")

            elif key != -1:  # user adds character to their answer
                user_answer = user_answer + str(chr(key))

            stdscr.addstr(start_y_problem, start_x_problem + 10,
                          user_answer)  # update user answer

        finished = True

        if x >= x_finish - 4:  # check if user won or lost
            winner = True

    stdscr.clear()

    if winner == True:
        title = 'Congratulations! You won!'
    else:
        title = 'You lost! Better luck next time!'

    subtitle = 'Press any key to continue'

    height, width = stdscr.getmaxyx()

    stdscr.addstr(
        int((height // 2) - 2) - 1,
        int((width // 2) - (len(title) // 2) - len(title) % 2), title)
    stdscr.addstr(
        int((height // 2) - 2) + 2,
        int((width // 2) - (len(subtitle) // 2) - len(subtitle) % 2), subtitle)

    stdscr.nodelay(False)  # pause until user enters a character

    stdscr.getch()

    curses.wrapper(main)  # back to main function
Beispiel #50
0
            strokes[millis] = key
            # print to screen
            waiting.addstr("\n Time: " + str(seconds) + "s," + milliseconds + "ms: Detected key:")
            waiting.addstr(str(key))
        except:
            pass

def flashing(self):
    self.addstr("TIME OUT")
    curses.beep()
    curses.flash()
    curses.napms(100)


# execute main function
curses.wrapper(main)

# notify the user that the program is done
curses.wrapper(flashing)

# sum up the summary lists (yes this has to be done that way - somehow curses does
# not like to modify a dictionary value internally)
for i in stroke_summary:
    stroke_summary[i] = sum(stroke_summary[i])
drop = stroke_summary.pop('', None)

# write the output
with open(sys.argv[1] + "_" + str(observation).zfill(padding) + "_ethoc.csv" , "w") as writefile:
    # write a header
    writefile.write("Time in ms,key pressed\n")
    # write all elements in the dictionary
            board.addstr(3 + j, x + 1, task.name)


def draw_board(board, buckets):
    board.border()
    draw_titles(board)
    draw_grid(board)
    draw_tasks(board, buckets)


def main(screen, tasks_file_path):
    curses.curs_set(0)
    tasks = build_tasks(tasks_file_path)
    buckets = sort_tasks(tasks)

    while True:
        draw_board(screen, buckets)
        char = screen.getch()
        if char == 27:
            break


if __name__ == '__main__':
    if len(sys.argv) == 1:
        tasks_file_path = "./tasks.txt"
    elif len(sys.argv) == 2:
        tasks_file_path = sys.argv[1]
    else:
        exit("Invalid argument length")
    curses.wrapper(main, tasks_file_path)
Beispiel #52
0
    panel = curses.panel.new_panel(win)
    return win, panel


def test(stdscr):
    curses.curs_set(0)
    stdscr.box()
    stdscr.addstr(2, 2, "panels everywhere")
    win1, panel1 = make_panel(10, 12, 5, 5, "Panel 1")
    win2, panel2 = make_panel(10, 12, 8, 8, "Panel 2")
    curses.panel.update_panels()
    stdscr.refresh()
    sleep(1)

    panel1.top()
    curses.panel.update_panels()
    stdscr.refresh()
    sleep(1)

    for i in range(20):
        panel2.move(8, 8 + i)
        curses.panel.update_panels()
        stdscr.refresh()
        sleep(0.1)

    sleep(1)


if __name__ == '__main__':
    curses.wrapper(test)
Beispiel #53
0
 def start(self):
     return curses.wrapper(self._start)
Beispiel #54
0
    shorter_esc_delay()

    parser = argparse.ArgumentParser(prog='tool',
                                     formatter_class=lambda prog: argparse.
                                     HelpFormatter(prog, max_help_position=50))
    parser.add_argument("-y",
                        "--height",
                        type=int,
                        help="size of y_axis",
                        metavar="[7-204]",
                        choices=range(7, 205))
    parser.add_argument("-x",
                        "--width",
                        type=int,
                        help="size of x_axis",
                        metavar="[10-477]",
                        choices=range(10, 478))
    parser.add_argument("-f",
                        "--full_screen",
                        action="store_true",
                        help="uses full height/width of terminal")
    parser.add_argument("-d",
                        "--difficulty",
                        type=int,
                        help="set difficulty",
                        metavar="[1-5]",
                        choices=range(1, 6))
    args = parser.parse_args()

    curses.wrapper(partial(main, args))
Beispiel #55
0
import curses


def center(length, width):
    return (width - length) // 2


def curses_fn(stdscr):
    stdscr.clear()
    y_max, x_max = stdscr.getmaxyx()

    text = 'Hello World!'
    stdscr.addstr(center(1, y_max), center(len(text), x_max), text)
    stdscr.refresh()

    while True:
        ch = stdscr.getch()
        if chr(ch) == 'q':
            break


if __name__ == '__main__':
    curses.wrapper(curses_fn)
Beispiel #56
0
                if index == len(items):
                    break
                #Skip linux select screen for ostree installation.
                if index == select_linux_index:
                    if (install_config['type'] == 'ostree_host'
                            or install_config['type'] == 'ostree_server'):
                        index += 1
            else:
                index -= 1
                while index >= 0 and items[index][1] == False:
                    index -= 1
                if index < 0:
                    index = 0
                #Skip linux select screen for ostree installation.
                if index == select_linux_index:
                    if (install_config['type'] == 'ostree_host'
                            or install_config['type'] == 'ostree_server'):
                        index -= 1


if __name__ == '__main__':
    usage = "Usage: %prog [options]"
    parser = ArgumentParser(usage)
    parser.add_argument("-j",
                        "--json-file",
                        dest="options_file",
                        default="input.json")

    options = parser.parse_args()
    curses.wrapper(IsoInstaller, options.options_file)
Beispiel #57
0
def run_interactive():
    locale.setlocale(locale.LC_ALL, '')
    code = locale.getpreferredencoding()
    # Then use code as the encoding for str.encode() calls.

    curses.wrapper(curses_main)
Beispiel #58
0
      
    scr.addch(y, x, ord(" "))

    # change the current position
          
    x = x + dx
    y = y + dy

    # get the character at the current position
    
    ch = scr.inch(y, x)

    if ch != ord(" "):   
      # it's not a space
             
      break

    # replace the character with a "O"
    
    scr.addch(y, x, ord("O"))
    
    # update the screen
    
    scr.refresh()
    
    # wait for 1/20 of a second
    
    time.sleep(0.05)
    
curses.wrapper(snake)
Beispiel #59
0
 def launch(self):
     """Launch the user interface."""
     signal.signal(signal.SIGINT, self._signal_handler)
     signal.signal(signal.SIGQUIT, self._signal_handler)
     curses.wrapper(self._launch_interface)
    def close(self):
        logging.info("Closing down")
        # self.device.close()

    def run(self, stdscr):
        # default terminal colors
        curses.use_default_colors()
        # no blinking cursor
        # curses.curs_set(0)
        # getch() pauses for one second
        curses.halfdelay(10)

        while True:
            stdscr.erase()

            stdscr.addstr("GPS messages since last refresh:\n")

            stdscr.refresh()
            c = stdscr.getch()
            if c == ord('q'):
                break


if __name__ == '__main__':
    logging.basicConfig(level=logging.WARNING)

    app = Main()
    curses.wrapper(app.run)
    app.close()