예제 #1
0
def print_table(final_results, sizes, scale):
    traffic_unit = scale["traffic_unit"]
    pkt_unit = scale["pkt_unit"]

    table = Texttable(max_width=0)
    table.set_chars(['', '|', '', ''])
    table.set_precision(2)
    table.set_deco(Texttable.VLINES)
    rows = [[
        "| Packet size", "Line Utilization (%)",
        "Total L1 {}".format(traffic_unit), "Total L2 {}".format(traffic_unit),
        "CPU Util (%)", "Total {}".format(pkt_unit),
        "BW per core {} <1>".format(traffic_unit),
        "{} per core <2>".format(pkt_unit), "Multiplier"
    ]]
    for size in sizes:
        pkt_result = final_results[size]
        pkt_str = "| " + str(pkt_result["Packet size"])
        row = [
            pkt_str, pkt_result["Line Utilization (%)"],
            pkt_result["Total L1 {}".format(traffic_unit)],
            pkt_result["Total L2 {}".format(traffic_unit)],
            pkt_result["CPU Util (%)"],
            pkt_result["Total {}".format(pkt_unit)],
            pkt_result["BW per core {}".format(traffic_unit)],
            pkt_result["{} per core".format(pkt_unit)],
            pkt_result["Multiplier"]
        ]
        rows.append(row)

    table.add_rows(rows)

    print(table.draw())
예제 #2
0
파일: tab.py 프로젝트: ccszwg/pyexam
def tab_text(df, columns_width=None, columns=None, vline=True):
    if type(df) is not pd.DataFrame:
        print('Warning:\n', type(df), '\n', df)
        print('input data is not DataFrame!')
        return
    colnum = df.columns.__len__()
    # rownum = df.__len__()
    table = Texttable()
    if not vline:
        table.set_deco(Texttable.HEADER)
    table.set_cols_align(["l"] * colnum)
    table.set_cols_valign(["m"] * colnum)
    table.set_chars(["-", "|", "+", "="])
    table.set_cols_dtype(['t'] * colnum)
    if not columns_width:
        columns_width = {}
    elif type(columns_width) != list:
        print('colWidth is not dict type!')
        return ''
    defaultwidth = [10] * colnum
    if len(columns_width) > 0:
        defaultwidth = columns_width
        # j = 0
        # for k in columns_width:
        #    defaultwidth[j] = columns_width[k]
    table.set_cols_width(defaultwidth)
    if columns:
        headnames = columns
    else:
        headnames = [s for s in df.columns]
    rowall = [headnames] + \
             [list(df.values[i]) for i in range(len(df))]
    table.add_rows(rowall)
    rr = table.draw()
    return rr
예제 #3
0
    def scrape_score(self):
        """ Scrape web page, retrieve necessary data, format it and return to the user """
        page = requests.get(self.url)
        parsed_markup = BeautifulSoup(page.text, "html.parser")

        # final version of the table to send to the user
        scores = Texttable()

        # settings for table
        scores.set_cols_width([10, 1, 10])
        scores.set_cols_align(['l', 'c', 'r'])  # c - center align (horizontal), l - left, r - right
        scores.set_cols_valign(['m', 'm', 'm'])  # m - middle align (vertical)
        scores.set_chars(['—', '|', '+', '='])  # replace dash with em dash
        scores.header(["Home Team", "", "Away Team"])

        # scrape needed data from the parsed markup
        for element in parsed_markup.find_all("div", "row-gray"):

            match_name_element = element.find(attrs={"class": "scorelink"})

            if match_name_element is not None and element.find("div", "sco").get_text().split("-")[0].strip() == "?":
                home_team = shorten_name(' '.join(element.find("div", "tright").get_text().strip().split(" ")))
                away_team = shorten_name(' '.join(element.find(attrs={"class": "ply name"}).get_text().strip().split(" ")))

                scores.add_row([home_team, "-", away_team])

        return '`' + scores.draw() + '`'
예제 #4
0
    def pformat_extended(self, sort_by: List[int] = []):
        cnt = 0
        headers = self.headers()
        output = ''
        try:
            for r in sorted(self.fetchall(), key=operator.itemgetter(
                    *sort_by)) if sort_by else self.fetchall():
                cnt += 1
                table = Texttable(max_width=0)
                table.set_deco(Texttable.VLINES)
                table.set_cols_align(['r', 'l'])
                table.set_chars(
                    ['-', ':', '+', '=']
                )  # Just replacing vertical line with ':' instead of default '|'
                for i, h in enumerate(headers):
                    table.add_row([h, r[i]])
                output += f'row {cnt}:\n'
                output += table.draw()
                output += '\n\n'

        except IndexError:
            raise TableFormattingError(
                f"You tried to sort by columns '{sort_by}' but at least one does not exist."
            )

        return {'table': output, 'rowcount': cnt}
