示例#1
0
    def decode(self, formatters, byte_order='big', word_order='big'):
        """
        Decode the register response to known formatters.

        :param formatters: int8/16/32/64, uint8/16/32/64, float32/64
        :param byte_order: little/big
        :param word_order: little/big
        :return: Decoded Value
        """
        # Read Holding Registers (3)
        # Read Input Registers (4)
        # Read Write Registers (23)
        if not isinstance(formatters, (list, tuple)):
            formatters = [formatters]

        if self.function_code not in [3, 4, 23]:
            print_formatted_text(
                HTML("<red>Decoder works only for registers!!</red>"))
            return
        byte_order = (Endian.Little if byte_order.strip().lower() == "little"
                      else Endian.Big)
        word_order = (Endian.Little if word_order.strip().lower() == "little"
                      else Endian.Big)
        decoder = BinaryPayloadDecoder.fromRegisters(self.data.get('registers'),
                                                     byteorder=byte_order,
                                                     wordorder=word_order)
        for formatter in formatters:
            formatter = FORMATTERS.get(formatter)
            if not formatter:
                print_formatted_text(
                    HTML("<red>Invalid Formatter - {}"
                         "!!</red>".format(formatter)))
                return
            decoded = getattr(decoder, formatter)()
            self.print_result(decoded)
    def output_formatted(self, line, *args):
        """
Outputs the given HTML-formatted line. Additional positional arguments are
used for string formatting.

:param line: Output line

:since: v1.0.0
        """

        output = HTML(line.format(*args)
                      if (len(args) > 0) else
                      line
                     )

        print_formatted_text(output)
示例#3
0
    def print_result(self, data=None):
        """
        Prettu print result object.

        :param data: Data to be printed.
        :return:
        """
        data = data or self.data
        if isinstance(data, dict):
            data = self._process_dict(data)
        elif isinstance(data, (list, tuple)):
            data = [v.decode('utf-8') if isinstance(v, bytes) else v
                    for v in data]
        elif isinstance(data, bytes):
            data = data.decode('utf-8')
        tokens = list(pygments.lex(json.dumps(data, indent=4),
                                   lexer=JsonLexer()))
        print_formatted_text(PygmentsTokens(tokens))
示例#4
0
def printWithColor(text, color, before="", after="", more=False):
    s = before
    if color == "red":
        s +=  '<ansired>' + text + '</ansired>'
    elif color == "green":
        s +=  '<ansigreen>' + text + '</ansigreen>'
    elif color == "yellow":
        s +=  '<ansiyellow>' + text + '</ansiyellow>'
    elif color == "blue":
        s +=  '<ansiblue>' + text + '</ansiblue>'
    elif color == "magenta":
        s +=  '<ansimagenta>' + text + '</ansimagenta>'
    elif color == "cyan":
        s +=  '<ansicyan>' + text + '</ansicyan>'
    elif color == 'gray':
        s += '<ansigray>' + text + '</ansigray>'
    else:
        s +=  '<ansiwhite>' + text + '</ansiwhite>'
    s += after
    if more:
        return s
    print_formatted_text(HTML(s))
def main():
    # Printing a manually constructed list of (Token, text) tuples.
    text = [
        (Token.Keyword, 'print'),
        (Token.Punctuation, '('),
        (Token.Literal.String.Double, '"'),
        (Token.Literal.String.Double, 'hello'),
        (Token.Literal.String.Double, '"'),
        (Token.Punctuation, ')'),
        (Token.Text, '\n'),
    ]

    print_formatted_text(PygmentsTokens(text))

    # Printing the output of a pygments lexer.
    tokens = list(pygments.lex('print("Hello")', lexer=PythonLexer()))
    print_formatted_text(PygmentsTokens(tokens))

    # With a custom style.
    style = Style.from_dict({
        'pygments.keyword': 'underline',
        'pygments.literal.string': 'bg:#00ff00 #ffffff',
    })
    print_formatted_text(PygmentsTokens(tokens), style=style)
