コード例 #1
0
ファイル: tests.py プロジェクト: jtruscott/ld27
 def setUp(self):
     if self.force_backend:
         term.init(backends=[self.force_backend], width=self.width, height=self.height)
     else:
         term.init(width=self.width, height=self.height)
     term.clear()
     term.set_title(self._testMethodName)
コード例 #2
0
def navigate_stacktrace(stacktrace, cache):
    cur_ref = 0
    refs = stacktrace.refs

    while True:
        ref = refs[cur_ref]
        clear()

        content = cache[ref.filename]
        display_ref_info(ref)
        display_line_context(content, ref.line_number)
        display_refs(refs, cur_ref)

        try:
            question = '[Next n] [Previous p] [Edit e] ? '
            c = input_one_char(question)
            if c == 'p' or c == 'UP':
                direction = 1
            elif c == 'n' or c == 'DOWN':
                direction = -1
            elif c == 'e':
                sp.call('vi %s +%s' % (filename, line_number), shell=True)
            elif c == 'LEFT':
                return
            else:
                direction = 0
            cur_ref = min(max(cur_ref - direction, 0), len(refs) - 1)

        except SyntaxError:
            pass
コード例 #3
0
ファイル: tests.py プロジェクト: jtruscott/ld27
 def setUp(self):
     if self.force_backend:
         term.init(backends=[self.force_backend],
                   width=self.width,
                   height=self.height)
     else:
         term.init(width=self.width, height=self.height)
     term.clear()
     term.set_title(self._testMethodName)
コード例 #4
0
ファイル: user.py プロジェクト: wi-cuckoo/IOT-Programming
	def __help(self):
		help_doc = '''So far, we just need to control the led on or off. Here are four operations:on, off, quit, and check.
on(*arg): you can turn on one or more led lights simultaneously. eg, on id1 id2 id3 ...
off(*arg): this method for turning off one or more lights. eg, off id1 id2 id3 ...
check(): for getting the status of all the lights in room. eg, check
quit(): to quit the interface and end the application, eg, quit
'''	
		term.clear()
		term.writeLine(help_doc, term.cyan, term.blink)
コード例 #5
0
def DEBUG_WIN(N,movements):
    clear()
    DEBUG_BOARD = [['' for i in xrange(N)] for i in xrange(N)]
    i = 0
    for mov in movements:
        i += 1
        DEBUG_BOARD[mov[1]-1][mov[0]-1] = i
    printBoard(DEBUG_BOARD,len(movements),"WIN")
    sleep(WIN_PAUSE)
コード例 #6
0
def DEBUG_MOVEMENT(N,movements):
    clear()
    DEBUG_BOARD = [['' for i in xrange(N)] for i in xrange(N)]
    i = 0
    for mov in movements:
        i += 1
        DEBUG_BOARD[mov[1]-1][mov[0]-1] = i
    printBoard(DEBUG_BOARD,i)
    sleep(DEBUG_SPEED)
コード例 #7
0
ファイル: Zydra.py プロジェクト: xavieryang007/Zydra
 def banner(self):
     term.clear()
     term.pos(1, 1)
     banner = pyfiglet.figlet_format("ZYDRA", font="epic").replace(
         "\n", "\n\t\t", 7)
     cprint("\r\n\t" + "@" * 61, "blue", end="")
     cprint("\n\t\t" + banner + "\t\tAuthor : Hamed Hosseini",
            "blue",
            attrs=['bold'])
     cprint("\t" + "@" * 61 + "\n", "blue")
コード例 #8
0
ファイル: quill.py プロジェクト: BluCodeGH/quill
def main():
    logging.info("Starting quill.")
    term.color(0, 7)
    term.clear()
    term.color(7, 0)
    T = Tab((0, 0), term.size, True)
    k = term.getkey()
    while k != "^C":
        T.handle(k)
        k = term.getkey()
    logging.info("Exiting.")