예제 #5
0
def test_chaining():
    table = Texttable()
    table.reset()
    table.set_max_width(50)
    table.set_chars(list('-|+='))
    table.set_deco(Texttable.BORDER)
    table.set_header_align(list('lll'))
    table.set_cols_align(list('lll'))
    table.set_cols_valign(list('mmm'))
    table.set_cols_dtype(list('ttt'))
    table.set_cols_width([3, 3, 3])
    table.set_precision(3)
    table.header(list('abc'))
    table.add_row(list('def'))
    table.add_rows([list('ghi')], False)
    s1 = table.draw()
    s2 = (Texttable()
          .reset()
          .set_max_width(50)
          .set_chars(list('-|+='))
          .set_deco(Texttable.BORDER)
          .set_header_align(list('lll'))
          .set_cols_align(list('lll'))
          .set_cols_valign(list('mmm'))
          .set_cols_dtype(list('ttt'))
          .set_cols_width([3, 3, 3])
          .set_precision(3)
          .header(list('abc'))
          .add_row(list('def'))
          .add_rows([list('ghi')], False)
          .draw())
    assert s1 == s2
예제 #6
0
    def cameraGet(self):
        print 'camera list'
        self.cameras = requests.get(self.nvrProtocol + '://' +
                                    self.nvrAddress + ':' + self.nvrPort +
                                    self.apiVersion + 'camera',
                                    cookies=self.loginReq.cookies,
                                    headers=self.apiHeader,
                                    verify=False)

        if str(self.cameras) == '<Response [200]>':
            print "camera list:..."
            cameraJson = self.cameras.json()
            cameraJsonData = cameraJson['data']
            cameraJsonZones = cameraJsonData[0]

            # create tabular with the texttable package
            t = Texttable()
            t.header(['Camera Name', 'Camera ID'])
            t.set_chars(['-', '|', '-', '-'])
            # not tested with more than 1 camera probably fails due to cameraJsonZones set to [0]['zones']
            for item in cameraJsonZones:
                #print cameraJsonZones[item]
                if str(item) == '_id':
                    #print cameraJsonZones[item]
                    #t.add_row([item['name'], item['_id']])
                    t.add_row(
                        [cameraJsonZones['name'], cameraJsonZones['_id']])

            print t.draw()
            return cameraJsonZones
        else:
            print self.cameras
            print self.cameras.headers
            print self.cameras.cookies
            print self.cameras.text
예제 #7
0
 def to_txt_file(self, rounds,file, print_header): 
     table = Texttable()
     table.set_cols_width([len(self.team_one.get_name()) + 9, len(self.team_two.get_name()) + 9])
     if print_header:
         deco = Texttable.HEADER | Texttable.VLINES
         table.header([self.team_one.get_name(), self.team_two.get_name()])
     else:
         deco = Texttable.VLINES
     table.set_deco(deco)
     table.set_chars(['-', '|', '=', '='])
     rows = [[str(rounds[0].get_team_one_points()),str(rounds[0].get_team_two_points())]]
     for i in range(1,len(rounds)):
         column1 = f"{sum([x.get_team_one_points() for x in rounds[:i]])} + {rounds[i].get_team_one_points()}"
         column2 = f"{sum([x.get_team_two_points() for x in rounds[:i]])} + {rounds[i].get_team_two_points()}"
         rows.append([column1,column2])
     column1 = f"{sum([x.get_team_one_points() for x in rounds])}"
     column2 = f"{sum([x.get_team_two_points() for x in rounds])}"
     rows.append([column1,column2])
     table.add_rows(rows, header = False)
     file.write(table.draw())
     file.write('\n')
     self.write_divider_to_file(file)
     table.reset()
     table.add_row([f"({self.team_one.games_won})", f"({self.team_two.games_won})"])
     table.set_cols_align(["c","c"])        
     file.write(table.draw())
     file.write('\n')
     self.write_divider_to_file(file)
예제 #8
0
파일: metrics.py 프로젝트: mbrukman/dvc
def _show_diff(diff):
    from texttable import Texttable

    if not diff:
        return ""

    table = Texttable()

    # disable automatic formatting
    table.set_cols_dtype(["t", "t", "t", "t"])

    # remove borders to make it easier for users to copy stuff
    table.set_chars(("", "", "", ""))
    table.set_deco(0)

    rows = [["Path", "Metric", "Value", "Change"]]
    for fname, mdiff in diff.items():
        for metric, change in mdiff.items():
            rows.append(
                [
                    fname,
                    metric,
                    change["new"],
                    change.get("diff", "diff not supported"),
                ]
            )
    table.add_rows(rows)
    return table.draw()
예제 #9
0
 def draw(self):
     table = Texttable()
     header, name = False, ""
     try:
         name = self.name + ":\n"
     except:
         name = "Untitled Table"
     try:
         table.set_cols_width(self.widths)
     except:
         pass
     try:
         table.set_cols_align(self.align)
     except:
         pass
     try:
         table.set_cols_dtype(self.dtype)
     except:
         pass
     try:
         table.set_chars(self.chars)
     except:
         pass
     try:
         table.header(self.header)
     except:
         header = False
     table.set_deco(Texttable.HEADER)
     table.add_rows(self.rows, header=header)
     o = (table.draw() + "\n")
     l = o.split('\n')
     w = max(len(x) for x in l)
     d = '-' * w
     return (name + d + '\n' + o + d + '\n')
예제 #10
0
def render_matrices(matr):
	print(matr)
	if len(matr)==0:
		return str(matr)
	max_len = 0
	has_nesting = True
	
	for row in matr:
		if type(row)==list:
			max_len = max(max_len,len(row))
		else:
			has_nesting = False
	table = Texttable(0)
	table.set_chars(['-','|','+','-'])
	

	if not has_nesting:
		table.set_cols_dtype(['t']*(len(matr)))
		table.add_row(matr)
	else:
		table.set_cols_dtype(['t']*(max_len))
		new_matr = []
		for row in matr:
			if len(row)<max_len:
				row.extend(['']*(max_len-len(row)))
			new_matr.append(row)
		table.add_rows(new_matr)
	return table.draw()
