def test_make_action_from_json(operation_manifest: OperationManifest, caplog):
    caplog.set_level(logging.INFO)
    esi_job_json = {
        "op_id": "get_markets_region_id_history",
        "max_attempts": 1,
        "parameters": {"region_id": 10000002, "type_id": 34},
        "callbacks": {
            "success": [
                {"callback_id": "response_content_to_json", "args": [], "kwargs": {}}
            ],
            "retry": [],
            "fail": [],
        },
    }
    esi_job = models.EsiJob.deserialize_obj(esi_job_json)
    callback_provider = new_manifest()
    action = JobsToActions().make_action(
        esi_job=esi_job,
        operation_manifest=operation_manifest,
        callback_manifest=callback_provider,
    )

    assert action.aiohttp_args.params == {"type_id": 34}
    assert isinstance(action, AiohttpAction)
    asyncio.run(single_action_runner(action))
    assert action.response.status == 200
    assert action.response_data is not None
    assert len(action.response_data) > 5
    inspect(action.context["esi_job"])
Exemplo n.º 2
0
def test_render():
    console = Console(width=100, file=io.StringIO(), legacy_windows=False)

    foo = Foo("hello")
    inspect(foo, console=console, all=True, value=False)
    result = console.file.getvalue()
    print(repr(result))
    expected = "╭────────────── <class 'tests.test_inspect.Foo'> ──────────────╮\n│ Foo test                                                     │\n│                                                              │\n│   broken = InspectError()                                    │\n│ __init__ = def __init__(foo: int) -> None: constructor docs. │\n│   method = def method(a, b) -> str: Multi line               │\n╰──────────────────────────────────────────────────────────────╯\n"
    assert expected == result
Exemplo n.º 3
0
    def xmlNFL(self):
        """Generate xml for NFL Streams"""
        channels = []
        programs = []
        for stream in self.getStreamsNFL():
            tvg_id = stream.get("stream_id")
            tvg_name = stream.get("name").split(":")[0].strip()
            tvg_logo = stream.get("stream_icon")
            # tvg_group = "NFL Sunday Games"

            epg_desc = stream.get("name").split(":", maxsplit=1)[1].strip()
            ##### THIS IS TEMPORARY FOR SUPER BOWL FIX ####
            # epg_desc = epg_desc.replace("02.11", "02.13")

            # if epg_desc := stream.get("name").split(":", maxsplit=1)[1].strip():
            if epg_desc:
                try:
                    epg_title = epg_desc.split('(')[0].strip()
                    date_now = getEPGTimeNow(dt_obj=True).date()
                    year_now = str(date_now.year)[-2:]
                    game_time = epg_desc.split('(')[1].strip().split(
                        ')')[0].strip()

                    regex = r'(\d+).(\d+)\s+(\d+):(\d+)\s*(\w*)\s*(\w*)'
                    game_datetime = pd.to_datetime(
                        re.sub(regex, rf'\1.\2.{year_now} \3:\4 \5',
                               game_time))

                    epg_start = convertEPGTime(
                        game_datetime.tz_localize('US/Eastern'), epg_fmt=True)
                    epg_stop = convertEPGTime(pd.to_datetime(epg_start) +
                                              pd.DateOffset(hours=3),
                                              epg_fmt=True)

                    if ((date_now - game_datetime.date()).days < 5):
                        channels.append({
                            "tvg_id": tvg_id,
                            "tvg_name": tvg_name,
                            "tvg_logo": tvg_logo,
                            "epg_desc": epg_desc
                        })
                        programs.append({
                            "tvg_id": tvg_id,
                            "epg_title": epg_title,
                            "epg_start": epg_start,
                            "epg_stop": epg_stop,
                            "epg_desc": epg_desc
                        })

                except Exception as e:
                    inspect(e)
                    pass
        # return gen_xmltv_xml(channels=channels, programs=programs, url=self.API_URL)
        url = furl(self.API_URL).origin
        tpl = str(Path(__file__).parent.joinpath("templates/epg.tpl"))
        return template(tpl, channels=channels, programs=programs, url=url)