示例#6
0
def get_datasets(asset, currency, granularity, datapoints, df_train_size=0.75):
    """Fetch the API and precess the desired pair

    Arguments:
        asset {str} -- First pair
        currency {str} -- Second pair
        granularity {str ['day', 'hour']} -- Granularity
        datapoints {int [100 - 2000]} -- [description]

    Returns:
        pandas.Dataframe -- The OHLCV and indicators dataframe
    """
    df_train_path = 'datasets/bot_train_{}_{}_{}.csv'.format(
        asset + currency, datapoints, granularity)
    df_rollout_path = 'datasets/bot_rollout_{}_{}_{}.csv'.format(
        asset + currency, datapoints, granularity)
    asset_icon = '₿' if asset == 'BTC' else asset
    currency_icon = '₿' if currency == 'BTC' else currency
    if not os.path.exists(df_rollout_path):
        headers = {'User-Agent': 'Mozilla/5.0',
                   'authorization': 'Apikey 3d7d3e9e6006669ac00584978342451c95c3c78421268ff7aeef69995f9a09ce'}

        url = 'https://min-api.cryptocompare.com/data/histo{}?fsym={}&tsym={}&limit={}'.format(
            granularity, asset, currency, datapoints)
        with yaspin(text='Downloading datasets') as sp:

            response = requests.get(url, headers=headers)
            sp.hide()
            print_formatted_text(HTML(
                u'<b>></b> <msg>{}/{}(s)</msg> <sub-msg>download complete</sub-msg>'.format(
                    asset_icon, currency_icon)
            ), style=style)
            sp.show()

        json_response = response.json()
        status = json_response['Response']
        if status == "Error":
            print(colored('=== {} ==='.format(
                json_response['Message']), 'red'))
            raise AssertionError()
        result = json_response['Data']
        df = pd.DataFrame(result)
        # print(df.tail())
        df['Date'] = pd.to_datetime(df['time'], utc=True, unit='s')
        df.drop('time', axis=1, inplace=True)

        # indicators
        # https://github.com/mrjbq7/ta-lib/blob/master/docs/func.md
        open_price, high, low, close = np.array(df['open']), np.array(
            df['high']), np.array(df['low']), np.array(df['close'])
        volume = np.array(df['volumefrom'])
        # cycle indicators
        df.loc[:, 'HT_DCPERIOD'] = talib.HT_DCPERIOD(close)
        df.loc[:, 'HT_DCPHASE'] = talib.HT_DCPHASE(close)
        df.loc[:, 'HT_PHASOR_inphase'], df.loc[:,
                                               'HT_PHASOR_quadrature'] = talib.HT_PHASOR(close)
        df.loc[:, 'HT_SINE_sine'], df.loc[:,
                                          'HT_SINE_leadsine'] = talib.HT_SINE(close)
        df.loc[:, 'HT_TRENDMODE'] = talib.HT_TRENDMODE(close)
        # momemtum indicators
        df.loc[:, 'ADX'] = talib.ADX(high, low, close, timeperiod=12)
        df.loc[:, 'ADXR'] = talib.ADXR(high, low, close, timeperiod=13)
        df.loc[:, 'APO'] = talib.APO(
            close, fastperiod=5, slowperiod=10, matype=0)
        df.loc[:, 'AROON_down'], df.loc[:, 'AROON_up'] = talib.AROON(
            high, low, timeperiod=15)
        df.loc[:, 'AROONOSC'] = talib.AROONOSC(high, low, timeperiod=13)
        df.loc[:, 'BOP'] = talib.BOP(open_price, high, low, close)
        df.loc[:, 'CCI'] = talib.CCI(high, low, close, timeperiod=13)
        df.loc[:, 'CMO'] = talib.CMO(close, timeperiod=14)
        df.loc[:, 'DX'] = talib.DX(high, low, close, timeperiod=10)
        df['MACD'], df['MACD_signal'], df['MACD_hist'] = talib.MACD(
            close, fastperiod=5, slowperiod=10, signalperiod=20)
        df.loc[:, 'MFI'] = talib.MFI(high, low, close, volume, timeperiod=12)
        df.loc[:, 'MINUS_DI'] = talib.MINUS_DI(high, low, close, timeperiod=10)
        df.loc[:, 'MINUS_DM'] = talib.MINUS_DM(high, low, timeperiod=14)
        df.loc[:, 'MOM'] = talib.MOM(close, timeperiod=20)
        df.loc[:, 'PPO'] = talib.PPO(
            close, fastperiod=17, slowperiod=35, matype=2)
        df.loc[:, 'ROC'] = talib.ROC(close, timeperiod=12)
        df.loc[:, 'RSI'] = talib.RSI(close, timeperiod=25)
        df.loc[:, 'STOCH_k'], df.loc[:, 'STOCH_d'] = talib.STOCH(
            high, low, close, fastk_period=35, slowk_period=12, slowk_matype=0, slowd_period=7, slowd_matype=0)
        df.loc[:, 'STOCHF_k'], df.loc[:, 'STOCHF_d'] = talib.STOCHF(
            high, low, close, fastk_period=28, fastd_period=14, fastd_matype=0)
        df.loc[:, 'STOCHRSI_K'], df.loc[:, 'STOCHRSI_D'] = talib.STOCHRSI(
            close, timeperiod=35, fastk_period=12, fastd_period=10, fastd_matype=1)
        df.loc[:, 'TRIX'] = talib.TRIX(close, timeperiod=30)
        df.loc[:, 'ULTOSC'] = talib.ULTOSC(
            high, low, close, timeperiod1=14, timeperiod2=28, timeperiod3=35)
        df.loc[:, 'WILLR'] = talib.WILLR(high, low, close, timeperiod=35)
        # overlap studies
        df.loc[:, 'BBANDS_upper'], df.loc[:, 'BBANDS_middle'], df.loc[:, 'BBANDS_lower'] = talib.BBANDS(
            close, timeperiod=12, nbdevup=2, nbdevdn=2, matype=0)
        df.loc[:, 'DEMA'] = talib.DEMA(close, timeperiod=30)
        df.loc[:, 'EMA'] = talib.EMA(close, timeperiod=7)
        df.loc[:, 'HT_TRENDLINE'] = talib.HT_TRENDLINE(close)
        df.loc[:, 'KAMA'] = talib.KAMA(close, timeperiod=5)
        df.loc[:, 'MA'] = talib.MA(close, timeperiod=5, matype=0)
        df.loc[:, 'MIDPOINT'] = talib.MIDPOINT(close, timeperiod=20)
        df.loc[:, 'WMA'] = talib.WMA(close, timeperiod=15)
        df.loc[:, 'SMA'] = talib.SMA(close)
        # pattern recoginition
        df.loc[:, 'CDL2CROWS'] = talib.CDL2CROWS(open_price, high, low, close)
        df.loc[:, 'CDL3BLACKCROWS'] = talib.CDL3BLACKCROWS(
            open_price, high, low, close)
        df.loc[:, 'CDL3INSIDE'] = talib.CDL3INSIDE(
            open_price, high, low, close)
        df.loc[:, 'CDL3LINESTRIKE'] = talib.CDL3LINESTRIKE(
            open_price, high, low, close)
        # price transform
        df.loc[:, 'WCLPRICE'] = talib.WCLPRICE(high, low, close)
        # statistic funcitons
        df.loc[:, 'BETA'] = talib.BETA(high, low, timeperiod=20)
        df.loc[:, 'CORREL'] = talib.CORREL(high, low, timeperiod=20)
        df.loc[:, 'STDDEV'] = talib.STDDEV(close, timeperiod=20, nbdev=1)
        df.loc[:, 'TSF'] = talib.TSF(close, timeperiod=20)
        df.loc[:, 'VAR'] = talib.VAR(close, timeperiod=20, nbdev=1)
        # volatility indicators
        df.loc[:, 'ATR'] = talib.ATR(high, low, close, timeperiod=7)
        df.loc[:, 'NATR'] = talib.NATR(high, low, close, timeperiod=20)
        df.loc[:, 'TRANGE'] = talib.TRANGE(high, low, close)
        # volume indicators
        df.loc[:, 'AD'] = talib.AD(high, low, close, volume)
        df.loc[:, 'ADOSC'] = talib.ADOSC(
            high, low, close, volume, fastperiod=10, slowperiod=20)
        df.loc[:, 'OBV'] = talib.OBV(close, volume)

        # df.fillna(df.mean(), inplace=True)
        df.dropna(inplace=True)
        df.set_index('Date', inplace=True)
        # print(colored('> caching' + asset + '/' + currency + ':)', 'cyan'))
        # 75% to train -> test with different value
        train_size = round(len(df) * df_train_size)
        df_train = df[:train_size]
        df_rollout = df[train_size:]
        df_train.to_csv(df_train_path)
        df_rollout.to_csv(df_rollout_path)
        # re-read to avoid indexing issue w/ Ray
        df_train = pd.read_csv(df_train_path)
        df_rollout = pd.read_csv(df_rollout_path)
    else:

        print_formatted_text(HTML(
            u'<b>></b> <msg>{}/{}</msg> <sub-msg>cached</sub-msg>'.format(
                asset_icon, currency_icon)
        ), style=style)

        # print(colored('> feching ' + asset + '/' + currency + ' from cache :)', 'magenta'))
        df_train = pd.read_csv(df_train_path)
        df_rollout = pd.read_csv(df_rollout_path)
        # df_train.set_index('Date', inplace=True)
        # df_rollout.set_index('Date', inplace=True)

    return df_train, df_rollout