예제 #11
0
 def render_table(self, filename=LOGFILE):
     """Render summary table."""
     table = Texttable(max_width=0)
     table.set_cols_align(["c", "c", "c"])
     table.set_cols_valign(["m", "m", "m"])
     table.set_chars(['-', '|', '+', '-'])
     table.set_deco(Texttable.VLINES | Texttable.HLINES | Texttable.HEADER)
     table.add_rows([["SUCCESS", "REDIRECTS", "ERRORS"],
                     [str(e) for e in self.parse_log(filename)]])
     return table.draw()
예제 #12
0
	def toString(self):
		table = Texttable()
		table.set_chars(['-','|','+','-'])
		rows = []
		for i in range(0, self.size):
			row = []
			for j in range(0, self.size):
				row.append("x" if (i, j) in self.cells else "o")
			rows.append(row)
		table.add_rows(rows)
		return table.draw()
예제 #13
0
파일: utils.py 프로젝트: thesps/ipbb
def formatRegTable(aRegs, aHeader=True, aSort=True):
    lRegTable = Texttable(max_width=0)
    lRegTable.set_deco(Texttable.VLINES | Texttable.BORDER | Texttable.HEADER)
    lRegTable.set_chars(['-', '|', '+', '-'])
    if aHeader:
        lRegTable.header(['name', 'value'])

    lRegs = sorted(aRegs) if aSort else aRegs
    for k in lRegs:
        lRegTable.add_row([str(k), hex(aRegs[k])])

    return lRegTable.draw()
예제 #14
0
파일: utils.py 프로젝트: thesps/ipbb
def formatDictTable(aDict, aHeader=True, aSort=True, aFmtr=str):
    lDictTable = Texttable(max_width=0)
    lDictTable.set_deco(Texttable.VLINES | Texttable.BORDER | Texttable.HEADER)
    lDictTable.set_chars(['-', '|', '+', '-'])
    if aHeader:
        lDictTable.header(['name', 'value'])

    for k in (sorted(aDict) if aSort else aDict):
        v = aDict[k]
        lDictTable.add_row([str(k), aFmtr(v) if aFmtr else v])

    return lDictTable.draw()
def detect_with_yolo(workingdir, imgpath, objtype):
    mydict = {}

    #i = 0
    for image in os.listdir(imgpath):
        if (image.endswith(('.png', '.jpg', '.jpeg'))):
            p = Popen([
                './darknet', 'detect', 'cfg/yolov3.cfg', 'yolov3.weights',
                imgpath + '/' + image
            ],
                      cwd=workingdir,
                      stdout=PIPE,
                      stderr=PIPE)
            stdout, stderr = p.communicate()
            response = stdout.decode("utf-8")

            # Split the whole string by newline and extract the lines with the predictions
            for item in response.split("\n"):
                if "%" in item:
                    obj = item.split(":")[0].strip()
                    if not obj in mydict:
                        mydict[obj] = 1
                    else:
                        mydict[obj] += 1
            # We just wanted to run for the first 10 images
            #i = i + 1
            #if(i == 10):
            #    break

    # Lets print a table
    tab = Texttable()
    header = [objtype + ' Object', 'No of Occurence']
    tab.header(header)
    tab.set_cols_width([25, 20])
    tab.set_cols_align(['c', 'c'])
    tab.set_cols_valign(['m', 'm'])
    tab.set_deco(tab.HEADER | tab.VLINES)
    tab.set_chars(['-', '|', '+', '#'])

    # LEts Sort the Dictionary
    ordered = OrderedDict(
        sorted(mydict.items(), key=itemgetter(1), reverse=True))
    for result in ordered:
        row = [result, ordered[result]]
        tab.add_row(row)

    # Lets draw the table
    s = tab.draw()
    print s
    print "\n\n"
예제 #16
0
 def __str__(self):
     from ..formatters import to_format
     table = Texttable(max_width=0)
     table.set_chars(self.__border__())
     data = self.to_array()
     for sub_array in data:
         new_array = []
         for item in sub_array:
             if item == "":
                 new_array.append(" ")
             else:
                 new_array.append(to_format(str, item))
         table.add_row(new_array)
     return table.draw()
예제 #17
0
파일: vivado.py 프로젝트: thesps/ipbb
def makeRunsTable(lInfos):
    lSummary = Texttable(max_width=0)
    if not lInfos:
        return lSummary

    # lSummary.set_deco(Texttable.HEADER | Texttable.BORDER)
    lSummary.set_deco(Texttable.HEADER | Texttable.BORDER)
    lSummary.set_chars( ['-', '|', '+', '-'] )
    lSummary.header(['Run'] + list(next(iter(itervalues(lInfos)))))
    for lRun in sorted(lInfos):
        lInfo = lInfos[lRun]
        lSummary.add_row([lRun] + list(itervalues(lInfo)))

    return lSummary
