import moviepy.editor as mp
import logging
import os

from app.settings.config import settings

async def convert_video(input_filename: str, output_format: str, temp_folder: str, name_file: str) -> str:
    """
    Функція, що конвертує файл в розширення output_format та повертає шлях до результуючого файлу
    :param input_filename: шлях до файлу
    :param output_format: розширення, в яке потрібно конвертувати
    :return: шлях до конвертованого файла
    """
    try:
        video = mp.VideoFileClip(input_filename)
        output_file = f"{temp_folder}{name_file}.{output_format}"
        video.write_videofile(output_file, codec=(lambda output_format: {
                                'mp4': 'libx264',
                                'ogv': 'libtheora',
                                'webm': 'libvpx',
                                'ogg': 'libtheora',
                                'mp3': 'pcm_s16le',
                                'wav': 'libvorbis',
                                'm4a': 'libfdk_aac',
                            }.get(format, 'libx264'))(output_format))
        logging.info('Відео файл було конвертовано успішно')

        return output_file

    except Exception as e:
        logging.error(f'Файл {input_filename} не був конвертований, detils: {e}')
        return None


import sys, getopt
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import socket

def main(argv):
	type = 0	#1=ICMP, 2=SYN
	portString = "80"
	host = argv[len(argv)-1]
	argv = argv[:((len(argv))-1)]

	#Convert host to an IP if it isn't
	hostCheckArr = host.split(".")
	if(len(hostCheckArr) != 4):
		#This is a domain name: Convert to IP
		try:
			host = socket.gethostbyname(host)
		except:
			sys.exit("Invalid host domain")
		#Prepare to check if found IP is valid
		hostCheckArr = host.split(".")
	#Check formatting of IP Address
	if(len(hostCheckArr) == 4):
		isValidIP = True
		validNum = 256
		for num in hostCheckArr:
			num = num.strip()
			try:
				#Convert String to Integer (If it is one)
				validNum = int(num)
			except:
				print("Part of IP is not an int - Failure:", sys.exc_info()[0])
				isValidIP = False
				break
			if(not(validNum >= 0 and validNum < 256)):
				print("IP part not within range of 0-255 - Failure")
				isValidIP = False
				break
		if(not isValidIP):
			sys.exit("Invalid host IP or Domain")
	else:
		sys.exit("Invalid Host IP or domain")
	#IP must be valid if code gets here
	#begin parsing other arguments
	try:
		opts, args = getopt.getopt(argv,"",["p=", "ICMP","SYN"])
	except getopt.GetoptError:
		sys.exit("INVALID INPUT: Correct arguments and try again")

	for opt, arg in opts:
		if opt == "--ICMP":
			if type != 0:
				sys.exit("Invalid Input: Only chose ICMP OR SYN")
			type=1
		elif opt == "--SYN":
			if type != 0:
				sys.exit("Invalid Input: Only chose ICMP OR SYN")
			type=2
		elif opt == "--p":
			portString = arg
	if type == 0:
		sys.exit("Invalid Input: Specify ICMP OR SYN")

	if type == 1:
		#Non-Stealth Scan
		try:
			p=sr1(IP(dst=host)/ICMP(), timeout=10)
			if p:
				print("ICMP scan: Machine Found")
			else:
				print("ICMP scan: Machine Not Found")

		except Exception:
			#port Closed
			print("ICMP scan: Machine Not Found")
	else:
		portSets = portString.split(',')
		trimedPortSets = []
		for part in portSets:
			trimedPortSets.append(part.strip())
		#Open ports will be put here
		openPorts = []
		#Run through all ports wanted
		for ports in trimedPortSets:
			if '-' in ports:
				nums = ports.split("-")
				start = nums[0]
				end = nums[1]
				#range of ports
				for testPort in range(int(start), (int(end)+1)):
					if(checkPort(testPort, host)):
						openPorts.append(testPort)
			else:
				#Just a single port number
				if(checkPort(int(ports), host)):
					openPorts.append(int(ports))
		print("Open Ports:", openPorts)

#Takes destination port, destination IP, and scan type and checks if port is open (1-ICMP, 2=SYN)
def checkPort(port, ip):

	dst_ip = ip
	src_port = RandShort()
	dst_port=port
	isItOpen = False

	#Stealth Scan
	stealth_scan_resp = sr1(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="S"),timeout=3)
	if(stealth_scan_resp==None):
		#Filtered
		print("Port Closed: ", dst_port)
	elif(stealth_scan_resp.haslayer(TCP)):
		if(stealth_scan_resp.getlayer(TCP).flags == 0x12):
			send_rst = sr(IP(dst=dst_ip)/TCP(sport=src_port,dport=dst_port,flags="R"),timeout=3)
			#Port is Open
			print("Port Open ", dst_port)
			isItOpen = True
		elif (stealth_scan_resp.getlayer(TCP).flags == 0x14):
			#Port Closed
			print("Port Closed: ", dst_port)
	elif(stealth_scan_resp.haslayer(ICMP)):
		if(int(stealth_scan_resp.getlayer(ICMP).type)==3 and int(stealth_scan_resp.getlayer(ICMP).code) in [1,2,3,9,10,13]):
			#Filtered
			print("Port Open: ", dst_port)
			isItOpen = True
	#retuns whether stealth scan method found the port to be open
	return isItOpen

if __name__ == "__main__":
	main(sys.argv[1:])


import xml.etree.ElementTree as ET
from pathlib import Path

import fire
import pandas as pd
from tqdm import tqdm

# pd.set_option("display.max_colwidth", None)
pd.set_option("display.unicode.east_asian_width", True)
pd.set_option("display.unicode.ambiguous_as_wide", True)
pd.set_option("display.max_rows", None)
# pd.set_option("display.max_columns", None)
pd.set_option("display.max_colwidth", 15)

TAGNAMES = {
    "d": "Disease",
    "a": "Anatomical",
    "f": "Feature",
    "c": "Change",
    "timex3": "TIMEX3",
    "t-test": "TestTest",
    "t-key": "TestKey",
    "t-val": "TestVal",
    "m-key": "MedicineKey",
    "m-val": "MedicineVal",
    "cc": "ClinicalContext",
    "r": "Remedy",
    "p": "Pending",
}

# TODO: Relation!

def len_null(a):
    """Return length of the input even if it is None (=> 0)."""
    return 0 if a is None else len(a)

def get_plain_text(root):
    """Get a plain, bare text of an XML-tagged text."""
    return "".join(root.itertext()).lstrip()

def root_to_df(root, plain_text):
    """Convert an XML object to Table."""
    data = []
    data_r = []
    # NOTE: assume that non-PRISM tags don't appear between <root>...<[first PRISM tag]>
    root.text = root.text.lstrip() if root.text else None
    root.tail = None
    csr = len(root.text) if root.text else 0
    for e in root.iter():
        if e.tag.lower() in TAGNAMES:
            st, ed = csr, csr + len(e.text) if e.text else csr
            orig_snip = plain_text[st:ed]
            tag_datum = [
                e.tag,
                e.attrib,
                e.text,
                e.tail,
                st,
                ed,
                repr(orig_snip),
                e.text == orig_snip,
            ]
            if "tid" in e.attrib:
                tag_datum.insert(0, int(e.attrib["tid"][1:]))
                del e.attrib["tid"]
            data.append(tag_datum)
            csr += len_null(e.text) + len_null(e.tail)
        if e.tag == "brel":
            data_r.append(
                [
                    int(e.attrib["rid"][1:]),
                    e.attrib["reltype"],
                    int(e.attrib["arg1"][1:]),
                    int(e.attrib["arg2"][1:]),
                ]
            )
        # else:
        #     # some unknown tags exist
        #     # TODO: to make this procedure robust
    header = [
        "tag",
        "attrib",
        "text",
        "tail",
        "start_pos",
        "end_pos",
        "orig",
        "matchOrig",
    ]
    if len(header) + 1 == len(data[0]):
        header.insert(0, "tid")
    df = pd.DataFrame(data, columns=header)
    assert df["matchOrig"].all(), "\n" + str(df)
    header_r = ["rid", "reltype", "arg1", "arg2"]
    df_r = pd.DataFrame(data_r, columns=header_r)
    return df, df_r

def row_to_tagstr(row):
    """Convert a Table row to ANN's Tag format"""
    id_ = row.tid if "tid" in row else row.name
    if "\n" not in row.text:  # assume #\n == 1 (more than that is illegal)
        return f"T{id_}\t{TAGNAMES[row.tag.lower()]} {row.start_pos} {row.end_pos}\t{row.text}"
    n_pos = row.text.find("\n")
    fend_pos = row.start_pos + n_pos
    sstart_pos = fend_pos + 1
    text_ = row.text.replace("\n", " ")
    return f"T{id_}\t{TAGNAMES[row.tag.lower()]} {row.start_pos} {fend_pos};{sstart_pos} {row.end_pos}\t{text_}"

def df_to_tagstrs(df):
    """Convert all entities in a whole Table to ANN-formatted strings."""
    return df.apply(
        row_to_tagstr,
        axis=1,
    ).to_list()

def row_to_attrstr(row):
    """Convert a Table row to ANN's Attribute format"""
    id_ = row.tid if "tid" in row else row["index"]
    key, val = list(row.attrib.items())[0]
    return f"A{row.name + 1}\t{key} T{id_} {val}"

def df_to_attrstrs(df):
    """Convert all attribute info in a whole Table to ANN-formatted strings."""
    return (
        df[df.attrib != {}]
        .reset_index()  # to generate attr IDs
        .apply(
            row_to_attrstr,
            axis=1,
        )
        .to_list()
    )

def row_to_relstr(row):
    """Convert a Table row to ANN's Relation format"""
    return f"R{row.rid}\t{row.reltype} Arg1:T{row.arg1} Arg2:T{row.arg2}"

def df_to_relstrs(df_r):
    """Convert all relations to ANN-formatted strings."""
    return df_r.apply(row_to_relstr, axis=1).to_list()

def get_first_child(elem):
    """Get the first child of an XML Element"""
    it = elem.iter()
    next(it)  # == elem itself
    return next(it)

def get_real_root(elem):
    """Get the 'real' root element.
    This returns the direct parent that contains the PRISM tags.
    """
    child = get_first_child(elem)
    return elem if child.tag.lower() in TAGNAMES.keys() else get_real_root(child)

