from time import sleep
from selenium.webdriver.edge.options import Options
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import pandas as pd
import re

options = Options()
# options.add_argument("headless")
# options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument('--disable-blink-features=AutomationControlled')
driver = webdriver.Edge(options=options)
actions = ActionChains(driver)

def clickpre() -> bool:
    try:
        elem = driver.find_element(By.CSS_SELECTOR, ".pagination:nth-child(1) > .page-item:nth-child(2)")
    except:
        return False
    if "disabled" in elem.get_attribute("class"):
        return False
    elem.click()
    sleep(2)
    return True
links = ["0x4a66ad0bca2d700f11e1f2fc2c106f7d3264504c"
, "0x4b319cE02BdC8977Fb39fa70C49258a1a7C27d9B"
, "0x4b71ad9c1a84b9b643aa54fdd66e2dec96e8b152"
, "0x4D391B4350cA1C690eBaf00d35bfcDd5721470F8"
, "0x4dAA9DC438a77Bd59E8A43C6D46cbfE84cD04255"
, "0x4e73b32ed6c35f570686b89848e5f39f20ecc106"
, "0x4Ea0Df261BA584572CDED3F2E35a0E63375Ac4f1"
, "0x50ca2DE80e803bF4b00f188545BCA959540C5582"
, "0x524960d55174d912768678d8c606b4d50b79d7b1"
, "0x524A1407223446e3BAb8819ABb3fb8348C29afEc"
, "0x52d2e0f9b01101a59b38a3d05c80b7618aeed984"
, "0x531917942B6Bb866031aC22BB00E7838613753AC"
, "0x561eac93c92360949ab1f1403323e6db345cbf31"
, "0x584a0EC8A7A3fcfEd27Db5C234A9062863883778"
, "0x5aa88d2901c68fda244f1d0584400368d2c8e739"
, "0x5aD6Dc0A267693c8A14AC9fF2A29c7D63A3d96c2"
, "0x610495793564aed0f9c7fc48dc4c7c9151d34fd6"
, "0x61dc161B06088b9cbaaD53391134929A83D1EB7A"
, "0x627fa62ccbb1c1b04ffaecd72a53e37fc0e17839"
, "0x63e634330A20150DbB61B15648bC73855d6CCF07"
]

# links = ["0xc7d020d8c92d099b3ade17321310b4815ef20a90"]

try:
    for i in range(len(links)):
        driver.get("https://etherscan.io/address/"+links[i])
        sleep(1.2)
        # get all the transactions in web
        # driver.get_screenshot_as_file("1.png")
        driver.set_window_size(1080,840)
        try:
            driver.find_element(By.CSS_SELECTOR, "#btnCookie").click()
        except:
            pass
        try:
            elem = driver.find_element(By.CSS_SELECTOR, ".mr-2 > a:nth-child(2)")
            actions.move_to_element(elem).click().perform()
            sleep(1)
        except:
            pass
        try:
            elem= driver.find_element(By.CSS_SELECTOR, ".pagination:nth-child(1) > .page-item:nth-child(5) > .page-link")
            actions.move_to_element(elem).click().perform()
            sleep(1)
        except:
            pass

        # num = 1250
        # for j in range(num//50):
        #     clicknext()
        output = []
        table = []
        times = 0
        while True:
            count = len(driver.find_elements(By.CSS_SELECTOR, "tr .u-label--info"))
            for j in range(count, 0, -1):
                # crawl_from
                detail = {}
                elem = driver.find_element(By.CSS_SELECTOR, "tr:nth-child("+str(j)+") > td:nth-child(7) a")
                actions.move_to_element(elem).perform()
                address = elem.get_attribute("data-original-title")
                if address is None:
                    address = elem.get_attribute("textContent")
                table.append(address)
                # print("{0},{1}".format(address,j))
                # get method name (temp)
                elem = driver.find_element(By.CSS_SELECTOR, "tr:nth-child("+str(j)+") .u-label--info")
                actions.move_to_element(elem).perform()
                method = elem.get_attribute("data-original-title")
                # click into transaction details
                elem = driver.find_element(By.CSS_SELECTOR, "tr:nth-child("+str(j)+") .myFnExpandBox_searchVal")
                actions.move_to_element(elem).click().perform()
                sleep(1.2)
                # click to open the arguments details
                driver.find_element(By.CSS_SELECTOR,"#collapsedLink > span").click()
                sleep(1.2)
                # get limit
                text = driver.find_element(By.CSS_SELECTOR, "#ContentPlaceHolder1_spanGasLimit").get_attribute("textContent")
                text = re.sub("[\n,]","",text)
                detail["GasLimit"] = text
                # get usage
                text = driver.find_element(By.CSS_SELECTOR, "#ContentPlaceHolder1_spanGasUsedByTxn").get_attribute("textContent")
                text = re.sub("[\n,]","",text)
                detail["GasUsage"] = text
                # get value
                text = driver.find_element(By.CSS_SELECTOR, "#ContentPlaceHolder1_spanValue").get_attribute("textContent")
                detail["Value"] = text
                # get method name
                text = driver.find_element(By.CSS_SELECTOR, "#inputdata").get_attribute("textContent")
                if "Function" in text:
                    try:
                        method = re.search("Function: (.*)\(",text).group(1)
                    except:
                        pass
                elif method == "0x60606040":
                    method = "constructor"
                print(method,j)
                detail["Method"] = method
                # use actionchains to click something that "Element is not clickable at point" , scroll the screen to make the buttom clickable
                # click to format the arguments
                try:
                    elem = driver.find_element(By.CSS_SELECTOR,"#ContentPlaceHolder1_btnDecodetab")
                    actions.scroll_to_element(elem).move_to_element(elem).click().perform()
                    sleep(1.3)
                except:
                    pass
                # markdown the arguments
                elem1s = driver.find_elements(By.CSS_SELECTOR,"tr > td:nth-child(3)")
                elem2s = driver.find_elements(By.CSS_SELECTOR,"tr > td:nth-child(4)")
                arguments = []
                for elem1,elem2 in zip(elem1s,elem2s):
                    text1 = elem1.get_attribute("textContent")
                    text2 = elem2.get_attribute("innerHTML")
                    text2 = re.sub(r'<br>',"\n",text2)
                    text2 = re.sub(r'<.*?>',"",text2)
                    arguments.append([text1,text2])
                detail["Args"] = arguments
                # print(arguments)
                output.append(detail)
                driver.back()
                sleep(1)
            sleep(2)
            times += 1
            #next page or quit
            if clickpre()==False or times == 7:
                break

        output = pd.DataFrame(data=output)
        output.to_csv(links[i]+"_result.csv",mode='a')
        address = pd.DataFrame(data=table)
        address.to_csv(links[i]+"_from.csv",header=False,mode='a')
    driver.quit()
except:
    output = pd.DataFrame(data=output)
    output.to_csv(links[i]+"_result.csv",header=False,mode='a')
    address = pd.DataFrame(data=table)
    address.to_csv(links[i]+"_from.csv",header=False,mode='a')


from typing import List

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        pPath = self.getPathToNode(root, p)
        qPath = self.getPathToNode(root, q)

        for i in range(min(len(pPath), len(qPath)) - 1, -1, -1):
            if pPath[i].val == qPath[i].val:
                return pPath[i]

        return pPath[0]

    def getPathToNode(self, start: 'TreeNode', target: 'TreeNode') -> List:
        path = []

        while start != target:
            path.append(start)

            if start.val > target.val:
                start = start.left
            else:
                start = start.right

        path.append(target)

        return path


from pynput import keyboard
from Hotkeys import hot_keys

def listener(open_ui, ui):
    combinations = hot_keys

    pressed_keys = set()

    def get_vk(key):
        # gets virtual key allowing pressed keys to easily be compared
        return key.vk if hasattr(key, 'vk') else key.value.vk

    def is_combination_pressed(combination):
        return all([get_vk(key) in pressed_keys for key in combination])

    def on_press(key):
        try:
            print("Added key")
            pressed_keys.add(get_vk(key))
        except:
            None

        for combination in combinations:  # Loop though each combination
            if is_combination_pressed(combination["shortcut"]):
                print("Got combination")

                if combination["input_required"]:
                    ui.set_event(combination["event"])
                    open_ui()
                else:
                    combination["event"]()

    def on_release(key):
        try:
            pressed_keys.remove(get_vk(key))
            print("Removed")
        except:
            pressed_keys.clear()

    with keyboard.Listener(on_press=on_press, on_release=on_release) as listen:
        listen.join()


import csv
import time
import requests
import os
from bs4 import BeautifulSoup
import lxml
import json

def get_pages():
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
    }

    req = requests.get(url="https://swisstime.by/catalog/filter/gender-is-muzhskie/apply/", headers=headers)

    if not os.path.exists("data"):
        os.mkdir("data")

    with open("data/page_1.html", "w", encoding="UTF-8") as file:
        file.write(req.text)

    with open("data/page_1.html", encoding="UTF-8") as file:
        src = file.read()

    soup = BeautifulSoup(src, "lxml")
    pages_count = int(soup.find("li", class_="pagination-item pages col-06").find_all("a")[-2].text)

    for i in range(1, pages_count + 1):
        url = f"https://swisstime.by/catalog/filter/gender-is-muzhskie/apply/?PAGEN_1={i}"

        r = requests.get(url=url, headers=headers)
        with open(f"data/page_{i}.html", "w", encoding="UTF-8") as file:
            file.write(r.text)

        time.sleep(2)

    return pages_count

def collect_options(pages_count):
    with open("data_results.csv", "w", encoding="UTF-8") as file:
        writer = csv.writer(file)
        writer.writerow(
            (
                "Бренд",
                "Модель",
                "Цена",
                "Имеется в продаже"
            )
        )

    data = []
    for page in range(1, pages_count + 1):
        with open(f"data/page_{page}.html", encoding="UTF-8") as file:
            src = file.read()

        soup = BeautifulSoup(src, "lxml")
        watch_cards = soup.find_all("a", class_="st-card__link")

        for item in watch_cards:
            watch_brand = item.find("div", class_="st-card__brand").text
            watch_model = item.find("div", class_="st-card__model").text
            watch_price = item.find("div", class_="st-card__price").text
            watch_stock = item.find("div", class_="st-card__stock").text.strip()
            watch_url = f'https://swisstime.by{item.get("href")}'

            data.append(
                {
                    "watch_brand": watch_brand,
                    "watch_model": watch_model,
                    "watch_price": watch_price,
                    "watch_stock": watch_stock,
                    "watch_url": watch_url
                }
            )

            with open("data_results.csv", "a", encoding="UTF-8") as file:
                writer = csv.writer(file)
                writer.writerow(
                    (
                        watch_brand,
                        watch_model,
                        watch_price,
                        watch_stock
                    )
                )

    with open("parsing_results.json", "a", encoding="UTF-8") as file:
        json.dump(data, file, indent=4, ensure_ascii=False)

    print(f"The work has done")

def main():
    pages_count = get_pages()
    collect_options(pages_count=pages_count)

if __name__ == '__main__':
    main()