예제 #18
0
    def parse_latest(self):
        """ Parse necessary data, format it and return to the user """
        # final version of the table to send to the user
        scores = Texttable()

        # settings for table
        scores.set_cols_width([9, 3, 9])
        scores.set_cols_align(['l', 'c', 'r'])  # c - center align (horizontal), l - left, r - right
        scores.set_cols_valign(['m', 'm', 'm'])  # m - middle align (vertical)
        scores.set_chars(['—', '|', '+', '='])  # replace dash with em dash

        scores.add_rows([["Home Team", "", "Away Team"]] + scrape_page(self.url))

        return '`' + scores.draw() + '`'
예제 #19
0
파일: matrix.py 프로젝트: Seabreg/PSTools
 def __str__(self):
     from ..formatters import to_format
     table = Texttable(max_width=0)
     table.set_chars(self.__border__())
     data = self.to_array()
     for sub_array in data:
         new_array = []
         for item in sub_array:
             if item == "":
                 new_array.append(" ")
             else:
                 new_array.append(to_format(str, item))
         table.add_row(new_array)
     return table.draw()
예제 #20
0
def service_table(services, width):
    table = Texttable(max_width=width)
    headers = ['uuid', 'state', 'instance', 'ip', 'service', 'scale']
    rows = []
    for service in services:
        rows.append([
            service['uuid'],
            service['state'],
            service['instance'],
            service['ip'],
            service['service'],
            service['scale']
        ])
    table.set_chars(['-', '|', '+', '-'])
    table.add_rows([headers] + rows)
    return table.draw()
예제 #21
0
 def repr_full(self, connection):
     """Full representation of a connection"""
     t = Texttable(78)
     t.set_deco(Texttable.HEADER | Texttable.VLINES)
     t.set_chars(['.', '|', 'o', '-'])
     t.header(['Field', 'Client', 'Server'])
     t.set_cols_align(['r', 'l', 'l'])
     t.add_row(['IP', connection.client_ip, connection.server_ip])
     t.add_row(['Port', connection.client_port, connection.server_port])
     t.add_row(['Datagrams', connection.client_sent_nb_datagrams,
         connection.server_sent_nb_datagrams])
     t.add_row(['Datagrams (bytes)', connection.client_sent_len,
         connection.server_sent_len])
     r = (
          'Connection %d\n%s'
          'Start date: %s\n'
          'Duration: %s'
         ) % (
             connection.nb, '' if connection.ssh else C.FMag +
                 'Not detected as a ssh connection' + C.FRes + '\n',
             connection.start_time.strftime('%b %d, %Y - %H:%M:%S'),
             str_td(connection.duration)
         )
     for plugin in self.plugins:
         plugin_results = self.result_plugin(connection, plugin)
         for field_short, field_client, field_server \
                 in self.plugins_fields_table[plugin]:
             if field_client not in plugin_results \
                     or plugin_results[field_client] is None:
                 plugin_results[field_client] = ''
             if field_server not in plugin_results \
                     or plugin_results[field_server] is None:
                 plugin_results[field_server] = ''
             if plugin_results[field_client] != '' \
                     or plugin_results[field_server] != '':
                 t.add_row([
                     field_short,
                     C.remove_color(plugin_results[field_client]),
                     C.remove_color(plugin_results[field_server])
                     ])
             del(plugin_results[field_client])
             del(plugin_results[field_server])
         for field in self.plugins_fields[plugin]:
             if field in plugin_results:
                 r += '\n%s: %s' % (field, plugin_results[field])
     r += '\n%s' % t.draw()
     print '%s\n' % r.replace('\n', '\n  ')
예제 #22
0
    def create_table(self):
        """ Parse table, format it and return to the user """
        # create matrix from zeros
        teamInfo = [[0 for x in range(self.table_width)]
                    for y in range(self.table_height)]

        # final version of the table to send to the user
        res_table = Texttable()

        # settings for table
        res_table.set_cols_width([2, 15, 4])
        res_table.set_cols_align(['c', 'l',
                                  'c'])  # c - center align (horizontal)
        res_table.set_cols_valign(['m', 'm',
                                   'm'])  # m - middle align (vertical)
        res_table.set_chars(['—', '|', '+', '='])  # replace dash with em dash

        # get team names and corresponding points
        team, pts = scrape_page(self.url)

        # current country
        country = self.url.split('/')[-3]

        if not team or not pts:
            res_table.add_row(["?", "Empty Table", "?"])
        else:
            z = 0
            for x in range(0, self.table_height):
                teamInfo[x][0] = shorten_name(team[x].text)
                for y in range(1, self.table_width):
                    teamInfo[x][y] = pts[z].text
                    z += 1

        for x in range(0, self.table_height):
            if x == 0:
                res_table.header(['#', date.today(), "Pts"])
            else:
                self.team_detail(country,
                                 teams_num=self.table_height - 1,
                                 team=teamInfo[x][0],
                                 position=x - 1)
                res_table.add_row([x, teamInfo[x][0], teamInfo[x][8]])

        return '`' + res_table.draw() + '`' + \
               "\n\n🏆 *Champions League zone*: " + ", ".join(self.champions_league) + \
               "\n\n🇪🇺 *Europa League zone*: " + ", ".join(self.europa_league) + \
               "\n\n⏬ *Relegation zone*: " + ", ".join(self.relegation)