Exemplo n.º 4
0
def test_load_schema_from_app_data(monkeypatch):
    """expects to find schema in real app_data

    May not work with travis
    """
    # Load from app data
    monkeypatch.delenv("PFMSOFT_eve_esi_jobs_APP_DIR")
    runner = CliRunner()
    result = runner.invoke(app, ["schema"])
    inspect(result)
    assert result.exit_code == 0
    assert "Loaded ESI schema version" in result.output
Exemplo n.º 5
0
def test_inspect_swig_edge_case():
    """Issue #1838 - Edge case with Faiss library - object with empty dir()"""
    class Thing:
        @property
        def __class__(self):
            raise AttributeError

    thing = Thing()
    try:
        inspect(thing)
    except Exception as e:
        assert False, f"Object with no __class__ shouldn't raise {e}"
def matterhelp(classOrObj=None):
    if (classOrObj is None):
        inspect(builtins.devCtrl, methods=True, help=True, private=False)
        inspect(mattersetlog)
        inspect(mattersetdebug)
    else:
        inspect(classOrObj, methods=True, help=True, private=False)
Exemplo n.º 7
0
    def handle(self, *args, **options):
        d = discogs_client.Client("BigHomeProductionBot/0.1",
                                  user_token=settings.DISCOGS_TOKEN)
        l = d.label(settings.DISCOGS_LABEL_ID)
        label, created = Label.objects.get_or_create(
            name=l.name,  # who said I was pedantic?
        )
        for r in l.releases.page(1):  # paging - how do?

            inspect(r)
            catalog_no = r.data["catno"]
            release, created = Release.objects.get_or_create(
                title=r.data["title"],
                vague_date=True,
                label=label,
            )
            print(title)
            release.save()
Exemplo n.º 8
0
def test_get_action(operation_manifest: OperationManifest):
    """Testing that AiohttpAction works.

    Also example of how to use.
    """

    op_id = "get_markets_region_id_history"
    url_template = Template(operation_manifest.url_template(op_id))
    path_params = {"region_id": 10000002}
    query_params = {"type_id": 34}
    url = url_template.substitute(path_params)
    aiohttp_args = AiohttpRequest(method="get", url=url, params=query_params)
    callbacks = ActionCallbacks(success=[ResponseContentToJson()])
    action = AiohttpAction(aiohttp_args=aiohttp_args, callbacks=callbacks)
    inspect(action)
    assert action is not None
    worker = AiohttpQueueWorker()
    asyncio.run(queue_runner([action], [worker]))
    assert action.response_data is not None
    assert len(action.response_data) > 5
Exemplo n.º 9
0
def report() -> None:  # pragma: no cover
    """Print a report to the terminal with debugging information"""
    console = Console()
    inspect(console)
    features = get_windows_console_features()
    inspect(features)

    env_names = (
        "TERM",
        "COLORTERM",
        "CLICOLOR",
        "NO_COLOR",
        "TERM_PROGRAM",
        "COLUMNS",
        "LINES",
        "JPY_PARENT_PID",
        "VSCODE_VERBOSE_LOGGING",
    )
    env = {name: os.getenv(name) for name in env_names}
    console.print(Panel.fit((Pretty(env)), title="[b]Environment Variables"))

    console.print(f'platform="{platform.system()}"')
Exemplo n.º 10
0
 def inspect(self,
             obj: Any,
             *,
             title: str = None,
             help: bool = False,
             methods: bool = False,
             docs: bool = True,
             private: bool = False,
             dunder: bool = False,
             sort: bool = True,
             all: bool = False,
             value: bool = True):
     rich.inspect(obj,
                  console=self,
                  title=title,
                  help=help,
                  methods=methods,
                  docs=docs,
                  private=private,
                  dunder=dunder,
                  sort=sort,
                  all=all,
                  value=value)