def print_formatted(*args, **kwargs):
    prompt_toolkit.print_formatted_text(*args, **kwargs)
示例#8
0
 def intro_message(self):
     print_formatted_text(HTML('<b>Starting prompt...</b>'))
示例#9
0
 def _print(self, text):
     tokens = list(pygments.lex(text, lexer=PythonLexer()))
     print_formatted_text(PygmentsTokens(tokens), end='')
示例#10
0
def fmt(text):
    s = io.StringIO()
    o = Vt100_Output(s, lambda : 80, write_binary=False)
    print_formatted_text(HTML(text), end='', output=o)
    return s.getvalue()
示例#11
0
 def get_nonce(self):
     print_formatted_text(self.safe.retrieve_nonce())
示例#12
0
 def print_startup_info(self):
     print_formatted_text(
         pyfiglet.figlet_format('Gnosis Safe CLI'))  # Print fancy text
     print_formatted_text(
         HTML(f'<b><ansigreen>Loading Safe information...</ansigreen></b>'))
     self.safe_operator.print_info()
示例#13
0
def __print_failure(result):
    if result.code != RESULT_OK:
        print_formatted_text('failed, code %d' % result.code)
        return True
    else:
        return False
示例#14
0
async def main(host: str, port: int):
    tlwbe = Tlwbe(host, port)

    print('waiting for connection to broker...')
    await tlwbe.wait_for_connection()

    session = PromptSession(completer=Completer(), lexer=Lexer())

    print_formatted_text(HTML("type <b>help</b> if you're confused... <b>ctrl-c</b> to quit"))

    while True:
        with patch_stdout():
            result: str = await session.prompt('tlwbe> ', async_=True)

            if result.startswith('help'):
                cmd_help()

            else:
                call = True

                matches = re.search(regex, result)
                if matches is not None:
                    obj = matches.group(1)
                    command = matches.group(3)
                    if command is None:
                        command = 'list'
                    raw_parameters = matches.group(4)
                    matches = re.finditer(parameter_regex, raw_parameters)
                    parameters = {}
                    for match in matches:
                        parameters[match.group(1)] = match.group(2)

                    # print('%s %s %s' % (obj, command, str(parameters)))

                    o = objects.get(obj)
                    c = o.commands.get(command)

                    if c is not None:
                        # work out if any required parameter are missing
                        if c.required_fields is not None:
                            missing_fields = c.required_fields.copy()
                            for f in parameters:
                                if f in missing_fields:
                                    missing_fields.remove(f)
                            if len(missing_fields) is not 0:
                                print_formatted_text("One or more required parameters are missing...")
                                for f in missing_fields:
                                    print_formatted_text(HTML('parameter <b>%s</b> is required' % f))
                                call = False

                        # work out if there are unclaimed parameters
                        claimed_parameters = {}
                        for pp in c.possible_fields:
                            if pp in parameters:
                                claimed_parameters[pp] = parameters.pop(pp)

                        if len(parameters) is not 0:
                            for p in parameters:
                                print_formatted_text(HTML('parameter <b>%s</b> isn\'t applicable here' % p))
                            call = False

                        if call:
                            try:
                                await c.func(tlwbe, claimed_parameters)
                            except asyncio.TimeoutError:
                                print_formatted_text('timeout :(')

                    else:
                        print_formatted_text(HTML('<b>%s</b> is not applicable to <b>%s</b>' % (command, obj)))
                else:
                    cmd_unknown()