예제 #23
0
def instance_table(instances, width):
    table = Texttable(max_width=width)
    headers = ['uuid', 'state', 'ip', 'size', 'group', 'scale', 'region']
    rows = []
    for instance in instances:
        rows.append([
            instance['uuid'],
            instance['state'],
            instance['ip'],
            instance['size'],
            instance['group'],
            instance['scale'],
            instance['region']
        ])
    table.set_chars(['-', '|', '+', '-'])
    table.add_rows([headers] + rows)
    return table.draw()
예제 #24
0
def render_text_table(sheet, _, write_title):
    content = ""
    if write_title:
        content += "%s:\n" % sheet.name
    table = Texttable(max_width=0)
    data = sheet.to_array()
    table.set_cols_dtype(['t'] * len(data[0]))
    if len(sheet.colnames) > 0:
        table.set_chars(['-', '|', '+', '='])
        table.header(list(_cleanse_a_row(data[0])))
    else:
        table.add_row(list(_cleanse_a_row(data[0])))
    for sub_array in data[1:]:
        new_array = _cleanse_a_row(sub_array)
        table.add_row(list(new_array))
    content += table.draw()
    return content
예제 #25
0
    def draw(self):
        from texttable import Texttable

        table = Texttable(max_width=88)
        table.set_deco(Texttable.HEADER)
        table.set_chars(["", "", "", "-"])
        ncols = len(self._values)
        table.set_cols_dtype(["t"] + ["e"] * ncols)
        table.set_cols_align(["l"] + ["r"] * ncols)

        rows = [[""] + self._columns]
        for i, r in enumerate(zip(*self._values)):
            rows.append([self._index[i]] + list(r))

        table.add_rows(rows)

        return table.draw()
예제 #26
0
def render_text_table(sheet, _, write_title):
    content = ""
    if write_title:
        content += "%s:\n" % sheet.name
    table = Texttable(max_width=0)
    data = sheet.to_array()
    table.set_cols_dtype(['t'] * len(data[0]))
    if len(sheet.colnames) > 0:
        table.set_chars(['-', '|', '+', '='])
        table.header(list(_cleanse_a_row(data[0])))
    else:
        table.add_row(list(_cleanse_a_row(data[0])))
    for sub_array in data[1:]:
        new_array = _cleanse_a_row(sub_array)
        table.add_row(list(new_array))
    content += table.draw()
    return content
예제 #27
0
파일: diff.py 프로젝트: rogervaas/dvc
def table(header, rows):
    from texttable import Texttable

    if not rows:
        return ""

    t = Texttable()

    # disable automatic formatting
    t.set_cols_dtype(["t"] * len(header))

    # remove borders to make it easier for users to copy stuff
    t.set_chars([""] * len(header))
    t.set_deco(0)

    t.add_rows([header] + rows)

    return t.draw()
예제 #28
0
def diode_map(diodes: List[Tuple], rows: int = 7) -> str:
    diode_list = []
    for _ in range(rows):
        diode_list.append(["", ""])

    for diode in diodes:
        name = diode[1]
        board = diode[0].name

        col = 1 if "A" in board else 0
        row = rows - 1 - int(board[1:])

        diode_list[row][col] = name

    t = Texttable()
    t.add_rows(diode_list)
    t.set_chars(['-', '|', '+', '-'])  # No headers

    return t.draw()
예제 #29
0
 def __str__(self):
     from ..formatters import to_format
     ret = "Sheet Name: %s\n" % self.name
     if len(self.colnames) > 0:
         table = Texttable(max_width=0)
         table.set_chars(self.__border__())
         data = self.to_array()
         new_data = []
         for sub_array in data:
             new_array = []
             for item in sub_array:
                 if item == "":
                     new_array.append(" ")
                 else:
                     new_array.append(to_format(str,item))
             new_data.append(new_array)
         table.add_rows(new_data)
         return ret+table.draw()
     else:
         return ret+FilterableSheet.__str__(self)
예제 #30
0
 def __str__(self):
     from ..formatters import to_format
     ret = "Sheet Name: %s\n" % self.name
     if len(self.colnames) > 0:
         table = Texttable(max_width=0)
         table.set_chars(self.__border__())
         data = self.to_array()
         new_data = []
         for sub_array in data:
             new_array = []
             for item in sub_array:
                 if item == "":
                     new_array.append(" ")
                 else:
                     new_array.append(to_format(str, item))
             new_data.append(new_array)
         table.add_rows(new_data)
         return ret + table.draw()
     else:
         return ret + FilterableSheet.__str__(self)
예제 #31
0
파일: command.py 프로젝트: TomRegan/roots
 def _print_results_table(self, results):
     """Print results formatted in a table.
     """
     table = Texttable()
     table.set_chars(['-', '|', '+', '-'])
     table.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES)
     header_type = ['t', 't']
     header = ['Auther', 'Title']
     if self._configuration['list']['isbn'] or self._arguments['-i']:
         header_type += ['t']
         header += ['Isbn']
     table.set_cols_dtype(header_type)
     table.header(header)
     for author, title, isbn in results:
         if isbn is None:
             isbn = ""
         row = [author.encode('utf-8'), title.encode('utf-8')]
         if self._configuration['list']['isbn'] or self._arguments['-i']:
             row += [isbn.encode('utf-8')]
         table.add_row(row)
     self.out(table.draw())