Exemplo n.º 11
0
def render(obj, methods=False, value=False, width=50) -> str:
    console = Console(file=io.StringIO(), width=width, legacy_windows=False)
    inspect(obj, console=console, methods=methods, value=value)
    return console.file.getvalue()
from rich import inspect

print(inspect('hello', methods=True))
Exemplo n.º 13
0
from hashlib import new
from notion.client import NotionClient
from notion.block import ColumnBlock, TodoBlock
from rich import inspect

client = NotionClient(
    token_v2=
    "02a65af9ae61ae50bc17f3333d251e2580d9fd1293bdc68990a474372a458a56b63b1b2868f47e5b21e947ddc093634ce8442de2390f14bcdc54bbaa0d6d2921fad82538d01c9d78c9931f6daea5"
)
page = client.get_block(
    "https://www.notion.so/1063a61b0a4548959373f995b008d13e?v=6fba291866984949abf7c2c6e2e85ae1"
)

inspect(page, methods=True)
# print(page)
content = page.get()
print(content)
Exemplo n.º 14
0
 def inspect(self, var):
     inspect(var, methods=True)
Exemplo n.º 15
0
from rich import inspect

# Se você quiser ver rapidamente quais atributos e métodos de um objeto Python estão disponíveis,
# use o método de inspeção do Rich.
# o método de inspeção de Rich permite criar um belo relatório para qualquer objeto Python,
# incluindo uma sequência.

inspect('ola mundo', methods=True)
Exemplo n.º 16
0
# -*- coding: utf-8 -*-
########################################################################
#                                                                      #
#                                                                      #
#                                                                      #
# MIT License                                                          #
# Copyright (c) 2021 Michael Nikitenko                                 #
#                                                                      #
########################################################################

from rich import inspect
from rich.color import Color

if __name__ == '__main__':
    color = Color.parse("red")
    inspect(color,
            methods=True)  # Выводит всю инфу по классу в удобочитаемом виде
Exemplo n.º 17
0
pretty.install()
print([False, True, None, 3.14, "Hello World! " * 5, {"foo": "bar"}])
# Console
from rich.console import Console

console = Console()
console.print("Hello", "World!")
console.print("Hello", "World!", style="bold red")
console.print(
    "Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i]."
)
# Inspect

my_list = ["foo", "bar"]
from rich import inspect
inspect(my_list, methods=True)
# tables

from rich.console import Console
from rich.table import Table

console = Console()

table = Table(show_header=True, header_style="bold magenta")
table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row("Dev 20, 2019", "Star Wars: The Rise of Skywalker",
              "$275,000,000", "$375,126,118")
