Exemplo n.º 1
0
 def test_various_splices(self):
     a = blue('hi')
     b = a + green('bye')
     c = b + red('!')
     self.assertEqual(
         c.splice('asdfg', 1),
         blue('h') + 'asdfg' + blue('i') + green('bye') + red('!'))
     self.assertEqual(c.splice('asdfg', 1, 4),
                      blue('h') + 'asdfg' + green('e') + red('!'))
     self.assertEqual(c.splice('asdfg', 1, 5),
                      blue('h') + 'asdfg' + red('!'))
Exemplo n.º 2
0
 def test_various_splices(self):
     a = blue("hi")
     b = a + green("bye")
     c = b + red("!")
     self.assertEqual(
         c.splice("asdfg", 1),
         blue("h") + "asdfg" + blue("i") + green("bye") + red("!"),
     )
     self.assertEqual(c.splice("asdfg", 1, 4),
                      blue("h") + "asdfg" + green("e") + red("!"))
     self.assertEqual(c.splice("asdfg", 1, 5),
                      blue("h") + "asdfg" + red("!"))
Exemplo n.º 3
0
    def update(self) -> None:
        """Updates display based on game state"""
        self.clear_main()

        if self.menu:
            if not self.menu_opened_at:
                self.menu_opened_at = pendulum.now()

            self.clear_main()
            if self.menu == "help":
                self.draw_help()
            elif self.menu == "confirm_new":
                self.draw_confirm_new()
            elif self.menu == "won":
                self.draw_won()
            elif self.menu == "lost":
                self.draw_lost()
            else:
                self.draw_menu(ff.blue("test"), [])

        elif self.field:
            if self.menu_opened_at:
                self.field.add_stoppage(pendulum.now() - self.menu_opened_at)
                self.menu_opened_at = None

            self.draw_header()
            self.draw_field()
            if not self.field.ended:
                if self.field.won:
                    self.menu = "won"
                elif self.field.lost:
                    self.menu = "lost"

        self.draw_debug()
        self.window.render_to_terminal(self.chars)
Exemplo n.º 4
0
def main():

    print(yellow('creating network'))
    net = Net()
    print(green('sending network to device'))
    net = net.to(device)

    loss_function = nn.CrossEntropyLoss()
    optimizer = optim.Adam(net.parameters(), lr=.00001)

    train_x, train_y, test_x, test_y = loadTrainingData()
    print(blue('begin training'))
    train(net, loss_function, optimizer, train_x, train_y, test_x, test_y)

    # x = train_x + test_x
    # y = train_y + test_y

    # training_data = np.load("hands.npy", allow_pickle=True)
    # x = torch.Tensor([i[0] for i in training_data]).view(-1, IMAGE_SIZE_X, IMAGE_SIZE_Y)
    # x /= 255.  # Change pixel value to range[0, 1)
    # y = [np.argwhere(i[1] == 1.)[0][0] for i in training_data]
    # y = torch.LongTensor(y)
    # acc, loss = test(net, loss_function, optimizer, x, y, size=len(train_x))
    # print(green(f'Total Dataset Accuracy: {acc}, Total Dataset Loss: {loss}'))

    while True:
        choice = str(input('test with a picture filename or type exit: '))
        if choice == 'exit':
            break
        test_image(net, choice)
Exemplo n.º 5
0
    def recv_watcher(self):
        t = threading.currentThread()
        self.fx.flogger.debug("Recv polling thread init {}".format(t))

        # How often to check DNS
        # TODO: Abstract this time to a parameter
        self.config['recv_watch'] = 5

        while getattr(t, "do_run", True):
            self.fx.flogger.debug("Polling Record for jobs")
            peek_data = self.fx.agent_peek()
            jpeek_data = json.loads(peek_data)

            # New request found
            if self.config['role'] == 'master':
                if jpeek_data['t'].lower() == 's' and jpeek_data["s"].upper(
                ) == 'W':
                    self.fx.action_recv()

            if self.config['role'] == 'slave':
                if jpeek_data['t'].lower() == 'q' and jpeek_data["s"].upper(
                ) == 'J':
                    print(blue("== Incoming request =="))
                    self.fx.action_recv()

            # TODO: implement timer
            time.sleep(self.config['recv_watch'])
        self.fx.flogger.debug("Recv polling thread exit {}".format(t))
        return
