def test_single_line():
    """Test single-lined cells."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
        ['Watermelon', 'green'],
        [],
    ]
    table = GithubFlavoredMarkdownTable(table_data)
    table.inner_footing_row_border = True
    table.justify_columns[0] = 'left'
    table.justify_columns[1] = 'center'
    table.justify_columns[2] = 'right'
    actual = table.table

    expected = (
        '| Name       | Color |      Type |\n'
        '|:-----------|:-----:|----------:|\n'
        '| Avocado    | green |       nut |\n'
        '| Tomato     |  red  |     fruit |\n'
        '| Lettuce    | green | vegetable |\n'
        '| Watermelon | green |           |\n'
        '|            |       |           |'
    )
    assert actual == expected
示例#2
0
def handle_tables(table_data: list):
    """Creates a table for all the list data is passed to it
        :table_data: Data in a list format.
    """
    table = GFMT(table_data)
    table.inner_row_border = True
    table = table = "{}".format(table.table)
    return table
示例#3
0
async def scores(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't show your scores in public channels..."
    ):
        return

    if ctfRunning() == False:
        await ctx.send("CTF isn't running yet")
        return

    # individual score
    msg = ''
    with db.db_session:
        user = db.User.get(name=username(ctx))  #simpler

        individual_points = db.getScore(user)
        if SETTINGS['_debug'] == True and SETTINGS['_debug_level'] == 2:
            logger.debug(f'{user.name} individual points {individual_points}')

        # teammates scores
        teammates = db.getTeammateScores(user)
        teammates = sorted(teammates, key=lambda x: x[1], reverse=True)
        teammates.insert(0, ['Teammate', 'Score'])
        table = GithubFlavoredMarkdownTable(teammates)

        team_points = sum([v for k, v in teammates[1:]])  #skip header

        msg += f'Your score is `{individual_points}`\n'
        msg += f'\nTeam `{user.team.name}` has `{team_points}` ```{table.table}```'

        if SETTINGS['scoreboard'] == 'public':
            #top 3 team scores
            scores = db.getTopTeams(
                num=SETTINGS['_scoreboard_size'])  # private settings with _
            scores.insert(0, ['Team Name', 'Score'])
            table = GithubFlavoredMarkdownTable(scores)

            msg += f'Top {SETTINGS["_scoreboard_size"]} Team scores \n```{table.table}```'
        else:
            msg += f"Scoreboard is set to private\n"

        if SETTINGS['_show_mvp'] == True:
            # top players in the game
            topPlayers = db.topPlayers(num=SETTINGS['_mvp_size'])
            data = [(p.name, p.team.name, v) for p, v in topPlayers]
            data.insert(0, ['Player', 'Team', 'Score'])
            table = GithubFlavoredMarkdownTable(data)
            table = GithubFlavoredMarkdownTable(data)
            msg += f'Top {SETTINGS["_mvp_size"]} Players\n```{table.table}```'
        else:
            msg += f"MVP is set to False    "

        await ctx.send(msg)
示例#4
0
def test_multi_line():
    """Test multi-lined cells."""
    table_data = [
        ['Show', 'Characters'],
        [
            'Rugrats',
            'Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles,\nDil Pickles'
        ],
        [
            'South Park',
            'Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick'
        ]
    ]
    table = GithubFlavoredMarkdownTable(table_data)

    # Test defaults.
    actual = table.table
    expected = (
        '| Show       | Characters                                                                          |\n'
        '|------------|-------------------------------------------------------------------------------------|\n'
        '| Rugrats    | Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, |\n'
        '|            | Dil Pickles                                                                         |\n'
        '| South Park | Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          |'
    )
    assert actual == expected

    # Test inner row border.
    table.inner_row_border = True
    actual = table.table
    expected = (
        '| Show       | Characters                                                                          |\n'
        '|------------|-------------------------------------------------------------------------------------|\n'
        '| Rugrats    | Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, |\n'
        '|            | Dil Pickles                                                                         |\n'
        '| South Park | Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          |'
    )
    assert actual == expected

    # Justify right.
    table.justify_columns = {1: 'right'}
    actual = table.table
    expected = (
        '| Show       |                                                                          Characters |\n'
        '|------------|------------------------------------------------------------------------------------:|\n'
        '| Rugrats    | Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, |\n'
        '|            |                                                                         Dil Pickles |\n'
        '| South Park |                          Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick |'
    )
    assert actual == expected
def test_simple():
    """Simple GithubFlavoredMarkdownTable test."""
    table_data = [
        ["Name", "Color", "Type"],
        ["Avocado", "green", "nut"],
        ["Tomato", "red", "fruit"],
        ["Lettuce", "green", "vegetable"],
    ]
    table = GithubFlavoredMarkdownTable(table_data)

    expected = (
        "| Name    | Color | Type      |\n"
        "|---------|-------|-----------|\n"
        "| Avocado | green | nut       |\n"
        "| Tomato  | red   | fruit     |\n"
        "| Lettuce | green | vegetable |"
    )
    assert expected == table.table

    table.justify_columns[0] = "center"
    expected = (
        "|   Name  | Color | Type      |\n"
        "|:-------:|-------|-----------|\n"
        "| Avocado | green | nut       |\n"
        "|  Tomato | red   | fruit     |\n"
        "| Lettuce | green | vegetable |"
    )
    assert expected == table.table

    table.justify_columns[1] = "left"
    expected = (
        "|   Name  | Color | Type      |\n"
        "|:-------:|:------|-----------|\n"
        "| Avocado | green | nut       |\n"
        "|  Tomato | red   | fruit     |\n"
        "| Lettuce | green | vegetable |"
    )
    assert expected == table.table

    table.justify_columns[2] = "right"
    expected = (
        "|   Name  | Color |      Type |\n"
        "|:-------:|:------|----------:|\n"
        "| Avocado | green |       nut |\n"
        "|  Tomato | red   |     fruit |\n"
        "| Lettuce | green | vegetable |"
    )
    assert expected == table.table
示例#6
0
async def logs(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't dump logs in public channels..."):
        return

    msg = "Your Transaction Log"
    with db.db_session:
        ts = list(
            db.select((t.value, t.type, t.sender.name, t.recipient.name,
                       t.message, t.time) for t in db.Transaction
                      if username(ctx) == t.recipient.name
                      or username(ctx) == t.sender.name))

    ts.insert(0, ["Value", 'Type', 'Sender', 'Recipient', 'Message', 'Time'])
    table = GithubFlavoredMarkdownTable(ts)

    if len(msg + table.table) >= 2000:
        # logger.debug(f'table > 2000 : {len(table.table)} {table.table}')

        await sendBigMessage(ctx, f'{msg}\n{table.table}')
    else:
        msg += f'```{table.table}```'
        await ctx.send(msg)
示例#7
0
async def show_hints(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't show your hints in public channels..."
    ):
        return

    if ctfRunning() == False:
        await ctx.send("CTF isn't running yet")
        return

    with db.db_session:
        user = db.User.get(name=username(ctx))
        hint_transactions = db.getHintTransactions(user)

        msg = f"Team {user.team.name}'s hints:\n"

        data = []
        teammates = db.getTeammates(
            user)  # throws an error about db session is over

        for tm in teammates:
            tm_hints = db.getHintTransactions(tm)
            data += [(ht.hint.challenge.id, ht.hint.text, ht.hint.cost,
                      ht.sender.name) for ht in tm_hints]

        data.insert(0, ['Chall_ID', 'Hint', 'Cost', 'Purchaser'])
        table = GithubFlavoredMarkdownTable(data)

    await sendBigMessage(ctx, f'{msg}{table.table}')
示例#8
0
def do_sqlite_run(sql_text):
    """
    Run this query over a sqlite database.
    This is just for debugging purposes
    """
    from terminaltables import GithubFlavoredMarkdownTable
    from sqlalchemy import (
        MetaData,
        create_engine,
    )
    engine = create_engine('sqlite:///:memory:', echo=False)
    metadata = MetaData()
    tables = []
    for name, t in table._tables.items():
        if name not in ['OneToTen', 'TestB', 'TwoToTwentyInTwos']:
            continue
        if name in ['Table']:
            continue
        t_sqla = t().to_sqlalchemy(metadata)
        t_sqla.sqlhild = t()
        tables.append(t_sqla)
    metadata.create_all(engine)

    conn = engine.connect()

    # Populate tables
    for t in tables:
        fields = [column.name for column in t.columns]
        for row in list(t.sqlhild.produce()):
            conn.execute(t.insert().values(dict(zip(fields, row))))

    r = list(conn.execute(sql_text))

    print(GithubFlavoredMarkdownTable(r).table)
    return r
示例#9
0
async def list_unsolved(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't view challenges in public channels..."
    ):
        return

    if ctfRunning() == False:
        await ctx.send("CTF isn't running yet")
        return

    with db.db_session:
        user = db.User.get(name=username(ctx))
        challs = db.get_unsolved_challenges(user)

        # logger.debug(challs)

        res = []
        for c in challs:
            if c.author not in db.getTeammates(
                    user
            ):  # you can't solve your teammates challenges, so don't show them.
                res.append([c.id, c.author.name, c.title])

    res.insert(0, ['ID', "Author", "Title"])
    table = GithubFlavoredMarkdownTable(res)

    # logger.debug("discord",challs)\
    msg = f'Showing all unsolved challenges```{table.table}```'

    await ctx.send(msg)
def results2markdown(result_dict):
    table_data = []
    is_multiple_results = False
    for cfg_name, value in result_dict.items():
        name = cfg_name.replace('configs/', '')
        fps = value['fps']
        ms_times_pre_image = value['ms_times_pre_image']
        if isinstance(fps, list):
            is_multiple_results = True
            mean_fps = value['mean_fps']
            mean_times_pre_image = value['mean_times_pre_image']
            fps_str = ','.join([str(s) for s in fps])
            ms_times_pre_image_str = ','.join(
                [str(s) for s in ms_times_pre_image])
            table_data.append([
                name, fps_str, mean_fps, ms_times_pre_image_str,
                mean_times_pre_image
            ])
        else:
            table_data.append([name, fps, ms_times_pre_image])

    if is_multiple_results:
        table_data.insert(0, [
            'model', 'fps', 'mean_fps', 'times_pre_image(ms)',
            'mean_times_pre_image(ms)'
        ])

    else:
        table_data.insert(0, ['model', 'fps', 'times_pre_image(ms)'])
    table = GithubFlavoredMarkdownTable(table_data)
    print(table.table, flush=True)
示例#11
0
def debug_description(description_kv, markdown=True):
    # always sort of the dictionary for consistency.
    sorted_description_kv = sorted(description_kv.items(),
                                   key=lambda kv: kv[0])
    description_rows = [["name", "value"]] + map(
        lambda kv: [str(kv[0]), str(kv[1])], sorted_description_kv)

    if markdown:
        description_table = GithubFlavoredMarkdownTable(description_rows)
    else:
        description_table = AsciiTable(description_rows)

        description_table.inner_heading_row_border = False
        description_table.outer_border = False

    return str(description_table.table)
def test_multi_line():
    """Test multi-lined cells."""
    table_data = [
        ['Show', 'Characters'],
        ['Rugrats', 'Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles,\nDil Pickles'],
        ['South Park', 'Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick']
    ]
    table = GithubFlavoredMarkdownTable(table_data)

    # Test defaults.
    actual = table.table
    expected = (
        '| Show       | Characters                                                                          |\n'
        '|------------|-------------------------------------------------------------------------------------|\n'
        '| Rugrats    | Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, |\n'
        '|            | Dil Pickles                                                                         |\n'
        '| South Park | Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          |'
    )
    assert actual == expected

    # Test inner row border.
    table.inner_row_border = True
    actual = table.table
    expected = (
        '| Show       | Characters                                                                          |\n'
        '|------------|-------------------------------------------------------------------------------------|\n'
        '| Rugrats    | Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, |\n'
        '|            | Dil Pickles                                                                         |\n'
        '| South Park | Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          |'
    )
    assert actual == expected

    # Justify right.
    table.justify_columns = {1: 'right'}
    actual = table.table
    expected = (
        '| Show       |                                                                          Characters |\n'
        '|------------|------------------------------------------------------------------------------------:|\n'
        '| Rugrats    | Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, |\n'
        '|            |                                                                         Dil Pickles |\n'
        '| South Park |                          Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick |'
    )
    assert actual == expected
示例#13
0
    def produce(self):
        data = list(self.sources[0].produce())
        self.seen = len(data)

        # Headers
        # TODO: if there is just one table ignore the full column name
        try:
            data.insert(0, [c.name for c in self.sources[0].columns.columns])
        except AttributeError:
            data.insert(0, ['unknown' for c in self.sources[0].columns.columns])

        yield GithubFlavoredMarkdownTable(data).table
示例#14
0
def test_simple():
    """Simple GithubFlavoredMarkdownTable test."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
    ]
    table = GithubFlavoredMarkdownTable(table_data)

    expected = ('| Name    | Color | Type      |\n'
                '|---------|-------|-----------|\n'
                '| Avocado | green | nut       |\n'
                '| Tomato  | red   | fruit     |\n'
                '| Lettuce | green | vegetable |')
    assert expected == table.table

    table.justify_columns[0] = 'center'
    expected = ('|   Name  | Color | Type      |\n'
                '|:-------:|-------|-----------|\n'
                '| Avocado | green | nut       |\n'
                '|  Tomato | red   | fruit     |\n'
                '| Lettuce | green | vegetable |')
    assert expected == table.table

    table.justify_columns[1] = 'left'
    expected = ('|   Name  | Color | Type      |\n'
                '|:-------:|:------|-----------|\n'
                '| Avocado | green | nut       |\n'
                '|  Tomato | red   | fruit     |\n'
                '| Lettuce | green | vegetable |')
    assert expected == table.table

    table.justify_columns[2] = 'right'
    expected = ('|   Name  | Color |      Type |\n'
                '|:-------:|:------|----------:|\n'
                '| Avocado | green |       nut |\n'
                '|  Tomato | red   |     fruit |\n'
                '| Lettuce | green | vegetable |')
    assert expected == table.table