예제 #32
0
 def _print_results_table(self, results):
     """Print results formatted in a table.
     """
     table = Texttable()
     table.set_chars(['-', '|', '+', '-'])
     table.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES)
     header_type = ['t', 't']
     header = ['Auther', 'Title']
     if self._configuration['list']['isbn'] or self._arguments['-i']:
         header_type += ['t']
         header += ['Isbn']
     table.set_cols_dtype(header_type)
     table.header(header)
     for author, title, isbn in results:
         if isbn is None:
             isbn = ""
         row = [author.encode('utf-8'), title.encode('utf-8')]
         if self._configuration['list']['isbn'] or self._arguments['-i']:
             row += [isbn.encode('utf-8')]
         table.add_row(row)
     self.out(table.draw())
예제 #33
0
def render_text_table(sheet, write_title):
    """return data in text table presentation"""
    content = ""
    if write_title:
        content += "%s:\n" % sheet.name
    table = Texttable(max_width=0)
    data = sheet.to_array()
    if isinstance(data, GeneratorType):
        data = list(data)
    if len(data) == 0:
        return content
    table.set_cols_dtype(['t'] * len(data[0]))
    if len(sheet.colnames) > 0:
        table.set_chars(['-', '|', '+', '='])
        table.header(list(_cleanse_a_row(data[0])))
    else:
        table.add_row(list(_cleanse_a_row(data[0])))
    for sub_array in data[1:]:
        new_array = _cleanse_a_row(sub_array)
        table.add_row(list(new_array))
    content += table.draw()
    return content
예제 #34
0
def render_text_table(sheet, write_title):
    """return data in text table presentation"""
    content = ""
    if write_title:
        content += "%s:\n" % sheet.name
    table = Texttable(max_width=0)
    data = sheet.to_array()
    if isinstance(data, GeneratorType):
        data = list(data)
    if len(data) == 0:
        return content
    table.set_cols_dtype(['t'] * len(data[0]))
    if len(sheet.colnames) > 0:
        table.set_chars(['-', '|', '+', '='])
        table.header(list(_cleanse_a_row(data[0])))
    else:
        table.add_row(list(_cleanse_a_row(data[0])))
    for sub_array in data[1:]:
        new_array = _cleanse_a_row(sub_array)
        table.add_row(list(new_array))
    content += table.draw()
    return content
예제 #35
0
파일: tabular.py 프로젝트: hasetz/gap_sdk
    def render(self, table):

        writer = Texttable(self._maxwidth)
        if self._chars:
            writer.set_chars(self._chars)

        current_header = None

        for row in table.rows:
            if current_header is None and row and\
                isinstance(row[0], AbstractTabularColumn):
                current_header = row
                headers = []
                align = []
                valign = []
                dtype = []
                for header in current_header:
                    for header_elem in header.contents:
                        if header_elem.show:
                            headers.append(header_elem.header_fmt.apply(header_elem.name))
                        else:
                            headers.append("")
                        align.append(get_textable_align(header_elem.fmt))
                        valign.append(get_textable_valign(header_elem.valign))
                        dtype.append(get_textable_dtype(header_elem.fmt))

                writer.header(headers)
                writer.set_cols_align(align)
                writer.set_cols_dtype(dtype)
                writer.set_cols_valign(valign)
                continue
            if not row:
                writer.add_row([""]*0)
                continue
            writer.add_row(row)

        self._output = writer.draw()