Exemplo n.º 6
0
 def test_multiple_bfs_splice(self):
     self.assertEqual(
         fmtstr('a') + blue('b'),
         on_blue(' ' * 2).splice(fmtstr('a') + blue('b'), 0, 2))
     self.assertEqual(
         on_red('yo') + on_blue('   '),
         on_blue(' ' * 5).splice(on_red('yo'), 0, 2))
     self.assertEqual(' ' + on_red('yo') + on_blue('   '),
                      on_blue(' ' * 6).splice(' ' + on_red('yo'), 0, 3))
     self.assertEqual(
         on_blue("hey") + ' ' + on_red('yo') + on_blue('   '),
         on_blue(' ' * 9).splice(on_blue("hey") + ' ' + on_red('yo'), 0, 6))
     self.assertEqual(
         on_blue(' ' * 5) + on_blue("hey") + ' ' + on_red('yo') +
         on_blue('   '),
         on_blue(' ' * 14).splice(
             on_blue("hey") + ' ' + on_red('yo'), 5, 11))
Exemplo n.º 7
0
 def render(self, isDead):
     if not isDead:
         a = FSArray(self.height, self.width)
         for seg in self.snake_segments:
             a[seg[0],seg[1]] = blue('X')
         return a
     else:
         a = self.deathSequence()
         return a
Exemplo n.º 8
0
 def render(self, isDead):
     if not isDead:
         a = FSArray(self.height, self.width)
         for seg in self.snake_segments:
             a[seg[0], seg[1]] = blue('X')
         return a
     else:
         a = self.deathSequence()
         return a
Exemplo n.º 9
0
def main(host, port):

    # Create a socket
    client = socket.socket()
    # Connect
    client.connect((host, port))
    # Set socket not to block?
    client.setblocking(False)

    # Create connection object
    conn = Connection(client)
    # Store keypresses
    keypresses = []

    with FullscreenWindow() as window:
        # Input() is from curtsies
        with Input() as input_generator:
            while True:
                # red is stuff at bottom, blue status at top, green 'window' with output

                # red at bottom
                a = FSArray(10, 80)
                in_text = ''.join(keypresses)[:80]
                a[9:10, 0:len(in_text)] = [red(in_text)]
                # render does the page in green
                for i, line in zip(reversed(range(2, 7)),
                                   reversed(conn.render())):
                    a[i:i + 1, 0:len(line)] = [line]

# Top line
                text = 'connected to %s:%d' % (host if len(host) < 50 else
                                               host[:50] + '...', port)
                a[0:1, 0:len(text)] = [blue(text)]

                window.render_to_terminal(a)
                ready_to_read, _, _ = select.select([conn, input_generator],
                                                    [], [])
                for r in ready_to_read:
                    if r is conn:
                        r.on_read()
                    else:
                        e = input_generator.send(0)
                        if e == '<ESC>':
                            return
                        elif e == '<Ctrl-j>':
                            keypresses.append('\n')
                            client.send(
                                (''.join(keypresses)).encode('latin-1'))
                            keypresses = []
                        elif e == '<SPACE>':
                            keypresses.append(' ')
                        elif e in ('<DELETE>', '<BACKSPACE>'):
                            keypresses = keypresses[:-1]
                        elif e is not None:
                            keypresses.append(e)
Exemplo n.º 10
0
 def test_right_sequence_in_py3(self):
     red_on_blue = fmtstr('hello', 'red', 'on_blue')
     blue_on_red = fmtstr('there', fg='blue', bg='red')
     green_s = fmtstr('!', 'green')
     full = red_on_blue + ' ' + blue_on_red + green_s
     self.assertEqual(
         full,
         on_blue(red("hello")) + " " + on_red(blue("there")) + green("!"))
     self.assertEqual(
         str(full),
         '\x1b[31m\x1b[44mhello\x1b[49m\x1b[39m \x1b[34m\x1b[41mthere\x1b[49m\x1b[39m\x1b[32m!\x1b[39m'
     )
Exemplo n.º 11
0
 def test_right_sequence_in_py3(self):
     red_on_blue = fmtstr("hello", "red", "on_blue")
     blue_on_red = fmtstr("there", fg="blue", bg="red")
     green_s = fmtstr("!", "green")
     full = red_on_blue + " " + blue_on_red + green_s
     self.assertEqual(
         full,
         on_blue(red("hello")) + " " + on_red(blue("there")) + green("!"))
     self.assertEqual(
         str(full),
         "\x1b[31m\x1b[44mhello\x1b[49m\x1b[39m \x1b[34m\x1b[41mthere\x1b[49m\x1b[39m\x1b[32m!\x1b[39m",
     )
