当前位置: 首页>>代码示例>>Python>>正文


Python Texttable.set_precision方法代码示例

本文整理汇总了Python中texttable.Texttable.set_precision方法的典型用法代码示例。如果您正苦于以下问题:Python Texttable.set_precision方法的具体用法?Python Texttable.set_precision怎么用?Python Texttable.set_precision使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在texttable.Texttable的用法示例。


在下文中一共展示了Texttable.set_precision方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: print_price_data

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_precision [as 别名]
def print_price_data(data):

    # Current BTC Price
    # --------------------
    print '\n%s' % colorize('CaVirtex Market\n---------------', colors.CYAN)
    

    status_color = colors.GREEN if data['net'] > 0 else colors.RED

    print '\n%s' % colorize('Price', colors.BLUE)
    
    print '\n%s' % colorize('$%.2f CAD/BTC' % data['current_price'], status_color)

    # Latest Trades
    # ----------------
    print '\n%s\n' % colorize('Latest Trades', colors.BLUE)
    
    trades_table = Texttable()
    trades_table.set_deco(Texttable.HEADER)
    trades_table.set_precision(2)
    trades_table.set_cols_dtype(['f', 'f', 'f', 't'])
    trades_table.add_rows(data['latest_trades'])

    print trades_table.draw()
    
    # Investment Returns
    # ---------------------
    print '\n%s' % colorize('Your Investment', colors.BLUE)

    print '\nNet: %s' % colorize('$%.2f CAD' % data['net'], status_color)
    print '\nVOI: %s' % colorize('$%.2f CAD' % data['voi'], status_color)
    print '\nROI: %s' % colorize('%.2f%%' % data['roi'], status_color)
开发者ID:mindcruzer,项目名称:calculations,代码行数:34,代码来源:bitcoin.py

示例2: _dataframe_to_texttable

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_precision [as 别名]
def _dataframe_to_texttable(df, align=None):
    """Convert data frame to texttable. Sets column widths to the
    widest entry in each column."""
    ttab = Texttable()
    ttab.set_precision(1)
    h = [[x for x in df]]
    h.extend([x for x in df.to_records(index=False)])
    if align:
        colWidths = [max(len(x), len(".. class:: {}".format(y))) for x,y in izip(df.columns, align)]
    else:
        colWidths = [len(x) for x in df.columns]
    for row in h:
        for i in range(0, len(row)):
            if type(row[i]) == str:
                colWidths[i] = max([len(str(x)) for x in row[i].split("\n")] + [colWidths[i]])
            colWidths[i] = max(len(str(row[i])), colWidths[i])
    table_data = []
    if align:
        for row in h:
            table_row = []
            i = 0
            for col, aln in izip(row, align):
                table_row.append(".. class:: {}".format(aln) + " " * colWidths[i] + "{}".format(col))
                i = i + 1
            table_data.append(table_row)
    else:
        table_data = h
    ttab.add_rows(table_data)
    ttab.set_cols_width(colWidths)
    # Note: this does not affect the final pdf output
    ttab.set_cols_align(["r"] * len(colWidths))
    return ttab
开发者ID:Galithil,项目名称:scilifelab,代码行数:34,代码来源:best_practice.py

示例3: eval_dir

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_precision [as 别名]
def eval_dir(path, markdown=False, dprefix=False,
             evalmethod=None, numlabel=False):
    """ Evaluate the results in the dir by MRR

        Argument:
            dirname -- the path to the diretory containing evaluation results
    """
    if evalmethod is None:
        ef = mrr
    else:
        ef = globals()[evalmethod]
    files = sorted(os.listdir(path))
    names = sorted(set([n.rsplit('.', 1)[0][3:] for n in files
                        if n.endswith('.res')]),
                   key=lambda item: (len(item), item))
    if dprefix:
        prefices = sorted(set([n[:2] for n in files]))
    else:
        prefices = PREFICES
    table = Texttable(max_width=0)
    if markdown:
        table.set_asmarkdown()
    else:
        table.set_deco(0)
    table.set_cols_dtype(['t'] + ['f'] * len(prefices))
    table.set_cols_align(['l'] + ['r'] * len(prefices))
    table.set_precision(4)
    table.add_rows([['', ] + prefices])
    for n in names:
        scores = list()
        for prefix in prefices:
            try:
                eva = NP.array([v for v in iterrank(
                    os.path.join(path, '%s_%s.res' % (prefix, n)))],
                    dtype=NP.float64)
                scores.append(ef(eva))
            except IOError:
                scores.append('N/A')
        if numlabel:
            n = ' '.join([m.group() for m in NUMBER.finditer(n)])
        table.add_row([n, ] + scores)
    print table.draw()
开发者ID:spacelis,项目名称:twhere,代码行数:44,代码来源:evalres.py