def main(dirpath, output_path, trav=False):
    """MAIN."""
    p = Path(dirpath)
    assert p.is_dir()
    p_lst = list(p.iterdir())
    outp = Path(output_path)
    if not outp.exists():
        outp.mkdir()
    for i in tqdm(p_lst):
        if i.name.startswith("."):
            continue
        if i.is_file() and i.suffix == ".xml":
            try:
                root = ET.parse(i).getroot()
                # if wrapped further by metadata elements like PERSON, ARTICLE
                # need to find the real "root"
                root = get_real_root(root)
            except ET.ParseError:
                with open(i, "r") as f:
                    cont = f.read()
                try:
                    root = ET.fromstring(f"<root>{cont}</root>")
                except ET.ParseError as e:
                    print()
                    print()
                    print("Error occured in:", i)
                    raise e
            plain_text = get_plain_text(root)
            try:
                df, df_r = root_to_df(root, plain_text)
            except AssertionError as e:
                print()
                print()
                print("Error occured in:", i)
                raise e
            tagstrs = df_to_tagstrs(df)
            attrstrs = df_to_attrstrs(df)
            relstrs = df_to_relstrs(df_r)
            with open(outp / i.with_suffix(".ann").name, "w") as outf:
                outf.write("\n".join(tagstrs + attrstrs + relstrs))
            with open(outp / i.with_suffix(".txt").name, "w") as outf:
                outf.write(plain_text)
        if i.is_dir() and trav:
            print("Dig into a child folder:", str(i))
            main(str(i), output_path)

if __name__ == "__main__":
    fire.Fire(main)
    # NOTE: only compatible with the 1-doc-per-file format


import time
from ...utils.main.base_page import BasePage
from ...utils.assertions import MainPageAssertion

class TestMainPage:

    def test_check_title (self, browser):
        link = "https://onepage.io/"
        page = BasePage(browser)
        page.open(link)
        assertion = MainPageAssertion(browser)
        assertion.assert_should_be_main_page()


import pygame
import sys, os

# sys.path.append(os.getcwd())

from internal.PygameApp import PygameApp, Screen
from widgets.BasicMenuBar import BasicMenuBar

# screen paths here
from screens.MapMakerScreen import map_maker_screen

clock = pygame.time.Clock()
size, screen = None, None

def action():
    print('action executed')

'''
    I mainly made these classes for annotations ahead of functions so ik what i'm doing

    @PygameApp:
        Creates the window and initializes everything for you
        Supports function based windows that can be added on to each other

    @Screen:
        Verifies that the function parameters are set correctly
        Validates the new function-based screen
'''

class HomeScreenNavResults:
    mapmaker = 'mapmaker'
    quit = 'quit'
    newgame = 'newgame'
    loadgame = 'loadgame'

def nav_to_newgame():
    return HomeScreenNavResults.newgame

def nav_to_loadgame():
    return HomeScreenNavResults.loadgame

def nav_to_mapmaker():
    return HomeScreenNavResults.mapmaker

def nav_to_quit():
    return HomeScreenNavResults.quit