Exemplo n.º 12
0
 def test_multiple_bfs_splice(self):
     self.assertEqual(
         fmtstr("a") + blue("b"),
         on_blue(" " * 2).splice(fmtstr("a") + blue("b"), 0, 2),
     )
     self.assertEqual(
         on_red("yo") + on_blue("   "),
         on_blue(" " * 5).splice(on_red("yo"), 0, 2))
     self.assertEqual(
         " " + on_red("yo") + on_blue("   "),
         on_blue(" " * 6).splice(" " + on_red("yo"), 0, 3),
     )
     self.assertEqual(
         on_blue("hey") + " " + on_red("yo") + on_blue("   "),
         on_blue(" " * 9).splice(on_blue("hey") + " " + on_red("yo"), 0, 6),
     )
     self.assertEqual(
         on_blue(" " * 5) + on_blue("hey") + " " + on_red("yo") +
         on_blue("   "),
         on_blue(" " * 14).splice(
             on_blue("hey") + " " + on_red("yo"), 5, 11),
     )
Exemplo n.º 13
0
def main(command):

    pexpect_session = pexpect.spawn(command)
    with curtsies.FullscreenWindow() as window:
        while True:
            a = curtsies.FSArray(window.height, window.width)
            text = 'pexpect window manager ' + str(window.height) + 'x' + str(
                window.width)
            a[0:1, 0:len(text)] = [blue(text)]
            window.render_to_terminal(a)
            try:
                res = pexpect_session.read_nonblocking(timeout=1)
            except pexpect.EOF:
                pass
Exemplo n.º 14
0
    def test_ljust_rjust(self):
        """"""
        b = fmtstr(u'ab', 'blue', 'on_red', 'bold')
        g = fmtstr(u'cd', 'green', 'on_red', 'bold')
        s = b + g
        self.assertEqual(s.ljust(6), b + g + on_red('  '))
        self.assertEqual(s.rjust(6), on_red('  ') + b + g)

        # doesn't add empties to end
        self.assertEqual(s.ljust(4), b + g)
        self.assertEqual(s.rjust(4), b + g)

        # behavior if background different
        s = on_blue('a') + on_green('b')
        self.assertEqual(s.ljust(3), fmtstr('ab '))
        self.assertEqual(s.rjust(3), fmtstr(' ab'))
        s = blue(on_blue('a')) + green(on_green('b'))
        self.assertEqual(s.ljust(3), blue('a') + green('b') + fmtstr(' '))
        self.assertEqual(s.rjust(3), fmtstr(' ') + blue('a') + green('b'))

        #using fillchar
        self.assertEqual(s.ljust(3, '*'), fmtstr('ab*'))
        self.assertEqual(s.rjust(3, '*'), fmtstr('*ab'))
Exemplo n.º 15
0
    def test_split(self):
        self.assertEqual(
            blue('hello there').split(' '),
            [blue('hello'), blue('there')])
        s = blue('hello there')
        self.assertEqual(s.split(' '), [s[:5], s[6:]])

        # split shouldn't create fmtstrs without chunks
        self.assertEqual(fmtstr('a').split('a')[0].chunks, fmtstr('').chunks)
        self.assertEqual(fmtstr('a').split('a')[1].chunks, fmtstr('').chunks)

        self.assertEqual((fmtstr('imp') + ' ').split('i'),
                         [fmtstr(''), fmtstr('mp') + ' '])
        self.assertEqual(
            blue('abcbd').split('b'),
            [blue('a'), blue('c'), blue('d')])
Exemplo n.º 16
0
    def test_ljust_rjust(self):
        """"""
        b = fmtstr("ab", "blue", "on_red", "bold")
        g = fmtstr("cd", "green", "on_red", "bold")
        s = b + g
        self.assertEqual(s.ljust(6), b + g + on_red("  "))
        self.assertEqual(s.rjust(6), on_red("  ") + b + g)

        # doesn't add empties to end
        self.assertEqual(s.ljust(4), b + g)
        self.assertEqual(s.rjust(4), b + g)

        # behavior if background different
        s = on_blue("a") + on_green("b")
        self.assertEqual(s.ljust(3), fmtstr("ab "))
        self.assertEqual(s.rjust(3), fmtstr(" ab"))
        s = blue(on_blue("a")) + green(on_green("b"))
        self.assertEqual(s.ljust(3), blue("a") + green("b") + fmtstr(" "))
        self.assertEqual(s.rjust(3), fmtstr(" ") + blue("a") + green("b"))

        # using fillchar
        self.assertEqual(s.ljust(3, "*"), fmtstr("ab*"))
        self.assertEqual(s.rjust(3, "*"), fmtstr("*ab"))