示例#15
0
def cmd_help():
    print_formatted_text(HTML('<b>Usage:</b>'))
    print_formatted_text(HTML('OBJECT COMMAND [PARAMETERS]'))
    print_formatted_text('')

    print_formatted_text(HTML('<b>Object manipulation</b>'))
    for o in objects:
        for c in objects[o].commands:
            print_formatted_text(HTML('%s %s' % (o, c)), objects[o].commands[c].print_summary())
        print_formatted_text('')
示例#16
0
文件: cli.py 项目: zha0/chepy
def print_in_colors(out):
    style = Style.from_dict({"cli_out": "fg:{}".format(config.cli_info_color)})
    print_formatted_text(FormattedText([("class:cli_out", str(out))]),
                         style=style)
示例#17
0
from prompt_toolkit import print_formatted_text, HTML
from prompt_toolkit.styles import Style

print_formatted_text(HTML('<b>This is bold</b>'))
print_formatted_text(HTML('<i>This is italic</i>'))
print_formatted_text(HTML('<u>This is underlined</u>'))

# Colors from the ANSI palette.
print_formatted_text(HTML('<ansired>This is red</ansired>'))
print_formatted_text(HTML('<ansigreen>This is green</ansigreen>'))

# Named colors (256 color palette, or true color, depending on the output).
print_formatted_text(HTML('<skyblue>This is sky blue</skyblue>'))
print_formatted_text(HTML('<seagreen>This is sea green</seagreen>'))
print_formatted_text(HTML('<violet>This is violet</violet>'))