"""Manage software dependencies"""
import glob
import logging
import os
import platform
import subprocess
import sys
import tempfile
import textwrap
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from distutils.version import LooseVersion
from shutil import which

import distro

from . import config, defs, util

logger = logging.getLogger(__name__)
runner = util.ProcessRunner(logger)

target_map = {
    "sdr": defs.sdr_setup_type,
    "usb": defs.linux_usb_setup_type,
    "standalone": defs.standalone_setup_type,
    "sat-ip": defs.sat_ip_setup_type
}
supported_distros = ["ubuntu", "debian", "raspbian", "fedora", "centos"]

def _check_distro(setup_type):
    """Check if distribution is supported"""
    if (distro.id() in supported_distros):
        return

    base_url = defs.user_guide_url + "doc/"
    instructions_url = {
        defs.sdr_setup_type: "sdr.md",
        defs.linux_usb_setup_type: "tbs.md",
        defs.standalone_setup_type: "s400.md",
        defs.sat_ip_setup_type: "sat-ip.md"
    }
    full_url = base_url + instructions_url[setup_type]
    logger.error("{} is not a supported Linux distribution".format(
        distro.name()))
    logger.info(
        textwrap.fill("Please, refer to the {} receiver setup "
                      "instructions at {}".format(setup_type, full_url)))
    raise ValueError("Unsupported Linux distribution")

def _get_apt_repo(distro_id):
    """Find the APT package repository for the given distro"""
    if distro_id == "ubuntu":
        apt_repo = "ppa:blockstream/satellite"
    elif distro_id in ["debian", "raspbian"]:
        apt_repo = ("https://aptly.blockstream.com/"
                    "satellite/{}/").format(distro_id)
    else:
        raise ValueError("Unsupported distribution {}".format(distro_id))
    return apt_repo

def _check_pkg_repo(distro_id):
    """Check if Blockstream Satellite's binary package repository is enabled

    Args:
        distro_id: Linux distribution ID

    Returns:
        (bool) True if the repository is already enabled

    """
    found = False
    if (which("apt")):
        apt_repo = _get_apt_repo(distro_id)
        grep_str = apt_repo.replace("ppa:", "")
        apt_sources = glob.glob("/etc/apt/sources.list.d/*")
        apt_sources.append("/etc/apt/sources.list")
        cmd = ["grep", grep_str]
        cmd.extend(apt_sources)
        res = runner.run(cmd, stdout=subprocess.DEVNULL, nocheck=True)
        found = (res.returncode == 0)
    elif (which("dnf")):
        res = runner.run(["dnf", "copr", "list", "--enabled"],
                         root=True,
                         capture_output=True)
        pkgs = res.stdout.decode().splitlines()
        found = ("copr.fedorainfracloud.org/blockstream/satellite" in pkgs)
    elif (which("yum")):
        yum_sources = glob.glob("/etc/yum.repos.d/*")
        cmd = ["grep", "blockstream/satellite"]
        cmd.extend(yum_sources)
        res = runner.run(cmd, stdout=subprocess.DEVNULL, nocheck=True)
        found = (res.returncode == 0)
    else:
        raise RuntimeError("Could not find a supported package manager")

    if (found):
        logger.debug("blockstream/satellite repository already enabled")

    return found

def _enable_pkg_repo(distro_id, interactive):
    """Enable Blockstream Satellite's binary package repository

    Args:
        distro_id: Linux distribution ID
        interactive: Interactive mode

    """
    cmds = list()
    if (which("apt")):
        apt_repo = _get_apt_repo(distro_id)

        # On debian, add the apt repository through "add-apt-repository". On
        # raspbian, where "add-apt-repository" does not work, manually add a
        # file into /etc/apt/sources.list.d/.
        if distro_id == "raspbian":
            release_codename = distro.codename()
            apt_list_filename = "blockstream-satellite-{}-{}.list".format(
                distro_id, release_codename)
            apt_list_file = os.path.join("/etc/apt/sources.list.d/",
                                         apt_list_filename)
            apt_component = "main"
            apt_file_content = "deb {0} {1} {2}\n# deb-src {0} {1} {2}".format(
                apt_repo, release_codename, apt_component)
            # In execution mode, create a temporary file and move it to
            # /etc/apt/sources.list.d/. With that, only the move command needs
            # root permissions, whereas the temporary file does not. In dry-run
            # mode, print an equivalent echo command.
            if (runner.dry):
                cmd = [
                    "echo", "-e",
                    repr(apt_file_content), ">>", apt_list_file
                ]
            else:
                tmp_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
                with tmp_file as fd:
                    fd.write(apt_file_content)
                cmd = ["mv", tmp_file.name, apt_list_file]
        else:
            cmd = ["add-apt-repository", apt_repo]
            if (not interactive):
                cmd.append("-y")

        cmds.append(cmd)

        if distro_id in ["debian", "raspbian"]:
            cmd = [
                "apt-key", "adv", "--keyserver", "keyserver.ubuntu.com",
                "--recv-keys", defs.blocksat_pubkey
            ]
            cmds.append(cmd)

        cmd = ["apt", "update"]
        if (not interactive):
            cmd.append("-y")
        cmds.append(cmd)
    elif (which("dnf")):
        cmd = ["dnf", "copr", "enable", "blockstream/satellite"]
        if (not interactive):
            cmd.append("-y")
        cmds.append(cmd)
    elif (which("yum")):
        cmd = ["yum", "copr", "enable", "blockstream/satellite"]
        if (not interactive):
            cmd.append("-y")
        cmds.append(cmd)
    else:
        raise RuntimeError("Could not find a supported package manager")

    for cmd in cmds:
        runner.run(cmd, root=True)

def _update_pkg_repo(interactive):
    """Update APT's package index

    NOTE: this function updates APT only. On dnf/yum, there is no need to run
    an update manually. The tool (dnf/yum) updates the package index
    automatically when an install/upgrade command is called.

    """

    if (not which("apt")):
        return

    cmd = ["apt", "update"]
    if (not interactive):
        cmd.append("-y")

    runner.run(cmd, root=True)

def _install_packages(apt_list,
                      dnf_list,
                      yum_list,
                      interactive=True,
                      update=False):
    """Install binary packages

    Args:
        apt_list    : List of package names for installation via apt
        dnf_list    : List of package names for installation via dnf
        dnf_list    : List of package names for installation via yum
        interactive : Whether to run an interactive install (w/ user prompting)
        update      : Whether to update pre-installed packages instead

    """
    if (which("apt")):
        manager = "apt"
        cmd = ["apt-get", "install"]
        if (update):
            cmd.append("--only-upgrade")
        cmd.extend(apt_list)
    elif (which("dnf")):
        manager = "dnf"
        if (update):
            cmd = ["dnf", "upgrade"]
        else:
            cmd = ["dnf", "install"]
        cmd.extend(dnf_list)
    elif (which("yum")):
        manager = "yum"
        if (update):
            cmd = ["yum", "upgrade"]
        else:
            cmd = ["yum", "install"]
        cmd.extend(yum_list)
    else:
        raise RuntimeError("Could not find a supported package manager")

    env = None
    if (not interactive):
        cmd.append("-y")
        if (manager == "apt"):
            env = os.environ.copy()
            env["DEBIAN_FRONTEND"] = "noninteractive"

    runner.run(cmd, root=True, env=env)

def _install_common(interactive=True, update=False, btc=False):
    """Install dependencies that are common to all setups"""
    util.print_header("Installing Common Dependencies")
    apt_pkg_list = ["software-properties-common"]
    dnf_pkg_list = ["dnf-plugins-core"]
    yum_pkg_list = ["yum-plugin-copr"]

    # "gnupg" is installed as a dependency of "software-properties-common" on
    # Ubuntu. In contrast, it is not a dependency on Debian. Hence, add it
    # explicitly to the list. Add also "dirmngr", which may not be
    # automatically installed with gnupg (it is only automatically installed
    # from buster onwards). Lastly, add "apt-transport-https" to fetch debian
    # and raspbian packages from Aptly using HTTPS.
    distro_id = distro.id()
    if distro_id in ["debian", "raspbian"]:
        apt_pkg_list.extend(["gnupg", "dirmngr", "apt-transport-https"])

    if distro_id == "centos":
        dnf_pkg_list.append("epel-release")
        yum_pkg_list.append("epel-release")

    _install_packages(apt_pkg_list, dnf_pkg_list, yum_pkg_list, interactive,
                      update)

    # Enable our binary package repository
    if runner.dry or (not _check_pkg_repo(distro_id)):
        _enable_pkg_repo(distro_id, interactive)

    # Install bitcoin-satellite
    if (btc):
        apt_pkg_list = [
            "bitcoin-satellite", "bitcoin-satellite-qt", "bitcoin-satellite-tx"
        ]
        dnf_pkg_list = ["bitcoin-satellite", "bitcoin-satellite-qt"]
        yum_pkg_list = ["bitcoin-satellite", "bitcoin-satellite-qt"]

        if (which("dnf")):
            # dnf matches partial package names, and so it seems that when
            # bitcoin-satellite and bitcoin-satellite-qt are installed in one
            # go, only the latter gets installed. The former is matched to
            # bitcoin-satellite-qt and assumed as installed. Hence, as a
            # workaround, install the two packages separately.
            for pkg in dnf_pkg_list:
                _install_packages(apt_pkg_list, [pkg], [pkg], interactive,
                                  update)
        else:
            _install_packages(apt_pkg_list, [], yum_pkg_list, interactive,
                              update)

def _install_specific(target, interactive=True, update=False):
    """Install setup-specific dependencies"""
    key = next(key for key, val in target_map.items() if val == target)
    pkg_map = {
        'sdr': {
            'apt': ["gqrx-sdr", "rtl-sdr", "leandvb", "tsduck"],
            'dnf': ["gqrx", "rtl-sdr", "leandvb", "tsduck"],
            'yum': ["rtl-sdr", "leandvb", "tsduck"]
        },
        'usb': {
            'apt': ["iproute2", "iptables", "dvb-apps", "dvb-tools"],
            'dnf': ["iproute", "iptables", "dvb-apps", "v4l-utils"],
            'yum': ["iproute", "iptables", "dvb-apps", "v4l-utils"]
        },
        'standalone': {
            'apt': ["iproute2", "iptables"],
            'dnf': ["iproute", "iptables"],
            'yum': ["iproute", "iptables"]
        },
        'sat-ip': {
            'apt': ["iproute2", "tsduck"],
            'dnf': ["iproute", "tsduck"],
            'yum': ["iproute", "tsduck"]
        }
    }
    # NOTE:
    # - leandvb and tsduck come from our repository. Also, note gqrx is not
    #   available on CentOS (hence not included on the yum list).
    # - In the USB setup, the only package from our repository is dvb-apps in
    #   the specific case of dnf (RPM) installation, given that dvb-apps is not
    #   available on the latest mainstream fedora repositories.

    util.print_header("Installing {} Receiver Dependencies".format(target))
    _install_packages(pkg_map[key]['apt'], pkg_map[key]['dnf'],
                      pkg_map[key]['yum'], interactive, update)

def _print_help(args):
    """Re-create argparse's help menu"""
    parser = ArgumentParser()
    subparsers = parser.add_subparsers(title='', help='')
    parser = subparser(subparsers)
    print(parser.format_help())