Exemplo n.º 17
0
    def test_split(self):
        self.assertEqual(
            blue("hello there").split(" "),
            [blue("hello"), blue("there")])
        s = blue("hello there")
        self.assertEqual(s.split(" "), [s[:5], s[6:]])

        # split shouldn't create fmtstrs without chunks
        self.assertEqual(fmtstr("a").split("a")[0].chunks, fmtstr("").chunks)
        self.assertEqual(fmtstr("a").split("a")[1].chunks, fmtstr("").chunks)

        self.assertEqual((fmtstr("imp") + " ").split("i"),
                         [fmtstr(""), fmtstr("mp") + " "])
        self.assertEqual(
            blue("abcbd").split("b"),
            [blue("a"), blue("c"), blue("d")])
Exemplo n.º 18
0
def action_based_on_percent(game):
    """Prints feedback for user based on performance (percent correct)."""

    you_suck_message = [
        "Keep trying! You'll get it!", "Come on, human.", "Try harder?"
    ]
    you_rock_message = [
        "WAY TO GO!",
        "You're doing awesomely! Are you *sure* you weren't on Quiz Bowl in highschool?",
        "WELL DONE!", "Rockin' this!"
    ]

    percent = game.compute_percent_correct()
    if percent <= 30:
        fancy_print(random.choice(you_suck_message))
    if percent >= 60:
        fancy_print(blue(random.choice(you_rock_message)))
Exemplo n.º 19
0
 def test_diff_testing(self):
     a = fsarray(['abc', 'def'])
     b = fsarray(['abc', 'dqf'])
     self.assertRaises(AssertionError, self.assertFSArraysEqual, a, b)
     a = fsarray([blue('abc'), red('def')])
     b = fsarray([blue('abc'), red('dqf')])
     self.assertRaises(AssertionError, self.assertFSArraysEqual, a, b)
     a = fsarray([blue('abc'), red('def')])
     b = fsarray([blue('abc'), red('d') + blue('e') + red('f')])
     self.assertRaises(AssertionError, self.assertFSArraysEqual, a, b)
     a = fsarray(['abc', 'def'])
     b = fsarray(['abc', 'def'])
     self.assertFSArraysEqual(a, b)
     a = fsarray([blue('abc'), red('def')])
     b = fsarray([blue('abc'), red('def')])
     self.assertFSArraysEqual(a, b)
Exemplo n.º 20
0
 def test_diff_testing(self):
     a = fsarray(["abc", "def"])
     b = fsarray(["abc", "dqf"])
     self.assertRaises(AssertionError, self.assertFSArraysEqual, a, b)
     a = fsarray([blue("abc"), red("def")])
     b = fsarray([blue("abc"), red("dqf")])
     self.assertRaises(AssertionError, self.assertFSArraysEqual, a, b)
     a = fsarray([blue("abc"), red("def")])
     b = fsarray([blue("abc"), red("d") + blue("e") + red("f")])
     self.assertRaises(AssertionError, self.assertFSArraysEqual, a, b)
     a = fsarray(["abc", "def"])
     b = fsarray(["abc", "def"])
     self.assertFSArraysEqual(a, b)
     a = fsarray([blue("abc"), red("def")])
     b = fsarray([blue("abc"), red("def")])
     self.assertFSArraysEqual(a, b)
Exemplo n.º 21
0
def main(host, port):
    client = socket.socket()
    client.connect((host, port))
    client.setblocking(False)

    conn = Connection(client)
    keypresses = []

    with FullscreenWindow() as window:
        with Input() as input_generator:
            while True:
                a = FSArray(10, 80)
                in_text = ''.join(keypresses)[:80]
                a[9:10, 0:len(in_text)] = [red(in_text)]
                for i, line in zip(reversed(range(2, 7)),
                                   reversed(conn.render())):
                    a[i:i + 1, 0:len(line)] = [line]
                text = 'connected to %s:%d' % (host if len(host) < 50 else
                                               host[:50] + '...', port)
                a[0:1, 0:len(text)] = [blue(text)]

                window.render_to_terminal(a)
                ready_to_read, _, _ = select.select([conn, input_generator],
                                                    [], [])
                for r in ready_to_read:
                    if r is conn:
                        r.on_read()
                    else:
                        e = input_generator.send(0)
                        if e == '<ESC>':
                            return
                        elif e == '<Ctrl-j>':
                            keypresses.append('\n')
                            client.send(
                                (''.join(keypresses)).encode('latin-1'))
                            keypresses = []
                        elif e == '<SPACE>':
                            keypresses.append(' ')
                        elif e in ('<DELETE>', '<BACKSPACE>'):
                            keypresses = keypresses[:-1]
                        elif e is not None:
                            keypresses.append(e)