コード例 #9
0
def main():
    global client, shell

    term.clear()
    msgWarning("Loading configuration...")

    # Load the configuration from files (to-do: replace with proper configuration file)

    try:
        hostFile = open('spacecore-cli.uri', 'r')
        uri = hostFile.read()
        hostFile.close()
    except:
        halt("Configuration error", "Could read uri file.")

    try:
        pwFile = open('spacecore-cli.pw', 'r')
        password = pwFile.read()
        pwFile.close()
    except:
        halt("Configuration error", "Could read password file.")

    msgWarning("Connecting to server ({})...".format(uri))

    client = RpcClient(uri)

    waitForConnection()

    if not client.createSession():
        halt("Communication error", "Could not start the session!")

    if not client.login("barsystem", password):
        halt("Communication error", "Could not authenticate!")

    msgWarning("Connecting to printer...")

    global printer
    try:
        printer = ReceiptPrinter("/dev/ttyUSB0")
    except:
        printer = None
        msgWarning("Printer not available!")

    msgWarning("Welcome!")

    initCompletion()
    shell = Shell()
    setPrompt()
    shell.do_clear("")
    shell.cmdloop()
コード例 #10
0
    def banner(self):
        term.clear()
        term.pos(1, 1)
        # check if font "epic" exists on this system
        # sudo wget http://www.figlet.org/fonts/epic.flf -O /usr/share/figlet/epic.flf
        bannerfont = "epic" if os.path.exists(
            '/usr/share/figlet/epic.flf') else "banner"
        banner = pyfiglet.figlet_format("ZYDRA", font=bannerfont).replace(
            "\n", "\n\t\t", 7)

        cprint("\r\n\t" + "@" * 61, "blue", end="")
        cprint("\n\t\t" + banner + "\t\tAuthor : Hamed Hosseini",
               "blue",
               attrs=['bold'])
        cprint("\t" + "@" * 61 + "\n", "blue")
コード例 #11
0
ファイル: utils.py プロジェクト: havocesp/clitopia
class BeautyCLI(Cursor):

    def __init__(self, clear=True):
        if clear:
            tm.sleep(.25)
            self.cls()


    cls = lambda self: trm.clear()
    cls_ln = lambda self: trm.clearLine()
    fmt = lambda self, *args, **kwargs: trm.format(*args, **kwargs)
    wrt = lambda self, *args, **kwargs: trm.write(*args, **kwargs)
    wln = lambda self, *args, **kwargs: trm.writeLine(*args, **kwargs)
    right = lambda self, t: trm.right(t)
    center = lambda self, t: trm.center(t)


    def echo(self, text, row=None, col=None, align='left', *args):
        formated_text = text

        if align in 'right':
            formated_text = self.right(formated_text)
        elif align in 'center':
            formated_text = self.center(formated_text)

        if row is not None and col is not None:
            self.pos(row, col)
        elif row is not None and row is None:
            self.pos(row, 1)
        elif col is not None and row is None:
            self.pos(1, col)

        self.wln(formated_text, *args)
コード例 #12
0
ファイル: ui.py プロジェクト: FREEproject-OSS/FREEproject-OS
def screen(title, closeButton=True, clear=True):
    if clear: term.clear(bg=probgbg, fg=probgfg)

    term.goto(0, 0)
    term.echo(term.colour(" " * 79, bg=proscbg, fg=proscfg))
    term.goto(0, 0)
    term.echo(term.colour(" " * 5, bg=prosccb, fg=proscfg))
    term.goto(0, 0)
    term.echo(
        term.colour(time.strftime("%H:%M", time.localtime()),
                    bg=prosccb,
                    fg=proscfg))
    term.goto(6, 0)
    term.echo(term.colour(title, bg=proscbg, fg=proscfg))

    if closeButton:
        term.goto(80, 0)
        term.echo(term.colour("X", bg=proscxb, fg=proscfg))
コード例 #13
0
def volume(min_vol=1000.0, limit=20, exchange='BTC'):
    """
    Show an desc volume sorted symbol list for 1 minute time-frame (useful to detect rising markets)

    :param float min_vol: volume filter cutoff value (default 1000.0 BTC)
    :param int limit: limit markets list
    :param str exchange: exchange used (default BTC)
    """

    tickers = api.get_tickers(market=exchange).query(
        'quoteVolume > {}'.format(min_vol))
    tickers = tickers.sort_values('quoteVolume', ascending=False).T
    if len(tickers) > limit:
        tickers = tickers[:limit]
    table_data = list()

    tf = '1m'

    for num, ts in enumerate(tickers.keys()):
        if num == 0: trm.clear()

        trm.pos(1, 1), trm.clearLine()
        echo('({:d}/{:d}) Loading {} ...\n'.format(num + 1,
                                                   len(tickers.columns), ts))
        ohlc = api.get_ohlc(ts, timeframe=tf)  # type: pd.DataFrame

        ohlc['qvolume'] = ohlc['close'] * ohlc['volume']

        if (ohlc['qvolume'] > min_vol)[-3:].all():
            continue
        tickers[ts]['ohlc'] = ohlc
        last = '{:9.8f}'.format(tickers[ts]['last'])

        table_data.append([
            ts, tickers[ts]['ohlc']['qvolume'][-1],
            tickers[ts]['ohlc']['qvolume'][-2], last
        ])

    print(
        tabulate(table_data,
                 headers=VOLUME_HEADERS,
                 numalign='right',
                 floatfmt='.3f'))  # disable_numparse=[3]))