def subparser(subparsers):
    """Parser for install command"""
    p = subparsers.add_parser('dependencies',
                              aliases=['deps'],
                              description="Manage dependencies",
                              help='Manage dependencies',
                              formatter_class=ArgumentDefaultsHelpFormatter)

    p.set_defaults(func=_print_help)
    p.add_argument("-y",
                   "--yes",
                   action='store_true',
                   default=False,
                   help="Non-interactive mode. Answers \"yes\" automatically \
                   to binary package installation prompts")
    p.add_argument("--dry-run",
                   action='store_true',
                   default=False,
                   help="Print all commands but do not execute them")

    subsubp = p.add_subparsers(title='subcommands', help='Target sub-command')

    p1 = subsubp.add_parser('install',
                            description="Install software dependencies",
                            help='Install software dependencies')
    p1.add_argument("--target",
                    choices=list(target_map.keys()),
                    default=None,
                    help="Target setup type for installation of dependencies")
    p1.add_argument("--btc",
                    action='store_true',
                    default=False,
                    help="Install bitcoin-satellite")
    p1.set_defaults(func=run, update=False)

    p2 = subsubp.add_parser('update',
                            aliases=['upgrade'],
                            description="Update software dependencies",
                            help='Update software dependencies')
    p2.add_argument("--target",
                    choices=list(target_map.keys()),
                    default=None,
                    help="Target setup type for the update of dependencies")
    p2.add_argument("--btc",
                    action='store_true',
                    default=False,
                    help="Update bitcoin-satellite")
    p2.set_defaults(func=run, update=True)

    p3 = subsubp.add_parser('tbs-drivers',
                            description="Install TBS USB receiver drivers",
                            help='Install TBS USB receiver drivers')
    p3.set_defaults(func=drivers)

    return p

def run(args):
    """Run installations"""

    # Interactive installation? I.e., requires user to press "y/n"
    interactive = (not args.yes)

    # Configure the subprocess runner
    runner.set_dry(args.dry_run)

    if (args.target is not None):
        target = target_map[args.target]
    else:
        info = config.read_cfg_file(args.cfg, args.cfg_dir)
        if (info is None):
            return
        target = info['setup']['type']

    _check_distro(target)

    if (os.geteuid() != 0 and not args.dry_run):
        util.fill_print("Some commands require root access and may prompt "
                        "for a password")

    if (args.dry_run):
        util.print_header("Dry Run Mode")

    # Update package index
    _update_pkg_repo(interactive)

    # Common dependencies (regardless of setup)
    _install_common(interactive=interactive, update=args.update, btc=args.btc)

    # Install setup-specific dependencies
    _install_specific(target, interactive=interactive, update=args.update)

def drivers(args):
    # Interactive installation? I.e., requires user to press "y/n"
    interactive = (not args.yes)

    # Configure the subprocess runner
    runner.set_dry(args.dry_run)

    if (os.geteuid() != 0 and not args.dry_run):
        util.fill_print("Some commands require root access and may prompt "
                        "for a password")

    if (args.dry_run):
        util.print_header("Dry Run Mode")

    # Install pre-requisites
    linux_release = platform.release()
    linux_headers = "linux-headers-" + linux_release
    kernel_devel = "kernel-devel-" + linux_release
    kernel_headers = "kernel-headers-" + linux_release
    apt_pkg_list = [
        "make", "gcc", "git", "patch", "patchutils",
        "libproc-processtable-perl", linux_headers
    ]
    dnf_pkg_list = [
        "make", "gcc", "git", "patch", "patchutils", "perl-Proc-ProcessTable",
        "perl-Digest-SHA", "perl-File-Copy-Recursive", kernel_devel,
        kernel_headers
    ]
    yum_pkg_list = dnf_pkg_list

    # On dnf, not always the kernel-devel/headers package will be available for
    # the same version as the current kernel. Check:
    dnf_update_required = False
    if (which("dnf")):
        res_d = runner.run(["dnf", "list", kernel_devel],
                           stdout=subprocess.DEVNULL,
                           stderr=subprocess.DEVNULL,
                           nocheck=True)
        res_h = runner.run(["dnf", "list", kernel_headers],
                           stdout=subprocess.DEVNULL,
                           stderr=subprocess.DEVNULL,
                           nocheck=True)
        if (not args.dry_run):
            kernel_devel_unavailable = (res_d.returncode != 0)
            kernel_headers_unavailable = (res_h.returncode != 0)
            dnf_update_required = kernel_devel_unavailable or \
                kernel_headers_unavailable
            if (kernel_devel_unavailable):
                print("Could not find package {}".format(kernel_devel))
            if (kernel_headers_unavailable):
                print("Could not find package {}".format(kernel_headers))

    # If the target kernel-devel/kernel-headers versions are not available for
    # the current release, suggest to run dnf update first. If no update is
    # available, and kernel-headers is the one that has a version mismatch (it
    # typically is), try with the version that is available.
    if (dnf_update_required):
        res = runner.run(["dnf", "list", "--upgrades", "kernel"],
                         stdout=subprocess.DEVNULL,
                         stderr=subprocess.DEVNULL,
                         nocheck=True)
        kernel_update_available = (res.returncode == 0)
        if (kernel_update_available):
            print("Kernel update required")
            if (util.ask_yes_or_no("OK to run \"dnf update\"?")):
                cmd = ["dnf", "update"]
                if (not interactive):
                    cmd.append("-y")
                runner.run(cmd, root=True)
                print("Please reboot to load the new kernel and try the " +
                      "command below again:")
                print("\n  blocksat-cli deps tbs-drivers\n")
                sys.exit(1)
                return

        # Fall back to the default kernel-headers package
        if kernel_headers_unavailable:
            print("Trying with the default kernel-headers package")
            dnf_pkg_list.remove(kernel_headers)
            dnf_pkg_list.append("kernel-headers")
        else:
            # Break if kernel-devel is missing for the current version and
            # there is no upgrade available.
            logger.error("Could not find an available kernel update")
            sys.exit(1)
            return

    _update_pkg_repo(interactive)
    _install_packages(apt_pkg_list,
                      dnf_pkg_list,
                      yum_pkg_list,
                      interactive=interactive,
                      update=False)

    # Clone the driver repositories
    driver_src_dir = os.path.join(args.cfg_dir, "src", "tbsdriver")
    media_build_dir = os.path.join(driver_src_dir, "media_build")
    media_dir = os.path.join(driver_src_dir, "media")

    if not os.path.exists(driver_src_dir):
        os.makedirs(driver_src_dir)

    if os.path.exists(media_build_dir):
        runner.run(["git", "pull", "origin", "master"], cwd=media_build_dir)
    else:
        runner.run(
            ["git", "clone", "https://github.com/tbsdtv/media_build.git"],
            cwd=driver_src_dir)

    if os.path.exists(media_dir):
        runner.run(["git", "pull", "origin", "latest"], cwd=media_dir)
    else:
        runner.run([
            "git", "clone", "--depth=1",
            "https://github.com/tbsdtv/linux_media.git", "-b", "latest",
            "./media"
        ],
                   cwd=driver_src_dir)

    # Build the media drivers
    nproc = int(subprocess.check_output(["nproc"]).decode().rstrip())
    nproc_arg = "-j" + str(nproc)

    runner.run(["make", "cleanall"], cwd=media_build_dir)
    runner.run(["make", "dir", "DIR=../media"], cwd=media_build_dir)
    runner.run(["make", "allyesconfig"], cwd=media_build_dir)

    # FIXME: Temporary workaround for error "modpost: "__devm_regmap_init_sccb"
    # ov9650.ko undefined!": disable ov9650 from the build. The problem was
    # observed on kernel versions 5.3.7 and 5.7.7. Apply the workaround for any
    # version < 5.8.
    if (distro.id() == "fedora"
            and LooseVersion(linux_release) < LooseVersion('5.8')):
        runner.run([
            "sed", "-i", "s/CONFIG_VIDEO_OV9650=m/CONFIG_VIDEO_OV9650=n/g",
            "v4l/.config"
        ],
                   cwd=media_build_dir)

    runner.run(["make", nproc_arg], cwd=media_build_dir)

    # Delete the previous Media Tree installation
    media_lib_path = "/lib/modules/" + linux_release + \
                     "/kernel/drivers/media/"
    runner.run(["rm", "-rf", media_lib_path], root=True, cwd=media_build_dir)

    # Install the new Media Tree
    runner.run(["make", "install"], root=True, cwd=media_build_dir)

    # Download the firmware
    tbs_linux_url = "https://www.tbsdtv.com/download/document/linux/"
    fw_tarball = "tbs-tuner-firmwares_v1.0.tar.bz2"
    fw_url = tbs_linux_url + fw_tarball
    util.download_file(fw_url, driver_src_dir, args.dry_run, logger=logger)

    # Install the firmware
    runner.run(["tar", "jxvf", fw_tarball, "-C", "/lib/firmware/"],
               root=True,
               cwd=driver_src_dir)

    if (not args.dry_run):
        print("Installation completed successfully. Please reboot now.")

def check_apps(apps):
    """Check if required apps are installed"""
    for app in apps:
        if (not which(app)):
            logging.error("Couldn't find {}. Is it installed?".format(app))
            print("\nTo install software dependencies, run:")
            print("""
            blocksat-cli deps install
            """)
            return False
    # All apps are installed
    return True


import Sorts
import sys
import time
from random import randint

inicio = time.time()
algoritmo = str(sys.argv[1])
n = int(sys.argv[2])
i = 0
A = []
while i!=n:
	A.append(randint(0,1000))
	i = i+1
if algoritmo == "MergeSort":
	Sorts.MergeSort(A, 0, n-1)
else:
	Sorts.InsertionSort(A, 0, n)
fin = time.time()
tiempo = (fin-inicio) * 1000
print(algoritmo, n, str(tiempo))


"""
-----------------------------------------
PGR107 Eksam                            #
Task 5                                  #
Group: PGR107_Students_2023             #
Description: Guess a word game          #
-----------------------------------------
"""
# libraries
import random

## function for opne file
def handle_file(filtype):

    with open(filtype, "r") as file:
        scan_words = file.readlines()
    return random.choice(scan_words).strip()

## function for displying words in terminal
def displaying_words(word, guessed_letters):

    show_display = ""
    for letter in word:
        if letter in guessed_letters:
            show_display += letter
        else:
            show_display += "_"
    return show_display