# Colors from the ANSI palette.
print_formatted_text(HTML('<aaa fg="ansiwhite" bg="ansigreen">White on green</aaa>'))

# style
style = Style.from_dict({
    'aaa': '#ff0066',
    'bbb': '#44ff00 italic',
})

print_formatted_text(HTML('<aaa>Hello</aaa> <bbb>world</bbb>!'), style=style)
示例#18
0
def exec_news_list(name, url):
    """加载rss url的信息"""
    rss_items_list = rss_items.select_list_by_channel_link(url)

    current_page = 1

    terminal_config.PROMPT_MESSAGE_BASE.append(('', name))
    terminal_config.PROMPT_MESSAGE_BASE.append(('class:path', '>'))

    def bottom_toolbar():
        return [
            ('class:bottom-toolbar', '[ b ]返回'),
            ('class:bottom-toolbar', '  [ r ]设置频道为已读'),
        ]

    while True:
        msg, has_more, total_page, rss_list = _get_list_by_page(
            rss_items_list, current_page, 20)

        print_formatted_text(FormattedText(msg), style=terminal_config.STYLE)

        num = -1

        try:
            if current_page < total_page:
                user_input = prompt(terminal_config.PROMPT_MESSAGE_BASE,
                                    style=terminal_config.STYLE,
                                    bottom_toolbar=bottom_toolbar_page(
                                        total_page, current_page))
            else:
                user_input = prompt(terminal_config.PROMPT_MESSAGE_BASE,
                                    style=terminal_config.STYLE,
                                    bottom_toolbar=bottom_toolbar)

            num = int(user_input)

        except KeyboardInterrupt:
            print('bye bye !!!')
            exit()
            break
        except EOFError:
            print('bye bye !!!')
            exit()
            break
        except ValueError:
            pass

        if user_input == 'b':
            terminal_config.PROMPT_MESSAGE_BASE = terminal_config.PROMPT_MESSAGE_BASE[
                0:-2]
            break

        elif user_input == 'n' and has_more is True:
            current_page += 1
            continue

        elif user_input == 'p' and current_page != 1:
            current_page -= 1
            continue

        elif user_input == 'r':
            rss_items.update_read_by_channel_link(url)
            print('已将频道[' + name + ' ] 全部文章标记为已读')
            continue

        elif 0 <= num < len(msg):
            exec_command_open_browse(rss_list[int(user_input)][8])
            continue