コード例 #14
0
 def emptyline(self):
     waitForConnection()
     #term.clear()
     print("")
     if (len(cart) == 0):
         term.clear()
         headerConfirm("")
         headerConfirm(
             "  The cart is empty. Scan a product to add it to the cart!")
         headerConfirm("")
         print("")
     else:
         term.clear()
         headerWarning("")
         headerWarning(
             "  The cart contains products. Enter your name to confirm the transaction!"
         )
         headerWarning("")
         print("")
     usage()
コード例 #15
0
 def send_message(self, pressed=True):
     """Blocking call. Prompt for a message via serial input, send the message to MQTT server"""
     if pressed:
         if self.client.is_conn_issue():
             self.client.reconnect()
         term.clear()
         self.clear()
         topic = "{}/{}".format(self.channel, NICKNAME)
         display.drawText(0, 8, "transmitting...", 0xFFFFFF, "7x5")
         display.flush()
         # prompt is a blocking call, waits here for the message
         message = term.prompt("message:", 0, 1)
         if len(message) > 0:
             self.client.publish(topic, message)
             self.client.send_queue()
             print("\nmessage sent")
             display.drawText(0, 16, "message sent", 0xFFFFFF, "7x5")
         # wait and clear
         utime.sleep_ms(500)
         self.clear()
コード例 #16
0
    for move in allMovements:
        if isOutsideOfTheBoard(move(pos)):
            continue
        if movementIsRepeated(move(pos), movements):
            continue
        bt = backtrack(move(pos), movements)
        if bt:
            if DEBUG: DEBUG_WIN(N,movements)
            return movements
        else:
            del movements[-1]

movements = backtrack(startingPosition, [])
if not movements:
    clear()
    print "No se encontró una solución"
    exit()

# print step-to-step board
board = [['' for i in xrange(N)] for i in xrange(N)]

i = 1
for mov in movements:
    board[mov[0]-1][mov[1]-1] = i
    printBoard(board,i,"BAD")
    i += 1
    sleep(0.03)
    clear()

printBoard(board,i,"OK")
コード例 #17
0
 def do_clear(self, arg):
     if not arg == "":
         print("Usage: clear")
         return
     term.clear()
     self.emptyline()
コード例 #18
0
 def drop_to_shell(self):
     self.menu = False
     term.clear()
     import shell
コード例 #19
0
ファイル: tests.py プロジェクト: jtruscott/ld27
 def test_clear(self):
     term.clear()
     self.check(0, 0, SPACE, colors.BLACK, colors.BLACK)
     self.check(self.width-1, self.height-1, SPACE, colors.BLACK, colors.BLACK)
コード例 #20
0
def paint(paint_map):
    term.clear()
    for pos, value in paint_map.items():
        term.pos(pos[0] + 20, pos[1] + 20)
        term.write('#' if value == 1 else ' ')