Exemplo n.º 22
0
def action_based_on_percent(game):
    """Prints feedback for user based on performance (percent correct)."""

    you_suck_message = [
        "Keep trying! You'll get it!",
        "Come on, human.",
        "Try harder?"
        ]
    you_rock_message = [
        "WAY TO GO!",
        "You're doing awesomely! Are you *sure* you weren't on Quiz Bowl in highschool?",
        "WELL DONE!",
        "Rockin' this!"
        ]

    percent = game.compute_percent_correct()
    if percent <= 30:
        fancy_print(random.choice(you_suck_message))
    if percent >= 60:
        fancy_print(blue(random.choice(you_rock_message)))
Exemplo n.º 23
0
def main(host, port):
    client = socket.socket()
    client.connect((host, port))
    client.setblocking(False)

    conn = Connection(client)
    keypresses = []

    with FullscreenWindow() as window:
        with Input() as input_generator:
            while True:
                a = FSArray(10, 80)
                in_text = ''.join(keypresses)[:80]
                a[9:10, 0:len(in_text)] = [red(in_text)]
                for i, line in zip(reversed(range(2,7)), reversed(conn.render())):
                    a[i:i+1, 0:len(line)] = [line]
                text = 'connected to %s:%d' % (host if len(host) < 50 else host[:50]+'...', port)
                a[0:1, 0:len(text)] = [blue(text)]

                window.render_to_terminal(a)
                ready_to_read, _, _ = select.select([conn, input_generator], [], [])
                for r in ready_to_read:
                    if r is conn:
                        r.on_read()
                    else:
                        e = input_generator.send(0)
                        if e == '<ESC>':
                            return
                        elif e == '<RETURN>':
                            keypresses.append('\n')
                            client.send((''.join(keypresses)).encode('latin-1'))
                            keypresses = []
                        elif e == '<SPACE>':
                            keypresses.append(' ')
                        elif e == '<DELETE>':
                            keypresses = keypresses[:-1]
                        elif e is not None:
                            keypresses.append(e)
Exemplo n.º 24
0
 def handle_near_to_goal():
     if game.current_turn == game.turns_goal - game.turns_goal / 10 and game.current_turn > 1:
         print(blue("Almost to your rounds goal! Finallll pushhhh!"))
Exemplo n.º 25
0
import sys
import os

from curtsies.fmtfuncs import blue, red, bold, on_red

from curtsies.window import FullscreenWindow

import time