示例#19
0
def base_end():
    print_formatted_text(MD('*Bye!*'))
    print(
        'This product uses the TMDb API but is not endorsed or certified by TMDb.'
    )
示例#20
0
            input('Enter last 4 digits (Account number) : XXXX XXXX '))
        for account in self.__all_account:
            for data in account:
                if data == account_number:
                    print('\nTotal Credit & Debit: ',
                          account[data]['total_no_transactions:'])
                    print('\tTotal Credits: ', account[data]['credit_count:'])
                    print('\tTotal Debits: ', account[data]['debit_count:'])
                    print('\nTotal Transfers: ',
                          len(account[data]['transfer_history:']))
                    temp = account[data]['transfer_history:']
                    for history in temp:
                        print('\nTransaction Number: ', s_no)
                        print('\tFrom: ', history[0])
                        print('\tTo: ', history[1])
                        print('\tAmount: ', history[2])
                        print('\tBalance: ', history[3])
                        s_no += 1
                    s_no = 1
        else:
            self.__bank_operation()


card = ATM()
print_formatted_text(HTML('\n\t\t<aaa>Welcome</aaa> <bbb>User</bbb>!\n'),
                     style=style)
card._login()

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=80)
示例#21
0
def cli(client):

    kb = KeyBindings()

    @kb.add('c-space')
    def _(event):
        """Initialize autocompletion, or select the next completion. """
        buff = event.app.current_buffer
        if buff.complete_state:
            buff.complete_next()
        else:
            buff.start_completion(select_first=False)

    @kb.add('enter', filter=has_selected_completion)
    def _(event):
        """
        Makes the enter key work as the tab key only when showing the menu.
        """

        event.current_buffer.complete_state = None
        b = event.cli.current_buffer
        b.complete_state = None

    def _process_args(args, string=True):
        kwargs = {}
        execute = True
        skip_index = None
        for i, arg in enumerate(args):
            if i == skip_index:
                continue
            arg = arg.strip()
            if "=" in arg:
                a, val = arg.split("=")
                if not string:
                    if "," in val:
                        val = val.split(",")
                        val = [int(v) for v in val]
                    else:
                        val = int(val)
                kwargs[a] = val
            else:
                a, val = arg, args[i + 1]
                try:
                    if not string:
                        if "," in val:
                            val = val.split(",")
                            val = [int(v) for v in val]
                        else:
                            val = int(val)
                    kwargs[a] = val
                    skip_index = i + 1
                except TypeError:
                    click.secho("Error parsing arguments!", fg='yellow')
                    execute = False
                    break
                except ValueError:
                    click.secho("Error parsing argument", fg='yellow')
                    execute = False
                    break
        return kwargs, execute

    session = PromptSession(lexer=PygmentsLexer(PythonLexer),
                            completer=CmdCompleter(),
                            style=style,
                            complete_while_typing=True,
                            bottom_toolbar=bottom_toolbar,
                            key_bindings=kb,
                            history=FileHistory('.pymodhis'),
                            auto_suggest=AutoSuggestFromHistory())
    click.secho("{}".format(TITLE), fg='green')
    result = None
    while True:
        try:

            text = session.prompt('> ', complete_while_typing=True)
            if text.strip().lower() == 'help':
                print_formatted_text(HTML("<u>Available commands:</u>"))
                for cmd, obj in sorted(session.completer.commands.items()):
                    if cmd != 'help':
                        print_formatted_text(
                            HTML("<skyblue>{:45s}</skyblue>"
                                 "<seagreen>{:100s}"
                                 "</seagreen>".format(cmd, obj.help_text)))

                continue
            elif text.strip().lower() == 'exit':
                raise EOFError()
            elif text.strip().lower().startswith("client."):
                with client:
                    try:
                        text = text.strip().split()
                        cmd = text[0].split(".")[1]
                        args = text[1:]
                        kwargs, execute = _process_args(args, string=False)
                        if execute:
                            result = Result(getattr(client, cmd)(**kwargs))
                            result.print_result()
                    except Exception as e:
                        click.secho(repr(e), fg='red')
            elif text.strip().lower().startswith("result."):
                if result:
                    words = text.lower().split()
                    if words[0] == 'result.raw':
                        result.raw()
                    if words[0] == 'result.decode':
                        args = words[1:]
                        kwargs, execute = _process_args(args)
                        if execute:
                            result.decode(**kwargs)
        except KeyboardInterrupt:
            continue  # Control-C pressed. Try again.
        except EOFError:
            break  # Control-D pressed.
        except Exception as e:  # Handle all other exceptions
            click.secho(str(e), fg='red')

    click.secho('GoodBye!', fg='blue')