コード例 #21
0
def loginBack():
    term.clear(bg=ui.prolibg, fg=ui.prolifg)

    term.goto(0, 0)
    term.echo(
        time.strftime("%H:%M ", time.localtime()) +
        term.colour(time.strftime("%A %d %B %Y", time.localtime()),
                    bg=ui.prolibg,
                    fg="lgrey"))

    term.goto(5, 5)
    term.echo("   " + term.colour("          ", bg="lblue").replace(
        "*",
        term.colour(" ", bg="black") +
        term.colour("", bg="lblue", revert=False)))
    term.goto(5, 6)
    term.echo(" " + term.colour("   ***        ", bg="lblue").replace(
        "*",
        term.colour(" ", bg="black") +
        term.colour("", bg="lblue", revert=False)))
    term.goto(5, 7)
    term.echo(" " + term.colour("   ***  ***   ", bg="lblue").replace(
        "*",
        term.colour(" ", bg="black") +
        term.colour("", bg="lblue", revert=False)))
    term.goto(5, 8)
    term.echo(
        term.colour("    *    *  *   ", bg="lblue").replace(
            "*",
            term.colour(" ", bg="black") +
            term.colour("", bg="lblue", revert=False)))
    term.goto(5, 9)
    term.echo(
        term.colour("    ***  *  *   ", bg="lblue").replace(
            "*",
            term.colour(" ", bg="black") +
            term.colour("", bg="lblue", revert=False)))
    term.goto(5, 10)
    term.echo(
        term.colour("    ***  ***    ", bg="lblue").replace(
            "*",
            term.colour(" ", bg="black") +
            term.colour("", bg="lblue", revert=False)))
    term.goto(5, 11)
    term.echo(" " + term.colour("   *    *     ", bg="lblue").replace(
        "*",
        term.colour(" ", bg="black") +
        term.colour("", bg="lblue", revert=False)))
    term.goto(5, 12)
    term.echo(" " + term.colour("        *     ", bg="lblue").replace(
        "*",
        term.colour(" ", bg="black") +
        term.colour("", bg="lblue", revert=False)))
    term.goto(5, 13)
    term.echo("   " + term.colour("          ", bg="lblue").replace(
        "*",
        term.colour(" ", bg="black") +
        term.colour("", bg="lblue", revert=False)))

    term.goto(23, 6)
    term.echo("*** **  *** *** **   **  *   *  *   ** *     *   **".replace(
        "*", term.colour(" ", bg="white")))
    term.goto(23, 7)
    term.echo("*** *** *** *** * * *   * *    * * *   *    * * *".replace(
        "*", term.colour(" ", bg="white")))
    term.goto(23, 8)
    term.echo("*   * * *   *   * * *   * *  * * * *   **   * *  *".replace(
        "*", term.colour(" ", bg="white")))
    term.goto(23, 9)
    term.echo("*** **  *** *** **  *   * *  * **  *   *    * *   *".replace(
        "*", term.colour(" ", bg="white")))
    term.goto(23, 10)
    term.echo("*** **  *   *   *   *   * *  * *   *   *    * *   *".replace(
        "*", term.colour(" ", bg="white")))
    term.goto(23, 11)
    term.echo("*   * * *** *** *   *    *  *   **  **  *    *  **".replace(
        "*", term.colour(" ", bg="white")))
コード例 #22
0
wLn = trm.writeLine
symbol = 'TRX/BTC'