예제 #36
0
파일: dep.py 프로젝트: gpetruc/ipbb
def report(env, filters):
    '''Summarise the dependency tree of the current project'''

    lCmdHeaders = ['path', 'flags', 'package', 'component', 'map', 'lib']

    lFilterFormat = re.compile('([^=]*)=(.*)')
    lFilterFormatErrors = []
    lFilters = []

    # print ( filters )

    for f in filters:
        m = lFilterFormat.match(f)
        if not m:
            lFilterFormatErrors.append(f)
        # print (m.group(1))

        try:
            i = lCmdHeaders.index(m.group(1))
            r = re.compile(m.group(2))
            lFilters.append((i, r))
        except RuntimeError as e:
            lFilterFormatErrors.append(f)

    if lFilterFormatErrors:
        raise click.ClickException(
            "Filter syntax errors: " +
            ' '.join(['\'' + e + '\'' for e in lFilterFormatErrors]))
    # return
    lParser = env.depParser

    # lTitle = Texttable(max_width=0)
    # lTitle.header(['Commands'])
    # lTitle.set_chars(['-', '|', '+', '-'])
    # lTitle.set_deco(Texttable.BORDER)
    # secho(lTitle.draw(), fg='blue')

    echo()
    secho('* Parsed commands', fg='blue')

    lPrepend = re.compile('(^|\n)')
    for k in lParser.CommandList:
        echo('  + {0} ({1})'.format(k, len(lParser.CommandList[k])))
        if not lParser.CommandList[k]:
            echo()
            continue

        lCmdTable = Texttable(max_width=0)
        lCmdTable.header(lCmdHeaders)
        lCmdTable.set_deco(Texttable.HEADER | Texttable.BORDER)
        lCmdTable.set_chars(['-', '|', '+', '-'])
        for lCmd in lParser.CommandList[k]:
            # print(lCmd)
            # lCmdTable.add_row([str(lCmd)])
            lRow = [
                relpath(lCmd.FilePath, env.workPath),
                ','.join(lCmd.flags()),
                lCmd.Package,
                lCmd.Component,
                lCmd.Map,
                lCmd.Lib,
            ]

            if lFilters and not all(
                [rxp.match(lRow[i]) for i, rxp in lFilters]):
                continue

            lCmdTable.add_row(lRow)

        echo(lPrepend.sub('\g<1>  ', lCmdTable.draw()))
        echo()

    string = ''

    string += '+----------------------------------+\n'
    string += '|  Resolved packages & components  |\n'
    string += '+----------------------------------+\n'
    string += 'packages: ' + str(list(lParser.Components.iterkeys())) + '\n'
    string += 'components:\n'
    for pkg in sorted(lParser.Components):
        string += '+ %s (%d)\n' % (pkg, len(lParser.Components[pkg]))
        for cmp in sorted(lParser.Components[pkg]):
            string += '  > ' + str(cmp) + '\n'

    if lParser.NotFound:
        string += '\n'
        string += '+----------------------------------------+\n'
        string += '|  Missing packages, components & files  |\n'
        string += '+----------------------------------------+\n'

        if lParser.PackagesNotFound:
            string += 'packages: ' + \
                str(list(lParser.PackagesNotFound)) + '\n'

        # ------
        lCNF = lParser.ComponentsNotFound
        if lCNF:
            string += 'components: \n'

            for pkg in sorted(lCNF):
                string += '+ %s (%d)\n' % (pkg, len(lCNF[pkg]))

                for cmp in sorted(lCNF[pkg]):
                    string += '  > ' + str(cmp) + '\n'
        # ------

        # ------
    echo(string)

    lFNF = lParser.FilesNotFound

    if lFNF:

        lFNFTable = Texttable(max_width=0)
        lFNFTable.header(
            ['path expression', 'package', 'component', 'included by'])
        lFNFTable.set_deco(Texttable.HEADER | Texttable.BORDER)

        for pkg in sorted(lFNF):
            lCmps = lFNF[pkg]
            for cmp in sorted(lCmps):
                lPathExps = lCmps[cmp]
                for pathexp in sorted(lPathExps):

                    lFNFTable.add_row([
                        relpath(pathexp, env.workPath),
                        pkg,
                        cmp,
                        '\n'.join([
                            relpath(src, env.workPath)
                            for src in lPathExps[pathexp]
                        ]),
                    ])
        echo(lPrepend.sub('\g<1>  ', lFNFTable.draw()))
예제 #37
0
'''
Just a small example on how to use the Refprop class to calculate a power cycle.
This file employs a working fluid mixture at supercritical conditions.
'''
from texttable import Texttable
# Define output routines for pretty-printing
pointsTable = Texttable()
pointsTable.set_deco(Texttable.HEADER)
pointsTable.set_chars(['-', '|', '+', '='])
pointsTable.set_cols_dtype(['t',  # text
                      'f',  # float (decimal) 
                      'f',  # float (decimal) 
                      'f',  # float (decimal) 
                      'f']) # float (decimal)
pointsTable.set_cols_align(["l", "r", "r", "r", "r"])
pointsTable.set_cols_valign(["t", "m", "m", "m", "m"])
#pointsTable.set_cols_width([10, 12, 13, 13, 13])
pointsTable.header(["Point","Temperature, C","Pressure, bar","Enthalpy, kJ/kg","Entropy, kJ/kg-K"])

# Define output routines for pretty-printing
paramsTable = Texttable()
paramsTable.set_deco(Texttable.HEADER)
paramsTable.set_chars(['-', '|', '+', '='])
paramsTable.set_cols_dtype(['t',  # text
                      'f',  # float (decimal)  
                      't']) # text
paramsTable.set_cols_align(["l", "r", "l"])
paramsTable.set_cols_valign(["t", "m", "m"])
#paramsTable.set_cols_width([20, 15, 15])
paramsTable.header(["Parameter","Value","Unit"])
예제 #38
0
    plt.ylim(0, .6)
    plt.legend(loc=0, prop={'size': 10})
    plt.show()