示例4: main

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_precision [as 别名]
def main():
    parser = buildArgsParser()
    args = parser.parse_args()

    sort_by = args.sort

    names = []
    results_files = []
    hyperparams_files = []
    status_files = []
    for f in args.results:
        exp_folder = f
        if os.path.isfile(f):
            exp_folder = os.path.dirname(f)

        result_file = pjoin(exp_folder, "result.json")
        hyperparams_file = pjoin(exp_folder, "hyperparams.json")
        status_file = pjoin(exp_folder, "status.json")

        if not os.path.isfile(result_file):
            print 'Skip: {0} is not a file!'.format(result_file)
            continue

        if not os.path.isfile(hyperparams_file):
            print 'Skip: {0} is not a file!'.format(hyperparams_file)
            continue

        if not os.path.isfile(status_file):
            print 'Skip: {0} is not a file!'.format(status_file)
            continue

        name = os.path.basename(exp_folder)
        if 'hyperparams.json' in os.listdir(os.path.abspath(pjoin(exp_folder, os.path.pardir))):
            name = os.path.basename(os.path.abspath(pjoin(exp_folder, os.path.pardir)))

        names.append(name)

        results_files.append(result_file)
        hyperparams_files.append(hyperparams_file)
        status_files.append(status_file)

    if len([no for no in sort_by if no == 0]) > 0:
        parser.error('Column ID are starting at 1!')

    # Retrieve headers from hyperparams
    headers_hyperparams = set()
    headers_results = set()
    headers_status = set()

    for hyperparams_file, status_file, results_file in zip(hyperparams_files, status_files, results_files):
        hyperparams = load_dict_from_json_file(hyperparams_file)
        results = load_dict_from_json_file(results_file)
        status = load_dict_from_json_file(status_file)
        headers_hyperparams |= set(hyperparams.keys())
        headers_results |= set(results.keys())
        headers_status |= set(status.keys())

    headers_hyperparams = sorted(list(headers_hyperparams))
    headers_status = sorted(list(headers_status))
    # TODO: when generating result.json split 'trainset' scores in two key:
    #       'trainset' and 'trainset_std' (same goes for validset and testset).
    headers_results |= set(["trainset_std", "validset_std", "testset_std"])
    headers_results = sorted(list(headers_results))
    headers = headers_hyperparams + headers_status + ["name"] + headers_results

    # Build results table
    table = Texttable(max_width=0)
    table.set_deco(Texttable.HEADER)
    table.set_precision(8)
    table.set_cols_dtype(['a'] * len(headers))
    table.set_cols_align(['c'] * len(headers))

    # Headers
    table.header([str(i) + "\n" + h for i, h in enumerate(headers, start=1)])

    if args.only_header:
        print table.draw()
        return

    # Results
    for name, hyperparams_file, status_file, results_file in zip(names, hyperparams_files, status_files, results_files):
        hyperparams = load_dict_from_json_file(hyperparams_file)
        results = load_dict_from_json_file(results_file)
        status = load_dict_from_json_file(status_file)

        # Build results table row (hyperparams columns)
        row = []
        for h in headers_hyperparams:
            value = hyperparams.get(h, '')
            row.append(value)

        for h in headers_status:
            value = status.get(h, '')
            row.append(value)

        row.append(name)

        for h in headers_results:
            if h in ["trainset", "validset", "testset"]:
                value = results.get(h, '')[0]
#.........这里部分代码省略.........
开发者ID:napsternxg,项目名称:iRBM,代码行数:103,代码来源:view_results.py

示例5: len

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_precision [as 别名]
        names.append(name)
        params = [float(i) for i in row[1:]]
        matrix.append(params)

n = len(matrix)
results_matrix = [[0]*n for i in range(n)]

for j in range(n-1):
    for i in range(j+1, n):
        row1 = matrix[i]
        row2 = matrix[j]
        score = [0, 0]
        for func in lpr:
            score[func([row1, row2])[2]] += 1
        if score[0] != score[1]:
            bigger = (i, j)[score.index(max(score))]
            smaller = (i, j)[score.index(min(score))]
            results_matrix[smaller][bigger] = 1

table = Texttable(max_width=150)
table.set_deco(Texttable.HEADER)
table.set_precision(1)
table.add_rows([['']+names])
for i in range(n):
    table.add_rows([[names[i]]+results_matrix[i]], header=False)
print table.draw()

print 'Best solutions:',
for i in range(n):
    if max(zip(*results_matrix)[i]) == 0:
        print names[i],
开发者ID:denself,项目名称:meo,代码行数:33,代码来源:main.py

示例6: len

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_precision [as 别名]
    offset += per_page


total_monthly_revenue = []