table.add_row(
Exemplo n.º 18
0
if __name__ == "__main__":  # pragma: no cover
    from rich.console import Console
    from rich import inspect

    console = Console()
    inspect(console)
    p(f'[green]Average: [blue] {scores.mean()}')

    formula = '    (1 / c_cnt) ** np.ceil(q_cnt * 0.7)'
    formula_result = eval(formula)
    syntax = Syntax(formula, "python")
    error = (simulation_result - formula_result) / formula_result

    title('[bold yellow]Conclusion')
    p('Each question is independent, therefor:')
    p('    P(q1,q2,q3)\n    = P(q1)P(q2)P(q3)')
    p('Each question has the same probability of being answered correctly')
    p('    = P(q1)^N\n    where N is the number of questions')
    p('and in this case where success is > 70%...')
    p(syntax, f'    = {toPercent(formula_result)}')
    p('The simulation results support this conclusion:')
    p(f'Experimental Error = {toPercent(error)}')


if __name__ == '__main__':
    args = setupArgParser()

    title('[bold cyan]Assumptions')
    p('- Interview has 3 questions instead of 20')
    p('- Success means a 70% or higher')
    p('  - That means 3/3 given the above assumption')

    title('[bold blue]Parameters')
    inspect(args, title='Simulation Params', docs=False)

    main(args)
Exemplo n.º 20
0
import re
from rich import inspect
from data_dicts import hsrp

with open("data_dicts.py") as f:
    inspect(f)
    inspect(f, methods=True)

m = re.search(r"\d+", "vlan 10,20")
inspect(m)
inspect(m, methods=True)

inspect(inspect)
Exemplo n.º 21
0
def update(tick):
    global play, newKeyboard, rectsToFill, playerSprite, screenshotPressedLastFrame

    [playerSprite.remove(sprite) for sprite in playerSprite if sprite not in sprites]

    rectsToFill = []

    fullboard = pygame.key.get_pressed()

    newKeyboard = copy.deepcopy(blankKeyboard)

    for event in pygame.event.get():
        if event.type == pygame.QUIT: close()
        if event.type == pygame.KEYDOWN: # KEY
            timer.start()
            if event.key == pygame.K_i and debug:
                mouserect = pygame.Rect((pygame.mouse.get_pos(),(1,1)))
                mouserect.topleft = (mouserect.x-24,mouserect.y-24)
                guys = sprites + terrains
                col = mouserect.collidelist(guys)
                if col != -1:
                    rich.inspect(guys[col])
            for i in range(len(binds)):
                if event.key in binds[i]:
                    newKeyboard[i][binds[i][event.key]] = True
                    keyboard[i][binds[i][event.key]] = True
        if event.type == pygame.KEYUP:
            for i in range(len(binds)):
                if event.key in binds[i]:
                    keyboard[i][binds[i][event.key]] = False
    
    if keyboard[0]["pause"]:
        pause()
    if newKeyboard[0]["reset"]:
        reset()
        return

    if levelEdit and not play:
        if newKeyboard[0]["reset"]:
            levelData["level"]["keys"] -= 1
        elif newKeyboard[0]["action"]:
            levelData["level"]["keys"] += 1

    screen.fill((0,0,0))

    if levelEdit and play:
        if fullboard[pygame.K_o]:
            play = False
            reset()

    if playerSprite:
        playerDead = any([(sprite.extraArgs["dead"] or sprite.extraArgs["won"]) for sprite in playerSprite])
    else:
        playerDead = True

    if not playerDead:
        [terrain.do_animation() for terrain in terrains if terrain.animation]

    for sprite in sprites: # SPRITES
        if sprite in playerSprite:
            continue
        if play and not playerSprite:
            sprite.update(tick)
        elif play and not playerDead:
            sprite.update(tick)
        scrollPos = (list(sprite.rect.topleft)[0]+24-scroll[0], list(sprite.rect.topleft)[1]+24-scroll[1])
        screen.blit(sprite.image,scrollPos)

    if play and not playerSprite:
        timer.update(tick)
    elif (play and not (playerDead and not frameN == 0)):
        timer.update(tick)

    if play and playerSprite:
        for sprite in playerSprite:
            sprite.update(tick)

    if levelEdit and not play:
        scroll[0] += 8 if keyboard[0]["right"] else -8 if keyboard[0]["left"] else 0
        scroll[1] += 8 if keyboard[0]["down"] else -8 if keyboard[0]["up"] else 0

    scroll[0] = bind(scroll[0],size[0]+48-screenSize[0],0)[0]
    scroll[1] = bind(scroll[1],size[1]+48-screenSize[1],0)[0]

    screen.blit(staticSurface,(0-scroll[0],0-scroll[1]))

    screen.blit(terrainSurface,(24-scroll[0],24-scroll[1]))

    for sprite in sorted(sprites):
        if sprite == playerSprite:
            continue
        scrollPos = (list(sprite.rect.topleft)[0]+24-scroll[0], list(sprite.rect.topleft)[1]+24-scroll[1])
        screen.blit(sprite.image,scrollPos)

    for sprite in playerSprite:
        scrollPos = (list(sprite.rect.topleft)[0]+24-scroll[0], list(sprite.rect.topleft)[1]+24-scroll[1])
        screen.blit(sprite.image,scrollPos)

    if levelEdit and not play:
        selectedIm,play = levelEdit.update(scroll)
        screen.blit(levelEdit.editStaticSurface,(24-scroll[0],24-scroll[1]))
        screen.blit(levelEdit.editSurface,(0,0))
        if selectedIm[1].topleft != (0,0):
            screen.blit(selectedIm[0],selectedIm[1])

    alpha = hudSurface.get_alpha()
    if pygame.Rect(1200,4,1328,60).collidelist(playerSprite) != -1:
        alpha = alpha - tick//2 if alpha - tick//2 > 50 else 50
    else:
        alpha = alpha + tick//2 if alpha + tick//2 < 255 else 255
    hudSurface.set_alpha(alpha)

    if not fullboard[pygame.K_F1]: # HUD Stuff.
        screen.blit(hudSurface,(0,0))

        if playerSprite:
            if any([sprite.extraArgs["won"] for sprite in playerSprite]):
                font_render("arial60","Congratulations!",(70,70),(255,255,255))

        if levelData['level']['keys']:
            font_render("munro18",f"{collectedKeys}/{levelData['level']['keys']}",(45,7),(25,25,25,alpha),antialiasing=False)

        if levelEdit:
            font_render("munro24",str(levelEdit.mousePos),(90,0))

        if debug:
            if not pygame.mouse.get_visible():
                pygame.mouse.set_visible(True)

            font_render("munro24",str(pygame.mouse.get_pos()),(400,0))

            if rectsToFill and fullboard[pygame.K_RETURN]:
                surface = pygame.Surface(size,pygame.SRCALPHA)
                for i in rectsToFill:
                    surface.fill(i[1],i[0],pygame.BLEND_RGBA_ADD)
                screen.blit(surface,(24,24))

            if playerSprite:
                font_render("consolas10",f"F {add_zeros(frameN)} PS {clock.get_fps():.2f} T {add_zeros(tick,3)} x {add_zeros(playerSprite[0].rect.x)} y {add_zeros(playerSprite[0].rect.y)} dir {add_zeros(playerSprite[0].direction,0)} pro {add_zeros(playerSprite[0].projected_direction,0)} T {add_zeros(playerSprite[0].rect.top)} L {add_zeros(playerSprite[0].rect.left)} R {add_zeros(playerSprite[0].rect.right)} B {add_zeros(playerSprite[0].rect.bottom)} | s {add_zeros(playerSprite[0].fSpeed,1)} {add_zeros(playerSprite[0].speed[0],1)} {add_zeros(playerSprite[0].speed[1],1)} su {add_zeros(playerSprite[0].startup,1)} | Scroll: {scroll} | Ani: {add_zeros(playerSprite[0].animationFrame)} {playerSprite[0].animation}",(4,730),(255,255,255),bg_colour=(0,0,0)) # The speed values and negetive numbers are kinda f****d but i dont care.
                font_render("consolas10",f"{' '.join([arg+'='+(str(value) if not isinstance(value,bool) else ('T' if value else 'F')) for arg,value in playerSprite[0].extraArgs.items()])}",(4,740),(255,255,255),bg_colour=(0,0,0))

        t = timer.time_readable(timer.time)
        font_render("munro24",t,(1216,10),(8,8,200,alpha))
        font_render("munro24",t,(1214,8),(255,255,255,alpha))
        t = timer.time_readable(timer.levelTime,False)
        font_render("munro24",t,(1245,40),(200,8,8,alpha))
        font_render("munro24",t,(1243,38),(255,255,255,alpha))

    if fullboard[pygame.K_F2] and not screenshotPressedLastFrame:
        i = 1
        while os.path.exists(os.path.join(application_path, "screenshots", f"{i}.png")):
            i += 1
        pygame.image.save(screen,os.path.join(application_path, "screenshots", f"{i}.png"))
    screenshotPressedLastFrame = fullboard[pygame.K_F2]
Exemplo n.º 22
0
### To do: Add -i, --input to use readlines() for a text file containing multiple URLs
### To do: Add error control (if you type ./url.py http:blah, it doesn't check that you forgot the -u

from rich import inspect
import requests
import sys, getopt

argumentList = sys.argv[1:]

# Options
options = "hu:"

# Long options
long_options = ["help", "url"]

try:
    # Parsing args
    arguments, values = getopt.getopt(argumentList, options, long_options)

    # checking args
    for currentArgument, currentValue in arguments:
        if currentArgument in ("-h", "--help"):
            print("Usage: ", sys.argv[0], " -u | --url https://something")
        elif currentArgument in ("-u", "--url"):
            url = currentValue
            r = requests.get(url, verify=False)
            # I set this to verify=False because I tend to check a lot of self-signed cert websites
            print(inspect(r))
except getopt.error as err:
    # output error and return
    print(str(err))
Exemplo n.º 23
0
 def help(self):
     inspect(self, help=True, title="{} help".format(self.name))
     raise HelpException
from rich.console import Console
from time import sleep
from rich.color import ANSI_COLOR_NAMES

console = Console()
# inspect(console)
# sys.exit(0)
grid = Table.grid()
# colors = ["red", "green", "blue"]
colors = list(ANSI_COLOR_NAMES)
grid.add_column()
grid.add_column()
grid.add_column()
grid.add_row("[red]r[/]", "[blue]b[/]", "[green]g[/]")
grid.add_row("[green]g[/]", "[red]r[/]", "[blue]b[/]")
inspect(grid, methods=True)
sys.exit(0)
with console.screen():
    for _ in range(console.width):
        grid.add_column()
    for i in range(console.height - 1):
        random.seed(i)
        random.shuffle(colors)
        color = cycle(colors)
        cells = []
        for j in range(len(grid.columns)):
            # cells.append(f"[white on {next(color)}] [/]")
            cells.append(f"[white on {random.choice(colors)}] [/]")
        grid.add_row(*cells)

    print(grid, end="")
Exemplo n.º 25
0
 def details(self, *args):
     for arg in args:
         inspect(arg, methods=True)
Exemplo n.º 26
0

def test_log():
    myvar = "content of my local var"
    enabled = True
    context = {
        "foo": "bar",
    }
    movies = ["Deadpool", "Rise of the Skywalker"]
    console.log("Hello from", console, "!")
    console.log("Another log")
    console.log(test_data, log_locals=False)


class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []  # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)


if __name__ == "__main__":
    print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
    inspect(Dog, methods=True)
    myDog = Dog('Brutus')
    myDog.add_trick('roll over')
    print(myDog.tricks)
    test_log()
Exemplo n.º 27
0
    proj.overwrite = argsd["overwrite"]
    profile = Profile()

    if argsd["get"]:
        brick = open_brick()
        # r = flash_read(brick, 0xFFF000, 256)
        # s = []
        # for rb in r:
        #     s.append("0x%02X " % (rb))
        # console.print("".join(s))
        brick.get_config()
        brick.print_config()
        profile.idx_playback.fetch_from_brick(brick)
        profile.idx_playback.print()
        profile.gated_playback.fetch_from_brick(brick)
        profile.gated_playback.print()
        inspect(profile.idx_playback)
    else:
        profile.set_with_dict(proj.__dict__)
        inspect(profile.settings)
        profile.print()

        if argsd["preview"]:
            profile.idx_playback.preview()
        else:
            brick = open_brick()
            brick.test_action(PFxAction().all_off())
            profile.copy_to_brick(brick)
            profile.configure_brick(brick)
            profile.settings.configure_brick(brick)