if __name__ == '__main__':

    print(blue('hey') + ' ' + red('there') + ' ' + red(bold('you')))
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 100

    with FullscreenWindow() as window:
        rows, columns = window.get_term_hw()
        t0 = time.time()
        for i in range(n):
            a = [blue(on_red('qwertyuiop'[i%10]*columns)) for _ in range(rows)]
            window.render_to_terminal(a)
        t1 = time.time()
        t2 = time.time()
        for i in range(n):
            a = [blue(on_red('q'[i%1]*columns)) for _ in range(rows)]
            window.render_to_terminal(a)
        t3 = time.time()
        t4 = time.time()
        a = [blue(on_red('q'*columns)) for _ in range(rows)]
        arrays = []
        for i in range(n):
            a[i // columns] = a[i // columns].setitem(i % columns, 'x')
Exemplo n.º 26
0
 def handle_encourage_to_goal():
     if game.current_turn == game.turns_goal / 10 or game.current_turn == game.turns_goal / 5:
         print(blue("You're doing a great job, keep going!"))
Exemplo n.º 27
0
 def test_slice(self):
     self.assertEqual(fmtstr('Hi!', 'blue')[1:2], fmtstr('i', 'blue'))
     self.assertEqual(fmtstr('Hi!', 'blue')[1:], fmtstr('i!', 'blue'))
     s = fmtstr('imp') + ' '
     self.assertEqual(s[1:], fmtstr('mp') + ' ')
     self.assertEqual(blue('a\nb')[0:1], blue('a'))
Exemplo n.º 28
0
 def draw_screen(self, draw_type='default', quick_help=None):
     if quick_help is None:
         quick_help = 'Help: (r)otate shutit sessions | re(d)raw screen | (1,2,3,4) zoom pane in/out | (q)uit'
     assert draw_type in ('default', 'clearscreen', 'zoomed1', 'zoomed2',
                          'zoomed3', 'zoomed4')
     # Header
     header_text = u'  <= Shutit'
     self.screen_arr = curtsies.FSArray(self.wheight, self.wwidth)
     self.screen_arr[0:1, 0:len(header_text)] = [blue(header_text)]
     # Footer
     space = (self.wwidth - len(quick_help)) * ' '
     footer_text = space + quick_help
     if not self.shutit_global.ispy3:
         footer_text = footer_text.decode('utf-8')
     self.screen_arr[self.wheight - 1:self.wheight,
                     0:len(footer_text)] = [invert(blue(footer_text))]
     if draw_type in ('default', 'zoomed3', 'zoomed4'):
         # get sessions - for each ShutIt object in shutit_global
         sessions = list(get_shutit_pexpect_sessions())
         # reverse sessions as we're more likely to be interested in later ones.
         sessions.reverse()
         # Update the lower_pane_rotate_count so that it doesn't exceed the length of sessions.
         self.shutit_global.lower_pane_rotate_count = self.shutit_global.lower_pane_rotate_count % len(
             sessions)
         sessions = sessions[
             -self.shutit_global.
             lower_pane_rotate_count:] + sessions[:-self.shutit_global.
                                                  lower_pane_rotate_count]
     # Truncate logstream if it gets too big.
     if self.shutit_global.logstream.getvalue(
     ) > self.shutit_global.logstream_size:
         self.shutit_global.logstream.truncate(
             self.shutit_global.logstream_size)
     if draw_type == 'default':
         # Draw the sessions.
         self.do_layout_default()
         logstream_lines = []
         logstream_string_lines_list = self.shutit_global.logstream.getvalue(
         ).split('\n')
         for line in logstream_string_lines_list:
             logstream_lines.append(
                 SessionPaneLine(line, time.time(), 'log'))
         self.write_out_lines_to_fit_pane(self.top_left_session_pane,
                                          logstream_lines, u'Logs')
         self.write_out_lines_to_fit_pane(
             self.top_right_session_pane,
             self.shutit_global.stacktrace_lines_arr, u'Code Context')
         # Count two sessions
         count = 0
         for shutit_pexpect_session in sessions:
             count += 1
             if count == 2:
                 self.write_out_lines_to_fit_pane(
                     self.bottom_left_session_pane,
                     shutit_pexpect_session.session_output_lines,
                     u'Shutit Session: ' +
                     str(shutit_pexpect_session.pexpect_session_number) +
                     '/' + str(len(sessions)))
             elif count == 1:
                 self.write_out_lines_to_fit_pane(
                     self.bottom_right_session_pane,
                     shutit_pexpect_session.session_output_lines,
                     u'ShutIt Session: ' +
                     str(shutit_pexpect_session.pexpect_session_number) +
                     '/' + str(len(sessions)))
             else:
                 break
     elif draw_type == 'zoomed1':
         self.do_layout_zoomed(zoom_number=1)
         logstream_lines = []
         logstream_string_lines_list = self.shutit_global.logstream.getvalue(
         ).split('\n')
         for line in logstream_string_lines_list:
             logstream_lines.append(
                 SessionPaneLine(line, time.time(), 'log'))
         self.write_out_lines_to_fit_pane(self.top_left_session_pane,
                                          logstream_lines, u'Logs')
     elif draw_type == 'zoomed2':
         self.do_layout_zoomed(zoom_number=2)
         self.write_out_lines_to_fit_pane(
             self.top_left_session_pane,
             self.shutit_global.stacktrace_lines_arr, u'Code Context')
     elif draw_type == 'zoomed3':
         self.do_layout_zoomed(zoom_number=3)
         # Get first session
         count = 0
         for shutit_pexpect_session in sessions:
             count += 1
             if count == 2:
                 self.write_out_lines_to_fit_pane(
                     self.top_left_session_pane,
                     shutit_pexpect_session.session_output_lines,
                     u'Shutit Session: ' +
                     str(shutit_pexpect_session.pexpect_session_number) +
                     '/' + str(len(sessions)))
             elif count > 2:
                 break
     elif draw_type == 'zoomed4':
         self.do_layout_zoomed(zoom_number=4)
         # Get second session
         for shutit_pexpect_session in sessions:
             self.write_out_lines_to_fit_pane(
                 self.top_left_session_pane,
                 shutit_pexpect_session.session_output_lines,
                 u'ShutIt Session: ' +
                 str(shutit_pexpect_session.pexpect_session_number) + '/' +
                 str(len(sessions)))
             break
     elif draw_type == 'clearscreen':
         for y in range(0, self.wheight):
             line = u' ' * self.wwidth
             self.screen_arr[y:y + 1, 0:len(line)] = [line]
     else:
         assert False, 'Layout not handled: ' + draw_type
     if self.do_render:
         self.window.render_to_terminal(self.screen_arr, cursor_pos=(0, 0))
Exemplo n.º 29
0
 def test_linessplit(self):
     text = blue('the sum of the squares of the sideways')
     result = [
         blue('the') + blue(' ') + blue('sum'),
         blue('of') + blue(' ') + blue('the'),
         blue('squares'),
         blue('of') + blue(' ') + blue('the'),
         blue('sideway'),
         blue('s')
     ]
     self.assertEqual(linesplit(text, 7), result)
Exemplo n.º 30
0
 def test_split_with_spaces(self):
     self.assertEqual(blue('a\nb').split(), [blue('a'), blue('b')])
     self.assertEqual(blue('a   \t\n\nb').split(), [blue('a'), blue('b')])
     self.assertEqual(
         blue('hello   \t\n\nthere').split(),
         [blue('hello'), blue('there')])
Exemplo n.º 31
0
	def draw_screen(self, draw_type='default', quick_help=None):
		if quick_help is None:
			quick_help = 'Help: (r)otate shutit sessions | re(d)raw screen | (1,2,3,4) zoom pane in/out | (q)uit'
		assert draw_type in ('default','clearscreen','zoomed1','zoomed2','zoomed3','zoomed4')
		# Header
		header_text = u'  <= Shutit'
		self.screen_arr           = curtsies.FSArray(self.wheight, self.wwidth)
		self.screen_arr[0:1,0:len(header_text)] = [blue(header_text)]
		# Footer
		space = (self.wwidth - len(quick_help))*' '
		footer_text = space + quick_help
		if not self.shutit_global.ispy3:
			footer_text = footer_text.decode('utf-8')
		self.screen_arr[self.wheight-1:self.wheight,0:len(footer_text)] = [invert(blue(footer_text))]
		if draw_type in ('default','zoomed3','zoomed4'):
			# get sessions - for each ShutIt object in shutit_global
			sessions = list(get_shutit_pexpect_sessions())
			# reverse sessions as we're more likely to be interested in later ones.
			sessions.reverse()
			# Update the lower_pane_rotate_count so that it doesn't exceed the length of sessions.
			self.shutit_global.lower_pane_rotate_count = self.shutit_global.lower_pane_rotate_count % len(sessions)
			sessions = sessions[-self.shutit_global.lower_pane_rotate_count:] + sessions[:-self.shutit_global.lower_pane_rotate_count]
		# Truncate logstream if it gets too big.
		if self.shutit_global.logstream.getvalue() > self.shutit_global.logstream_size:
			self.shutit_global.logstream.truncate(self.shutit_global.logstream_size)
		if draw_type == 'default':
			# Draw the sessions.
			self.do_layout_default()
			logstream_lines = []
			logstream_string_lines_list = self.shutit_global.logstream.getvalue().split('\n')
			for line in logstream_string_lines_list:
				logstream_lines.append(SessionPaneLine(line,time.time(),'log'))
			self.write_out_lines_to_fit_pane(self.top_left_session_pane, logstream_lines, u'Logs')
			self.write_out_lines_to_fit_pane(self.top_right_session_pane, self.shutit_global.stacktrace_lines_arr, u'Code Context')
			# Count two sessions
			count = 0
			for shutit_pexpect_session in sessions:
				count += 1
				if count == 2:
					self.write_out_lines_to_fit_pane(self.bottom_left_session_pane,
					                                 shutit_pexpect_session.session_output_lines,
					                                 u'Shutit Session: ' + str(shutit_pexpect_session.pexpect_session_number) + '/' + str(len(sessions)))
				elif count == 1:
					self.write_out_lines_to_fit_pane(self.bottom_right_session_pane,
					                                 shutit_pexpect_session.session_output_lines,
					                                 u'ShutIt Session: ' + str(shutit_pexpect_session.pexpect_session_number) + '/' + str(len(sessions)))
				else:
					break
		elif draw_type == 'zoomed1':
			self.do_layout_zoomed(zoom_number=1)
			logstream_lines = []
			logstream_string_lines_list = self.shutit_global.logstream.getvalue().split('\n')
			for line in logstream_string_lines_list:
				logstream_lines.append(SessionPaneLine(line,time.time(),'log'))
			self.write_out_lines_to_fit_pane(self.top_left_session_pane, logstream_lines, u'Logs')
		elif draw_type == 'zoomed2':
			self.do_layout_zoomed(zoom_number=2)
			self.write_out_lines_to_fit_pane(self.top_left_session_pane, self.shutit_global.stacktrace_lines_arr, u'Code Context')
		elif draw_type == 'zoomed3':
			self.do_layout_zoomed(zoom_number=3)
			# Get first session
			count = 0
			for shutit_pexpect_session in sessions:
				count += 1
				if count == 2:
					self.write_out_lines_to_fit_pane(self.top_left_session_pane,
					                                 shutit_pexpect_session.session_output_lines,
					                                 u'Shutit Session: ' + str(shutit_pexpect_session.pexpect_session_number) + '/' + str(len(sessions)))
				elif count > 2:
					break
		elif draw_type == 'zoomed4':
			self.do_layout_zoomed(zoom_number=4)
			# Get second session
			for shutit_pexpect_session in sessions:
				self.write_out_lines_to_fit_pane(self.top_left_session_pane,
					                                 shutit_pexpect_session.session_output_lines,
					                                 u'ShutIt Session: ' + str(shutit_pexpect_session.pexpect_session_number) + '/' + str(len(sessions)))
				break
		elif draw_type == 'clearscreen':
			for y in range(0,self.wheight):
				line = u' '*self.wwidth
				self.screen_arr[y:y+1,0:len(line)] = [line]
		else:
			assert False, 'Layout not handled: ' + draw_type
		if self.do_render:
			self.window.render_to_terminal(self.screen_arr, cursor_pos=(0,0))
Exemplo n.º 32
0
 def test_linessplit(self):
     text = blue("the sum of the squares of the sideways")
     result = [
         blue("the") + blue(" ") + blue("sum"),
         blue("of") + blue(" ") + blue("the"),
         blue("squares"),
         blue("of") + blue(" ") + blue("the"),
         blue("sideway"),
         blue("s"),
     ]
     self.assertEqual(linesplit(text, 7), result)
Exemplo n.º 33
0
 def test_fg(self):
     red("asdf")
     blue("asdf")
     self.assertTrue(True)
Exemplo n.º 34
0
 def test_slice(self):
     self.assertEqual(fmtstr("Hi!", "blue")[1:2], fmtstr("i", "blue"))
     self.assertEqual(fmtstr("Hi!", "blue")[1:], fmtstr("i!", "blue"))
     s = fmtstr("imp") + " "
     self.assertEqual(s[1:], fmtstr("mp") + " ")
     self.assertEqual(blue("a\nb")[0:1], blue("a"))
Exemplo n.º 35
0
import sys

from curtsies.fmtfuncs import blue, red, bold, on_red

from curtsies.window import Window
from curtsies.terminal import Terminal

if __name__ == '__main__':

    print(blue('hey') + ' ' + red('there') + ' ' + red(bold('you')))

    with Terminal(sys.stdin, sys.stdout) as tc:
        with Window(tc) as t:
            rows, columns = t.tc.get_screen_size()
            while True:
                c = t.tc.get_event()
                if c == "":
                    sys.exit() # same as raise SystemExit()
                elif c == "a":
                    a = [blue(on_red(c*columns)) for _ in range(rows)]
                elif c == "b":
                    a = t.array_from_text("a small array")
                else:
                    a = t.array_from_text("try a, b, or ctrl-D")
                t.render_to_terminal(a)


Exemplo n.º 36
0
 def test_change_color(self):
     a = blue(red('hello'))
     self.assertEqual(a, blue('hello'))
Exemplo n.º 37
0
 def test_fg(self):
     red('asdf')
     blue('asdf')
     self.assertTrue(True)
Exemplo n.º 38
0
import sys
import os

from curtsies.fmtfuncs import blue, red, bold, on_red

from curtsies.window import FullscreenWindow

import time

if __name__ == '__main__':

    print(blue('hey') + ' ' + red('there') + ' ' + red(bold('you')))
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 100

    with FullscreenWindow() as window:
        rows, columns = window.get_term_hw()
        t0 = time.time()
        for i in range(n):
            a = [
                blue(on_red('qwertyuiop'[i % 10] * columns))
                for _ in range(rows)
            ]
            window.render_to_terminal(a)
        t1 = time.time()
        t2 = time.time()
        for i in range(n):
            a = [blue(on_red('q'[i % 1] * columns)) for _ in range(rows)]
            window.render_to_terminal(a)
        t3 = time.time()
        t4 = time.time()
        a = [blue(on_red('q' * columns)) for _ in range(rows)]