@PygameApp
@Screen
def main_screen(sizep=None, screenp=None):
    size, screen = sizep, screenp
    print(f'this is the current screen {screen}')

    menu_width, menu_height = 600, 300
    menu_rect = pygame.rect.Rect(size[0] // 2 - menu_width // 2, size[1] // 2 - menu_height // 2, menu_width,
                                 menu_height)
    menu_padding = {
        't': 40,
        'b': 10
    }

    menu_items = ['new game', 'load game', 'map maker', 'quit']
    menu_actions = [nav_to_newgame, nav_to_loadgame, nav_to_mapmaker, nav_to_quit]

    menu = BasicMenuBar(screen, menu_width, menu_height, pos_x=(size[0] // 2) - (menu_width // 2),
                        pos_y=(size[1] // 2) - (menu_height // 2), menu_items=menu_items,
                        menu_actions=menu_actions, menu_title='Welcome!', menu_padding=menu_padding,
                        font_color=(0, 0, 0), font_size=25, title_font_size=35, menu_item_spacing=15, cursor=True)

    running, result = True, None

    while 1:
        clock.tick(60)

        # background
        screen.fill((0, 0, 0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    result = menu.execute_action_cursor(1)
                    running = False

        menu.render()
        pygame.display.flip()

        if not running and result == HomeScreenNavResults.quit:
            pygame.quit()
            break
        else:
            running = True

        if result == HomeScreenNavResults.mapmaker:
            return map_maker_screen(size, screen)


from __future__ import annotations

import ast
import importlib.metadata
import operator
import platform
import stat
from typing import Any, AnyStr, ClassVar, Generator

import flake8.options.manager

ast_Constant = ast.Constant  # noqa: N816

_use_optparse = tuple(int(s) for s in importlib.metadata.version('flake8').split('.')) < (3, 8, 0)

if _use_optparse:  # pragma: no cover
    import optparse  # noqa: F401 pylint: disable=deprecated-module, unused-import
else:
    import argparse

# ==============================================================================

_DEFAULT_MAX_MODE = 0o755

SCS100 = 'SCS100 use of os.path.abspath() and os.path.relpath() should be avoided in favor of os.path.realpath()'
SCS101 = 'SCS101 `eval()` and `exec()` represent a security risk and should be avoided'
SCS102 = 'SCS102 use of `os.system()` should be avoided'
SCS103 = ' '.join(
    [
        'SCS103 use of `shell=True` in subprocess functions or use of functions that internally set it should be',
        'avoided',
    ]
)
SCS104 = 'SCS104 use of `tempfile.mktemp()` should be avoided, prefer `tempfile.mkstemp()`'
SCS105 = ' '.join(
    [
        'SCS105 use of `yaml.load()` should be avoided, prefer `yaml.safe_load()` or',
        '`yaml.load(xxx, Loader=SafeLoader)`',
    ]
)
SCS106 = 'SCS106 use of `jsonpickle.decode()` should be avoided'
SCS107 = 'SCS107 debugging code should not be present in production code (e.g. `import pdb`)'
SCS108 = 'SCS108 `assert` statements should not be present in production code'
SCS109 = ' '.join(
    [
        'SCS109 Use of builtin `open` for writing is discouraged in favor of `os.open` to allow for setting file',
        'permissions',
    ]
)
SCS110 = 'SCS110 Use of `os.popen()` should be avoided, as it internally uses `subprocess.Popen` with `shell=True`'
SCS111 = 'SCS111 Use of `shlex.quote()` should be avoided on non-POSIX platforms (such as Windows)'
SCS112 = 'SCS112 Avoid using `os.open` with unsafe permissions (should be {})'
SCS113 = 'SCS113 Avoid using `pickle.load()` and `pickle.loads()`'
SCS114 = 'SCS114 Avoid using `marshal.load()` and `marshal.loads()`'
SCS115 = 'SCS115 Avoid using `shelve.open()`'
SCS116 = 'SCS116 Avoid using `os.mkdir` and `os.makedirs` with unsafe file permissions (should be {})'
SCS117 = 'SCS117 Avoid using `os.mkfifo` with unsafe file permissions (should be {})'
SCS118 = 'SCS118 Avoid using `os.mknod` with unsafe file permissions (should be {})'
SCS119 = 'SCS119 Avoid using `os.chmod` with unsafe file permissions (W ^ X for group and others)'

# ==============================================================================
# Helper functions

def _read_octal_mode_option(name, value, default):
    """
    Read an integer or list of integer configuration option.

    Args:
        name (str): Name of option
        value (str): Value of option from the configuration file or on the CLI. Its value can be any of:
            - 'yes', 'y', 'true' (case-insensitive)
                The maximum mode value is then set to self.DEFAULT_MAX_MODE
            - a single octal or decimal integer
                The maximum mode value is then set to that integer value
            - a comma-separated list of integers (octal or decimal)
                The allowed mode values are then those found in the list
            - anything else will count as a falseful value
        default (int,list): Default value for option if set to one of
            ('y', 'yes', 'true') in the configuration file or on the CLI

    Returns:
        A single integer or a (possibly empty) list of integers

    Raises:
        ValueError: if the value of the option is not valid
    """

    def _str_to_int(arg):
        try:
            return int(arg, 8)
        except ValueError:
            return int(arg)

    value = value.lower()
    modes = [mode.strip() for mode in value.split(',')]

    if len(modes) > 1:
        # Lists of allowed modes
        try:
            allowed_modes = [_str_to_int(mode) for mode in modes if mode]
        except ValueError as error:
            raise ValueError(f'Unable to convert {modes} elements to integers!') from error
        else:
            if not allowed_modes:
                raise ValueError(f'Calculated empty value for `{name}`!')
            return allowed_modes
    elif modes and modes[0]:
        # Single values (ie. max allowed value for mode)
        try:
            return _str_to_int(value)
        except ValueError as error:
            if value in ('y', 'yes', 'true'):
                return default
            if value in ('n', 'no', 'false'):
                return None
            raise ValueError(f'Invalid value for `{name}`: {value}!') from error
    else:
        raise ValueError(f'Invalid value for `{name}`: {value}!')

# ==============================================================================

def _is_posix():
    """Return True if the current system is POSIX-compatible."""
    # NB: we could simply use `os.name` instead of `platform.system()`. However, that solution would be difficult to
    #     test using `mock` as a few modules (like `pytest`) actually use it internally...
    return platform.system() in ('Linux', 'Darwin')

_is_unix = _is_posix

# ------------------------------------------------------------------------------

def _is_function_call(node: ast.Call, module: AnyStr, function: list[AnyStr] | tuple[AnyStr] | AnyStr) -> bool:
    if not isinstance(function, (list, tuple)):
        function = (function,)
    return (
        isinstance(node.func, ast.Attribute)
        and isinstance(node.func.value, ast.Name)
        and node.func.value.id == module
        and node.func.attr in function
    )

# ==============================================================================

def _is_os_path_call(node: ast.Call) -> bool:
    return (
        isinstance(node.func, ast.Attribute)  # pylint: disable=R0916
        and (
            (isinstance(node.func.value, ast.Name) and node.func.value.id == 'op')
            or (
                isinstance(node.func.value, ast.Attribute)
                and node.func.value.attr == 'path'
                and isinstance(node.func.value.value, ast.Name)
                and node.func.value.value.id == 'os'
            )
        )
        and node.func.attr in ('abspath', 'relpath')
    )

def _is_builtin_open_for_writing(node: ast.Call) -> bool:
    if isinstance(node.func, ast.Name) and node.func.id == 'open':
        mode = ''
        if len(node.args) > 1:
            if isinstance(node.args[1], ast.Name):
                return True  # variable -> to be on the safe side, flag as inappropriate
            if isinstance(node.args[1], ast_Constant):
                mode = node.args[1].value
            if isinstance(node.args[1], ast.Str):
                mode = node.args[1].s
        else:
            for keyword in node.keywords:
                if keyword.arg == 'mode':
                    if not isinstance(keyword.value, ast_Constant):
                        return True  # variable -> to be on the safe side, flag as inappropriate
                    mode = keyword.value.value
                    break
        if any(m in mode for m in 'awx'):
            # Cover:
            #  * open(..., "w").
            #  * open(..., "wb").
            #  * open(..., "a").
            #  * open(..., "x").
            return True
    return False

def _get_mode_arg(node, args_idx):
    mode = None
    node_intern = None
    if len(node.args) > args_idx:
        node_intern = node.args[args_idx]
    elif node.keywords:
        for keyword in node.keywords:
            if keyword.arg == 'mode':
                node_intern = keyword.value
                break
    if node_intern:
        if isinstance(node_intern, ast_Constant):
            mode = node_intern.value
        elif isinstance(node_intern, ast.Num):  # pragma: no cover
            mode = node_intern.n
    return mode

def _is_allowed_mode(node, allowed_modes, args_idx):
    mode = _get_mode_arg(node, args_idx=args_idx)
    if mode is not None and allowed_modes:
        return mode in allowed_modes

    # NB: default to True in all other cases
    return True

def _is_shell_true_call(node: ast.Call) -> bool:
    _n_args_max = 8
    if not (isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name)):
        return False

    # subprocess module
    if node.func.value.id in ('subprocess', 'sp'):
        if node.func.attr in ('call', 'check_call', 'check_output', 'Popen', 'run'):
            for keyword in node.keywords:
                if keyword.arg == 'shell' and isinstance(keyword.value, ast_Constant) and bool(keyword.value.value):
                    return True
            if (
                len(node.args) > _n_args_max
                and isinstance(node.args[_n_args_max], ast_Constant)
                and bool(node.args[_n_args_max].value)
            ):
                return True
        if node.func.attr in ('getoutput', 'getstatusoutput'):
            return True

    # asyncio module
    if (node.func.value.id == 'asyncio' and node.func.attr == 'create_subprocess_shell') or (
        node.func.value.id == 'loop' and node.func.attr == 'subprocess_shell'
    ):
        return True

    return False

def _is_pdb_call(node: ast.Call) -> bool:
    if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id == 'pdb':
        # Cover:
        #  * pdb.func().
        return True
    if isinstance(node.func, ast.Name) and node.func.id == 'Pdb':
        # Cover:
        # * Pdb().
        return True
    return False

def _is_mktemp_call(node: ast.Call) -> bool:
    if isinstance(node.func, ast.Attribute) and node.func.attr == 'mktemp':
        # Cover:
        #  * tempfile.mktemp().
        #  * xxxx.mktemp().
        return True
    if isinstance(node.func, ast.Name) and node.func.id == 'mktemp':
        # Cover:
        #  * mktemp().
        return True
    return False

def _is_yaml_unsafe_call(node: ast.Call) -> bool:
    _n_args_max = 2
    _safe_loaders = ('BaseLoader', 'SafeLoader')
    _unsafe_loaders = ('Loader', 'UnsafeLoader', 'FullLoader')
    if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id == 'yaml':
        if node.func.attr in ('unsafe_load', 'full_load'):
            # Cover:
            #  * yaml.full_load().
            #  * yaml.unsafe_load().
            return True
        if node.func.attr == 'load':
            for keyword in node.keywords:
                if keyword.arg == 'Loader' and isinstance(keyword.value, ast.Name):
                    if keyword.value.id in _unsafe_loaders:
                        # Cover:
                        #  * yaml.load(x, Loader=Loader).
                        #  * yaml.load(x, Loader=UnsafeLoader).
                        #  * yaml.load(x, Loader=FullLoader).
                        return True
                    if keyword.value.id in _safe_loaders:
                        # Cover:
                        #  * yaml.load(x, Loader=BaseLoader).
                        #  * yaml.load(x, Loader=SafeLoader).
                        return False

            if (
                len(node.args) < _n_args_max  # pylint: disable=too-many-boolean-expressions
                or (isinstance(node.args[1], ast.Name) and node.args[1].id in _unsafe_loaders)
                or (
                    isinstance(node.args[1], ast.Attribute)
                    and node.args[1].value.id == 'yaml'
                    and node.args[1].attr in _unsafe_loaders
                )
            ):
                # Cover:
                #  * yaml.load(x).
                #  * yaml.load(x, Loader).
                #  * yaml.load(x, UnsafeLoader).
                #  * yaml.load(x, FullLoader).
                #  * yaml.load(x, yaml.Loader).
                #  * yaml.load(x, yaml.UnsafeLoader).
                #  * yaml.load(x, yaml.FullLoader).
                return True

    if isinstance(node.func, ast.Name) and node.func.id in ('unsafe_load', 'full_load'):
        # Cover:
        #  * unsafe_load(...).
        #  * full_load(...).
        return True
    return False

# ==============================================================================

_unop = {ast.USub: operator.neg, ast.Not: operator.not_, ast.Invert: operator.inv}
_binop = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.FloorDiv: operator.floordiv,
    ast.Mod: operator.mod,
    ast.BitXor: operator.xor,
    ast.BitOr: operator.or_,
    ast.BitAnd: operator.and_,
}
_chmod_known_mode_values = (
    'S_ISUID',
    'S_ISGID',
    'S_ENFMT',
    'S_ISVTX',
    'S_IREAD',
    'S_IWRITE',
    'S_IEXEC',
    'S_IRWXU',
    'S_IRUSR',
    'S_IWUSR',
    'S_IXUSR',
    'S_IRWXG',
    'S_IRGRP',
    'S_IWGRP',
    'S_IXGRP',
    'S_IRWXO',
    'S_IROTH',
    'S_IWOTH',
    'S_IXOTH',
)

def _chmod_get_mode(node):
    """
    Extract the mode constant of a node.

    Args:
        node: an AST node

    Raises:
        ValueError: if a node is encountered that cannot be processed
    """
    if isinstance(node, ast.Name) and node.id in _chmod_known_mode_values:
        return getattr(stat, node.id)
    if (
        isinstance(node, ast.Attribute)
        and isinstance(node.value, ast.Name)
        and node.attr in _chmod_known_mode_values
        and node.value.id == 'stat'
    ):
        return getattr(stat, node.attr)
    if isinstance(node, ast.UnaryOp):
        return _unop[type(node.op)](_chmod_get_mode(node.operand))
    if isinstance(node, ast.BinOp):
        return _binop[type(node.op)](_chmod_get_mode(node.left), _chmod_get_mode(node.right))

    raise ValueError(f'Do not know how to process node: {ast.dump(node)}')

def _chmod_has_wx_for_go(node):
    if platform.system() == 'Windows':
        # On Windows, only stat.S_IREAD and stat.S_IWRITE can be used, all other bits are ignored
        return False

    try:
        modes = None
        if len(node.args) > 1:
            modes = _chmod_get_mode(node.args[1])
        elif node.keywords:
            for keyword in node.keywords:
                if keyword.arg == 'mode':
                    modes = _chmod_get_mode(keyword.value)
                    break
    except ValueError:
        return False
    else:
        if modes is None:
            # NB: this would be from invalid code such as `os.chmod("file.txt")`
            raise RuntimeError('Unable to extract `mode` argument from function call!')
        # pylint: disable=no-member
        return bool(modes & (stat.S_IWGRP | stat.S_IXGRP | stat.S_IWOTH | stat.S_IXOTH))

# ==============================================================================

class Visitor(ast.NodeVisitor):
    """AST visitor class for the plugin."""

    os_mkdir_modes_allowed: ClassVar[list[int]] = []
    os_mkdir_modes_msg_arg: ClassVar[str] = ''
    os_mkfifo_modes_allowed: ClassVar[list[int]] = []
    os_mkfifo_modes_msg_arg: ClassVar[str] = ''
    os_mknod_modes_allowed: ClassVar[list[int]] = []
    os_mknod_modes_msg_arg: ClassVar[str] = ''
    os_open_modes_allowed: ClassVar[list[int]] = []
    os_open_modes_msg_arg: ClassVar[str] = ''

    mode_msg_map: ClassVar[dict[str, str]] = {
        SCS112: 'open',
        SCS116: 'mkdir',
        SCS117: 'mkfifo',
        SCS118: 'mknod',
    }

    def _format_mode_msg(self, msg_id):
        """Format a mode message."""
        return self.__class__.format_mode_msg(msg_id)

    @classmethod
    def format_mode_msg(cls, msg_id):
        """Format a mode message."""
        return msg_id.format(getattr(cls, f'os_{cls.mode_msg_map[msg_id]}_modes_msg_arg'))

    def __init__(self) -> None:
        """Initialize a Visitor object."""
        self.errors: list[tuple[int, int, str]] = []
        self._from_imports: dict[str, str] = {}

    def visit_Call(self, node: ast.Call) -> None:  # pylint: disable=too-many-branches # noqa: PLR0912
        """Visitor method called for ast.Call nodes."""
        if _is_pdb_call(node):
            self.errors.append((node.lineno, node.col_offset, SCS107))
        elif _is_mktemp_call(node):
            self.errors.append((node.lineno, node.col_offset, SCS104))
        elif _is_yaml_unsafe_call(node):
            self.errors.append((node.lineno, node.col_offset, SCS105))
        elif _is_function_call(node, module='jsonpickle', function='decode'):
            self.errors.append((node.lineno, node.col_offset, SCS106))
        elif _is_function_call(node, module='os', function='system'):
            self.errors.append((node.lineno, node.col_offset, SCS102))
        elif _is_os_path_call(node):
            self.errors.append((node.lineno, node.col_offset, SCS100))
        elif _is_function_call(node, module='os', function='popen'):
            self.errors.append((node.lineno, node.col_offset, SCS110))
        elif _is_shell_true_call(node):
            self.errors.append((node.lineno, node.col_offset, SCS103))
        elif _is_builtin_open_for_writing(node):
            self.errors.append((node.lineno, node.col_offset, SCS109))
        elif isinstance(node.func, ast.Name) and (node.func.id in ('eval', 'exec')):
            self.errors.append((node.lineno, node.col_offset, SCS101))
        elif not _is_posix() and _is_function_call(node, module='shlex', function='quote'):
            self.errors.append((node.lineno, node.col_offset, SCS111))
        elif (
            _is_function_call(node, module='os', function='open')
            and self.os_open_modes_allowed
            and not _is_allowed_mode(node, self.os_open_modes_allowed, args_idx=2)
        ):
            self.errors.append((node.lineno, node.col_offset, self._format_mode_msg(SCS112)))
        elif _is_function_call(node, module='pickle', function=('load', 'loads')):
            self.errors.append((node.lineno, node.col_offset, SCS113))
        elif _is_function_call(node, module='marshal', function=('load', 'loads')):
            self.errors.append((node.lineno, node.col_offset, SCS114))
        elif _is_function_call(node, module='shelve', function='open'):
            self.errors.append((node.lineno, node.col_offset, SCS115))
        elif _is_function_call(node, module='os', function='chmod') and _chmod_has_wx_for_go(node):
            self.errors.append((node.lineno, node.col_offset, SCS119))
        elif _is_unix():
            if (
                _is_function_call(node, module='os', function=('mkdir', 'makedirs'))
                and self.os_mkdir_modes_allowed
                and not _is_allowed_mode(node, self.os_mkdir_modes_allowed, args_idx=1)
            ):
                self.errors.append((node.lineno, node.col_offset, self._format_mode_msg(SCS116)))
            elif (
                _is_function_call(node, module='os', function='mkfifo')
                and self.os_mkfifo_modes_allowed
                and not _is_allowed_mode(node, self.os_mkfifo_modes_allowed, args_idx=1)
            ):
                self.errors.append((node.lineno, node.col_offset, self._format_mode_msg(SCS117)))
            elif (
                _is_function_call(node, module='os', function='mknod')
                and self.os_mknod_modes_allowed
                and not _is_allowed_mode(node, self.os_mknod_modes_allowed, args_idx=1)
            ):
                self.errors.append((node.lineno, node.col_offset, self._format_mode_msg(SCS118)))

        self.generic_visit(node)

    def visit_Import(self, node: ast.Import) -> None:
        """Visitor method called for ast.Import nodes."""
        for alias in node.names:
            if alias.name == 'pdb':
                # Cover:
                #  * import pdb.
                #  * import pdb as xxx.
                self.errors.append((node.lineno, node.col_offset, SCS107))

        self.generic_visit(node)

    def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
        """Visitor method called for ast.ImportFrom nodes."""
        for alias in node.names:
            if (node.module is None and alias.name == 'pdb') or node.module == 'pdb':
                # Cover:
                #  * from pdb import xxx.
                self.errors.append((node.lineno, node.col_offset, SCS107))
            elif node.module == 'tempfile' and alias.name == 'mktemp':
                # Cover:
                #  * from tempfile import mktemp.
                self.errors.append((node.lineno, node.col_offset, SCS104))
            elif node.module in ('os.path', 'op') and alias.name in ('relpath', 'abspath'):
                # Cover:
                #  * from os.path import relpath, abspath.
                #  * import os.path as op; from op import relpath, abspath.
                self.errors.append((node.lineno, node.col_offset, SCS100))
            elif (node.module == 'subprocess' and alias.name in ('getoutput', 'getstatusoutput')) or (
                node.module == 'asyncio' and alias.name == 'create_subprocess_shell'
            ):
                # Cover:
                # * from subprocess import getoutput.
                # * from subprocess import getstatusoutput.
                # * from asyncio import create_subprocess_shell.
                self.errors.append((node.lineno, node.col_offset, SCS103))
            elif node.module == 'os' and alias.name == 'system':
                # Cover:
                # * from os import system.
                self.errors.append((node.lineno, node.col_offset, SCS102))
            elif node.module == 'os' and alias.name == 'popen':
                # Cover:
                # * from os import popen.
                self.errors.append((node.lineno, node.col_offset, SCS110))
            elif not _is_posix() and node.module == 'shlex' and alias.name == 'quote':
                # Cover:
                # * from shlex import quote.
                # * from shlex import quote as quoted.
                self.errors.append((node.lineno, node.col_offset, SCS111))
            elif node.module == 'pickle' and alias.name in ('load', 'loads'):
                # Cover:
                # * from pickle import load.
                # * from pickle import loads as load.
                self.errors.append((node.lineno, node.col_offset, SCS113))
            elif node.module == 'marshal' and alias.name in ('load', 'loads'):
                # Cover:
                # * from marshal import load.
                # * from marshal import loads as load.
                self.errors.append((node.lineno, node.col_offset, SCS114))
            elif node.module == 'shelve' and alias.name == 'open':
                # Cover:
                # * from shelve import open.
                self.errors.append((node.lineno, node.col_offset, SCS115))
        self.generic_visit(node)

    def visit_With(self, node: ast.With) -> None:
        """Visitor method called for ast.With nodes."""
        for item in node.items:
            if isinstance(item.context_expr, ast.Call):
                if _is_builtin_open_for_writing(item.context_expr):
                    self.errors.append((node.lineno, node.col_offset, SCS109))
                elif _is_function_call(item.context_expr, module='os', function='open') and not _is_allowed_mode(
                    item.context_expr, self.os_open_modes_allowed, args_idx=2
                ):
                    self.errors.append((node.lineno, node.col_offset, self._format_mode_msg(SCS112)))
                elif _is_function_call(item.context_expr, module='shelve', function='open'):
                    self.errors.append((node.lineno, node.col_offset, SCS115))

    def visit_Assert(self, node: ast.Assert) -> None:
        """Visitor method called for ast.Assert nodes."""
        self.errors.append((node.lineno, node.col_offset, SCS108))
        self.generic_visit(node)

class Plugin:  # pylint: disable=R0903
    """Plugin class."""

    name = __name__
    version = importlib.metadata.version(__name__)

    def __init__(self, tree: ast.AST):
        """Initialize a Plugin object."""
        self._tree = tree

    @classmethod
    def add_options(cls: type[Plugin], option_manager: flake8.options.manager.OptionManager) -> None:
        """Add command line options."""
        options_data: ClassVar[dict[str, dict[str, str | bool]]] = (
            (
                '--os-mkdir-mode',
                {
                    'type': str,
                    'parse_from_config': True,
                    'default': False,
                    'dest': 'os_mkdir_mode',
                    'help': "If provided, configure how 'mode' parameter of the os.mkdir() function are handled",
                },
            ),
            (
                '--os-mkfifo-mode',
                {
                    'type': str,
                    'parse_from_config': True,
                    'default': False,
                    'dest': 'os_mkfifo_mode',
                    'help': "If provided, configure how 'mode' parameter of the os.mkfifo() function are handled",
                },
            ),
            (
                '--os-mknod-mode',
                {
                    'type': str,
                    'parse_from_config': True,
                    'default': False,
                    'dest': 'os_mknod_mode',
                    'help': "If provided, configure how 'mode' parameter of the os.mknod() function are handled",
                },
            ),
            (
                '--os-open-mode',
                {
                    'type': str,
                    'parse_from_config': True,
                    'default': False,
                    'dest': 'os_open_mode',
                    'help': "If provided, configure how 'mode' parameter of the os.open() function are handled",
                },
            ),
        )

        if _use_optparse:  # pragma: no cover
            cls.add_options_optparse(option_manager, options_data)
        else:
            cls.add_options_argparse(option_manager, options_data)

    @classmethod
    def add_options_optparse(
        cls: type[Plugin], option_manager: flake8.options.manager.OptionManager, options_data: tuple
    ) -> None:  # pragma: no cover
        """Add command line options using optparse."""

        def octal_mode_option_callback(option, _, value, parser):
            """Octal mode option callback."""
            setattr(parser.values, f'{option.dest}', _read_octal_mode_option(option.dest, value, _DEFAULT_MAX_MODE))

        callback = {'action': 'callback', 'callback': octal_mode_option_callback}
        for opt_str, kwargs in options_data:
            option_manager.add_option(opt_str, **{**kwargs, **callback})

    @classmethod
    def add_options_argparse(
        cls: type[Plugin], option_manager: flake8.options.manager.OptionManager, options_data: tuple
    ) -> None:
        """Add command line options using argparse."""

        class OctalModeAction(argparse.Action):
            """Action class for octal mode options."""

            def __call__(self, parser, namespace, values, option_string=None):  # noqa: ARG002
                setattr(namespace, self.dest, _read_octal_mode_option(self.dest, values, _DEFAULT_MAX_MODE))

        action = {'action': OctalModeAction}
        for opt_str, kwargs in options_data:
            option_manager.add_option(opt_str, **{**kwargs, **action})

    @classmethod
    def parse_options(cls: type[Plugin], options: argparse.Namespace) -> None:
        """Parse command line options."""

        def _set_mode_option(name, modes):
            if isinstance(modes, int) and modes > 0:
                setattr(Visitor, f'os_{name}_modes_allowed', list(range(0, modes + 1)))
                setattr(Visitor, f'os_{name}_modes_msg_arg', f'0 < mode < {oct(modes)}')
            elif modes:
                setattr(Visitor, f'os_{name}_modes_allowed', modes)
                setattr(Visitor, f'os_{name}_modes_msg_arg', f'mode in {[oct(mode) for mode in modes]}')
            else:
                getattr(Visitor, f'os_{name}_modes_allowed').clear()

        _set_mode_option('mkdir', options.os_mkdir_mode)
        _set_mode_option('mkfifo', options.os_mkfifo_mode)
        _set_mode_option('mknod', options.os_mknod_mode)
        _set_mode_option('open', options.os_open_mode)

    def run(self) -> Generator[tuple[int, int, str, type[Any]], None, None]:
        """Entry point for flake8."""
        visitor = Visitor()
        visitor.visit(self._tree)

        for line, col, msg in visitor.errors:
            yield line, col, msg, type(self)


from termcolor import colored, cprint
import os
import random
import time

O = 'O'
X = 'X'

def clr():
    os.system('clear')
    # os.system('cls')

def display():
    global pos

    clr()
    print("\n\t ",end="")
    for index, p in enumerate(pos):
        if index in [2,5,8]:
            pos_print(p,end="\n\t")
            if index == 8:
                print()
            else:
                print("â”€â”€â”€â”¼â”€â”€â”€â”¼â”€â”€â”€ ", end="\n\t ")

        else:
            pos_print(p,end=" â”‚ ")

def pos_print(p,end):
    if type(p) == int:
        cprint(p,"grey",end=end)
    else:
        cprint(p,"yellow",end=end)

def play(turn):
    global av_pos
    turn_sym = O if turn == 0 else X
    choice = -1
    if( ( turn_sym == p1_symbol ) or mode == 2 ):
        if mode == 2:
            print(turn_sym,"turn...")
        else:
            print("Player turn...")

        while choice not in av_pos:
            print("Available positions:",av_pos)
            cprint('Choose a position','yellow',end=':')
            choice = int(input())

        pos[pos.index(choice)] = turn_sym
        display()
    else:
        computersturn = "Computer's turn..."
        for i in computersturn:
            print(i,end='',flush=True)
            time.sleep(0.1)
        print()
        choice = random.choice(av_pos)
        pos[pos.index(choice)] = turn_sym
        display()

def check_status():
    global pos, turn
    turn_sym = O if turn == 0 else X

    # WIN STATUS
    if ( (pos[0] == pos[1] == pos[2] == turn_sym) or \
         (pos[3] == pos[4] == pos[5] == turn_sym) or \
         (pos[6] == pos[7] == pos[8] == turn_sym) or \
         (pos[0] == pos[3] == pos[6] == turn_sym) or \
         (pos[1] == pos[4] == pos[7] == turn_sym) or \
         (pos[2] == pos[5] == pos[8] == turn_sym) or \
         (pos[0] == pos[4] == pos[8] == turn_sym) or \
         (pos[6] == pos[4] == pos[2] == turn_sym) ):

        display()
        if (turn_sym == p1_symbol):
            print( "\t  ðŸŽ‰ðŸŽ‰ðŸŽ‰")
            player1won_msg = "    PLAYER1 WON! ðŸ¥³"
            for i in player1won_msg:
                cprint(i,'green',end='',flush=True)
                time.sleep(0.1)
            return 1
        elif (mode == 2):
            print( "\t  ðŸŽ‰ðŸŽ‰ðŸŽ‰")
            player2won_msg = "    PLAYER2 WON! ðŸ¥³"
            for i in player2won_msg:
                cprint(i,'green',end='',flush=True)
                time.sleep(0.1)
            return 2
        else:
            youlost_msg = "    Sorry, You Lost ðŸ˜” "
            for i in youlost_msg:
                cprint(i,'red',end='',flush=True)
                time.sleep(0.1)
            return 2

    # FULL STATUS
    elif (len( av_pos ) == 0):
        cprint( "  ðŸŸ¨ DRAW | The Board is full ", 'yellow')
        return 3

    else:
        return 0

while 1:

    pos = [7,8,9, 4,5,6, 1,2,3]

    '''
    Modes:
        1: with computer
        2: with player2
    '''
    mode = -1

    '''
    Player 1 symbol:
        X: X
        O: O
    '''
    p1_symbol = -1

    '''
    Turn:
        0(False) = Its O turn
        1(True) = Its X turn
    '''
    turn = 0 # start with O
    game_status = 0 # 0 = running, 1 = P1 Won, 2 = P2 Won, 3 = Full/Draw

    clr()
    cprint(" OX Welcome to tic-tac-toe XO", 'cyan')

    while mode not in [1,2]:
        cprint("\nYou can either play against a friend or a computer, Who do you want to play against?",'yellow')
        mode = int(input("  [1] Computer  \n  [2] PLAYER2 \n  Choose [1 or 2]: ") or 1)

    print()
    while p1_symbol not in [X,O]:
        cprint("Which symbol would you like? ( O starts first )",'yellow')
        p1_symbol = input("  Choose [O or X]: ")
        p1_symbol = O if p1_symbol in ['o','O', '1', ''] else p1_symbol
        p1_symbol = X if p1_symbol in ['x','X', '0'] else p1_symbol

    display()
    av_pos = pos
    while game_status == 0:
        play(turn)
        av_pos = [x for x in pos if type(x) == int] # available positions
        game_status = check_status()
        turn = not turn # switch player

    restart = -1
    cprint("\n\nRestart the game?",'yellow')
    while(restart not in [1,2]):
        restart = int(input("  [1] Yes \n  [2] No \n  Choose [1 or 2]:"))
    if restart == 2:
        break


import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

class Test(unittest.TestCase):
    def setUp(self):
        self.browser = webdriver.Firefox()

    def tearDown(self):
        self.browser.close()

    def testSearchAtYouTube(self):
        self.browser.get('http://www.youtube.com')
        elem = self.browser.find_element_by_name('search_query')
        elem.send_keys('webdriver' + Keys.RETURN)
        time.sleep(0.2) # For now isn't in API.
        self.browser.find_element_by_css_selector('p.num-results')

    def testSearchAtGoogleImages(self):
        self.browser.get('http://images.google.com')
        elem = self.browser.find_element_by_name('q')
        elem.send_keys('webdriver' + Keys.RETURN)
        time.sleep(0.2) # For now isn't in API.
        self.browser.find_element_by_css_selector('div#resultStats')

if __name__ == '__main__':
    unittest.main()


from __future__ import absolute_import
import unittest
from io import BytesIO

from py_trace_event.trace_event_impl import perfetto_trace_writer

class PerfettoTraceWriterTest(unittest.TestCase):
  """ Tests functions that write perfetto protobufs.

  TODO(crbug.com/944078): Switch to using python-protobuf library
  and implement proper protobuf parsing then.
  """
  def setUp(self):
    perfetto_trace_writer.reset_global_state()

  def testWriteThreadDescriptorEvent(self):
    result = BytesIO()
    perfetto_trace_writer.write_thread_descriptor_event(
        output=result,
        pid=1,
        tid=2,
        ts=1556716807306000,
    )
    expected_output = b"".join([
        b'\n\x1b@\x80\xec\xea\xda\x83\xb6\xa4\xcd\x15P\x80\x80@',
        b'\xc8\x02\x01\xe2\x02\x04\x08\x01\x10\x02\xd0\x03@'
    ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteTwoEvents(self):
    result = BytesIO()
    perfetto_trace_writer.write_thread_descriptor_event(
        output=result,
        pid=1,
        tid=2,
        ts=1556716807306000,
    )
    perfetto_trace_writer.write_event(
        output=result,
        ph="M",
        category="category",
        name="event_name",
        ts=1556716807406000,
        args={},
        tid=2,
    )
    expected_output = b"".join([
        b'\n\x1b@\x80\xec\xea\xda\x83\xb6\xa4\xcd\x15P\x80\x80@',
        b'\xc8\x02\x01\xe2\x02\x04\x08\x01\x10\x02\xd0\x03@\n;@',
        b'\x80\xb0\xc2\x8a\x84\xb6\xa4\xcd\x15P\x80\x80@Z\x08',
        b'\x18\x012\x04\x08\x01\x10Mb\x1e\n\x0c\x08\x01\x12\x08',
        b'category\x12\x0e\x08\x01\x12\nevent_name\xd0\x03@'
    ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteMetadata(self):
    result = BytesIO()
    perfetto_trace_writer.write_metadata(
        output=result,
        benchmark_start_time_us=1556716807306000,
        story_run_time_us=1556716807406000,
        benchmark_name="benchmark",
        benchmark_description="description",
        story_name="story",
        story_tags=["foo", "bar"],
        story_run_index=0,
        label="label",
    )
    expected_output = b"".join([
        b'\nG\x82\x03D\x08\x90\xf6\xc2\x82\xb6\xfa\xe1',
        b'\x02\x10\xb0\x83\xc9\x82\xb6\xfa\xe1\x02\x1a\tbenchmark"',
        b'\x0bdescription*\x05label2\x05story:\x03foo:\x03bar@\x00'
        ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteArgs(self):
    result = BytesIO()
    perfetto_trace_writer.write_thread_descriptor_event(
        output=result,
        pid=1,
        tid=2,
        ts=0,
    )
    perfetto_trace_writer.write_event(
        output=result,
        ph="M",
        category="",
        name="",
        ts=0,
        args={'int': 123, 'double': 1.23, 'string': 'onetwothree'},
        tid=2,
    )
    expected_output = b"".join([
        b'\n\x13@\x00P\x80\x80@\xc8\x02\x01\xe2\x02\x04\x08\x01\x10',
        b'\x02\xd0\x03@\nT@\x00P\x80\x80@Z;\x18\x01"\x07R\x03int {"\x11',
        b'R\x06double)\xaeG\xe1z\x14\xae\xf3?"\x15R\x06string2\x0bonetwothree2',
        b'\x04\x08\x01\x10Mb\x0c\n\x04\x08\x01\x12\x00\x12\x04\x08\x01\x12\x00',
        b'\xd0\x03@'
    ])
    self.assertEqual(expected_output, result.getvalue())

  def testWriteChromeMetadata(self):
    result = BytesIO()
    perfetto_trace_writer.write_chrome_metadata(
        output=result,
        clock_domain='FOO',
    )
    expected_output = b'\n\x17*\x15\x12\x13\n\x0cclock-domain\x12\x03FOO'
    self.assertEqual(expected_output, result.getvalue())

  def testWriteClockSnapshot(self):
    result = BytesIO()
    perfetto_trace_writer.write_clock_snapshot(
        output=result,
        tid=1,
        telemetry_ts=1234.567,
        boottime_ts=7654.321,
    )
    expected_output = b"".join([
       b'\n\x172\x11\n\x06\x08@\x10\x87\xadK\n\x07\x08\x06\x10',
       b'\xb1\x97\xd3\x03P\x80\x80@'
    ])
    self.assertEqual(expected_output, result.getvalue())


from tools.utils import execute
from os import chdir

class Deployer:
    def __init__(self, config):
        self.config = config

    def deploy(self):
        chdir(self.config.proxy_root)
        self._prepare_env_file()
        execute('yarn deploy-skale-manager-components')
        execute('yarn deploy-to-both-chains')

    def deploy_mainnet(self):
        chdir(self.config.proxy_root)
        self._prepare_env_file()
        execute('yarn deploy-skale-manager-components')
        execute('yarn deploy-to-mainnet')

    def deploy_schain(self, schain_name):
        chdir(self.config.proxy_root)
        self._prepare_env_file(schain_name)
        execute('yarn deploy-to-schain')

    def deploy_second_schain(self):
        self.deploy()
        self.deploy_schain(self.config.schain_name_2)

    # private

    def _prepare_env_file(self, schain_name=''):
        if schain_name == '' : schain_name = self.config.schain_name
        env_file = [f'NETWORK_FOR_ETHEREUM="{self.config.network_for_mainnet}"',
                    f'NETWORK_FOR_SCHAIN="{self.config.network_for_schain}"',
                    f'PRIVATE_KEY_FOR_ETHEREUM="{self.config.mainnet_key}"',
                    f'URL_W3_ETHEREUM="{self.config.mainnet_rpc_url}"',
                    f'PRIVATE_KEY_FOR_SCHAIN="{self.config.schain_key}"',
                    f'URL_W3_S_CHAIN="{self.config.schain_rpc_url}"',
                    f'CHAIN_NAME_SCHAIN="{schain_name}"',
                    'NO_SIGNATURES=true']

        with open('.env', 'w') as dot_env:
            dot_env.write('\n'.join(env_file))


# Libraries
import sqlite3
from alpha import test_alpha
from num import test_num
import csv
from clear import clear
from sys import exit

def students():

    # Define connection to sqlite3 database
    connection = sqlite3.connect("STUDENTS DATABASE/students.db")

    # Cursor to connect to sqlite3 database
    db_cursor = connection.cursor()

    # Create table for students database
    db_cursor.execute("CREATE TABLE IF NOT EXISTS students (ID INTEGER, First TEXT, Middle TEXT, Last TEXT, Age INTEGER, Class INTEGER, Father TEXT, Number INTEGER)")

    # Forever Loop
    while (True):

        # UI Menu
        print("1. New Entry     2. Open Entries     3. Search For Student      4. Delete Entry     5.Update Entry")
        print("---------------------------------------------------------------------------------------------------\n")

        answer = input("Type option: ")

        ## NEW ENTRY ##
        if answer == "1":

            clear()

            # Keep entering the data until user exits
            while (True):

                # Welcome screen
                print(" \n---| NEW STUDENT DATABASE |---\n")

                # Student ID initializer
                ID = 1

                # Ask for student's first name
                while (True):

                    # Prompt for valid first name
                    first = input("First Name: ")

                    # Call function to check validity
                    check = test_alpha(first)

                    # Check if correct
                    if check == True:
                        break

                    # Print Error if input is not correct
                    print("Enter Valid Name")

                # Ask for student's middle name
                while (True):

                    # Prompt for valid middle name
                    middle = input("Middle Name: ")

                    # Call function to check validity
                    check = test_alpha(middle)

                    # Check if correct
                    if check == True:
                        break

                    # Print Error if input is not correct
                    print("Enter Valid Name")

                # Ask student's last name
                while (True):

                    # Prompt for valid last name
                    last = input("Last Name: ")

                    # Call function to check validity
                    check = test_alpha(last)

                    # Check if correct
                    if check == True:
                        break

                    # Print Error if input is not correct
                    print("Enter Valid Name")

                # Ask for student's age
                while (True):

                    # Prompt again for valid age
                    age = input("Age: ")

                    # Call function to check validity
                    check = test_num(age)

                    # Check if correct
                    if check == True and int(age) >= 5 and int(age) <= 30:
                        break

                    # Print Error if input is not correct
                    print("Enter Valid age between 5 - 30")

                # Ask for Class
                while (True):

                    # Prompt for valid class
                    class_no = input("Class: ")

                    # Call function to check validity
                    check = test_num(class_no)

                    # Check if correct
                    if check == True and int(class_no) <= 10 and int(class_no) >= 1:
                        break

                    # Print Error if input is not correct
                    print("Enter Valid Class between 1 - 10")

                # Ask for student's father name
                while (True):

                    # Prompt again for valid father name
                    father = input("Father Name: ")

                    # Call function to check validity
                    check = test_alpha(father)

                    # Check if correct
                    if check == True:
                        break

                    # Print Error if input is not correct
                    print("Enter Valid Name")

                # Ask student's number
                while (True):

                    # Prompt for valid number
                    number = input("Phone Number: ")

                    # Call function to check validity
                    check = test_num(number)

                    # Check if correct
                    if check == True:
                        break

                    print("Enter Valid Phone Number")

                print()

                # GENERATES NEW STUDENT ID
                # Return last ID
                key = db_cursor.execute("SELECT ID from students ORDER BY ID DESC LIMIT 1")

                # Fetch data into list
                value = key.fetchone()

                # Value to store student ID
                student_id = 0

                # If first student ID
                if value == None:
                    student_id = 0

                # Else
                if value != None:
                    student_id = int(value[0])

                # Update ID
                ID = student_id + 1

                # Ask for confirmation
                clear()

                print()
                print("------------------")
                print("Confirm New Entry")
                print("------------------")
                print(f"First Name: {first}")
                print(f"Middle Name: {middle}")
                print(f"Last Name: {last}")
                print(f"Age: {age}")
                print(f"Class: {class_no}")

                print()

                print(f"Father's Name: {father}")
                print(f"Phone Number: {number}")
                print("---------------------")

                # Prompt for option
                option = input("Type YES or NO: ")

                # If yes, insert new data into table
                if option.lower() == "yes" or option.lower() == "y":

                    # Insert data into database
                    db_cursor.execute("INSERT INTO students (ID, First, Middle, Last, Age, Class, Father, Number) VALUES(?, ?, ?, ?, ?, ?, ?, ?)", (ID, first, middle, last, int(age), int(class_no), father, int(number)))

                    # Commit connection
                    connection.commit()

                    # Print success
                    print("Entry Successful")

                # Ask for re-entering data
                if option.lower() == "no" or option.lower() == "n":

                    # Prompt again to re-enter data
                    print("Do you want to re-enter data ?")
                    ask = input("Type YES or NO: ")

                    # If no, exit the loop
                    if ask.lower() == "no" or ask.lower() == "n":
                        print("\nOK")
                        break

                # Ask for new data entry
                option = input("New data entry?\n Type YES or NO: ")

                # If no, exit the loop
                if option.lower() == "no" or option.lower() == "n":
                    print("\nOK")
                    break

            # Compliment
            print("Thankyou!")
            db_cursor.close()
            connection.close()

        ## OPEN ENTRIES ##
        if answer == "2":

            clear()

            # Keep prompting until valid option no
            while (True):

                # UI Menu
                print("\n                   ---| Open Entries |---")
                print("---------------------------------------------------------------\n")
                print("1. By Age     2. By Class    3.By Alphabet   4.Open All Entries\n")

                # Ask for option no
                query = input("(1 - 5): ")

                ## SEARCH BY AGE ##
                if query == "1":

                    clear()

                    print("---| SEARCH BY AGE |---")

                    # Keep prompting until valid age
                    while (True):

                        query_age = input("Enter Age: ")

                        check = test_num(query_age)

                        if check == True:
                            break

                        else:
                            print("Enter Correct Age\n")

                    # Look into database and select all columns
                    age_entries = db_cursor.execute("SELECT * from students WHERE Age = ? ORDER BY First", (query_age,))

                    # Fetch data into nested lists
                    entries = age_entries.fetchall()

                    # List to store full name of student
                    full_name = []

                    # Get first, last and middle name of student
                    for i in range(len(entries)):

                        # Store in list
                        full_name.append([entries[i][1], entries[i][2], entries[i][3]])

                    # Be ready to print results
                    print("\nStudent ID | Full Name      | Age | Class | Father | Number\n")

                    # Iterate through each nested list in entries
                    for i in range(len(entries)):

                        # Get Student ID
                        ID_no = entries[i][0]

                        # Print ID and Full Name of Student
                        print(ID_no, " | ", full_name[i][0], full_name[i][1], full_name[i][2], "|", end="")

                        # Print Every column after 'Last' name column
                        for j in range(4, 8):
                            values = entries[i][j]
                            print(values, "|", end="")

                        # Print New-line
                        print("\n")

                    # Print New-line, Exit loop
                    print()
                    break

                ## SEARCH BY CLASS ##
                if query == "2":

                    clear()

                    print("---| SEARCH BY CLASS |---")

                    # Keep prompting until valid age
                    while (True):

                        query_class = input("Enter Class: ")

                        check = test_num(query_class)

                        if check == True:
                            break

                        else:
                            print("Enter Correct Class No\n")

                    # Look into database and select all columns
                    class_entries = db_cursor.execute("SELECT * from students WHERE Class = ? ORDER BY First", (query_class,))

                    # Fetch data into nested lists
                    entries = class_entries.fetchall()

                    # List to store full name of student
                    full_name = []

                    # Get first, last and middle name of student
                    for i in range(len(entries)):

                        # Store in list
                        full_name.append([entries[i][1], entries[i][2], entries[i][3]])

                    # Be ready to print results
                    print("\nStudent ID | Full Name     | Age | Class | Father | Number\n")

                    # Iterate through each nested list in entries
                    for i in range(len(entries)):

                        # Get Student ID
                        ID_no = entries[i][0]

                        # Print ID and Full Name of Student
                        print(ID_no, " | ", full_name[i][0], full_name[i][1], full_name[i][2], "|", end="")

                        # Print Every column after 'Last' name column
                        for j in range(4, 8):
                            values = entries[i][j]
                            print(values, "|", end="")

                        # Print New-line
                        print("\n")

                    # Print New-line, Exit loop
                    print()
                    break

                ## SEARCH BY FIRST ALPHABET ##
                if query == "3":

                    clear()

                    print("---| SEARCH BY ALPHABET |---")

                    # Select all data from students database
                    alpha_entries = db_cursor.execute("SELECT * from students ORDER BY first")

                    # Fetch all entries
                    entries = alpha_entries.fetchall()

                    # Keep prompting till valid input
                    while (True):

                        query_alpha = input("Enter Alphabet (A - Z): ")

                        check = test_alpha(query_alpha)

                        if len(query_alpha) == 1 and check == True:
                            break

                        print("Incorrect Alphabet")

                    # Ready to print queries
                    print("\nStudent ID | Full Name       | Age | Class | Father' Name | Phone Number\n")

                    # List to store full name of students
                    full_name = []
                    student_id = None

                    # Get first, last and middle name of student
                    for i in range(len(entries)):

                        # Store in list
                        full_name.append([entries[i][1], entries[i][2], entries[i][3]])

                        # Get first, middle and last name
                        first_name = full_name[i][0]
                        middle_name = full_name[i][1]
                        last_name = full_name[i][2]

                        # Check if 1st char of first name matches with query
                        if first_name[0] == query_alpha.upper():

                            # Get Student ID
                            student_id = entries[i][0]

                            # Get student age
                            age = entries[i][4]

                            # Get student class no
                            class_no = entries[i][5]

                            # Get student's father name
                            father_name = entries[i][6]

                            # Get student's phone number
                            number = entries[i][7]

                            # Print ID, full name, age, class, father's name and phone number
                            print(student_id, "|", first_name, middle_name, last_name, "|", age, "|", class_no, "|", father_name, "|", number)

                    # Print New-line, exit the loop
                    print("\n")
                    break

                ## OPEN ALL ENTRIES ##
                if query == "4":

                    clear()

                    # UI Title
                    print("\n\n---| ALL ENTRIES |---\n\n")

                    # COUNT all rows in database
                    entries = db_cursor.execute("SELECT COUNT(*) from students")

                    # Fetch data
                    entries_no = entries.fetchone()

                    # Store total number of entries
                    total = entries_no[0]

                    # Print total Number of entries
                    print("Found Total: ", total, "\n")

                    # Ready to print all entries
                    print("\n\nID   |   Full Name       | Age | Class | Father's Name | Phone Number\n\n")

                    # Select all entries from database
                    entries = db_cursor.execute("SELECT * from students")

                    # Fetch data
                    all_entries = entries.fetchall()

                    # For each entry
                    for i in range(len(all_entries)):

                        # Get student ID
                        student_id = all_entries[i][0]

                        # Get first, middle and last name of student
                        first_name = all_entries[i][1]
                        middle_name = all_entries[i][2]
                        last_name = all_entries[i][3]

                        # Print ID, First, Middle and Last name of student
                        print(student_id, "|", first_name, "|", middle_name, "|", last_name, "|", end="")

                        # Print Age, Class, Father's Name and Phone number of student
                        for j in range(4, 8):

                            print(all_entries[i][j], "|", end="")

                        # Print New-line
                        print("\n")

                else:
                    print("Type Correct Option\n")

        ## SEARCH FOR STUDENT ##
        if answer == "3":

            clear()

            # UI Menu
            print("\n---| SEARCH FOR STUDENT |---\n")

            # Keep prompting till valid input for first name
            while (True):
                search_first = input("Enter Student's First Name: ")

                check = test_alpha(search_first)

                if check == True:
                    break

                print("Enter Correct Name!")

            # Keep prompting till valid input for middle name
            while (True):
                search_middle = input("Enter Student's Middle Name: ")

                check = test_alpha(search_middle)

                if check == True:
                    break

                print("Enter Correct Name!")

            # Keep prompting till valid input for last name
            while (True):
                search_last = input("Enter Student's Last Name: ")

                check = test_alpha(search_last)

                if check == True:
                    break

                print("Enter Correct Name!")

            # Go inside database and select required info
            entry = db_cursor.execute("SELECT ID, First, Middle, Last, Age, Class, Father, Number from students WHERE First = ? AND Middle = ? AND Last = ?", (search_first, search_middle, search_last))

            # Fetch all entries
            student_entries = entry.fetchall()

            # If no record or entry found
            if len(student_entries) == 0:
                print("\nNo record Found!\n")

            # Print number of record(s) found
            print("\nFound: ", len(student_entries), "\n")

            # Be ready to print matching queries
            print("ID |  Full Name    |   Age  |   Class |  Father's Name |  Phone Number")

            # Print all matching queries
            for i in range(len(student_entries)):

                for j in range(len(student_entries[i])):
                    print(student_entries[i][j], "|", end="")

                print()

            # Print New-line
            print()

        ## DELETE ENTRY ##
        if answer == "4":

            clear()

            # UI Menu
            print("\n---| DELETE ENTRY |---\n")

            # Keep prompting till valid student ID
            while (True):

                ask_id = input("Enter Student ID: ")

                check = test_num(ask_id)

                if check == True and len(ask_id) < 100 and ask_id > "0":
                    break

                print("\nEnter Correct Student ID!\n")

            print()

            # Select entry from database matching input ID
            id_entry = db_cursor.execute("SELECT ID, First, Middle, Last, Age, Class, Father, Number from students WHERE ID = ?", (ask_id, ))

            # Fetch student entry
            id_match = id_entry.fetchone()

            # If no record Found
            if id_match == None:
                print("No record Found!\n")
                print()

            # Start printing full name of student
            print("Name: ", end="")

            # Print first, middle and last name of student
            for i in range(1, 4):
                print(id_match[i], "", end="")

            # Print New-line
            print()

            # Get age, class, father's name, phone number
            id_age = id_match[4]
            id_class = id_match[5]
            id_father = id_match[6]
            id_number = id_match[7]

            # Print all info
            print("Age: ", id_age)
            print("Class: ", id_class)
            print("Father Name: ", id_father)
            print("Phone Number: ", id_number)

            # Print New-line
            print()

            # Ask for confirmation
            print("\nCONFIRM DELETE ENTRY?    (once done it cannot be reversed)\n")

            # Keep promting till valid option
            while (True):

                confirm = input("Type YES or NO: ")

                # If confirmation is cancelled
                if confirm.lower() == "n" or confirm.lower() == "no":
                    print("\nOK DELETE QUERY CANCELLED\n")
                    break

                # Else
                if confirm.lower() == "y" or confirm.lower() == "yes":

                    # Select entry from database matching input ID, DELETE entry
                    db_cursor.execute("DELETE from students WHERE ID = ?", (ask_id, ))
                    connection.commit()

                    # Print Success
                    print("\nENTRY DELETED SUCCESSFULLY! \n")
                    break

                print("Please Type Correct Option!\n\n")

            # Print New-line
            print()

        ## UPDATE EXISTING ENTRY ##
        if answer == "5":

            clear()

            # UI Menu
            print("\n---| UPDATE EXISTING ENTRY |---\n")

            # Keep prompting till valid student ID
            while (True):

                ask_id = input("Enter Student ID: ")

                check = test_num(ask_id)

                if check == True:
                    break

                print("\nEnter Correct Student ID\n")

            # Print New-line
            print("\n")

            # Go inside database and select entry matching ID
            id_entry = db_cursor.execute("SELECT ID from students WHERE ID = ?", (ask_id, ))

            # Fetch data
            id_match = id_entry.fetchone()

            # If no record found
            if id_match == None:
                print("\nNo record Found!\n")
                print()

            # Be ready to collect required info
            print("\nENTER INFO\n\n")

            # Keep prompting till valid first name
            while (True):

                ask_first = input("First Name: ")

                check = test_alpha(ask_first)

                if check == True:
                    break

                print("\nEnter Valid Name!\n\n")

            # Keep prompting till valid middle name
            while (True):

                ask_middle = input("Middle Name: ")

                check = test_alpha(ask_middle)

                if check == True:
                    break

                print("\nEnter Valid Name!\n\n")

            # Keep prompting till valid last name
            while (True):

                ask_last = input("Last Name: ")

                check = test_alpha(ask_last)

                if check == True:
                    break

                print("\nEnter Valid Name!\n\n")

            # Keep prompting till valid age
            while (True):

                ask_age = input("Age: ")

                check = test_num(ask_age)

                if check == True:
                    break

                print("\nEnter Valid Age between 5 - 30!\n\n")

            # Keep prompting till valid class no
            while (True):

                ask_class = input("Class: ")

                check = test_num(ask_class)

                if check == True:
                    break

                print("\nEnter Valid Class No Between 1 - 10\n\n")

            # Keep prompting till valid father's name
            while (True):

                ask_father = input("Father's Name: ")

                check = test_alpha(ask_father)

                if check == True:
                    break

                print("\nEnter Valid Name!\n\n")

            # Keep prompting till valid phone number
            while (True):

                ask_number = input("Phone Number: ")

                check = test_num(ask_number)

                if check == True:
                    break

                print("\nEnter Valid Phone Number!\n\n")

            # Ask for confirmation
            print("\n")
            print("CONFIRM UPDATE ENTRY\n")
            print("First Name: ", ask_first)
            print("Middle Name: ", ask_middle)
            print("Last Name: ", ask_last)
            print("Age: ", ask_age)
            print("Class: ", ask_class)
            print("Father's Name: ", ask_father)
            print("Phone Number: ", ask_number)

            # Keep prompting till valid option
            while (True):

                # Ask for option
                option = input("\nType YES or NO: ")

                # If no, cancel operation
                if option.lower() == "n" or option.lower() == "no":
                    print("\nOPERATION CANCELLED\n\n")

                # Else
                if option.lower() == "y" or option.lower() == "yes":

                    # Update entry inside database, matching input ID of student
                    db_cursor.execute("UPDATE students SET First = ?, Middle = ?, Last = ?, Age = ?, Class = ?, Father = ?, Number = ? WHERE ID = ?", (ask_first, ask_middle, ask_last, ask_age, ask_class, ask_father, ask_number, ask_id))
                    connection.commit()

                    # Print Success
                    print("\nENTRY UPDATED SUCCESSFULLY!\n\n")
                    print()


import cv2
import numpy as np

def nothing(x):
	pass

cv2.namedWindow('Color Capture')

#Create TrackBars
cv2.createTrackbar('M1', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('S1', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('V1', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('M2', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('S2', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('V2', 'Color Capture', 0, 255, nothing)

frame = cv2.imread('test2.jpg')
frame = cv2.resize(frame,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)

while(1):

	cv2.imshow('Color Capture', frame)

	hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

	if cv2.waitKey(1) & 0xFF == ord('q'):
		break

	m1 = cv2.getTrackbarPos('M1', 'Color Capture')
	s1 = cv2.getTrackbarPos('S1', 'Color Capture')
	v1 = cv2.getTrackbarPos('V1', 'Color Capture')

	m2 = cv2.getTrackbarPos('M2', 'Color Capture')
	s2 = cv2.getTrackbarPos('S2', 'Color Capture')
	v2 = cv2.getTrackbarPos('V2', 'Color Capture')

	lower_color=np.array([m1, s1, v1])
	upper_color=np.array([m2, s2, v2])
	#apply mask
	mask = cv2.inRange(hsv, lower_color, upper_color)
	res = cv2.bitwise_and(frame, frame, mask=mask)
	#show the result
	cv2.imshow('res', res)
file.close()
cap.release()
cv2.destroyAllWindows()


#!/usr/bin/env python3
def combinations_array(num_array, r):
    import itertools
    return list(itertools.combinations(num_array, r))

def main():
    A, B, C, D, E = map(int,input().split())
    ans = set()

    for itm in combinations_array([A,B,C,D,E], 3):
        ans.add(sum(list(itm)))

    ans = list(ans)
    ans.sort(reverse=True)
    return ans[2]

print(main())

# self AC


# %%

import json
import os
import shutil
from copy import deepcopy
from enum import Enum, auto
from pathlib import Path
from sys import platform
from typing import Any, Tuple
from zipfile import ZipFile
from deeppavlov import build_model, configs
from deeppavlov.core.commands.utils import parse_config

class ModelCodename(Enum):
    TEST = auto()
    TEST2 = auto()
    ORIGIN = auto()

class BaseDD:
    def __init__(self, codename: ModelCodename):
        self.codename = codename

class JsonDD(BaseDD):
    def __init__(self, codename: ModelCodename):
        super().__init__(codename)

class DDFactory:
    @staticmethod
    def create(dataset_codename: ModelCodename) -> BaseDD:
        return JsonDD(dataset_codename)

class BaseDataset:
    def __init__(self, data: Any, descriptor: BaseDD):
        self.data = data
        self.descriptor = descriptor

class JsonDataset:
    def __init__(self, data: list, view_config: str, descriptor: BaseDD):
        self.data = data
        self.view_config = view_config
        self.descriptor = descriptor

class DatasetKeeper:
    DATASET_DIR = "DS"
    DATASET_TASKS_FILENAME = "data.json"

    @staticmethod
    def load_dataset(dataset_descriptor: BaseDD) -> BaseDataset:
        filename = DatasetKeeper._get_filename(dataset_descriptor.codename)

        data, view_config = DatasetKeeper._load_json_dataset(filename)
        return JsonDataset(data, view_config, dataset_descriptor)

    @staticmethod
    def _load_json_dataset(filename) -> Tuple[list, str]:
        directory = os.path.dirname(filename)
        json_filename = os.path.join(directory, DatasetKeeper.DATASET_TASKS_FILENAME)
        with open(json_filename, "r", encoding="utf-8") as json_file:
            data = json.load(json_file)
        return data, None

    @staticmethod
    def _get_filename(dataset_codename: ModelCodename) -> str:
        path = os.path.join(DatasetKeeper.DATASET_DIR, f"{dataset_codename}")
        os.makedirs(path, exist_ok=True)
        filename = os.path.join(path, DatasetKeeper.DATASET_TASKS_FILENAME)
        return filename

class BaseMD:
    def __init__(self, model_codename: ModelCodename):
        self.model_codename = model_codename

class MDFactory:
    @staticmethod
    def create(model_codename: ModelCodename) -> BaseMD:
        return BaseMD(model_codename)

class BaseModel:
    def __init__(self, instance, descriptor: BaseMD):
        self.instance = instance
        self.descriptor = descriptor

    def __call__(self, *args, **kwargs):
        return self.instance(*args, **kwargs)

class ModelKeeper:
    MODEL_DIR = "models"
    TRAIN_PATH = "training"

    @staticmethod
    def load_model(model_descriptor: BaseMD) -> BaseModel:
        model_dir = ModelKeeper._make_model_dir(model_descriptor.model_codename)
        parsed_config = ModelKeeper._load_config(model_dir)
        instance = build_model(parsed_config)
        return BaseModel(instance, model_descriptor)

    @staticmethod
    def train_model(model_descriptor: BaseMD, dataset_descriptor: BaseDD, keep_train_files: bool) -> BaseModel:
        model_dir = ModelKeeper._make_model_dir(model_descriptor.model_codename)
        basic_config = ModelKeeper._load_config(model_dir)
        train_config = ModelKeeper._prepare_for_training(basic_config)
        dataset = DatasetKeeper.load_dataset(dataset_descriptor)

        from trainer import Trainer

        trainer = Trainer(keep_train_files, train_config, dataset, ModelKeeper.TRAIN_PATH)
        model = trainer.fit()
        return BaseModel(model, model_descriptor)

    @staticmethod
    def _load_config(model_dir) -> dict:
        #используем модель ner_rus_bert
        with open(configs.ner.ner_rus_bert, "r") as raw_config:
            wrong_config = json.load(raw_config)
        wrong_config["metadata"]["variables"]["MODEL_PATH"] = model_dir
        parsed_config = parse_config(wrong_config)
        return parsed_config

    @staticmethod
    def _prepare_for_training(config: dict) -> dict:
        # TODO Magic numbers
        config = deepcopy(config)
        config["train"]["epochs"] = 10  # 45
        config["train"]["batch_size"] = 10  # 14
        config["dataset_reader"]["data_path"] = ModelKeeper.TRAIN_PATH
        return config

    @staticmethod
    def _backup_model_files(model_dir):
        ext = "zip"
        base_name = os.path.basename(model_dir)
        shutil.make_archive(base_name, ext, model_dir)
        shutil.move(f"{base_name}.{ext}", Path(model_dir).parent)

    @staticmethod
    def _make_model_dir(model_codename: ModelCodename) -> str:
        model_path = os.path.join(ModelKeeper.MODEL_DIR, f"{model_codename}")
        os.makedirs(model_path, exist_ok=True)
        return model_path

#------------------------------------------------------------------------------------------------------------------------------------------------
#запускаем здесь

if __name__ == "__main__":

    train_model = True  # True - обучаем модель, False - просмотриваем результат
    keep_train_files = True # True - не обновляем файлы обучения в папке training, False - обновляем файлы обучения в папке training из Label Studio
    model_path = ModelCodename.TEST2 # model_path - наименование папки с моделью
    dd = DDFactory.create(model_path)
    dd.codename='test2' # codename - наименование папки с обучающим json
    ds = DatasetKeeper.load_dataset(dd)
    md = MDFactory.create(model_path)
    if train_model:
        # Обучение новой модели
        model = ModelKeeper.train_model(md, dd, keep_train_files)
        model.instance.save()
    else:
        model = ModelKeeper.load_model(md)

    print(model.instance(['королевич и Шрек сыграли свадьбу']))


import json
import os
from vars import *

def jsonl_dumper(arg,jsonl_list):  #make input for factcc
    if arg == 'factcc':
        seq_id=0
        with open('factCC/data-dev.jsonl', 'w') as outfile:
            for item in jsonl_list:
                data={'id' : str(seq_id),'text': str(item[0]), 'claim' : str(item[1]), 'label': 'INCORRECT'}
                json.dump(data, outfile)
                outfile.write('\n')
                seq_id+=1
def load_preds(f_name,method=1):
    PATH_F=os.path.join(PATH_D,f_name)
    with open(PATH_F,encoding="utf8") as f:
        lines=f.readlines()
    input=s_format(lines)

    if method == 2: # filtering list, take only the first input for each prediction (method 2 for test)
        f_list=[]
        for n in range(0,len(input),4):
            f_list.append(input[n])
        print(len(f_list))
        return f_list
    return input

def s_format(lines=[]):
    f_lines=[]
    for l in lines:
        f_lines.append(l.translate({ord(i): None for i in "[,']"})) # filter input lines
    return f_lines
def max_score(score_list,i_max):  #method 3 for test
    s_index=i_max-4
    split_list=score_list[s_index:i_max]
    return max(split_list)


from Service import CameraManager
import cv2
import time

cv2.startWindowThread()
CameraManager.createCamera(name="TEST", url=0, initial_mode="MODE")
isThis = False
while True:
    if CameraManager.getStatus("TEST"):
        CameraManager.resumeCamera("TEST")
        time.sleep(1)
        isThis = True
        break

while True:
    if isThis:
        frame = CameraManager.getCameraFrame("TEST")
        cv2.imshow("Test", frame)

    if cv2.waitKey(1) == ord('p'):
        isThis = False
        CameraManager.pauseCamera("TEST")

    if cv2.waitKey(1) == ord('s'):
        isThis = True
        CameraManager.resumeCamera("TEST")

    if cv2.waitKey(1) == ord('q'):
        CameraManager.cleanCamera("TEST")
        cv2.destroyAllWindows()
        break


import requests
import datetime as dt
from datetime import timedelta

USERNAME = "yanjun"
TOKEN = "<TOKEN>"
GRAPH_ID = "yjgraph1"
pixela_endpoint = "https://pixe.la/v1/users"

user_params = {
    "token": TOKEN,
    "username": USERNAME,
    "agreeTermsOfService": "yes",
    "notMinor": "yes"
}

# response = requests.post(url=pixela_endpoint, json=user_params)
# print(response.text)

graph_endpoint = f"{pixela_endpoint}/{USERNAME}/graphs"

graph_config = {
    "id": GRAPH_ID,
    "name": "Cycling Graph",
    "unit": "Km",
    "type": "float",
    "color": "ajisai"
}

headers = {
    "X-USER-TOKEN": TOKEN
}

# response = requests.post(url=graph_endpoint, json=graph_config, headers=headers)
# print(response.text)

post_pixel_endpoint = f"{pixela_endpoint}/{USERNAME}/graphs/{GRAPH_ID}"

today = str(dt.datetime.today().date().strftime("%Y%m%d"))
yesterday = str((dt.datetime.today().date() - timedelta(1)).strftime("%Y%m%d"))

post_pixel_params = {
    "date": today,
    "quantity": input("How many kilometres did you cycled today? ")
}

# response = requests.post(url=post_pixel_endpoint, json=post_pixel_params, headers=headers)
# print(response.text)

update_pixel_endpoint = f"{post_pixel_endpoint}/{yesterday}"

update_pixel_params = {
    "quantity": "20"
}

# response = requests.put(url=update_pixel_endpoint, json=update_pixel_params, headers=headers)
# response.raise_for_status()
# print(response.text)

delete_pixel_endpoint = f"{post_pixel_endpoint}/{yesterday}"

response = requests.delete(url=delete_pixel_endpoint, headers=headers)
print(response.text)


import numpy as np
import random
import pickle

import torch.nn.functional as functional
import torch
from torch.utils.data import Dataset,DataLoader
from torch.autograd import Variable
import torch.nn as nn
import sys

class Encoder(nn.Module):
    def __init__(self, input_size, hidden_size, word_len,embed_size):
        super(Encoder, self).__init__()
        self.embed = nn.Embedding(word_len, embed_size)
        self.gru = nn.GRU(embed_size, hidden_size, 1, batch_first = True,bidirectional=True)
    def forward(self, seq, hid):
        out = self.embed(seq)
        out, hid = self.gru(out, hid)
        return out, hid

class Decoder(nn.Module):
    def __init__(self, input_size, hidden_size, word_len, sent_limit,embed_size):
        super(Decoder, self).__init__()
        self.embed = nn.Embedding(word_len, embed_size)
        self.lstm = nn.GRU(hidden_size//2, hidden_size, 1, batch_first = True)
        self.fc1 = nn.Linear(hidden_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, word_len)

        self.attn = nn.Linear(hidden_size + embed_size, sent_limit)
        self.attn_com = nn.Linear(hidden_size + embed_size, hidden_size//2)

        self.sent_limit = sent_limit
        self.softmax = nn.LogSoftmax(dim = 1)
        self.word_len = word_len
        self.hidden_size = hidden_size
        self.embed_size = embed_size
    def forward(self, enco_out, emb, hid):
        attn_weight = torch.cat((emb, hid),2) #[1, 40, 800]
        #print(attn_weight.size())
        attn_weight = self.attn(attn_weight)
        attn_weight = functional.softmax(attn_weight,dim = 2) #[1, 40, 12]

#        print(attn_weight.size())
#        print(enco_out.size())
        attn_applied = torch.bmm(attn_weight.view(-1,1,self.sent_limit), enco_out) #torch.Size([40, 1, 400])

        #print('in decoder :',attn_applied.size())
        #exit()
        out = torch.cat((emb.view(-1,1,self.embed_size), attn_applied),2)
        out = self.attn_com(out)
        out = functional.relu(out) #[40,1,400]
        #print('in decoder :',out.size())

        out, hid = self.lstm(out, hid)
        #out = self.fc1(out)
        #out = functional.relu(out)
        out = self.fc2(out)
        out = out.view(-1, self.word_len)
        out = self.softmax(out)
        emb = self.embed(torch.max(out, 1)[1])
        emb = emb.view(-1,1,self.embed_size)
        #print(emb.size())
        #exit()
        return out, emb, hid