## main function to play the-game
def play_game():
    folder_path = ''
    while True:
        try:
            filtype = input("Enter the filename containing the words (e.x..words.txt):\n>>")
            folder_path += f'resources/../resources/{filtype}.txt'
            word = handle_file(folder_path)
            break

        except Exception  as e:
            print(f"Error: {e}. Please try again with valid filename\n")

    guessed_letters = set()
    incorrect_guess = 0
    word_length = len(word)

    ## display of instrcutions and menu
    print("          __        ___  __   __  ")
    print("|  |     / _` |  | |__  /__` /__` ")
    print("|/\| ___ \__> \__/ |___ .__/ .__/ ")
    print("                                  ")
    print("Version 1.0")
    print("\n")
    print(f"Welcome to the guessing game\n"
    f"Type \q command to leave the game early\n\n")
    print("-" * 75)
    print(f"The word you need to guess has {word_length} characters. "
    f"You have {word_length} guesses left.\n")

    while incorrect_guess < word_length:
        print("Current word:" , displaying_words(word, guessed_letters))
        sGuess = input("Guess a character: ").lower()

        ## check to quit the game after
        if sGuess == '\\q':
            print("Exiting game..")
            break

        ## check to warn the user to only add only a singe letter

        if not sGuess.isalpha() or len(sGuess) > 1:
            print("Please enter a single letter only.\n")
            continue

        if sGuess in guessed_letters:
            print("You already guessed this letter\n")

        elif sGuess in word:
            guessed_letters.add(sGuess)
            print("Correct letter\n")
            print("-" * 55)

        else:
            incorrect_guess += 1
            print("-" * 55)
            print(f"Sorry, incorrect letter. You have {word_length - incorrect_guess} guesses left.")

        if set(word).issubset(guessed_letters):
            print(f"Congratulations! You guessed the word: {word}")
            break
    else:
        print(f"Game over! The word was: {word}")

##------- End_of_Program ---------- ##


import pafy
import vlc # Windows requires VLC installed 64 bits
import time
import requests
import random
import api # Python file which return youtube api key
import os

#Command line tools
from PyInquirer import prompt
from examples import custom_style_2

#Junming Qiu
#Youtubeify - Command line Youtube audio player from URLs

#HOW TO USE
#Fill api_key
#fill songlist.txt with youtube links
#ctrl-c to pause

global api_key
api_key = api.get_api_key()

#Opens title file name and pulls random title art
def grab_title_art(titlefonts=None):
    if not titlefonts:
        return "{==Welcome to Youtubify==}"

    with open(titlefonts, "r") as f:
        rand_title = random.randint(1, int(f.readline()))
        line = f.readline()
        count = 0
        while len(line) != 0 and count < rand_title:
            line = f.readline()
            if line[:2] == "~>":
                count += 1
                height = int(line.strip().split(" ")[1])

        ret_title = ""

        for i in range(height):
            ret_title += f.readline()

        f.close()
        return ret_title