示例#22
0
 def get_owners(self):
     print_formatted_text(self.safe.retrieve_owners())
示例#23
0
def welcome_message():
    """Print the welcome message to terminal."""
    print_formatted_text()
    print_formatted_text(HTML('<ansired>Smallsource version 0.1</ansired>'))
    print_formatted_text()
    print_formatted_text(
        HTML('type <blue>quit</blue> or <blue>exit</blue> to exit'))
    print_formatted_text(HTML('type <blue>help</blue> for on-line help'))
    print_formatted_text(
        HTML('type <blue>info</blue> for the current configuration'))
    print_formatted_text(
        HTML('type <blue>version</blue> for information about the current ' +
             '<ansired>Smallsource</ansired> version'))
    print_formatted_text()
示例#24
0
# -*- coding: utf-8 -*-
import json

import requests

from prompt_toolkit.completion import WordCompleter
from prompt_toolkit import prompt
from prompt_toolkit.formatted_text import ANSI
from prompt_toolkit import print_formatted_text

kw = input('library keyword: ')
resp = requests.get('https://api.cdnjs.com/libraries?search={0}'.format(kw))
if resp.ok:
    data = json.loads(resp.text)
    if isinstance(data, dict) and 'results' in data:
        results = data['results']
        results = sorted(list(map(lambda item: item['name'], results)),
                         reverse=False)

        completer = WordCompleter(results, ignore_case=True, match_middle=True)
        selected = prompt('choose library: ',
                          completer=completer,
                          complete_while_typing=True)
        if selected in results:
            print('your choice is:', end=' ')
            print_formatted_text(ANSI('\x1b[91m{0}'.format(selected)))
        else:
            print('canceled')
示例#25
0
 def print(self, msg: str):
     print_formatted_text(HTML(msg), style=self.style)
示例#26
0
def print_processes_status(status, *args):
    kwargs = {}
    if args:
        kwargs["filter"] = args[0]
    for text in processes_status(status, **kwargs):
        print_formatted_text(text, style=STYLE)
示例#27
0
from prompt_toolkit import print_formatted_text, HTML
from prompt_toolkit.output.vt100 import FG_ANSI_COLORS, BG_ANSI_COLORS

for bg_color in sorted(BG_ANSI_COLORS):
    for fg_color in sorted(FG_ANSI_COLORS):
        message = "<p fg='{fg_color}' bg='{bg_color}'>XX <u>XX</u> <i>XX</i> <b>XX</b>   </p>".format(
            fg_color=fg_color, bg_color=bg_color)
        print_formatted_text(HTML(message), end="")

    print()
示例#28
0
 def exit_message(self):
     print_formatted_text(HTML('<b>Exiting prompt...</b>'))
示例#29
0
    def _print_mandatory_option(self, key, option):
        if str(option.value) == "None":
            print_formatted_text(HTML(f''' |_[<{ColorSelected().theme.warn}>REQUIRED</{ColorSelected().theme.warn}>] \
{key}  = <{ColorSelected().theme.confirm}>{option.value}</{ColorSelected().theme.confirm}> ({option.description})'''))     
        else:
            print_formatted_text(HTML(f''' |_{key} = <{ColorSelected().theme.confirm}>{option.value} </{ColorSelected().theme.confirm}> ({option.description})'''))
示例#30
0
def loading():
    emojis = [':moneybag:', ':yen:', ':dollar:', ':pound:', ':euro:']
    print_formatted_text(
        HTML(u'<b>> {}</b> <loading>loading...</loading>'.format(emoji.emojize(random.choice(emojis), use_aliases=True))), style=style)