while True:
    raw = api.get_trades(symbol, limit=100)

    trades = raw.query('amount != 1.0')
    sells = trades.loc[trades.side == "sell"]
    buys = trades.loc[trades.side == "buy"]
    num_sells = len(sells)
    num_buys = len(buys)
    if num_sells > num_buys:
        sells = sells[-num_buys:]
    else:
        buys = buys[-num_sells:]
    trm.clear(), trm.pos(1, 1)

    # print(buys.tail(3))
    sells_index = trades.side == "sell"
    datos_precios = (trades['price'] *
                     sells_index.apply(lambda x: -1.0 if x else 1.0)
                     )  # type: pd.Series
    datos_volumen = (trades['cost'] *
                     sells_index.apply(lambda x: -1.0 if x else 1.0)
                     )  # type: pd.Series

    buy_cost = pd.DataFrame(buys['cost'].values,
                            columns=['close'],
                            index=buys.index)
    buy_price = pd.DataFrame(sells['price'].values,
                             columns=['close'],
コード例 #23
0
    def run(self):
        """Enable multithreading to complete tasks"""

        global flag
        flag = True

        thread_get = threading.Thread(
            target=Manage("get").mamage_get)
        thread_cpu = threading.Thread(
            target=Manage("frames_cpu").mamage_put)
        thread_memory = threading.Thread(
            target=Manage("frames_memory").mamage_put)
        thread_swap = threading.Thread(
            target=Manage("frames_swap").mamage_put)
        thread_disk = threading.Thread(
            target=Manage("frames_disk").mamage_put)
        thread_diskio = threading.Thread(
            target=Manage("frames_diskio").mamage_put)
        thread_system = threading.Thread(
            target=Manage("frames_system").mamage_put)
        thread_network = threading.Thread(
            target=Manage("frames_network").mamage_put)
        thread_version = threading.Thread(
            target=Manage("frames_version").mamage_put)
        thread_process = threading.Thread(
            target=Manage("frames_process").mamage_put)

        thread_process.start()
        thread_cpu.start()
        thread_memory.start()
        thread_swap.start()
        thread_disk.start()
        thread_diskio.start()
        thread_network.start()
        thread_system.start()
        thread_version.start()
        thread_get.start()

        # Short execution framewor
        frames = Frames()
        time.sleep(1)
        term.clear()
        term.pos(1, 0)
        frames.header()
        term.pos(2, 0)
        time.sleep(3)

        # Judge the input and exit
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        tty.setraw(sys.stdin.fileno())
        quit = sys.stdin.read(1)
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        if len(quit) == 1:
            flag = False
            time.sleep(1)
            que.queue.clear()
            # Reduction of the cursor
            os.system("echo -e \033[?25h")
            term.pos(1, 0)
            term.clear()
コード例 #24
0
ファイル: tests.py プロジェクト: jtruscott/ld27
 def test_clear(self):
     term.clear()
     self.check(0, 0, SPACE, colors.BLACK, colors.BLACK)
     self.check(self.width - 1, self.height - 1, SPACE, colors.BLACK,
                colors.BLACK)
コード例 #25
0
ファイル: main.py プロジェクト: nmeyering/colorgrid
def game():
#	board = Board( block_char='\u2592')
	board = Board(
		size = config.board_size)

	instructions = '''
The goal is to flood-fill the whole board with the same color.
Your starting point is the upper left corner.
By successively filling in colors that are adjacent to your captured
area you expand your territory until every field is uniformly colored.

Good luck!

<press any key to continue>
'''

	menu = '\033[s\033[{}A'.format(
		board.size + 1)

	for c in range(board.max_colors):
		menu += '\033[{indent}C{idx}: {val}\n'.format(
			indent = 1 + 2 * board.size,
			idx = c,
			val = term.colored(term.colors[c], c))

	menu += '\n'
	menu += '\033[{indent}Cn: New Game\n'.format(
			indent = 1 + 2 * board.size)
	menu += '\033[{indent}Cq: Quit\n'.format(
			indent = 1 + 2 * board.size)
	menu += '\033[{indent}Ch: Help\n'.format(
			indent = 1 + 2 * board.size)
	menu += '\033[u'

	turnlimit = config.turnlimit
	turn = 0

	while turn < turnlimit:
		print(25*'\n')
		term.clear()
		print(board)
		print(menu)
		cmd = input('your move ({} turns left): '.format(
			turnlimit - turn))
		try:
			board.flood(int(cmd))
			turn += 1
		except AttributeError as e:
			print(e)
		except ValueError:
			if cmd == 'n':
				return True
			elif cmd == 'q':
				return False
			elif cmd == 'h':
				term.clear()
				print(instructions)
				input()
				term.clear()
		if board.uniform():
			print('Congratulations, you won!')
			break

	if turn == turnlimit:
		print('Too bad, you lost.')
	return not input('Play again? [Y/n] ').lower() == 'n'
コード例 #26
0
ファイル: __init__.py プロジェクト: havocesp/clitopia
cols = ['price', 'amount']

pd.options.display.precision = 8

exchange = 'BTC'
coin = 'ETN'

symbol = '{}/{}'.format(coin, exchange)

# book = api.fetch_order_book(symbol, limit=10)
#
# asks, bids = book['asks'], book['bids']
# df_asks = pd.DataFrame(asks, columns=cols)
# df_bids = pd.DataFrame(bids, columns=cols)

tm.sleep(.25), trm.clear(), trm.pos(1, 1)
api = cryptopia()
while True:
    try:
        sep = lambda: trm.writeLine(trm.center('-' * 80), trm.dim, trm.cyan)
        book = api.fetch_order_book(symbol, limit=5)

        asks, bids = book['asks'], book['bids']
        df_asks = pd.DataFrame(asks, columns=cols)
        df_bids = pd.DataFrame(bids, columns=cols)
        df_asks['amount'] = df_asks['amount'].apply(
            lambda v: '{: >16.2f}'.format(v))
        df_asks['price'] = df_asks['price'].apply(
            lambda v: '{: >16.8f}'.format(v))
        df_bids['amount'] = df_bids['amount'].apply(
            lambda v: '{: >16.2f}'.format(v))