示例#15
0
def test_single_line():
    """Test single-lined cells."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
        ['Watermelon', 'green'],
        [],
    ]
    table = GithubFlavoredMarkdownTable(table_data)
    table.inner_footing_row_border = True
    table.justify_columns[0] = 'left'
    table.justify_columns[1] = 'center'
    table.justify_columns[2] = 'right'
    actual = table.table

    expected = ('| Name       | Color |      Type |\n'
                '|:-----------|:-----:|----------:|\n'
                '| Avocado    | green |       nut |\n'
                '| Tomato     |  red  |     fruit |\n'
                '| Lettuce    | green | vegetable |\n'
                '| Watermelon | green |           |\n'
                '|            |       |           |')
    assert actual == expected
示例#16
0
async def byoc_stats(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't submit a challenge in public channels..."
    ):
        return

    msg = ''
    with db.db_session:
        user = db.User.get(name=username(ctx))
        team_challs = list(
            db.select(c for c in db.Challenge
                      if c.author in db.getTeammates(user)))

        # num solves per challenge
        stats = []
        for chall in team_challs:
            num_solves = list(
                db.select(s for s in db.Solve if s.challenge == chall))

            chall_rewards = sum(
                db.select(
                    sum(t.value) for t in db.Transaction
                    if t.type == "byoc reward"
                    and t.recipient in db.getTeammates(user)
                    and t.challenge == chall).without_distinct())

            line = [
                chall.id, chall.title,
                len(num_solves), chall.author.name, chall_rewards
            ]

            stats.append(line)
        stats.insert(0, ['Chall ID', 'Title', '# Solves', 'Author', 'Payout'])

        table = GithubFlavoredMarkdownTable(stats)

        # team total byoc rewards sum
        total_byoc_rewards = sum(
            db.select(
                sum(t.value) for t in db.Transaction if t.type == "byoc reward"
                and t.recipient in db.getTeammates(user)))

    await ctx.send(
        f"Your stats ```{table.table}```\n**Team Total BYOC Rewards:** `{total_byoc_rewards}` points"
    )
示例#17
0
async def ctfstatus(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't view ctf status info in public channels..."
    ):
        return

    data = [(k, SETTINGS[k]) for k in SETTINGS.iterkeys() if k[0] != '_'
            ]  # filter out the private settings; see settings.py config object
    data.insert(0, ['Setting', 'Value'])
    table = GithubFlavoredMarkdownTable(data)
    await ctx.send(f'CTF Status ```{table.table}```')
示例#18
0
def create_table(
        conversion: str,
        s3_stats: typing.Sequence[BucketStats]) -> GithubFlavoredMarkdownTable:
    """
    creates final display table
    :param conversion: convert to ki, Mi and Gi
    :param s3_stats: List[BucketStats] calculated from get_bucket_stats
    """
    converter = DisplayConverter(conversion)
    header = [field for field in s3_stats[0].fields]
    table_data = [header]
    for stats in s3_stats:
        table_row = [str(value) if key != 'total_file_size' else str(converter.convert(value)) \
                         for key, value in zip(header, stats.props)]
        table_data.append(table_row)
    return GithubFlavoredMarkdownTable(table_data)
示例#19
0
    def make_table(self, filepath: str, counter: Dict[Tuple[str, str], int], keys: Dict[str, Set[str]]):
        header = [
            ["Lemma", "Categories(Occurrences)"]
        ]
        data = [
            [lemma, ", ".join([
                "{}({})".format(index, counter[(lemma, index)])
                for index in sorted(set_of_index, key=lambda index: counter[(lemma, index)])[::-1]
            ])]
            for lemma, set_of_index in keys.items()
        ]
        data = sorted(data,
                      key=lambda elem: "{categories:02d}{lemma}".format(categories=elem[1].count(","), lemma=elem[0]))
        table = GithubFlavoredMarkdownTable(header + data)

        with open(filepath, "w") as f:
            f.write(table.table)
示例#20
0
async def public_solves(ctx, chall_id: int = 0):
    if await isRegistered(ctx) == False:
        return
    if await inPublicChannel(
            ctx,
            msg=f"Hey, <@{ctx.author.id}>, don't dump logs public channels..."
    ):
        return

    with db.db_session:
        if chall_id > 0:
            if SETTINGS['scoreboard'] == 'public':
                logs = list(
                    db.select(
                        (t.recipient.team.name, t.recipient.name,
                         t.challenge.title, t.value, t.time)
                        for t in db.Transaction
                        if t.type == 'solve' and t.challenge.id == chall_id))
                logs.insert(
                    0, ['Team', 'Recipient', 'Challenge', 'Amount', 'Time'])
            else:
                logs = list(
                    db.select(
                        (t.recipient.team.name, t.recipient.name,
                         t.challenge.name, t.time) for t in db.Transaction
                        if t.type == 'solve' and t.challenge.id == chall_id))
                logs.insert(0, ['Team', 'Recipient', 'Challenge', 'Time'])
        else:
            if SETTINGS['scoreboard'] == 'public':
                logs = list(
                    db.select((t.recipient.team.name, t.recipient.name,
                               t.challenge.title, t.value, t.time)
                              for t in db.Transaction if t.type == 'solve'))
                logs.insert(
                    0, ['Team', 'Recipient', 'Challenge', 'Amount', 'Time'])
            else:
                logs = list(
                    db.select((t.recipient.team.name, t.recipient.name,
                               t.challenge.name, t.time)
                              for t in db.Transaction if t.type == 'solve'))
                logs.insert(0, ['Team', 'Recipient', 'Challenge', 'Time'])

    table = GithubFlavoredMarkdownTable(logs)
    await sendBigMessage(
        ctx, f"Public Log of Solves for all challenges:\n\n{table.table}")
示例#21
0
def exp(projects):
    result = {}
    for name in projects:
        # print(name)
        result[name] = experiment(name, f'./styler/{name}-corpus')
    # json_pp(result)
    keys = list(list(result.values())[0].keys())
    result = {
        project: {tool: len(repair)
                  for tool, repair in p_results.items()}
        for project, p_results in result.items()
    }
    result['total'] = {
        key: sum([e[key] for e in result.values()])
        for key in keys
    }
    #json_pp(total)
    table = [[''] + keys]
    table += [[key] + list(values.values()) for key, values in result.items()]
    print(GithubFlavoredMarkdownTable(table).table)
示例#22
0
def contest(number, all):
    number = max(number, 1)
    data = json.loads(
        requests.get("http://codeforces.com/api/contest.list").text)
    contests = data['result'][:min(len(data['result']), number
                                   )] if not all else data['result']
    table_data = [['ID', 'Contest Name', 'Status']]
    for x in contests:
        idx = str(x['id'])
        name = '\n'.join(textwrap.wrap(x['name'], 50))
        data = [
            Color('{autogreen}' + idx + '{/autogreen}'), name,
            Color('{autored}' + x['phase'] +
                  '{/autored}') if x['phase'] != 'BEFORE' else
            Color('{autogreen}' +
                  time.strftime('%Y-%m-%d %H-%M-%S %Z',
                                time.localtime(x['startTimeSeconds'])) +
                  '{/autogreen}')
        ]
        table_data.append(data)
    print(GithubFlavoredMarkdownTable(table_data).table)
示例#23
0
async def solves(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't show your flags in public channels..."
    ):
        return

    with db.db_session:
        user = db.User.get(name=username(ctx))

        msg = f"`{user.team.name}`'s solves "

        teammates = db.getTeammates(user)
        solved = []
        for teammate in teammates:
            solved += list(
                db.select(solve for solve in db.Solve
                          if teammate.name == solve.user.name))

        res = []
        for solve in solved:
            line = (solve.flag_text, solve.challenge.id, solve.challenge.title,
                    solve.user.name, solve.time)
            res.append(line)

        res.insert(0,
                   ["Flag", "Chall ID", "Chall Title", "User", "Solve Time"])
        table = GithubFlavoredMarkdownTable(res)

        if len(msg + table.table) >= 2000:
            await sendBigMessage(ctx, f'{msg}\n{table.table}')
        else:
            msg += f"```{table.table}```"
            await ctx.send(msg)
示例#24
0
async def public_log(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=f"Hey, <@{ctx.author.id}>, don't dump logs public channels..."
    ):
        return
    with db.db_session:
        if SETTINGS['scoreboard'] == 'public':
            logs = list(
                db.select(
                    (t.sender.name, t.recipient.name, t.type, t.value, t.time)
                    for t in db.Transaction))
            logs.insert(0, ['Sender', 'Recipient', 'Type', 'Amount', 'Time'])
        else:
            logs = list(
                db.select((t.sender.name, t.recipient.name, t.type, t.time)
                          for t in db.Transaction))
            logs.insert(0, ['Sender', 'Recipient', 'Type', 'Time'])

    table = GithubFlavoredMarkdownTable(logs)
    await sendBigMessage(ctx, f"Public Log of Transactions:\n\n{table.table}")
示例#25
0
async def list_all(ctx, *, tags=None):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't view challenges in public channels..."
    ):
        return

    if ctfRunning() == False:
        await ctx.send("CTF isn't running yet")
        return

    with db.db_session:
        user = db.User.get(name=username(ctx))
        challs = db.get_all_challenges(user)
        # It'd be nice to show a percentage complete as well...
        #
        # don't show teammates challenges or your own challenges. !bstat to see yours. helps prevent a teammate working on your challenges when they couldn't submit it anyway.
        res = []
        if tags == None:
            res = [(c.id, c.author.name, c.title, db.challValue(c),
                    f"{db.percentComplete(c, user)}%", "*" * int(
                        db.avg(r.value
                               for r in db.Rating if r.challenge == c) or 0),
                    ', '.join([t.name for t in c.tags])) for c in challs
                   if c.id > 0 and c.author not in db.getTeammates(user)]

        else:
            tags = tags.split(' ')
            includes = [x for x in tags if x.startswith('!') == False]
            excludes = [x[1:] for x in tags if x.startswith('!')]

            if SETTINGS['_debug'] and SETTINGS['_debug_level'] >= 1:
                logger.debug(
                    f'tags: {tags}; filter including {includes}; excluding {excludes}'
                )

            for chall in challs:
                chall_tags = [t.name for t in chall.tags]

                if anyIn(
                        excludes, chall_tags
                ):  # kick it back if any of the excludes are in the chall_tags
                    continue

                if len(includes) > 0 and anyIn(
                        includes, chall_tags
                ) == False:  # if it doesn't have any of the includes, skip it.
                    continue

                if chall.id < 1 or chall.author in db.getTeammates(
                        user):  # other reasons to skip this challenge...
                    continue

                res += [[
                    chall.id, chall.author.name, chall.title,
                    db.challValue(chall),
                    f"{db.percentComplete(chall, user)}%", "*" * int(
                        db.avg(r.value
                               for r in db.Rating if r.challenge == chall)
                        or 0), ', '.join(chall_tags)
                ]]

    res.insert(0, ['ID', "Author", "Title", "Value", "Done", "Rating", "Tags"])
    table = GithubFlavoredMarkdownTable(res)
    # logger.debug("discord",challs)
    msg = f'Showing all unlocked challenges```{table.table}```'
    await ctx.send(msg)
示例#26
0
文件: starred.py 项目: tqdv/starred
def starred(username, token, sort, repository, message, output, http_proxy,
            https_proxy, launch, type):
    """GitHub starred

    creating your own Awesome List used GitHub stars!

    example:
        starred --username 1132719438 --output README.md
    """
    if output.strip():
        output = output.strip()
        output_path = os.path.split(output)[0]
        if output_path and not os.path.isdir(output_path):
            os.makedirs(output_path)
        output_file = open(output, "w", encoding='utf-8')
    else:
        output_file = None

    if repository:
        if not token:
            click.secho('Error: create repository need set --token',
                        fg='red',
                        file=sys.stderr)
            return
        repo_file = BytesIO()
        sys.stdout = repo_file
        # do not output to file when update repository
        output_file = None
    else:
        repo_file = None

    try:
        gh = GitHub(token=token)
        if http_proxy:
            gh.session.proxies['http://'] = http_proxy
            if https_proxy:
                gh.session.proxies['https://'] = https_proxy
            else:
                gh.session.proxies['https://'] = http_proxy

        stars = gh.starred_by(username)
    except ForbiddenError as e:
        click.secho('Error: talk to Github failed: {}'.format(e),
                    fg='red',
                    file=sys.stderr)
        return
    today = str(datetime.date.today())
    month = datetime.date.today().strftime('%Y%m')

    repo_dict = {}
    new_dict = {}

    # starred order
    star_order = 0
    for s in stars:
        language = s.language or 'Others'
        description = html_escape(s.description).replace(
            '\n', '') if s.description else ''
        if language not in repo_dict:
            repo_dict[language] = []
        repo_dict[language].append([
            s.name, s.html_url,
            description.strip(), s.owner.login, s.stargazers_count, star_order
        ])
        if language not in new_dict:
            new_dict[language] = []
        new_dict[language].append([s.name, s.html_url])
        star_order += 1

    repo_dict = OrderedDict(sorted(repo_dict.items(), key=lambda l: l[0]))
    new_dict = OrderedDict(sorted(new_dict.items(), key=lambda l: l[0]))

    # load prev repo dict and compare with new repo dict
    save_pkl = True
    cur_path = os.path.split(os.path.realpath(__file__))[0]
    repo_pkl_path = os.path.join(cur_path, 'starred-repo.pkl')
    if os.path.isfile(repo_pkl_path):
        with open(repo_pkl_path, 'rb') as file:
            old_dict = pickle.load(file, encoding='utf-8')
        if operator.eq(old_dict, new_dict):
            save_pkl = False
            if repo_file:
                click.secho(
                    'Error: starred repositories not change in {}'.format(
                        today),
                    fg='red',
                    file=sys.stderr)
                return

    if save_pkl:
        with open(repo_pkl_path, 'wb') as file:
            pickle.dump(new_dict, file)

    total = 0
    # sort by language and date
    if sort == 'date':
        for language in repo_dict:
            repo_dict[language] = sorted(repo_dict[language],
                                         key=lambda l: l[5])
            total += len(repo_dict[language])
    # sort by language and name
    elif sort == 'name':
        for language in repo_dict:
            repo_dict[language] = sorted(repo_dict[language],
                                         key=lambda l: l[0])
            total += len(repo_dict[language])
    # sort by language and stars
    else:
        for language in repo_dict:
            repo_dict[language] = sorted(repo_dict[language],
                                         key=lambda l: l[4],
                                         reverse=True)
            total += len(repo_dict[language])

    # desc
    count_badge_url = count_badge.format(count=total, color='green')
    date_badge_url = date_badge.format(today=today.replace('-', '--'),
                                       color='blue')
    click.echo(desc.format(badge_url=badge_url,
                           awesome_url=awesome_url,
                           github_url=github_url,
                           count_badge_url=count_badge_url,
                           date_badge_url=date_badge_url),
               file=output_file)

    # contents
    title_dict = {}
    for language in repo_dict.keys():
        title = '{} ({})'.format(language, len(repo_dict[language]))
        title_url = title2url(title)
        if title_url not in title_dict:
            title_dict[title_url] = 1
        else:
            cnt = title_dict[title_url]
            title_dict[title_url] += 1
            title_url = title_url + '-' + str(cnt)

        data = u'  - [{}](#{})'.format(title, title_url)
        click.echo(data, file=output_file)
    click.echo('', file=output_file)

    info_dict = {}
    for language in repo_dict:
        info_dict[language] = [
            [
                index + 1,  # index
                '[{}]({})'.format(repo[0], repo[1]),  # name with url
                repo[2],  # description
                repo[3],  # owner
                repo[4]
            ]  # stars
            for index, repo in enumerate(repo_dict[language])
        ]

    info_dict = OrderedDict(sorted(info_dict.items(), key=lambda l: l[0]))

    # repo
    for language in info_dict:
        count = len(info_dict[language])
        info_dict[language].insert(
            0, ['', 'Name', 'Description', 'Owner', 'Stars'])
        click.echo('## {} ({}) \n'.format(language, count), file=output_file)
        if type == 'table':
            table = GithubFlavoredMarkdownTable(info_dict[language])
            click.echo(table.table, file=output_file)
        else:
            for repo in repo_dict[language]:
                data = u'- [{}]({}) - {}'.format(*repo)
                click.echo(data, file=output_file)
        click.echo('', file=output_file)

    # license
    click.echo(license_.format(username=username), file=output_file)

    if repo_file:
        if not message:
            message = 'Add starred {}'.format(today)

        try:
            rep = gh.repository(username, repository)
            try:
                rep.file_contents('/Archives/{}/README-{}.md'.format(
                    month, today))
                click.secho(
                    'Error: already commit [/Archives/{}/README-{}.md]'.format(
                        month, today),
                    fg='red',
                    file=sys.stderr)
            except NotFoundError:
                readme = rep.readme()
                readme.update(message, repo_file.getvalue())
                rep.create_file(
                    'Archives/{}/README-{}.md'.format(month, today),
                    'Archive starred {}'.format(today), repo_file.getvalue())
        except NotFoundError:
            rep = gh.create_repository(repository,
                                       'A curated list of my GitHub stars!')
            rep.create_file('README.md', 'Add starred {}'.format(today),
                            repo_file.getvalue())
            rep.create_file('Archives/{}/README-{}.md'.format(month, today),
                            'Archive starred {}'.format(today),
                            repo_file.getvalue())
        if launch:
            click.launch(rep.html_url)
示例#27
0
    if (index > number_of_reps - 2):
        break

# Creating the table
table_data = [["" for x in range(len(names_of_props))]
              for y in range(number_of_reps + 1)]

for i in range(len(names_of_props)):
    table_data[0][i] = names_of_props[i]

for i in range(number_of_reps):
    for j in range(len(names_of_props)):
        table_data[i + 1][j] = results[i][j]

# Generating the ascii table
table = GithubFlavoredMarkdownTable(table_data)
table_str = table.table

# Writing the md file
with codecs.open(md_file_name, "w", "utf-8") as f:
    f.write(table_str)

labels = [i[1] for i in table_data if i[0] != 'Id']
for i in range(len(labels)):
    labels[i] = labels[i].partition('(')[0]
    labels[i] = labels[i][1:len(labels[i]) - 1]

valueStar = [i[4] for i in table_data if i[0] != 'Id']
valueFork = [i[5] for i in table_data if i[0] != 'Id']

dpi = 80
示例#28
0
        s = results[keyStdDev]
        #tableRow.append("{:10.2f}".format(m) + "/" + "{:10.2f}".format(s))
        tableRow.append("{:10.2f}".format(m))
        tableRowStdDev.append("{:10.2f}".format(s))

tableData.append(tableRow)
tableData.append(tableRowStdDev)

#from pprint import pprint
#pprint(results)
#pprint(tableData)

#table = DoubleTable(tableData, 'Natural Methods')

#table = SingleTable(tableData, 'Natural Methods')
table = GithubFlavoredMarkdownTable(tableData)
table.inner_heading_row_border = False

#table.justify_columns[2] = 'right'
print()
print(table.table)

for f in funcs:
    for a in axes:
        graphData = []
        #GA-evalfuncs.Sixhump-10-True
        nameGA = "GA-" + str(f) + "-" + str(a)+ "-" + "False"
        nameGAHybrid = "GA-" + str(f) + "-" + str(a)+ "-" + "True"
        namePSO = "PSO-" + str(f) + "-" + str(a)

        info = str(f).split(".")[1] + "-" + str(a) + " axes"