#Simple song progress bar
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd="\r"):
    """
    Call in a loop to create terminal progress bar
    @params:
        iteration   - Required  : current iteration (Int)
        total       - Required  : total iterations (Int)
        prefix      - Optional  : prefix string (Str)
        suffix      - Optional  : suffix string (Str)
        decimals    - Optional  : positive number of decimals in percent complete (Int)
        length      - Optional  : character length of bar (Int)
        fill        - Optional  : bar fill character (Str)
        printEnd    - Optional  : end character (e.g. "\r", "\r\n") (Str)
    """
    if iteration == total:
        filledLength = int(length * iteration // total)
        bar = fill * filledLength + '-' * (length - filledLength)
        print(f"\r{prefix} |{bar}| {100}% {suffix}", end = printEnd)
        print()
    else:
        percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
        filledLength = int(length * iteration // total)
        bar = fill * filledLength + '-' * (length - filledLength)
        print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)

#Finds all titles of urls from playlist txt files
#show_url setting is for debug -> determining what url matches to each song
def update_song_directory(songs, show_url = False):
    name_url = []

    for song in songs:
        song_id = song.split("=")[1]
        new_url = f"https://www.googleapis.com/youtube/v3/videos?id={song_id}&part=snippet&key={api_key}"
        response = requests.get(new_url)
        json_thing = response.json()

        if show_url:
            name_url.append((json_thing["items"][0]["snippet"]["title"], song))
        else:
            name_url.append(json_thing["items"][0]["snippet"]["title"])

    return name_url

#Gets duration of video using API
def get_duration(song_id):
    new_url = f"https://www.googleapis.com/youtube/v3/videos?id={song_id}&part=contentDetails&key={api_key}"
    response = requests.get(new_url)
    json_thing = response.json()
    time = json_thing["items"][0]["contentDetails"]["duration"][2:]
    seconds = 0

    if "H" in time:
        seconds += 360 * int(time[:time.index("H")])
        time = time[time.index("H") + 1:]

    if "M" in time:
        seconds += 60 * int(time[:time.index("M")])
        time = time[time.index("M") + 1:]

    if "S" in time:
        seconds += int(time[:time.index("S")])

    return seconds

#Searches for videos and returns one which user chooses
def search_mode(max_results=10):
    print("Enter a search term:")
    search_q = input()
    new_url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults={max_results}&q={search_q}&type=video&key={api_key}"
    response = requests.get(new_url)
    json_thing = response.json()

    result_ids = []
    name_ids = []
    print("Results: ")
    for i in range(max_results):
        result_ids.append(json_thing["items"][i]["id"]["videoId"])
        name_ids.append(json_thing["items"][i]["snippet"]["title"])

    search_CLI = [
        {
            'type': 'list',
            'name': 'user_option',
            'message': 'Choose a Song: ',
            'choices': name_ids
        }
    ]

    answers = prompt(search_CLI, style=custom_style_2)
    answers_name = answers.get("user_option")
    choice = name_ids.index(answers_name)

    if 0 <= choice <= 10:
        return result_ids[choice], name_ids[choice]
    else:
        return None

#Main Program loop
def play(songs, shuffle:bool):
    STOP = False
    searched_song = None

    print(grab_title_art("titlefonts.txt"))
    print("Press 'ctrl-c' to pause and see controls")
    print("Press enter now to add all playlists")
    print("Type anything else and enter to add songs by search")

    if input() != "":
        songs = []

    print("Loading Playlists...\n")

    if not shuffle:
        song_directory = update_song_directory(songs)

    # Load playlist loop
    while not STOP:
        if shuffle:
            print("Shuffling Songs...\n")
            random.shuffle(songs)
            song_directory = update_song_directory(songs)

        curr_song_num = 0

        # Initialize song loop
        while curr_song_num < len(songs):
            os.system('cls' if os.name == 'nt' else 'clear')
            print(len(songs), "songs loaded")
            if searched_song == None:
                song = songs[curr_song_num]
                print()
                print(f"Now Playing #{curr_song_num}:", song_directory[curr_song_num], 50 * " ")

            else:
                song = f"https://www.youtube.com/watch?v={searched_song[0]}"
                print()
                print(f"Now Playing", searched_song[1], 50 * " ")

            searched_song = None

            url = song.strip()
            try:
                video = pafy.new(url)
            except KeyError:
                curr_song_num += 1
                break

            best = video.getbest()
            playurl = best.url
            playtime = get_duration(song.split("=")[1])

            Instance = vlc.Instance()
            player = Instance.media_player_new()
            Media = Instance.media_new(playurl, ':no-video')
            Media.get_mrl()
            player.set_media(Media)
            time.sleep(1)
            player.play()

            count = 0

            printProgressBar(0, playtime, prefix = ' Time', suffix = '', length = 50)

            # Play song loop
            while count < playtime:
                try:
                    time.sleep(1)
                    items = list(range(0, 57))

                    printProgressBar(count, playtime, prefix = ' Time', suffix = '', length = 50)
                    count += 1
                except KeyboardInterrupt:
                    player.pause()
                    print("h = help", " " * 100)
                    instr = input()

                    if len(instr) == 0:
                        player.play()

                    #Play
                    elif instr == "p":
                        print()
                        player.play()

                    #Skip Song
                    elif instr == "s":
                        print()
                        player.stop()
                        break

                    #Reload song
                    elif instr == "r":
                        print()
                        curr_song_num -= 1
                        player.stop()
                        break

                    elif instr == "rr":
                        print()

                    #Display Timestamp
                    elif instr == "l":
                        print(f"Currently Playing #{curr_song_num}:", song_directory[curr_song_num])
                        print("Current time:", count // 60, "m", count % 60, "s")
                        print("Total Length:", playtime // 60, "m", playtime % 60, "s\n")
                        player.play()

                    #Show List of Songs -> Select Song
                    elif instr == "g":

                        playlist_CLI = [
                            {
                                'type': 'list',
                                'name': 'user_option',
                                'message': 'Choose a Song: ',
                                'choices': song_directory
                            }
                        ]

                        answers = prompt(playlist_CLI, style=custom_style_2)
                        answer_name = answers.get("user_option")
                        new_song_num = song_directory.index(answer_name)

                        if 0 <= new_song_num < len(songs):
                            player.stop()
                            curr_song_num = new_song_num
                            curr_song_num -= 1
                            print()
                            break
                        else:
                            player.play()

                    #Shuffle Songs
                    elif instr == "sh":
                        print("Shuffling Songs...\n")
                        random.shuffle(songs)
                        song_directory = update_song_directory(songs)
                        curr_song_num = -1
                        player.stop()
                        break

                    #Increase volume by 10/+
                    elif instr[0] == "+":
                        player.audio_set_volume(player.audio_get_volume() + len(instr) * 10)
                        print("Current Volume:", player.audio_get_volume())
                        player.play()

                    #Decrease volume by 10/-
                    elif instr[0] == "-":
                        player.audio_set_volume(player.audio_get_volume() - len(instr) * 10)
                        print("Current Volume:", player.audio_get_volume())
                        player.play()

                    #Show commands
                    elif instr == "h":
                        print("Media Controls: l = remaining playtime, +/- = volume controls")
                        print("Song Controls: p = play, s = skip, r = reload, g = go to song")
                        print("App Controls: sh = shuffle, ed = edit playlists, exit = close app\n")
                        print("Search Controls: $p = search + play, $aq = search + add to queue")
                        player.play()

                    #Enter Search Mode -> Select song || Add song to playlist
                    elif instr[0] == "$":
                        # $p = play now
                        # $aq = add song to queue
                        # $ap = add song to playlist
                        # $apq = add song to queue and playlist

                        searched_song = search_mode()
                        command = instr[1:]

                        if searched_song and len(command) > 0:
                            if command == "p":
                                player.stop()
                                break
                            elif command == "aq":
                                songs.append(f"https://www.youtube.com/watch?v={searched_song[0]}")
                                print(searched_song[0], searched_song[1])
                                song_directory.append(searched_song[1])
                                print(f"Song: {searched_song[1]} added to queue")
                                searched_song = None
                                player.play()

                            elif command == "ap":
                                print(f"Song: {searched_song[1]} added to playlist{1}")

                            elif command == "apq":
                                print(f"Song: {searched_song[1]} added to queue and to playlist{1}")

                        else:
                            player.play()

                    #List and select playlist
                    elif instr == "pl":
                        pass

                    #Close Player
                    elif instr == "exit":
                        player.stop()
                        STOP = True
                        curr_song_num = len(songs)
                        print("Shutting Down")
                        break

                    else:
                        player.play()

            curr_song_num += 1
            player.release()

        if not STOP:
            print("Reached End of Songs!\n")

def main():
    songs = []

    f = open("config.txt", "r")

    for line in f:
        if line[0] != "-":
            plist = open(line.strip(), "r")

            for song in plist:
                strip = song.strip()

                if len(strip) != 0:
                    songs.append(strip)

    plist.close()
    f.close()

    play(songs, shuffle=False)

if __name__ == "__main__":
    main()

"""
Features:
play, pause, skip, shuffle, volume controls
goto song, playlist management (manual for now)
search song, show song timestamp, progress bar
"""

"""
WIP:
- Make downloadable mp3s
- Executable to run
- Procedural loading for playlists
- Reload playlists -> to edit playlist and add new song on the fly
- Fast forward, back
- Add albums by url
- Edit playlists
- Find by genre?
- Show next song
- Config file more options
- Generate sound from app
- More error catching
- Move functions into other package
- Song classification system
- Playlist classification system
"""


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 14:09:32 2020

@author: slomogangsta
"""

matrix={'|': [
            [(0,0)],
            [(0,1),(1,0),(1,2),(2,1),(1,3),(3,1),(3,2),(2,3),(1,1)],
            [(0,2),(2,0),(2,2)],
            [(0,3),(3,0),(3,3)]
            ],

        '&':[[(0,0),(0,1),(1,0),(0,2),(2,0),(3,0),(0,3),(2,3),(3,2)],
            [(1,1)],
            [(2,1),(1,2),(2,2)],
            [(3,1),(1,3),(3,3)]],

        '^':[[(0,0),(1,1),(2,2),(3,3)],
            [(1,0),(3,2),(2,3),(0,1)],
            [(0,2),(2,0),(1,3),(3,1)],
            [(0,3),(3,0),(1,2),(2,1)]] }

def rank(op):

    if (op == '|'):
        return 1
    if (op == '^'):
        return 2
    if (op == '&'):
        return 3
    return 0

def operation(a, b, op):
    global matrix
    answer = []
    if (op == "|"):
        for i in matrix[op]:
            sum1=0
            for j in i:
                prod = a[j[0]] * b[j[1]]
                sum1+=prod
            answer.append(sum1)
    elif (op == "&"):
        for i in matrix[op]:
            sum1=0
            for j in i:
                prod = a[j[0]] * b[j[1]]
                sum1+=prod
            answer.append(sum1)
    elif (op == "^"):
        for i in matrix[op]:
            sum1=0
            for j in i:
                prod = a[j[0]] * b[j[1]]
                sum1+=prod
            answer.append(sum1)
    return answer

def evaluateExpression(tok):

    vst = []
    ost = []
    i = 0

    while i < len(tok):

        if tok[i] == '(':
            ost.append(tok[i])

        elif (tok[i] == '#'):
            value = [1,1,1,1]
            vst.append(value)

        elif tok[i] == ')':

            while len(ost) != 0 and ost[-1] != '(':

                v2 = vst.pop()
                v1 = vst.pop()
                op = ost.pop()
                vst.append(operation(v1, v2, op))

            ost.pop()

        else:
            while (len(ost) != 0 and rank(ost[-1]) >= rank(tok[i])):
                v2 = vst.pop()
                v1 = vst.pop()
                op = ost.pop()
                vst.append(operation(v1, v2, op))

            ost.append(tok[i])
        i += 1

    while len(ost) != 0:

        v2 = vst.pop()
        v1 = vst.pop()
        op = ost.pop()

        vst.append(operation(v1, v2, op))

    return vst[-1]

def powerc(num, n, m):
    num%=m;
    prod=1;
    while(n!=0):
        if((n&1)==1):
            prod=(prod*num)%m;
        num=(num*num)%m;
        n>>=1;
    print(prod)
    return prod;

t = int(input())
for _ in range(t):
    expression = input()
    result = evaluateExpression(expression)
    print(result)
    m = expression.count('#')
    m = 4**m
    moderator = 998244353
    for i in range(len(result)):
        result[i]= result[i]*powerc(m,moderator-2,moderator)%moderator
    print(*result)


# -*- coding: utf-8 -*-
from datetime import datetime

from sqlalchemy import Column, Integer, Text, String

from app.lib.orm import db
from app.model.base import Base

class Project(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String(64), nullable=True, unique=True)
    mocks = db.relationship('Mock', backref=db.backref('project', lazy="joined"), lazy='joined')
    desc = Column(Text)

    # GET
    @staticmethod
    def fetch_project(project_id):
        project = Project.query.filter_by(id=project_id).first_or_404()
        return project

    # UPDATE
    @staticmethod
    def update_project(project_id, form):
        project = Project.query.filter_by(id=project_id).first_or_404()
        new_project_name = None
        new_project_desc = None
        if 'name' in form:
            new_project_name = form['name']
        if 'desc' in form:
            new_project_desc = form['desc']
        try:
            with db.auto_commit():
                if new_project_name:
                    project.name = new_project_name
                if new_project_desc:
                    project.desc = new_project_desc
                # 更新时间
                project.update_time = datetime.now()
        except IndentationError as e:
            print(e)
            return False
        return True

    # CREATE
    @staticmethod
    def insert(project_name, project_desc):
        try:
            with db.auto_commit():
                project = Project(name=project_name, desc=project_desc)
                db.session.add(project)
        except IndentationError as e:
            print(e)
            return False
        return True


# Course: CS261 - Data Structures
# Student Name: Casey Levy
# Assignment: Assignment 2 - bag_da.py
# Description: Writing add, remove, count, and clear methods for Bag class.
# Last revised: 10/19/2020

from dynamic_array import *

class Bag:
    def __init__(self, start_bag=None):
        """
        Init new bag based on Dynamic Array
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        self.da = DynamicArray()

        # populate bag with initial values (if provided)
        # before using this feature, implement add() method
        if start_bag is not None:
            for value in start_bag:
                self.add(value)

    def __str__(self) -> str:
        """
        Return content of stack in human-readable form
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        out = "BAG: " + str(self.da.length()) + " elements. ["
        out += ', '.join([str(self.da.get_at_index(_))
                          for _ in range(self.da.length())])
        return out + ']'

    def size(self) -> int:
        """
        Return total number of items currently in the bag
        DO NOT CHANGE THIS CLASS IN ANY WAY
        """
        return self.da.length()

    def add(self, value: object) -> None:
        """
        This method will add a value
        """

        self.da.append(value)

    def remove(self, value: object) -> bool:
        """
        This method will remove the given value.
        False will be returned if the value is not found, True if found
        """

        for i in range(self.size()):
            if self.da.get_at_index(i) == value:
                self.da.remove_at_index(i)
                return True                   # Returning True if value is found
        return False                  # Returning False if value not found

    def count(self, value: object) -> int:
        """
        This method will count how many times the given value appears in
        the array.
        """
        val_count = 0

        for i in range(self.size()):
            if value == self.da.get_at_index(i):  # Checking if given value is in the array and incrememnting the variable by 1
                val_count += 1

        return val_count

    def clear(self) -> None:
        """
        This method clears all the contents of the bag
        """

        for i in range(self.size()):
            self.da.remove_at_index(0)

    def equal(self, second_bag: object) -> bool:
        """
        Compares the content of the current bag with that of the second bag provided by the user.
        Returns True if bags are equal, False if not. Both Bags must have the same number
           of elements and the same elements to be equal. Order does not matter in the Bags.
        """

        if self.size() != second_bag.size():
            return False

        for i in range(self.size()):
            found = False
            for x in range(self.size()):
                if self.da.get_at_index(i) == second_bag.da.get_at_index(x):
                    found = True
            if found is False:
                return False

        return True

# BASIC TESTING
if __name__ == "__main__":

    print("\n# add example 1")
    bag = Bag()
    print(bag)
    values = [10, 20, 30, 10, 20, 30]
    for value in values:
        bag.add(value)
    print(bag)

    print("\n# remove example 1")
    bag = Bag([1, 2, 3, 1, 2, 3, 1, 2, 3])
    print(bag)
    print(bag.remove(7), bag)
    print(bag.remove(3), bag)
    print(bag.remove(3), bag)
    print(bag.remove(3), bag)
    print(bag.remove(3), bag)

    print("\n# count example 1")
    bag = Bag([1, 2, 3, 1, 2, 2])
    print(bag, bag.count(1), bag.count(2), bag.count(3), bag.count(4))

    print("\n# clear example 1")
    bag = Bag([1, 2, 3, 1, 2, 3])
    print(bag)
    bag.clear()
    print(bag)

    print("\n# equal example 1")
    bag1 = Bag([10, 20, 30, 40, 50, 60])
    bag2 = Bag([60, 50, 40, 30, 20, 10])
    bag3 = Bag([10, 20, 30, 40, 50])
    bag_empty = Bag()

    print(bag1, bag2, bag3, bag_empty, sep="\n")
    print(bag1.equal(bag2), bag2.equal(bag1))
    print(bag1.equal(bag3), bag3.equal(bag1))
    print(bag2.equal(bag3), bag3.equal(bag2))
    print(bag1.equal(bag_empty), bag_empty.equal(bag1))
    print(bag_empty.equal(bag_empty))
    print(bag1, bag2, bag3, bag_empty, sep="\n")

    bag1 = Bag([100, 200, 300, 200])
    bag2 = Bag([100, 200, 30, 100])
    print(bag1.equal(bag2))


import os.path
import time

import openhtf as htf
from openhtf import util
from examples import example_plugs
from openhtf.output import callbacks
from openhtf.output.callbacks import console_summary
from openhtf.output.callbacks import json_factory
from openhtf.plugs import user_input
from openhtf.util import units

@htf.plug(example=example_plugs.example_plug_configured)
@htf.plug(frontend_aware=example_plugs.ExampleFrontendAwarePlug)
def example_monitor(example, frontend_aware):
  time.sleep(.2)
  frontend_aware.increment()
  return example.increment()

@htf.measures(
    htf.Measurement('widget_type').matches_regex(r'.*Widget$').doc(
        """This measurement tracks the type of widgets."""),
    htf.Measurement('widget_color').doc('Color of the widget'),
    htf.Measurement('widget_size').in_range(1, 4).doc('Size of widget'))
@htf.measures(
    'specified_as_args',
    docstring='Helpful docstring',
    units=units.HERTZ,
    validators=[util.validators.matches_regex('Measurement')])
@htf.plug(example=example_plugs.example_plug_configured)
@htf.plug(prompts=user_input.UserInput)
def hello_world(test, example, prompts):
  """A hello world test phase."""
  test.logger.info('Hello World!')
  test.measurements.widget_type = prompts.prompt(
      'What\'s the widget type? (Hint: try `MyWidget` to PASS)',
      text_input=True)
  if test.measurements.widget_type == 'raise':
    raise Exception()
  test.measurements.widget_color = 'Black'
  test.measurements.widget_size = 3
  test.measurements.specified_as_args = 'Measurement args specified directly'
  test.logger.info('Plug value: %s', example.increment())

# Timeout if this phase takes longer than 10 seconds.
@htf.PhaseOptions(timeout_s=10)
@htf.measures(
    *(htf.Measurement('level_%s' % i) for i in ['none', 'some', 'all']))
@htf.monitors('monitor_measurement', example_monitor)
def set_measurements(test):
  """Test phase that sets a measurement."""
  test.measurements.level_none = 0
  time.sleep(1)
  test.measurements.level_some = 8
  time.sleep(1)
  test.measurements.level_all = 9
  time.sleep(1)
  level_all = test.get_measurement('level_all')
  assert level_all.value == 9

@htf.measures(
    htf.Measurement('dimensions').with_dimensions(units.HERTZ),
    htf.Measurement('lots_of_dims').with_dimensions(
        units.HERTZ, units.SECOND,
        htf.Dimension(description='my_angle', unit=units.RADIAN)))
def dimensions(test):
  """Phase with dimensioned measurements."""
  for dim in range(5):
    test.measurements.dimensions[dim] = 1 << dim
  for x, y, z in zip(
      list(range(1, 5)), list(range(21, 25)), list(range(101, 105))):
    test.measurements.lots_of_dims[x, y, z] = x + y + z

@htf.measures(
    htf.Measurement('replaced_min_only').in_range('{minimum}', 5, type=int),
    htf.Measurement('replaced_max_only').in_range(0, '{maximum}', type=int),
    htf.Measurement('replaced_min_max').in_range(
        '{minimum}', '{maximum}', type=int),
)
def measures_with_args(test, minimum, maximum):
  """Phase with measurement with arguments."""
  del minimum  # Unused.
  del maximum  # Unused.
  test.measurements.replaced_min_only = 1
  test.measurements.replaced_max_only = 1
  test.measurements.replaced_min_max = 1

@htf.measures(
    htf.Measurement('replaced_marginal_min_only').in_range(
        0, 10, '{marginal_minimum}', 8, type=int),
    htf.Measurement('replaced_marginal_max_only').in_range(
        0, 10, 2, '{marginal_maximum}', type=int),
    htf.Measurement('replaced_marginal_min_max').in_range(
        0, 10, '{marginal_minimum}', '{marginal_maximum}', type=int),
)
def measures_with_marginal_args(test, marginal_minimum, marginal_maximum):
  """Phase with measurement with marginal arguments."""
  del marginal_minimum  # Unused.
  del marginal_maximum  # Unused.
  test.measurements.replaced_marginal_min_only = 3
  test.measurements.replaced_marginal_max_only = 3
  test.measurements.replaced_marginal_min_max = 3

def attachments(test):
  test.attach('test_attachment',
              'This is test attachment data.'.encode('utf-8'))
  test.attach_from_file(
      os.path.join(os.path.dirname(__file__), 'example_attachment.txt'))

  test_attachment = test.get_attachment('test_attachment')
  assert test_attachment.data == b'This is test attachment data.'

@htf.PhaseOptions(run_if=lambda: False)
def skip_phase():
  """Don't run this phase."""

def analysis(test):  # pylint: disable=missing-function-docstring
  level_all = test.get_measurement('level_all')
  assert level_all.value == 9
  test_attachment = test.get_attachment('test_attachment')
  assert test_attachment.data == b'This is test attachment data.'
  lots_of_dims = test.get_measurement('lots_of_dims')
  assert lots_of_dims.value.value == [
      (1, 21, 101, 123),
      (2, 22, 102, 126),
      (3, 23, 103, 129),
      (4, 24, 104, 132),
  ]
  test.logger.info('Pandas datafram of lots_of_dims \n:%s',
                   lots_of_dims.value.to_dataframe())

def teardown(test):
  test.logger.info('Running teardown')

def main():
  test = htf.Test(
      htf.PhaseGroup.with_teardown(teardown)(
          hello_world,
          set_measurements,
          dimensions,
          attachments,
          skip_phase,
          measures_with_args.with_args(minimum=1, maximum=4),
          measures_with_marginal_args.with_args(
              marginal_minimum=4, marginal_maximum=6),
          analysis,
      ),
      # Some metadata fields, these in particular are used by mfg-inspector,
      # but you can include any metadata fields.
      test_name='MyTest',
      test_description='OpenHTF Example Test',
      test_version='1.0.0')
  test.add_output_callbacks(
      callbacks.OutputToFile(
          './{dut_id}.{metadata[test_name]}.{start_time_millis}.pickle'))
  test.add_output_callbacks(
      json_factory.OutputToJSON(
          './{dut_id}.{metadata[test_name]}.{start_time_millis}.json',
          indent=4))
  test.add_output_callbacks(console_summary.ConsoleSummary())

  # Example of how to output to testrun protobuf format and save to disk then
  # upload.  Replace json_file with your JSON-formatted private key downloaded
  # from Google Developers Console when you created the Service Account you
  # intend to use, or name it 'my_private_key.json'.
  # inspector = (mfg_inspector.MfgInspector
  #    .from_json(json.load(json_file)))
  #    .set_converter(test_runs_converter.test_run_from_test_record))
  # test.add_output_callbacks(
  #     inspector.save_to_disk('./{dut_id}.{start_time_millis}.pb'),
  #     inspector.upload())

  test.execute(test_start=user_input.prompt_for_test_start())

if __name__ == '__main__':
  main()


import os
import cv2
import skimage
import numpy as np

from caffe2.proto import caffe2_pb2
from caffe2.python import workspace, core, dyndep

from detectron.core.config import merge_cfg_from_file, cfg
import detectron.utils.model_convert_utils as mutils
import detectron.utils.blob as blob_utils

def crop_center(img,cropx,cropy):
    y,x,c = img.shape
    startx = x//2-(cropx//2)
    starty = y//2-(cropy//2)
    return img[starty:starty+cropy,startx:startx+cropx]

def rescale(img, input_height, input_width):
    print("Original image shape:" + str(img.shape) + " and remember it should be in H, W, C!")
    print("Model's input shape is %dx%d") % (input_height, input_width)
    aspect = img.shape[1]/float(img.shape[0])
    print("Orginal aspect ratio: " + str(aspect))
    if(aspect>1):
        # landscape orientation - wide image
        res = int(aspect * input_height)
        imgScaled = skimage.transform.resize(img, (input_width, res))
    if(aspect<1):
        # portrait orientation - tall image
        res = int(input_width/aspect)
        imgScaled = skimage.transform.resize(img, (res, input_height))
    if(aspect == 1):
        imgScaled = skimage.transform.resize(img, (input_width, input_height))

    return imgScaled

def _sort_results(boxes, segms, keypoints, classes):
    indices = np.argsort(boxes[:, -1])[::-1]
    if boxes is not None:
        boxes = boxes[indices, :]
    if segms is not None:
        segms = [segms[x] for x in indices]
    if keypoints is not None:
        keypoints = [keypoints[x] for x in indices]
    if classes is not None:
        if isinstance(classes, list):
            classes = [classes[x] for x in indices]
        else:
            classes = classes[indices]

    return boxes, segms, keypoints, classes

def _prepare_blobs(
    im,
    pixel_means,
    target_size,
    max_size,
    ):
    """ Reference: blob.prep_im_for_blob()"""

    im = im.astype(np.float32, copy=False)
    im -= pixel_means
    im_shape = im.shape

    im_size_min = np.min(im_shape[0:2])
    im_size_max = np.max(im_shape[0:2])
    im_scale = float(target_size) / float(im_size_min)
    if np.round(im_scale * im_size_max) > max_size:
        im_scale = float(max_size) / float(im_size_max)
    im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,
                    interpolation=cv2.INTER_LINEAR)

    # Reuse code in blob_utils and fit FPN
    blob = blob_utils.im_list_to_blob([im])

    blobs = {}
    blobs['data'] = blob
    blobs['im_info'] = np.array(
        [[blob.shape[2], blob.shape[3], im_scale]],
        dtype=np.float32
    )
    return blobs

def _get_result_blobs(check_blobs):
    ret = {}
    for x in check_blobs:
        sn = core.ScopedName(x)
        if workspace.HasBlob(sn):
            ret[x] = workspace.FetchBlob(sn)
        else:
            ret[x] = None

    return ret

## JUST PLAYING AROUND. KEEPING TRACK OF WHAT NEEDS TO BE DONE.

def load_model():
    """ Loads the model defined in INIT_NET and PREDICT_NET into
    the caffe2 workspace. """

    device_opts = caffe2_pb2.DeviceOption()
    device_opts.device_type = caffe2_pb2.CPU
    INIT_NET = "out/model_init.pb"
    PREDICT_NET = "out/model.pb"
    init_def = caffe2_pb2.NetDef()
    with open(INIT_NET, 'rb') as f:
        init_def.ParseFromString(f.read())
        init_def.device_option.CopyFrom(device_opts)
        workspace.RunNetOnce(init_def.SerializeToString())

    net_def = caffe2_pb2.NetDef()
    with open(PREDICT_NET, 'rb') as f:
        net_def.ParseFromString(f.read())
        net_def.device_option.CopyFrom(device_opts)
        workspace.CreateNet(net_def.SerializeToString(), overwrite=True)

    return init_def, net_def

def get_image(img_url):
    return skimage.img_as_float(skimage.io.imread(img_url)).astype(np.float32)

def run_on_image(img_url, net):
    img = get_image(img_url)
    input_blobs = _prepare_blobs(
                                 img,
                                 cfg.PIXEL_MEANS,
                                 cfg.TEST.SCALE,
                                 cfg.TEST.MAX_SIZE
                                )

    for k, v in input_blobs.items():
        workspace.FeedBlob(
                           core.ScopedName(k),
                           v,
                           mutils.get_device_option_cpu()
                          )
    workspace.RunNetOnce(net)
    blob_names = workspace.Blobs()
    for x in blob_names:
        print(x)
    #goods = [x for x in blob_names if x.split('_')[-1] == 'nms']
    #print(goods)
    scores = workspace.FetchBlob('score_nms')
    classids = workspace.FetchBlob('class_nms')
    boxes = workspace.FetchBlob('bbox_nms')
    cls_prob = workspace.FetchBlob('cls_prob')
    bbox_pred = workspace.FetchBlob('bbox_pred')

    print(scores)
    print(classids)
    print(boxes)

    print("cls_prob: shape {}".format(cls_prob.shape))
    print(cls_prob)
    print("bbox_pred: shape {}".format(bbox_pred.shape))
    print(bbox_pred)
    #except Exception as e:
    #    print('Model failed to run')
    #    R = 0
    #    scores = np.zeros((R,), dtype=np.float32)
    #    boxes = np.zeros((R, 4), dtype=np.float32)
    #    classids = np.zeros((R,), dtype=np.float32)

    boxes = np.column_stack((boxes, scores))
    #print(boxes)
    boxes, _, _, classids = _sort_results(
        boxes, None, None, classids)

    check_blobs = [
        "result_boxes", "result_classids",  # result
        ]
    workspace.FeedBlob('result_boxes', boxes)
    workspace.FeedBlob('result_classids', classids)

    ret = _get_result_blobs(check_blobs)

    return ret

def load_environment():

    core.GlobalInit(['caffe2', '--caffe2_log_level=0'])
    DETECTRON_HOME = os.environ.get('DETECTRON_HOME')
    if DETECTRON_HOME is None:
        DETECTRON_HOME = '/home/thomas/code/detectron_service/detectron'
    cfg_fname = os.path.join(
                DETECTRON_HOME,
                'configs/12_2017_baselines/e2e_mask_rcnn_R-101-FPN_2x.yaml'
                          )
    merge_cfg_from_file(cfg_fname)
    detectron_ops_lib = "/home/thomas/caffe2/lib/libcaffe2_detectron_ops_gpu.so"
    dyndep.InitOpsLibrary(detectron_ops_lib)
    _, net = load_model()
    return net

def main():
    #img_url = "https://cdn.japantimes.2xx.jp/wp-content/uploads/2018/03/p9-masangkay-cathat-a-20180319-870x580.jpg"
    img_url = "https://d3d00swyhr67nd.cloudfront.net/w1200h1200/STF/STF_STKMG_030.jpg"
    net = load_environment()
    ret = run_on_image(img_url, net)
    print(ret)

if __name__ == "__main__":
    main()


"""------------------------------------------------------------------------
------------------ Balanced Parantheses------------------------------------
--> Take an Arithmetic Expressio such as (5+6)*(7+8)/(4+3)(5+6)*(7+8)/(4+3)
---Where parentheses are used to order the performance of operations.Ensure
---parentheses must apper in abalanced fashion
------------------------------------------------------------------------"""
from Fellowship_programs.DataStructurePrograms.Stack import Stack

# creating object for the Stack
stk = Stack()
# Reading the expression from user
exp = str(input("enter the expression"))
balance = 0
# reading the each character in the string
for i in exp:
    # if i == '(' it will be pushed in to the stack
    r = stk.push(i)
    if r == '(':
        balance +=1
    elif r == ')':
        balance -=1
    # balance is < 0 means ')' is misplaced s
    if balance < 0 :
        print(" ')' is in wrong place , Equation is not balanced")
        exit()

# if  balance == 0  the expression is balanced
# balance > 0 the expression has excess'('
if balance == 0 :
    print("the expression is balanced")
else:
    print("the expression is not balanced")
    print("it have excess '(' ")


#!/usr/bin/python3
from __future__ import print_function

import numpy as np
from .antenna_model import Antenna_Model, Antenna_Optimizer, Arg_Handler
from .antenna_model import Excitation, antenna_actions

class Multi_Dipole (Antenna_Model):
    """ Multiple coupled dipoles for 10m-15m, inspired by:
        Martin Erger. Endgespeiste Vertikalantenne für 15 m, 12 m und 10 m.
        Funkamateur, (5):384–387, May 2022.
    """

    name          = 'Multi Dipole 10m, 12m, 15m'
    wire_radius   = 1.5e-3 / 2.0
    radius_feed   = 3e-3
    lu_15m        = 3.26
    ll_15m        = 3.4
    lu_12m        = 3.05
    ll_12m        = 2.26
    lu_10m        = 2.45
    ll_10m        = 2.35
    d_12_15       = 50e-3
    d_10_15       = 33e-3
    seglen        = 0.15
    feedpoint_h   = 5
    # Use the data parts of each band
    frq_ranges    = [(28.070, 28.190), (24.915, 24.940), (21.070, 21.149)]
    # Theta must be < 90° when we have ground
    theta_range   = 90

    def __init__ \
        ( self
        , lu_15m        = lu_15m
        , ll_15m        = ll_15m
        , lu_12m        = lu_12m
        , ll_12m        = ll_12m
        , lu_10m        = lu_10m
        , ll_10m        = ll_10m
        , d_12_15       = d_12_15
        , d_10_15       = d_10_15
        , wire_radius   = wire_radius
        , radius_feed   = radius_feed
        , feedpoint_h   = feedpoint_h
        , ** kw
        ):
        self.lu_15m      = lu_15m
        self.ll_15m      = ll_15m
        self.lu_12m      = lu_12m
        self.ll_12m      = ll_12m
        self.lu_10m      = lu_10m
        self.ll_10m      = ll_10m
        self.d_12_15     = d_12_15
        self.d_10_15     = d_10_15
        self.radius_feed = radius_feed
        self.feedpoint_h = feedpoint_h
        self.__super.__init__ (** kw)
    # end def __init__

    def cmdline (self):
        return \
            ("--lu15 %(lu_15m)1.4f --ll15 %(ll_15m)1.4f "
             "--lu12 %(lu_12m)1.4f --ll12 %(ll_12m)1.4f "
             "--lu10 %(lu_10m)1.4f --ll10 %(ll_10m)1.4f "
             "--d12 %(d_12_15)1.4f --d10 %(d_10_15)1.4f"
            % self.__dict__
            )
    # end def cmdline

    def geometry (self, nec = None):
        if nec is None:
            nec = self.nec
        geo = nec.get_geometry ()
        self.tag = 1
        self.ex  = None
        # 15m is in the middle
        geo.wire \
            ( self.tag
            , round (self.lu_15m / self.seglen)
            , 0, 0, self.seglen * 1.5
            , 0, 0, self.lu_15m
            , self.wire_radius
            , 1, 1
            )
        self.tag += 1
        geo.wire \
            ( self.tag
            , round (self.ll_15m / self.seglen)
            , 0, 0, -self.seglen * 1.5
            , 0, 0, -self.ll_15m
            , self.radius_feed
            , 1, 1
            )
        self.tag += 1
        # A very small piece for the feedpoint
        geo.wire \
            ( self.tag
            , 3
            , 0, 0,  self.seglen * 1.5
            , 0, 0, -self.seglen * 1.5
            , self.wire_radius
            , 1, 1
            )
        self.ex = Excitation (self.tag, 1)
        self.tag += 1
        # 10m is to the left with distance -d_10_15
        geo.wire \
            ( self.tag
            , round (self.lu_10m / self.seglen)
            , -self.d_10_15, 0, 0
            , -self.d_10_15, 0, self.lu_10m
            , self.wire_radius
            , 1, 1
            )
        self.tag += 1
        geo.wire \
            ( self.tag
            , round (self.ll_10m / self.seglen)
            , -self.d_10_15, 0, 0
            , -self.d_10_15, 0, -self.ll_10m
            , self.wire_radius
            , 1, 1
            )
        self.tag += 1
        # 12m is to the right with distance d_12_15
        geo.wire \
            ( self.tag
            , round (self.lu_12m / self.seglen)
            , self.d_12_15, 0, 0
            , self.d_12_15, 0, self.lu_12m
            , self.wire_radius
            , 1, 1
            )
        self.tag += 1
        geo.wire \
            ( self.tag
            , round (self.ll_12m / self.seglen)
            , self.d_12_15, 0, 0
            , self.d_12_15, 0, -self.ll_12m
            , self.wire_radius
            , 1, 1
            )
        self.tag += 1
        geo.move (0, 0, 0, 0, 0, self.feedpoint_h, 0, 0, 0)
    # end def geometry

    def ground (self, nec = None):
        """ We currently asume a medium ground with sommerfield-norton
            ground model
        """
        if nec is None:
            nec = self.nec
        # ground-type 2: Sommerfield-Norton
        # No radials for ground screen
        # Dieelectric-constant:
        # Conductivity:
        # Infinite groundplane: 0
        # Infinite groundplane: 0
        # Infinite groundplane: 0
        # Infinite groundplane: 0
        nec.gn_card (2, 0, 13, 0.005, 0, 0, 0, 0)
    # end def ground

# end class Multi_Dipole

class Multi_Dipole_Optimizer (Antenna_Optimizer):
    """ Optimize given multi-dipole for several bands
        Length are encoded as integers with a resolution of .5mm
        We use:
        2m <= l <= 4m
        for all lengths of half-elements (not quite half because the
        elements may have different length above and below the
        feedpoint) and
        3cm <= d <= 40cm
        for distances of 10/12m dipole from 15m
    """

    ant_cls = Multi_Dipole

    def __init__ \
        (self, radius_feed = None, feedpoint_h = 5, **kw):
        self.minmax = \
            [ (2,    4)
            , (2,    4)
            , (2,    4)
            , (2,    4)
            , (2,    4)
            , (2,    4)
            , (0.03, 0.4)
            , (0.03, 0.4)
            ]
        self.feedpoint_h = feedpoint_h
        # Force multiobjective
        if not kw.get ('multiobjective'):
            kw ['multiobjective'] = True
        self.radius_feed = radius_feed or self.ant_cls.radius_feed
        self.__super.__init__ (**kw)
    # end def __init__

    def compute_antenna (self, p, pop):
        lu_15m  = self.get_parameter (p, pop, 0)
        ll_15m  = self.get_parameter (p, pop, 1)
        lu_12m  = self.get_parameter (p, pop, 2)
        ll_12m  = self.get_parameter (p, pop, 3)
        lu_10m  = self.get_parameter (p, pop, 4)
        ll_10m  = self.get_parameter (p, pop, 5)
        d_12_15 = self.get_parameter (p, pop, 6)
        d_10_15 = self.get_parameter (p, pop, 7)
        md = self.ant_cls \
            ( lu_15m  = lu_15m
            , ll_15m  = ll_15m
            , lu_12m  = lu_12m
            , ll_12m  = ll_12m
            , lu_10m  = lu_10m
            , ll_10m  = ll_10m
            , d_12_15 = d_12_15
            , d_10_15 = d_10_15
            , radius_feed   = self.radius_feed
            , avg_gain      = self.avg_gain
            , feedpoint_h   = feedpoint_h
            , **self.antenna_args
            )
        return md
    # end def compute_antenna

    def get_eval_and_constraints (self):
        """ We have three constraints on VSWR, one for each frequency.
            Then we have three constraints on the gain in opposite PHI
            direction (but equal THETA): These should not be off by more
            than 0.5dB. The real eval function is the gain on each
            frequency. Note that we ignore self.min_fb.
        """
        add = bool (self.min_gain) * 3
        return dict (num_eval = 9 + add, num_constraint = 6 + add)
    # end def get_eval_and_constraints

    def evaluate (self, p, pop):
        phenos = self.phenotype (p, pop)
        assert self.multiobjective
        retval = []
        for pheno in phenos:
            swr_max = max (pheno.vswrs)
            # We take absolute value of F/B ratio: We want about same
            # gain in all directions, note that the term
            # pheno.gmax - pheno.rmax may <0 if the gain is not the same
            # on all frequency points in one range: The gmax takes the
            # *minimum* while rmax takes the *maximum* over the
            # computed frequencies in one range.
            v = [ pheno.gmax
                , abs (pheno.gmax - pheno.rmax) - 1 # Less than 1 dB
                , swr_max - self.maxswr
                ]
            if self.min_gain:
                v.append (self.min_gain - pheno.gmax)
            retval.append (v)
        return tuple (np.array (retval).T.flatten ())
    # end def evaluate

    def get_gain_fw_maxswr (self, sub_eval):
        """ For printing the middle value is the F/B ration minus 1, see
            evaluate above, and for the last value we need to re-add
            maxswr.
        """
        sub_eval [-1] += self.maxswr
        sub_eval [-2] += 1
        return tuple (sub_eval)
    # end def get_gain_fw_maxswr

# end class Multi_Dipole_Optimizer

def main ():
    cmd = Arg_Handler (multiobjective = True)
    cmd.add_argument \
        ( '--lu15'
        , type = float
        , help = "Upper part of 15m (above feedpoint)"
        , default = Multi_Dipole.lu_15m
        )
    cmd.add_argument \
        ( '--ll15'
        , type = float
        , help = "Lower part of 15m (below feedpoint)"
        , default = Multi_Dipole.ll_15m
        )
    cmd.add_argument \
        ( '--lu12'
        , type = float
        , help = "Upper part of 12m (above feedpoint)"
        , default = Multi_Dipole.lu_12m
        )
    cmd.add_argument \
        ( '--ll12'
        , type = float
        , help = "Lower part of 12m (below feedpoint)"
        , default = Multi_Dipole.ll_12m
        )
    cmd.add_argument \
        ( '--lu10'
        , type = float
        , help = "Upper part of 10m (above feedpoint)"
        , default = Multi_Dipole.lu_10m
        )
    cmd.add_argument \
        ( '--ll10'
        , type = float
        , help = "Lower part of 10m (below feedpoint)"
        , default = Multi_Dipole.ll_10m
        )
    cmd.add_argument \
        ( '--d12'
        , type    = float
        , help    = "Distance of 12m dipole from 15m dipole"
        , default = Multi_Dipole.d_12_15
        )
    cmd.add_argument \
        ( '--d10'
        , type    = float
        , help    = "Distance of 10m dipole from 15m dipole"
        , default = Multi_Dipole.d_10_15
        )
    args = cmd.parse_args ()
    if args.action == 'optimize':
        mo = Multi_Dipole_Optimizer (** cmd.default_optimization_args)
        mo.run ()
    else:
        md = Multi_Dipole \
            ( lu_15m  = args.lu15
            , ll_15m  = args.ll15
            , lu_12m  = args.lu12
            , ll_12m  = args.ll12
            , lu_10m  = args.lu10
            , ll_10m  = args.ll10
            , d_12_15 = args.d12
            , d_10_15 = args.d10
            , ** cmd.default_antenna_args
            )
        antenna_actions (cmd, args, md)
# end def main

if __name__ == '__main__':
    main ()


import collections
import functools
import json
import os
import time
from datetime import datetime
import faulthandler

import jsonpickle
import torch
import hashlib
from progress.bar import Bar
from concurrent.futures import ProcessPoolExecutor

from sequence import NoteSeq, EventSeq, ControlSeq
import utils
from collections import Counter

def preprocess_midi(path, metadata):
    note_seq, instr_to_note_count = NoteSeq.from_midi_file(path)
    note_seq.adjust_time(-note_seq.notes[0].start)
    event_seq = EventSeq.from_note_seq(note_seq)
    control_seq = ControlSeq.from_event_seq(event_seq, metadata)
    event_array = event_seq.to_array()
    return event_array, control_seq.to_compressed_array(), control_seq.metadatas, instr_to_note_count

def preprocess_midi_files_under(midi_root, save_dir, num_workers):
    midi_paths = list(utils.find_files_by_extensions(midi_root, ['.mid', '.midi']))
    os.makedirs(save_dir, exist_ok=True)
    out_fmt = '{}-{}.data'

    results = []
    executor = ProcessPoolExecutor(num_workers)
    note_count_dict = dict()
    note_density_bin_dict = dict()
    avg_pitches_played_bin_dict = dict()
    entropy_bin_dict = dict()
    instr_to_note_count_dict = dict()

    metadata_paths = list(utils.find_files_by_extensions(midi_root, ['.json']))
    all_metadata = list()
    for metadata_path in metadata_paths:
        with open(metadata_path) as f:
            metadata_part = jsonpickle.decode(f.read())
            all_metadata.extend(metadata_part)

    all_metadata_dict = {metadata.name: metadata for metadata in all_metadata}

    for path in midi_paths:
        try:
            metadata = all_metadata_dict[os.path.basename(path)]
            partial_preprocess_midi = functools.partial(preprocess_midi, path, metadata)
            results.append((path, executor.submit(partial_preprocess_midi)))
        except KeyboardInterrupt:
            print(' Abort')
            return
        except:
            print(' Error')
            continue

    for path, future in Bar('Processing').iter(results):
        print(' ', end='[{}]'.format(path), flush=True)
        name = os.path.basename(path)
        code = hashlib.md5(path.encode()).hexdigest()  # convert path to hashcode
        save_path = os.path.join(save_dir, out_fmt.format(name, code))
        try:
            (event_seq, control_seq, metadata_seq, instr_to_note_count) = future.result()
            torch.save((event_seq, control_seq), save_path)
            for metadata in metadata_seq:
                c = note_count_dict.get(metadata.note_count, 0)
                note_count_dict[metadata.note_count] = c + 1
                c = note_density_bin_dict.get(metadata.density_bin, 0)
                note_density_bin_dict[metadata.density_bin] = c + 1
                c = avg_pitches_played_bin_dict.get(metadata.avg_pitches_played_bin, 0)
                avg_pitches_played_bin_dict[metadata.avg_pitches_played_bin] = c + 1
                c = entropy_bin_dict.get(metadata.entropy_bin, 0)
                entropy_bin_dict[metadata.entropy_bin] = c + 1
                instr_to_note_count_dict = dict(Counter(instr_to_note_count_dict) + Counter(instr_to_note_count))
        except Exception as e:
            print(f'Could not process file: {path}. Error {e}')

    return note_count_dict, note_density_bin_dict, avg_pitches_played_bin_dict, entropy_bin_dict, instr_to_note_count_dict

if __name__ == '__main__':
    faulthandler.enable()

    # if you want to run after some time
    # print("Started sleeping at: ", datetime.now())
    # time.sleep(3600)
    # print("Ended sleeping at: ", datetime.now())

    metadata = preprocess_midi_files_under(
        midi_root=r'',  # input
        save_dir=r'dataset/everything-game-30s-transposed',   # output
        num_workers=4)

    print('\nNote counts:')
    print(json.dumps(collections.OrderedDict(sorted(metadata[0].items())), indent=2))
    print('\nNote density bins:')
    print(json.dumps(collections.OrderedDict(sorted(metadata[1].items())), indent=2))
    print('\nAvg pitches played bins:')
    print(json.dumps(collections.OrderedDict(sorted(metadata[2].items())), indent=2))
    print('\nEntropy bins:')
    print(json.dumps(collections.OrderedDict(sorted(metadata[3].items())), indent=2))
    print('\nInstrument to note count (not working properly)')
    print(json.dumps(collections.OrderedDict(sorted(map(lambda kv: (kv[0].__int__(), kv[1].__int__()), metadata[4].items()))), indent=2))
    print('\nDONE')


import cherrypy
import os
from jsonschema import Draft4Validator
import json
from functools import wraps
import logging
from pathlib import Path

def resolve_schema(resource, verb):
    return Path(os.path.dirname(os.path.realpath(__file__)), '..', 'api', 'schema', resource, verb + '.json')

def validation(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        resource, verb = f.__qualname__.lower().split('.')
        schema_path = resolve_schema(resource, verb)

        logging.debug('Validating resource {} for verb {} using {} '.format(resource, verb, schema_path))

        if schema_path.is_file():
            with schema_path.open('r') as schema:
                schema_contents = schema.read()
                validator = Draft4Validator(json.loads(schema_contents))
                errors = list()
                for validation_error in sorted(validator.iter_errors(cherrypy.request.json), key=str):
                    path = list(validation_error.path)
                    logging.debug(path)
                    errors.append({
                        "status": "400",
                        "title": validation_error.message,
                        "path": '/'.join(str(x) for x in path),
                        "validator": validation_error.validator,
                        "validator_value": validation_error.validator_value
                    })
                if len(errors) > 0:
                    logging.debug('Found {} validation errors'.format(len(errors)))
                    cherrypy.response.status = 400
                    return {
                        'errors': errors
                    }
        else:
            logging.debug('No JSON SCHEMA document found, not validating')

        logging.debug('No validation errors found')
        return f(*args, **kwargs)
    return wrapper


"""Melhore o DESAFIO 061, perguntando para o usuário se ele quer mostrar mais alguns termos.
O programa encerrará quando ele disser que quer mostrar 0 termos."""
print('Gerador de PA')
primeiro = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
PA = primeiro
termo = 0
total = 0
mais = 10
while mais != 0:
    total += mais
    while termo < total:
        print(PA, end=' ')
        PA += razao
        termo += 1
    mais = int(input('\nQuantos termos Você quer mostrar mais?: '))
print('Finalizado...')
print('No total foram mostrados ', total, ' termos.')


import sys
from collections import deque

MAX_POINTS = 100_001
def bfs(N, K, visited, diary):
    q = deque()
    q.append(N)

    while q:
        now = q.popleft()
        for node in [now-1, now + 1, now*2]:
            if MAX_POINTS > node > -1 and not visited[node]:
                visited[node] = True
                diary[node] = now
                q.append(node)

def solution(N, K):
    visited = [False]*MAX_POINTS
    visited[N] = True

    diary = [i for i in range(MAX_POINTS)]

    bfs(N, K, visited, diary)
    start = K
    arr = [K]
    cnt = 0
    while diary[start] != start:
        arr.append(diary[start])
        cnt += 1
        start = diary[start]

    return [cnt, " ".join(map(str, arr[::-1]))]

def main():
    N, K = map(int,sys.stdin.readline().split())
    answer = solution(N, K)
    for ele in answer:
        print(ele)

if __name__ == "__main__":
    main()


import json
import requests
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from jsonschema import validate

# Path to schema used for validation
filename = "schema.json"

# Request data from database
headers = {'content-type': 'application/json'}
response = requests.get("http://localhost:3000/world_select/countries_male/", headers=headers)
response2 = requests.get("http://localhost:3000/world_select/countries_female/", headers=headers)
response3 = requests.get("http://localhost:3000/world_select/countries_groupby", headers=headers)

# Open schema and read
with open(filename, 'r') as f:
    data=f.read()
schema = json.loads(data)

# Convert response into variable
my_json = response.json()
my_json2 = response2.json()
my_json3 = response3.json()

# Pull 'data' from json file
elements = response.json()['Countries']
elements2 = response2.json()['Countries']
elements3 = response3.json()['Countries']

# Validate json to schema
if validate(instance=my_json, schema=schema) == None and validate(instance=my_json2, schema=schema) == None and validate(instance=my_json2, schema=schema) == None:

    # Create bar chart based off data pulled with JSON from database
    fig = go.Figure(data=[
        go.Bar(name='Male', x=[x['Name'] for x in elements], y=[x['Suicide_rate'] for x in elements]),
        go.Bar(name='Female', x=[x['Name'] for x in elements2], y=[x['Suicide_rate'] for x in elements2])
    ])

    fig2 = go.Figure(data=[
        go.Bar(name='Happiness Index', x=[x['Name'] for x in elements3], y=[x['Score'] for x in elements3])
    ])

    # Change the bar mode
    fig.update_layout(title="Suicide rate among 15 year old millenials", barmode='group', xaxis_title="Countries", yaxis_title="Suicide Rate")
    fig2.update_layout(title="Happiness index in countries", barmode='group', xaxis_title="Countries", yaxis_title="Happiness Index")

    # Show graph
    fig.show()
    fig2.show()

    print("JSON Validation completed!")
else :
    print("JSON Validation failed!")