if __name__ == '__main__':
    N, Tf, Tr = 5, 1, 1/8
    S_1, S_2 = 2, 3
    op_1, op_2 = 1, 2
    Iter = 10000
    table_1, table_2, table_3 = Texttable(), Texttable(), Texttable()
    color_1, color_2, color_3 = '#0A4D6D', '#FF0000', '#6272A4'
    title = ['Iter', 'mu', 'sigma^2', 'sigma']

    # Configure tables
    table_1.set_chars(['', '&', '', '='])
    table_2.set_chars(['', '&', '', '='])
    table_3.set_chars(['', '&', '', '='])
    table_1.add_row(title)
    table_2.add_row(title)
    table_3.add_row(title)

    # Exercice 1
    values_1, mean_1, variance_1, Iter_1 = simulation(experiment, N, S_1, Tf,
                                                      Tr, op_1)
    std_dev_1 = sqrt(variance_1)
    table_1.add_row([str(Iter_1), str(mean_1), str(variance_1),
                    str(std_dev_1)])

    # Exercice 2
    values_2, mean_2, variance_2, Iter_2 = simulation(experiment, N, S_1, Tf,
예제 #39
0
def show_incident():
    global args
    global db
    if args.incident not in db:
        print("# cannot find {}".format(args.incident))
        sys.exit(-1)
    #print(json.dumps(db[args.incident],indent=2,sort_keys=True))
    cout = ""
    mout = ""
    wout = "<html>\n<header>\n"
    wout += "<tt>\n"
    i = db[args.incident]
    mout += "## {}\n".format(i["brief"])
    mout += "### {} \n".format(i["incident_number"])
    mout += "| __meta__ | __value__ |\n"
    mout += "| ---- | ---- |\n"
    cout += "# ({}) {}\n\n".format(i["incident_number"], i["brief"])
    wout += "<title>{} Postmortem</title>\n".format(i["incident_number"])
    wout += "<h2>{} - {}</h2>\n".format(i["incident_number"], i["brief"])
    wout += "</header>\n"
    wout += "<table>\n"
    mout += "|{}|{}|\n".format("CreateTime", i["create_time"])
    cout += "Create_time :\n    {}\n".format(i["create_time"])
    wout += "<tr><td><b>CreateTime</b></td><td>{}</td></tr>\n".format(
        i["create_time"])
    for keym in [
            "OncallOps", "Status", "Impact", "RootCause", "DurationOfProblem",
            "ServiceImpacted", "%Impacted", "UserImpact", "RevenueImpact",
            "HowToRepeat", "Resolution", "References", "LessonLearned",
            "ActionItem", "KeywordsForSearch"
    ]:
        if keym in i and i[keym]:
            cout += "{} : \n".format(keym)
            cout += "    {}\n".format(i[keym])
            wout += "<tr><td><b>{}</b></td><td>{}</td></tr>\n".format(
                keym, i[keym])
            mout += "| {} | {} |\n".format(keym, i[keym])
        else:
            if args.post:
                i[keym] = input("# {}=".format(keym))
                cout += "{} : \n".format(keym)
                cout += "    {}\n".format(i[keym])
                wout += "<tr><td><b>{}</b></td><td>{}</td></tr>\n".format(
                    keym, i[keym])
                mout += "| {} | {} |\n".format(keym, i[keym])
                closedb()
    wout += "</table>\n"
    if args.json:
        print(json.dumps(i, indent=2, sort_keys=True))
        return
    cout += "\n\n# timeline   : \n"
    wout += "<h2>Timeline    :</h2>\n"
    mout += "\n\n"
    mout += "### {} \n".format("Timeline :")
    mout += "| __datetime__ | __brief__ | __detail__ | \n"
    mout += "| ---- | ---- | ---- | \n"
    #wout += "<table style=\"border-collapse: collapse;border: 1px;\">\n"
    wout += "<table border=1 style=\"border-collapse: collapse;\">\n"
    wout += "<tr style=\"background-color:#F3F3F3\"><th>update_time</th><th>brief</th><th>detail</th></tr>\n"
    table = Texttable()
    table.set_header_align(['l', 'l', 'l'])
    table.set_cols_align(['l', 'l', 'l'])
    table.set_chars([' ', ' ', ' ', '-'])
    maxw = 0
    for x in [ u.get("xcontent","") for u in i.get("updates",dict()) ] :
        for l in x.splitlines() :
            if len(l) > maxw :
                maxw = len(l)
    table.set_cols_width([12, 25, maxw+1])
    rows = list()
    rows.append(["update_time", "brief", "detail"])
    for u in sorted(i.get("updates", []),
                    key=lambda x: x["create_time"],
                    reverse=True):
        rows.append([
            u["create_time"][:-3], u["update_content"],
            u.get("xcontent", "")
        ])
        mout += "| {} | {} | <pre>{}</pre> | \n".format(
            u["create_time"][:-3], u["update_content"],
            re.sub(
                r"([\\\`\*\_\{\}\[\]\(\)#+-.!|])", r"\\\1",
                u.get("xcontent", "").replace("\n",
                                              "</br>").replace("~", "\$HOME")))
        wout += "<tr>\n"
        for val in [
                u["create_time"][:-3], u["update_content"],
                u.get("xcontent", "")
        ]:
            wout += "<td>{}</td>\n".format(
                val.replace("\n", "</br>").replace(" ", "&nbsp;"))
        wout += "</tr>\n"

    mout += "\n\n"
    table.add_rows(rows)
    stbl = table.draw()
    stbl = "\n".join([re.sub(r"\s+$", "", ln) for ln in stbl.splitlines()])
    cout += stbl + "\n"
    wout += "</table>\n"
    wout += "</html>\n"
    if args.export:
        if args.expand:
            incdir = args.incident + "." + "".join(
                c for c in re.sub(r"\s+", ".", i["brief"])
                if c in set(string.ascii_letters + string.digits + "_-."))
        else:
            incdir = args.incident
        if not os.path.exists(incdir):
            os.mkdir(incdir)
        with open("{}/{}.html".format(incdir, args.incident), "w") as f:
            f.write(wout)
        with open("{}/{}.txt".format(incdir, args.incident), "w") as f:
            f.write(cout)
        with open("{}/{}.md".format(incdir, args.incident), "w") as f:
            f.write(mout)
        with open("{}/{}.json".format(incdir, args.incident), "w") as f:
            f.write(json.dumps(db[args.incident], indent=2, sort_keys=True))
        sys.exit(0)
    if args.html:
        print(wout)
    elif args.markdown:
        print(mout)
    else:
        print(cout)