for type, customers in by_status.iteritems():

    print '*' * 80
    print 'Subscriptions: ', type, ' - ', len(customers)
    print '*' * 80
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(['l', 'r', 'l', 'r'])
    table.header(['Customer', 'Plan', 'Coupon', 'Monthly'])
    table.set_precision(2)

    for c in customers:
        row = []
        row.append(c.description or c.email)

        monthly = 0
        if c.subscription:
            amount = '$%d' % (c.subscription.quantity * c.subscription.plan.amount / 100)
            if c.subscription.plan.interval == 'month':
                monthly = c.subscription.quantity * c.subscription.plan.amount
            elif c.subscription.plan.interval == 'year':
                if c.subscription.status == 'active':
                    monthly = c.subscription.quantity * c.subscription.plan.amount / 12
                amount += ' ANNUAL'
            else:
开发者ID:dtran320,项目名称:stripe-revenue,代码行数:32,代码来源:stripe_rev.py

示例7: main

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_precision [as 别名]

#.........这里部分代码省略.........
        header.append("Newton's: x_n")
        
        if args.func_vals:    
            iterates.append(f_n)
            header.append("Newton's: f(x_n)")

    if 'halley' in args.methods:
        x_n, f_n = rm.halleys_method(M,eps,delta,f,fp,fpp,x_0)

        if args.verbosity >= 1:
            print "\nHalley's method:"
            print "\tNumber of iterations: " + str(len(x_n))
            print "\tx_"+str(len(x_n)-1)+" = "+str(x_n[-1])
            print "\tf(x_"+str(len(f_n)-1)+") = "+str(f_n[-1])
        
        iterates.append(x_n)
        header.append("Halley's: x_n")
        
        if args.func_vals:    
            iterates.append(f_n)
            header.append("Halley's: f(x_n)")

    if 'steffenson' in args.methods:
        x_n, f_n = rm.steffensons_method(M,eps,delta,f,x_0)

        if args.verbosity >= 1:
            print "\nSteffenson's method:"
            print "\tNumber of iterations: " + str(len(x_n))
            print "\tx_"+str(len(x_n)-1)+" = "+str(x_n[-1])
            print "\tf(x_"+str(len(f_n)-1)+") = "+str(f_n[-1])
        
        iterates.append(x_n)
        header.append("Steffenson's: x_n")
        
        if args.func_vals:    
            iterates.append(f_n)
            header.append("Steffenson's: f(x_n)")

    if 'secant' in args.methods:
        x_n, f_n = rm.secant_method(M,eps,delta,f,x_0,x_1)

        if args.verbosity >= 1:
            print "\nSecant method:"
            print "\tNumber of iterations: " + str(len(x_n))
            print "\tx_"+str(len(x_n)-1)+" = "+str(x_n[-1])
            print "\tf(x_"+str(len(f_n)-1)+") = "+str(f_n[-1])
        
        iterates.append(x_n)
        header.append('Secant: x_n')
        
        if args.func_vals:    
            iterates.append(f_n)
            header.append('Secant: f(x_n)')
        
    if 'secant_swap' in args.methods:
        x_n, f_n = rm.secant_method_swap(M,eps,delta,f,x_0,x_1)

        if args.verbosity >= 1:
            print "\nSecant method (swap):"
            print "\tNumber of iterations: " + str(len(x_n))
            print "\tx_"+str(len(x_n)-1)+" = "+str(x_n[-1])
            print "\tf(x_"+str(len(f_n)-1)+") = "+str(f_n[-1])
        
        iterates.append(x_n)
        header.append('Secant swap: x_n')

        if args.func_vals:    
            iterates.append(f_n)
            header.append('Secant swap: f(x_n)')

    # create a texttable and add the records
    table = Texttable()
    # set the table style
    table.set_deco(Texttable.HEADER)
    # set precision of floating point data type
    table.set_precision(7)
    # set column data types in table
    table.set_cols_dtype(['i']+['f' for i in iterates])
    # set the table column alignment
    table.set_cols_align(['r']+['r' for i in iterates])
    # add table column headers
    table.header(header)

    # add the records to the table
    i = 0
    for ROW in izip_longest(*iterates):
        table.add_row([i]+list(ROW))
        i=i+1

    # draw table
    print table.draw()

    if args.csv != None:
        # create CSV writer
        with open(args.csv, 'wb') as csvfile:
            writer = csv.writer(csvfile, delimiter=',',
                quotechar='|', quoting=csv.QUOTE_MINIMAL)
            writer.writerow(header)
            for RECORD in records:
                writer.writerow(RECORD)
开发者ID:ohearnk,项目名称:MTH499-02,代码行数:104,代码来源:test_root_methods.py


注:本文中的texttable.Texttable.set_precision方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。