示例#31
0
 def _print_optional_option(self, key, option):
     if str(option.value) == "None":
         print_formatted_text(HTML(f" |_[OPTIONAL] {key} = <{ColorSelected().theme.confirm}>{option.value}</{ColorSelected().theme.confirm}> ({option.description})"))
     else:
         print_formatted_text(HTML(f" |_{key} = <{ColorSelected().theme.confirm}>{option.value}</{ColorSelected().theme.confirm}> ({option.description})"))
示例#32
0
 def print_result(text: str) -> str:
     return print_formatted_text(HTML(f'<b fg="{color}">{text}</b>'))
示例#33
0
    def print_info(self):
        for key, value in dataclasses.asdict(self.safe_cli_info).items():
            print_formatted_text(
                HTML(f'<b><ansigreen>{key.capitalize()}</ansigreen></b>='
                     f'<ansiblue>{value}</ansiblue>'))
        if self.ens_domain:
            print_formatted_text(
                HTML(f'<b><ansigreen>Ens domain</ansigreen></b>='
                     f'<ansiblue>{self.ens_domain}</ansiblue>'))
        if self.safe_tx_service:
            url = f'{self.safe_tx_service.base_url}/api/v1/safes/{self.address}/transactions/'
            print_formatted_text(
                HTML(f'<b><ansigreen>Safe Tx Service</ansigreen></b>='
                     f'<ansiblue>{url}</ansiblue>'))

        if self.safe_relay_service:
            url = f'{self.safe_relay_service.base_url}/api/v1/safes/{self.address}/transactions/'
            print_formatted_text(
                HTML(f'<b><ansigreen>Safe Relay Service</ansigreen></b>='
                     f'<ansiblue>{url}</ansiblue>'))

        if self.etherscan.base_url:
            url = f'{self.etherscan.base_url}/address/{self.address}'
            print_formatted_text(
                HTML(f'<b><ansigreen>Etherscan</ansigreen></b>='
                     f'<ansiblue>{url}</ansiblue>'))

        if not self.is_version_updated():
            print_formatted_text(
                HTML(
                    '<ansired>Safe is not updated! You can use <b>update</b> command to update '
                    'the Safe to a newest version</ansired>'))
示例#34
0
def formatText(text, format):
    if format == "bold" or format == "b":
        s = '<b>' + text + '</b>'
        print_formatted_text(HTML(s))
    elif format == "blink":
        s = '<blink>' + text + '</blink>'
        print_formatted_text(HTML(s))
    elif format == "italic" or format == "i":
        s = '<i>' + text + '</i>'
        print_formatted_text(HTML(s))
    elif format == "reverse" or format == "r": # swap text color and background color
        s = '<reverse>' + text + '</reverse>'
        print_formatted_text(HTML(s))
    elif format == "underline" or format == "u":
        s = '<underline>' + text + '</underline>'
        print_formatted_text(HTML(s))
    elif format == "hidden" or format == "h":
        s = '<hidden>' + text + '</hidden>'
        print_formatted_text(HTML(s))
示例#35
0
 def get_threshold(self):
     print_formatted_text(self.safe.retrieve_threshold())
示例#36
0
 def print_text(self, parent_depth=0, with_date=False):
     print_formatted_text(
         self.get_show_text(align=parent_depth, with_date=with_date))
     for child in self.children:
         child.print_text(parent_depth=parent_depth + 1,
                          with_date=with_date)
示例#37
0

@register_builtin
def help():
    """
    Print the help
    """

    commands_help = "\n".join(
        f"%{fn.__name__}: {fn.__doc__}" for fn in builtins.values()
    )
    print(f"{HELP_MESSAGE}\n\n{commands_help}")


if __name__ == '__main__':
    print_formatted_text(HTML(WELCOME_PROMPT), style=style)

    args, _ = parser.parse_known_args()
    our_history = FileHistory(".example-history-file")
    session = PromptSession(
        history=our_history, lexer=PygmentsLexer(lkql.LKQLPygmentsLexer),
        completer=FuzzyCompleter(LKQLCompleter())
    )

    dummy_unit = ctx.get_from_buffer('<dummy>', '12')
    dummy_unit.root.p_interp_init_from_project(args.project)

    if args.script:
        cmd_unit = ctx.get_from_file(args.script)
        cmd_unit.root.p_interp_eval
    for i in itertools.count(start=1):