import argparse
import requests
import platform
from typing import Union
import json
from datetime import datetime
import os
from prettytable import PrettyTable
import subprocess

SYSTEMS = ('Linux', 'Windows')    # Supported Operating Systems
ERROR_CODES = {300: "PLATFORM_INVALID",
               400: "NETWORK_ACCESS_FAILED",
               500: "UNKNOWN_ERROR"
              }

API_ENDPOINT = 'https://api.intellivoid.net/openblu/v1'  # You may setup your own API endpoint if you wish

def get_server_info(uuid: str, key: str, verbose: bool = False):
    """Fetches a single OpenVPN server from the OpenBlu API, given its unique ID

       :param uuid: The unique ID of the desired server
       :type uuid: str
       :param key: The OpenBlu API key
       :type key: str
       :param verbose: If ``True``, make output verbose, default to ``False``
       :type verbose: bool, optional
       :returns: A dictionary containing the requested info, or ``None`` if the server doesn't exist
       :rtype: dict, None
    """

    link = API_ENDPOINT + "/servers/get"
    if verbose:
        print(f"API key is {key}")
        print(f"Fetching from {link}...")
    post_data = {}
    post_data["access_key"] = key
    post_data["id"] = uuid
    response = requests.post(link, data=post_data)
    try:
        data = json.loads(response.content)
    except json.JSONDecoder.JSONDecodeError as decode_error:
        print(f"Error: The API did not send a properly formatted response, error: {decode_error}")
        exit(decode_error)
    return data

def fetch_servers(endpoint: str = API_ENDPOINT, filter_by: Union[None, tuple] = None, order_by: Union[None, str] = None, sort_by: Union[None, str] = None, verbose: bool = True, key: Union[None, str] = None):
    """Fetches OpenVPN servers from the OpenBlu API

       :param endpoint: The API endpoint to contact and fetch the servers list from, defaults to 'https://api.intellivoid.info/openblu/v1'
       :type endpoint: str, None, optional
       :param filter_by: If not ``None``, filter the results by the given country, defaults to ``None``
       :type filter_by: tuple, None, optional
       :param order_by: If not ``None``, order the results by this order. It can either be ``'ascending'`` or ``'descending'``, defaults to ``None``
       :type order_by: str, None, optional
       :param sort_by: Sorts the list by the given condition, defaults to ``None`` (no sorting)
       :type sort_by: str, None, optional
       :param verbose: If ``True``, make the output verbose, default to ``False``
       :type verbose: bool, optional
       :param key: The OpenBlu API key, defaults to ``None``
       :type key: str, None, optional
       :returns servers_list: The list of available servers with the specified filters
       :rtype servers_list: dict
    """

    link = API_ENDPOINT + "/servers/list"
    if verbose:
        print(f"API key is {key}")
        print(f"Fetching from {link}...")
    post_data = {}
    post_data["access_key"] = key
    if filter_by[0]:
        post_data["by"] = filter_by[1]
        post_data["filter"] = filter_by[0]
    if order_by:
        post_data["order_by"] = order_by
    if sort_by:
        post_data["sort_by"] = sort_by
    response = requests.post(link, data=post_data)
    try:
        data = json.loads(response.content)
    except json.JSONDecoder.JSONDecodeError as decode_error:
        print(f"Error: The API did not send a properly formatted response, error: {decode_error}")
        exit(decode_error)
    return data

def openblu(parsed_args):
    """Main entry point for the OpenBlu client UI

       :param parsed_args: The result of ``argparse.ArgumentParser().parse_args()``
       :type parsed_args: class: Namespace
    """

    if parsed_args.verbose:
        print(f"Platform is: '{platform.system()}'")
    api_key = parsed_args.key
    if parsed_args.fetch_servers:
        if parsed_args.verbose:
            print(f"Fetching available VPN servers from {API_ENDPOINT}\nCountry: {'Any' if not parsed_args.filter_by else parsed_args.filter_by}\nOrder: {None if not parsed_args.order_by else parsed_args.order_by}\nSorted by: {None if not parsed_args.sort_by else parsed_args.sort_by}")
        servers_list = fetch_servers(API_ENDPOINT, (parsed_args.filter_by, parsed_args.filter), parsed_args.order_by, parsed_args.sort_by, parsed_args.verbose, api_key)
        if not servers_list['success']:
            print(f"Error: Something went wrong when retrieving the servers! More details below\nHTTP Response Code: {servers_list['response_code']}\nAPI Error Code: {servers_list['error']['error_code']}\nAPI Error Message: {servers_list['error']['message']}\nAPI Error Type: {servers_list['error']['type']}")
        else:
            if parsed_args.verbose:
                print(f"Success! Retrieved {len(servers_list['servers'])} servers matching the provided filters")
            servers = PrettyTable()
            if parsed_args.verbose:
                servers.field_names = ["ID", "Hostname", "Country", "Country Short", "Score", "Ping (ms)", "Active Sessions", "Total Sessions", "Last Updated", "Created"]
            else:
                servers.field_names = ["ID", "Hostname", "Country", "Ping (ms)", "Active Sessions", "Last Updated"]
            for x in range(parsed_args.limit):
                if not servers_list['servers']:
                    break
                try:
                    server = servers_list['servers'].pop(x)
                except IndexError:
                    break
                server_id = server['id']
                host_name = server['host_name']
                country = server['country']
                country_short = server['country_short']
                score = server['score']
                ping = server['ping']
                sessions = server['sessions']
                total_sessions = server['total_sessions']
                last_updated = datetime.utcfromtimestamp(server['last_updated']).strftime('%Y-%m-%d %H:%M:%S %p')
                created = datetime.utcfromtimestamp(server['created']).strftime('%Y-%m-%d %H:%M:%S')
                if parsed_args.verbose:
                    servers.add_row([server_id, host_name, country, country_short, score, ping, sessions, total_sessions, last_updated, created])
                else:
                    servers.add_row([server_id, host_name, country, ping, sessions, last_updated])
            print(servers)
    elif parsed_args.set_access_key:
        try:
            access_key = input("Type here your access key: ")
        except (EOFError, KeyboardInterrupt):
            print()
            exit(1)
        if not access_key:
            print("Error: Access Key cannot be blank!")
            exit(1)
        try:
            with open(os.path.join(os.getcwd(), "openblu.key"), "w") as access_file:
                access_file.write(access_key)
        except PermissionError:
            print("Error: Could not create the configuration file due to a permission issue, please consider using the --key option or provide read/write access to the current working directory")
    elif parsed_args.info:
        server = get_server_info(parsed_args.info, api_key, parsed_args.verbose)
        if server['success']:
            if parsed_args.verbose:
                print(f"Success, creating .ovpn file...")
            try:
                with open(os.path.join(os.getcwd(), f"{server['server']['id']}.ovpn"), "w") as access_file:
                    access_file.write(server['server']['openvpn']['ovpn_configuration'])
            except PermissionError:
                print("Error: Could not create the .ovpn file for the server, please make sure that the program has read/write access to the current workdir")
                exit(1)
        elif server['response_code'] == 404:
            print("Error: A VPN Server with that ID doesn't exist")
            exit(1)
        elif server['response_code'] not in (200, 404):
            print(f"Error: Something went wrong when retrieving the servers! More details below\nHTTP Response Code: {server['response_code']}\nAPI Error Code: {server['error']['error_code']}\nAPI Error Message: {server['error']['message']}\nAPI Error Type: {server['error']['type']}")
            exit(ERROR_CODES[500])
    elif parsed_args.country:
        if parsed_args.connect_best:
            print(f"Looking for the best server in selected country...")
            servers_list = fetch_servers(API_ENDPOINT, ("country", parsed_args.country), parsed_args.order_by, parsed_args.sort_by, parsed_args.verbose, api_key)
            if servers_list['success']:
                if servers_list['servers']:
                    server = max(servers_list['servers'], key=lambda x: x['last_updated'])
                else:
                    server = None
            else:
                print(f"Error: Something went wrong when retrieving the servers! More details below\nHTTP Response Code: {servers_list['response_code']}\nAPI Error Code: {servers_list['error']['error_code']}\nAPI Error Message: {servers_list['error']['message']}\nAPI Error Type: {servers_list['error']['type']}")
                exit(ERROR_CODES[500])
        else:
            servers_list = fetch_servers(verbose=parsed_args.verbose)
            if servers_list['success']:
                if servers_list['servers']:
                    server = servers_list['servers'][0]
                else:
                    server = None
        if not server:
            print("Error: No server found with given parameters")
        else:
            print("Connecting to found server...")
            if parsed_args.verbose:
                print("Retrieving info about the server...")
            server = get_server_info(server['id'], api_key, parsed_args.verbose)
            if server['success']:
                if parsed_args.verbose:
                    print(f"Success, creating .ovpn file...")
                try:
                    with open(os.path.join(os.getcwd(), f"{server['server']['id']}.ovpn"), "w") as access_file:
                        access_file.write(server['server']['openvpn']['ovpn_configuration'])
                except PermissionError:
                    print("Error: Could not create the .ovpn file for the server, please make sure that the program has read/write access to the current workdir")
                    exit(1)
                if parsed_args.verbose:
                    print(f"Spawning subprocess for OpenVPN with file '{server['id']}'")
                process = subprocess.run(f"nohup openvpn --config {server['server']['id']}.ovpn &", shell=True)
                if process.returncode != 0:
                    print(f"Error: The OpenVPN process exited with error: {process.returncode}")
            else:
                print(f"Error: Something went wrong when retrieving the servers! More details below\nHTTP Response Code: {server['response_code']}\nAPI Error Code: {server['error']['error_code']}\nAPI Error Message: {server['error']['message']}\nAPI Error Type: {server['error']['type']}")
                exit(ERROR_CODES[500])

def setup_args(system: str):
    """Performs the necessary setup for the ``argparse`` module and does some checks on the arguments

       :param system: The qualified name of the current OS
       :type system: str
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("--key", help="The API Key for Intellivoid API", type=str)
    parser.add_argument("-b", "--connect-best", help="This flag tells the client to search for the best server to connect to", action='store_true')
    parser.add_argument("-c", "--country", help="Connects to the first available server in the chosen country, if any", type=str)
    parser.add_argument("-f", "--fetch-servers", help='Fetches all available OpenBlu VPN servers and shows them to the user', action='store_true')
    parser.add_argument("-i", "--info", help='Fetches specific information about a server, given its unique ID. The .ovpn configuration is saved in the current workdir', type=str)
    parser.add_argument("--filter-by", help='Filters the retrieved servers list by country or country_short, requires --filter', type=str, choices=('country', 'country_short'))
    parser.add_argument("--filter", help='The value to filter by, e.g. japan, thailand, etc. Requires --filter-by')
    parser.add_argument("-o", "--order-by", help="Orders the results by score, ping, sessions, total_sessions, last_updated and created", choices=("score", "ping", "sessions", "total_sessions", "last_updated", "created"), type=str)
    parser.add_argument("-s", "--sort-by", help='Sorts the ordered results by descending or ascending order', choices=("ascending", "descending"), type=str)
    parser.add_argument("-v", "--verbose", help='Make the output verbose', action='store_true')
    parser.add_argument("-l", "--limit", help='Sets the limit of servers that are printed to stdout, defaults to 5. Only applicable when fetching servers', type=int, default=5)
    parser.add_argument("--set-access-key", help='Saves your access key for future use, please note that if a config file is present in the current workdir, the --key option is ignored', action='store_true')
    args = parser.parse_args()
    if os.path.isfile(os.path.join(os.getcwd(), "openblu.key")):
        try:
            with open(os.path.join(os.getcwd(), "openblu.key"), "r") as access_file:
                access_key = access_file.readline()
        except PermissionError:
            print("Error: Could not read configuration file due to a permission issue, please consider using the --key option or provide read/write access to the current working directory")
            exit(1)
        if access_key:
            args.key = access_key
        else:
            print("Error: The configuration file is empty, try running openblu --set-access-key again or use the --key option")
            exit(1)
    if args.filter_by:
        if not args.filter:
            print("Error: --filter-by requires --filter!")
            exit(1)
    elif args.filter:
        if not args.filter_by:
            print("Error: --filter requires --filter-by!")
    openblu(args)

def get_platform():
    """Ran on startup, determines if the current platform is supported or not

        :returns: The value of ``platform.system()``, if the platform is supported
        :rtype: str
    """

    if platform.system() not in SYSTEMS:
        print("Error: Your platform is either unsupported or could not be determined, exiting")
        exit(ERROR_CODES[300])
    return platform.system()

if __name__ == "__main__":
    setup_args(get_platform())


import time

from bs4 import BeautifulSoup

from koohii.login import bugmenot_login_to_kanjii_koohi
from koohii.settings import REQUEST_HEADERS
from koohii.stories import get_kanji_stories, STORIES_URL
from koohii.utils import to_unicode_decimal, to_integer

def test_get_kanji_stories():
    number_of_stories = 10
    kanji_character = "五"

    koohii_session = bugmenot_login_to_kanjii_koohi()
    stories = get_kanji_stories(
        koohii_session=koohii_session,
        kanji_character=kanji_character,
        number_of_stories=number_of_stories,
    )

    assert len(stories) == number_of_stories
    assert "story" in stories[0]
    assert "stars" in stories[0]
    assert "reports" in stories[0]
    assert stories[0].get("story")
    assert stories[0].get("stars") >= 0
    assert stories[0].get("reports") >= 0

    time.sleep(2)

    kanji_character = "衣"
    stories = get_kanji_stories(koohii_session, kanji_character,)
    assert len(stories) == 10


import enum
import time
from typing import Optional

from fastapi import FastAPI, Path, HTTPException, Query, Depends
from pydantic import BaseModel, field_validator

class EventState(enum.Enum):
    NEW = 'New'
    FINISHED_LOSE = 'Lose'
    FINISHED_WIN = 'Win'

class Event(BaseModel):
    id: str | int
    coefficient: Optional[float] = None
    deadline: Optional[int] = None
    state: Optional[EventState] = None

    @field_validator('coefficient')
    def name_must_contain_space(cls, v):
        if v <= 0:
            raise ValueError('coefficient must be greater than 0')
        return round(v, 2)

events: dict[str, Event] = {
    '1': Event(id='1', coefficient=1.2, deadline=int(time.time()) + 600, state=EventState.NEW),
    '2': Event(id='2', coefficient=1.15, deadline=int(time.time()) + 60, state=EventState.NEW),
    '3': Event(id='3', coefficient=1.67, deadline=int(time.time()) + 90, state=EventState.NEW),
    '4': Event(id='1', coefficient=1.2, deadline=int(time.time()) + 600, state=EventState.NEW),
    '5': Event(id='2', coefficient=1.33, deadline=int(time.time()) + 60, state=EventState.FINISHED_WIN),
    '6': Event(id='3', coefficient=1.67, deadline=int(time.time()) + 90, state=EventState.FINISHED_LOSE)
}

app = FastAPI(docs_url="/docs")

@app.put('/event')
async def upsert_event(event: Event):
    if event.id not in events:
        events[event.id] = event
        return "Succsessfully created event"
    else:
        events[event.id] = event
        return "Succsessfully updated event"

@app.get('/event/{event_id}')
async def get_event(event_id: str = Path()):
    if event_id in events:
        return events[event_id]

    raise HTTPException(status_code=404, detail="Event not found")

class EventsRequest(BaseModel):
    events_ids: list[str] = Query(Query(default=[]))

@app.get('/events')
async def get_events(data: EventsRequest = Depends()):
    for event in events.values():
        print(event, time.time() < event.deadline, event.id in data.events_ids)
    if not data.events_ids:
        return list(e for e in events.values() if time.time() < e.deadline)
    else:
        return list(e for e in events.values() if time.time() < e.deadline or e.id in data.events_ids)


## TrackBar
import numpy as np
import cv2
# 변환용 콜백함수
def change_color(x):
    r = cv2.getTrackbarPos("R", "IMAGE")
    g = cv2.getTrackbarPos("G", "IMAGE")
    b = cv2.getTrackbarPos("B", "IMAGE")
    image[:]=[b,g,r] # 전체 행렬에 모두 적용
    cv2.imshow("IMAGE",image)
# 600x400x rgb값d에, int8 타입으로 모든 요소에 0값으로 넘파이객체 생성
image = np.zeros((600,400,3), np.uint8)
# openCV 윈도우창 이름 설정해 만들고
cv2.namedWindow("IMAGE")
# openCV 트랙바를 각각 생성한 윈도우창에 만들어준다
# bar이름,'윈도우창이름',0부터,255까지,콜백함수
cv2.createTrackbar("R", "IMAGE",0,255,change_color)
cv2.createTrackbar("G", "IMAGE",0,255,change_color)
cv2.createTrackbar("B", "IMAGE",0,255,change_color)
cv2.imshow('IMAGE',image)
cv2.waitKey(0)


import os
from bitvec import BitVec

class Reg(object):
    """
    Defines name of architectural registers.
    Scalar: SR0 - SR7
    Vector: VR0 - VR7
    """

    SCALAR = "SR"
    VECTOR = "VR"

    def __init__(self, ty=SCALAR, idx=1):
        if ty not in {Reg.SCALAR, Reg.VECTOR}:
            raise Exception(f"Invalid type: {ty}")
        if idx < 0 or idx > 7:
            raise Exception(f"Invalid index: {idx}")
        self.ty = ty
        self.idx = idx

    def __repr__(self):
        return f"{self.ty}{self.idx}"

    def __eq__(self, other):
        return self.ty == other.ty and self.idx == other.idx

    @staticmethod
    def parse(s):
        # Parse string and determine register type and index
        try:
            return Reg(s[:2], int(s[2:]))
        except Exception as e:
            # print(s, e)
            return None

class RegisterFile(object):
    def __init__(self, ty, count, length=1, size=32):
        self.ty = ty
        self.name = ty + "F"
        self.reg_count = count
        self.vec_length = length  # words in a vector.
        self.reg_bits = size
        self.min_value = -pow(2, self.reg_bits - 1)
        self.max_value = pow(2, self.reg_bits - 1) - 1
        # Register file as list of lists
        self.registers = [
            [BitVec(0, size) for e in range(self.vec_length)]
            for r in range(self.reg_count)
        ]

    def Read(self, reg):
        # print(f"    READ Reg[{reg}]: {self.registers[reg.idx]}")
        assert reg.ty == self.ty
        if self.vec_length == 1:
            # Read scalar directly, don't pass list of 1 element
            return self.registers[reg.idx][0]
        else:
            return self.registers[reg.idx]

    def Write(self, reg, val, mask=None, length=None):
        # VL and VM taken to perform partial writes to register
        assert reg.ty == self.ty
        if length is None:
            length = self.vec_length
        if mask is None:
            mask = [1]*length
        # print(f"    WRITE Reg[{reg}] mask={mask} length={length}")
        # print(f"        {val}")

        if self.vec_length == 1:
            self.registers[reg.idx][0] = val
        else:
            # Update with mask
            for i in range(length):
                if mask[i]:
                    self.registers[reg.idx][i] = val[i]

    def dump(self, iodir):
        opfilepath = os.path.abspath(os.path.join(iodir, self.name + ".txt"))
        with open(opfilepath, "w") as opf:
            row_format = "{:<13}" * self.vec_length + "\n"
            lines = [
                row_format.format(*[str(i) for i in range(self.vec_length)]),
                "-" * (self.vec_length * 13) + "\n",
            ]
            lines += [
                row_format.format(*[str(val) for val in data])
                for data in self.registers
            ]
            opf.writelines(lines)
        print(self.name, "- Dumped data into output file in path:", opfilepath)


import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KernelDensity
import pandas as pd
from sklearn.model_selection import train_test_split

csv_file = pd.read_csv("/Pattern_Classification_pro/P_01/dataset.txt", delimiter =' ', header = None)
csv_file.columns = ['x1', 'x2', 'y']
csv_file.to_csv('C:/Users/Ladan_Gh/PycharmProjects/pythonProject/Pattern_Classification_pro/dataset_01.csv',index = None)

csv_file_01 = pd.read_csv('/Pattern_Classification_pro/P_01/dataset_01.csv')
df = pd.DataFrame(csv_file_01)

x = df.iloc[:, 0:2].values #rows
y = df.iloc[:, 2].values #lable

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.30)

#============================================================
model = KernelDensity()
model.fit(x_train)
log_dens = model.score_samples(x_test)

plt.fill(x_test, np.exp(log_dens), c='green')
plt.show()


from mad_gui import start_gui
from mad_gui.plot_tools.labels import BaseRegionLabel

from custom_importer import CustomImporter
from custom_importer import CustomExporter
from mad_gui.config import BaseTheme
from PySide2.QtGui import QColor

class MyTheme(BaseTheme):
    # COLOR_DARK = QColor(0, 255, 100)
    # COLOR_LIGHT = QColor(255, 255, 255)
    FAU_PHILFAK_COLORS = {
        "dark": QColor(255, 0, 0),
        "medium": QColor(0, 255, 0),
        "light": QColor(0, 0, 255),
    }

class Self_Recall_Labels(BaseRegionLabel):
    # This label will always be shown at the upper 20% of the plot view
    min_height = 0.6
    max_height = 1
    name = "Activity"
    color = [255, 0, 127, 70]
    descriptions = {
        'walking': None,
        'running': None,
        'cycling': None,
        'car_driving': None,
        'cooking': None,
        'playing_an_instrument': None,
        'horse_riding': None,
        'other': None}

start_gui(plugins=[CustomImporter, CustomExporter], theme=MyTheme, labels=[Self_Recall_Labels])


from rest_framework.routers import SimpleRouter
from django.urls import include, path
from rest_framework.authtoken import views
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from django.conf.urls import url

from .views import RequestViewSet, MessageViewSet, ServiceViewSet, SetRatingViewSet

router_v1 = SimpleRouter()
router_v1.register('requests', RequestViewSet)
router_v1.register(r'requests/(?P<request_id>\d+)/messages', MessageViewSet, basename='message')
router_v1.register('services', ServiceViewSet)
router_v1.register('requests/set-rating', SetRatingViewSet)

urlpatterns = [
    path('v1/', include(router_v1.urls)),
    path('v1/auth/', include('djoser.urls')),  # аутентификация jwt. работа с пользователями
    path('v1/auth/', include('djoser.urls.jwt')),  # аутентификация jwt. работа с токенами
    path('v1/auth/', include('rest_framework.urls')),  # ссылки на логин/логаут при работе с api через web.
    path('v1/auth/api-token-auth/', views.obtain_auth_token),  # аутентификация токеном.
]

# Настраиваем автоматическую документацию для API
schema_view = get_schema_view(
   openapi.Info(
       title="HelpDesk API",
       default_version='v1',
       description="Документация для приложения HelpDesk",
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

# Подключаем автоматическую документацию для API
urlpatterns += [
   url(r'^swagger(?P<format>\.json|\.yaml)$',
       schema_view.without_ui(cache_timeout=0), name='schema-json'),
   url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0),
       name='schema-swagger-ui'),
   url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0),
       name='schema-redoc'),
]


# Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
# determine if the input string is valid

"""
An input string is valid if:
1. Open brackets must be closed by the same type of brackets
2. Open brackets must be closed in the correct order.
"""

# {[]} --> True
# ([)]) --> False

# Time Complexity: O(n) to loop through every character in String + O(1) look up time
# Space Complexity: O(n) to store the stack. Worst case all char in string
# + Constact for the dict

def isValid(s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        dict = {
            ")": "(",
            "}": "{",
            "]": "[",
        }
        for i in range(len(s)):
            if s[i] == "(" or s[i] == "{" or s[i] == "[":
                stack.append(s[i])
            elif s[i] in dict.keys():
                if len(stack) == 0:
                    return False
                elif stack[-1] != dict[s[i]]:
                    # print ("here", stack[-1])
                    return False
                else:
                    stack.pop()
        if len(stack) > 0:
            return False
        else:
            return True

# print (isValid("([]])"))

# Time Complexity: O(n) --> traverse string + O(m) --> dict.keys()
# Space Complexity: 0(m)--> dict + O(n) --> stack
def isValidParenthesis(s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) < 1:
            return True
        stack = []
        dict = {
            ')': '(',
            '}': '{',
            ']': '['
        }
        for i in range(len(s)):
            if s[i] not in dict.keys():
                stack.append(s[i])
            else:
                if len(stack) == 0:
                    return False
                if stack.pop() != dict[s[i]]:
                    return False
        if len(stack) != 0:
            return False
        return True

s = ''
s1 = '('
s2 = '{([])}'
s3 = '{([])]}'
s4 = '{([{])]'

print (isValidParenthesis(s))
print (isValidParenthesis(s1))
print (isValidParenthesis(s2))
print (isValidParenthesis(s3))
print (isValidParenthesis(s4))


import re #modulo importado para la función de validar correo electronico

# Funciones utilitarias

def is_only_digits (num):
    """ Función utilitaria que validar que los dígitos ingresados sean números."""
    for i in num:
        aux = ord(i)
        if aux not in range(48,58):
          return False
        return True

def is_valid_date(date):
    """ Función utilitaria que validar la fecha con los requerimientos solicitados en el ejercicio."""
    if len(date) != 10:
        return False
    if date[2] != "/" or date[5] != "/":
        return False
    dia = int(date[:2])
    mes = int(date[3:5])
    ano = int(date[6:])
    if ano < 1900:
        return False
    if mes >= 1 and mes <= 12:
        if mes == 2:
            if not ano % 4 and (ano % 100 or not ano % 400):
                if dia >= 1 and dia <= 29:
                    return True
                else:
                    return False
            elif dia >= 1 and dia <= 28:
                return True
            else:
                return False
        elif mes == 4 or mes == 6 or mes == 9 or mes == 11:
            if dia >= 1 and dia <= 30:
                return True
            else:
                return False
        elif dia >= 1 and dia <= 31:
            return True
        else:
            return False
    else:
        return False

def is_valid_phone(phone):
    """ Función utilitaria que valida el número de teléfono y que llama a su vez a la función is_only_digits para validar que solo contenga números."""
    if len(phone) == 9:
        if phone[0] == "9" or phone[0] == "6":
            return is_only_digits(phone)
        else:
            return False
    else:
        return False

def is_valid_email(email):
    """ Función utilitaria que verifica que el correo electronico caracteres alfanumericos, simbolo arroba, seguido un dominnio."""
    if re.match("^[(a-z0-9\_\-\.)]+@[(a-z0-9\_\-\.)]+\.[(a-z)]{2,15}$", email.lower()):
        return True
    else:
        return False

def is_valid_nif(nif):
    """ Función utilitaria que verifica si el NIF es correcto, se utiliza un bucle para pedir nuevamente el NIF si no cumple con los requisitos"""
    while True:
        valido = len(nif) == 9
        if valido:
            nif_aux = nif[:8]
            letra = ord(nif[8:].upper())
            if is_only_digits(nif_aux):
                if letra >= 65 and letra <= 90:
                    return True, nif
                else:
                    print("-------------------------")
                    print("El último caracter debe ser una letra.")
                    print("-------------------------")
                    nif = input("Introduce el NIF del nuevo cliente: ").strip()
            else:
                print("-------------------------")
                print("Introduce un NIF valido, debe tener ocho digitos y una letra.")
                print("-------------------------")
                nif = input("Introduce el NIF del nuevo cliente: ").strip()
        else:
            print("-------------------------")
            print("Introduce un NIF valido, debe tener nueve caracteres.")
            print("-------------------------")
            nif = input("Introduce el NIF del nuevo cliente: ").strip()

def is_valid_name(name):
  """Función utilitaria que valida cadena de caracteres para nombre y apellido"""
  while True:
    if len(name) > 1:
      cont = 0
      for i in name:
        aux = ord(i.lower())
        if (aux > 96 and aux < 123) or aux == 241 or aux == 32:
          cont = cont + 1
          if cont == len(name):
            return name
        else:
          name = input("Intentalo nuevamente: ").strip()
    else:
      print("Al menos debe contener dos caracteres")
      name = input("Intentalo otra vez: ")

def pedir_habitual ():
    """Función que valida los datos sobre el el campo cliente habitual"""
    while True:
        habitual = input ("¿El cliente es habitual? Si / No ").strip()
        if habitual != "Si" and habitual != "No":
          print("Selecciona una opción correcta")
        else:
          if habitual == "Si":
            return True
          else:
            return False

title = "Listado de clientes"
caracter ="-"

def print_header (title, pad_chard):
  espacio = 57 + (len(title)//2)
  print_cabecera_1 = title.rjust(espacio, pad_chard).ljust(114, pad_chard)
  print_cabecera_2 = "NIF          |Nombre      |Apellido      |Dirección  |Teléfon          |Habitual |Fecha            |Correo                   "
  return print_cabecera_1 + "\n" + print_cabecera_2

#----------------------
# Funciones Principales
#----------------------

def agregar_cliente():
    """ Funcion para opción 1, llama a funciones utilitarias para validar y agrega los datos al diccionario dic_clientes."""
    nif = input ("Introduce el NIF del nuevo cliente: ").strip()
    nif = (is_valid_nif(nif)[1])
    nombre = input("Introduce nombre de cliente: ").strip()
    is_valid_name(nombre)
    apellidos = input("Introduce apellidos de cliente: ").strip()
    is_valid_name(apellidos)
    direccion = input("Introduce dirección: ").strip()
    telefono = input ("Introduce el teléfono del cliente: ").strip()
    is_valid_phone(telefono)
    correo = input("Introduce correo electrónico: ").strip()
    is_valid_email(correo)
    habitual = pedir_habitual()
    fecha = input("Introduce la fecha del nuevo cliente: ").strip()
    is_valid_date(fecha)

    dic_clientes[nif] = {"Nombre": nombre, "Apellidos": apellidos,\
                         "Dirección": direccion, "Teléfono": telefono, \
                         "habitual": habitual, "Fecha": fecha, "Correo electrónico": correo}
    print("--------------------------------------------------------")
    print("Se han creado los datos del cliente con NIF:", "{}".format(nif))
    print("--------------------------------------------------------")

def eliminar_cliente():
    """Función para eliminar cliente."""
    nif_eliminar = input ("Indique el NIF a eliminar: ")
    nif_aux = dic_clientes.pop(nif_eliminar, False)
    if nif_aux == False:
        print("El NIE no existe en el registro")
    else:
        print("--------------------------------------------------------")
        print("Se han eliminado los datos del cliente NIF {}".format(nif_eliminar))
        print("--------------------------------------------------------")

def mostrar_cliente():
    nif_cliente = input("Indique el NIF que desea consultar: ").strip()
    datos_aux = dic_clientes.get(nif_cliente, False)
    if datos_aux == False:
        print("El NIE no existe en el registro")
    else:
        print(print_header(title, caracter))
        for nif, datos in dic_clientes.items():
            if nif == None:
                continue
            elif nif_cliente == nif:

                print(nif, "   |", end=" ")
                for datos1, informacion in datos.items():
                    print(informacion, "     |", end=" ")

def todos_clientes():
    """Función para mostrar todos los clientes."""
    print(print_header(title, caracter))
    for nif, datos in dic_clientes.items():
      if nif == None:
        continue
      print(nif,"   |" , end=" ")
      for datos1, informacion in datos.items():
        print(informacion,"     |", end=" ")
      print("\n")

def clientes_habituales():
    """Función para mostrar todos los clientes habituales."""
    print(print_header(title, caracter))
    for nif, datos in dic_clientes.items():
        if nif == None:
            continue
        if datos["habitual"] == True:
            print(nif, "   |", end=" ")
            for datos1, informacion in datos.items():
                print(informacion, "     |", end=" ")
            print("\n")

def salir_fun():
    """función para salir el programa"""
    print()
    print("----------------------------")
    print("** Ha salido del programa **")
    print("----------------------------")
    exit()

def default():
    print("Selecciona una opción valida dentro del menú")

cases = {
    "1": agregar_cliente,
    "2": eliminar_cliente,
    "3": mostrar_cliente,
    "4": todos_clientes,
    "5": clientes_habituales,
    "6": salir_fun
}

#dic_clientes = {None:{}}

dic_clientes = {
    None:{},
    "77841238t" : {
        "nombre": "Cesar",
        "apellido" : "Longart",
        "direccion" : "Vigo",
        "telefono": "9999999999",
        "habitual" : True,
        "fecha" : "14/11/2022",
        "correo" : "cesar@email.com"
    },
    "12345678p" : {
        "nombre": "Cata",
        "apellido" : "Lagos",
        "direccion" : "Vigo",
        "telefono": "111111111",
        "habitual" : True,
        "fecha" : "24/02/2023",
        "correo" : "cata@email.com"
    }
}

def menu():
  """Función definida para imprimir menú en pantalla y pedir una opción al usuario"""
  salir =True
  while salir:
    print()
    print("__________________")
    print("------ MENU ------")
    print("__________________")
    print()
    print("1. Agregar cliente \n"
          "2. Eliminar cliente \n"
          "3. Mostrar cliente \n"
          "4. Mostrar todos los clientes \n"
          "5. Mostrar clientes habituales \n"
          "6. Salir \n     ")

    op = input("Seleccione una opción: ").strip()
    cases.get(op, default)()

menu()


# -*- coding = utf-8 -*-
# @Author: 97694
# @Time: 2021/6/26 18:51

# for i in range(5):
#     print(i)

# 从0开始，到10结束，步进值为3  (每次加3)
# for i in range(0, 10, 3):
#     print(i)

# for i in range(-10, -100, -30):
#     print(i)

# name = "chengdu"
#
# for x in name:
#     print(x, end="\t")

# a = ["aa", "bb", "cc", "dd"]
# for i in range(len(a)):
#     print(i, a[i])

# i = 0
# while i < 5:
#     print("当前是第%d次执行循环" % (i + 1))
#     print("i=%d" % i)
#     i += 1

# n = 100
# result = 0
# counter = 1
# while counter <= n:
#     result += counter
#     counter += 1
#
# print("1到 %d 的和为：%d" % (n, result))

# count = 10
# while count < 5:
#     print(count, "小于5")
#     count += 1
# else:
#     print(count, "大于或等于5")

# i = 0
# while i < 10:
#     i += 1
#     print("-"*30)
#     if i == 5:
#         # 结束整个while循环
#         break
#     print(i)

# i = 0
# while i < 10:
#     i += 1
#     print("-"*30)
#     if i == 5:
#         # 结束本次循环
#         continue
#     print(i)

# 九九乘法表
for i in range(1, 10, 1):
    for j in range(1, i + 1, 1):
        if j == i:
            print("%d*%d=%d" % (i, j, i * j), end="\n")
        else:
            print("%d*%d=%d" % (i, j, i * j), end="\t")


# -*- coding: utf-8 -*-
"""
Created on Tue May 28 14:55:46 2013

@author: belza
"""

import sys
sys.path +=['..']

import Queue
import libmanagement.NetworkConfiguration as NetworkConfiguration
import libmanagement.DiscoveryPeeringController as DiscoveryPeeringController
import libmanagement.Beacon as Beacon
import libadaptationlayer.scheduler as scheduler
import libadaptationlayer.transmitFrame as transmitFrame
import virtualchannel

def simulates():
    "-------------------NODO 100-------------------------------------------------------"
    frame_rx_q1 = Queue.Queue(10)
    frame_tx_q1 = Queue.Queue(10)
    ctrl_q1 = Queue.Queue(10)
    mgmt_q1 = Queue.Queue(10)
    data_q1 = Queue.Queue(10)
    tx_ev_q1= Queue.Queue(10)
    sch1 = scheduler.Scheduler(frame_rx_q1,ctrl_q1,data_q1,mgmt_q1)
    sch1.start()
    tr1 = transmitFrame.TransmitFrame(frame_tx_q1,tx_ev_q1)
    tr1.start()
    net_conf1 = NetworkConfiguration.NetworkConfiguration("100",'my network',"256",1)
    net_conf1.retry_timeout = 5
    dpcontrol1 =  DiscoveryPeeringController.DiscoveryPeeringController(net_conf1,None,mgmt_q1,tx_ev_q1)
    dpcontrol1.start()
    myBeacon1 = Beacon.Beacon(net_conf1 ,tx_ev_q1)
    myBeacon1.start()
    "---------------------FIN NODO 100 -----------------------------------------------"
#

    "-------------------NODO 102-------------------------------------------------------"
    frame_rx_q2 = Queue.Queue(10)
    " En el simulador todos escriben los paquetes a la misma cola del canal virtual"
    frame_tx_q2 = frame_tx_q1
    ctrl_q2 = Queue.Queue(10)
    mgmt_q2 = Queue.Queue(10)
    data_q2 = Queue.Queue(10)
    tx_ev_q2= Queue.Queue(10)
    sch2 = scheduler.Scheduler(frame_rx_q2,ctrl_q2,data_q2,mgmt_q2)
    sch2.start()
    tr2 = transmitFrame.TransmitFrame(frame_tx_q2,tx_ev_q2)
    tr2.start()
    net_conf2 = NetworkConfiguration.NetworkConfiguration("102",'my network',"256",1)
    net_conf2.retry_timeout = 5
    dpcontrol2 =  DiscoveryPeeringController.DiscoveryPeeringController(net_conf2,None,mgmt_q2,tx_ev_q2)
    dpcontrol2.start()
    myBeacon2 = Beacon.Beacon(net_conf2 ,tx_ev_q2)
    myBeacon2.start()
    "---------------------FIN NODO 101 -----------------------------------------------"

    "-------------------NODO 102-------------------------------------------------------"
    frame_rx_q3 = Queue.Queue(10)
    " En el simulador todos escriben los paquetes a la misma cola del canal virtual"
    frame_tx_q3 = frame_tx_q2
    ctrl_q3 = Queue.Queue(10)
    mgmt_q3 = Queue.Queue(10)
    data_q3 = Queue.Queue(10)
    tx_ev_q3= Queue.Queue(10)
    sch3 = scheduler.Scheduler(frame_rx_q3,ctrl_q3,data_q3,mgmt_q3)
    sch3.start()
    tr3 = transmitFrame.TransmitFrame(frame_tx_q3,tx_ev_q3)
    tr3.start()
    net_conf3 = NetworkConfiguration.NetworkConfiguration("103",'my network',"256",1)
    net_conf3.retry_timeout = 5
    dpcontrol3 =  DiscoveryPeeringController.DiscoveryPeeringController(net_conf3,None,mgmt_q3,tx_ev_q3)
    dpcontrol3.start()
    myBeacon3 = Beacon.Beacon(net_conf3 ,tx_ev_q3)
    myBeacon3.start()
    "---------------------FIN NODO 102 -----------------------------------------------"

    vc= virtualchannel.VirtualChannel(frame_tx_q2)
    vc.add(frame_rx_q1)
    vc.add(frame_rx_q2)
    vc.add(frame_rx_q3)
    vc.start()

if __name__ == '__main__':
    try:
        simulates()
    except KeyboardInterrupt:
        pass


#!/usr/bin/env python3

a = 0
for a in range(5):
	if (a == 3):
		break
	if (a > 0):
		print(a)

a = 0
while a < 5:
	print(a)
	a += 1

a = 0
while True:
	print(a)
	a += 1
	if (a == 6):
		break

import random
a = random.randint(1, 10)
print(a)


# -*- coding: utf-8 -*-

from functools import partial

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

from timm.models.layers import DropPath, trunc_normal_
from torch.autograd import Variable
import sys
from torch.nn import BatchNorm2d, Conv1d, Conv2d, ModuleList, Parameter, LayerNorm, InstanceNorm2d

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import sys
from torch.nn import BatchNorm2d, Conv1d, Conv2d, ModuleList, Parameter, LayerNorm, BatchNorm1d
import torch
from torch.nn import Parameter as Param
from torch_geometric.nn.conv import MessagePassing
import torch.nn.functional as F
"""
x-> [batch_num,in_channels,num_nodes,tem_size],
"""
class RGCNConv(MessagePassing):
    r"""The relational graph convolutional operator from the `"Modeling
    Relational Data with Graph Convolutional Networks"
    <https://arxiv.org/abs/1703.06103>`_ paper

    .. math::
        \mathbf{x}^{\prime}_i = \mathbf{\Theta}_0 \cdot \mathbf{x}_i +
        \sum_{r \in \mathcal{R}} \sum_{j \in \mathcal{N}_r(i)}
        \frac{1}{|\mathcal{N}_r(i)|} \mathbf{\Theta}_r \cdot \mathbf{x}_j,

    where :math:`\mathcal{R}` denotes the set of relations, *i.e.* edge types.
    Edge type needs to be a one-dimensional :obj:`torch.long` tensor which
    stores a relation identifier
    :math:`\in \{ 0, \ldots, |\mathcal{R}| - 1\}` for each edge.

    Args:
        in_channels (int): Size of each input sample.
        out_channels (int): Size of each output sample.
        num_relations (int): Number of relations.
        num_bases (int): Number of bases used for basis-decomposition.
        bias (bool, optional): If set to :obj:`False`, the layer will not learn
            an additive bias. (default: :obj:`True`)
        **kwargs (optional): Additional arguments of
            :class:`torch_geometric.nn.conv.MessagePassing`.
    """

    def __init__(self,
                 in_channels,
                 out_channels,
                 num_relations,
                 num_bases,
                 bias=True,
                 **kwargs):
        super(RGCNConv, self).__init__(aggr='add', **kwargs)

        self.in_channels = in_channels
        self.out_channels = out_channels
        self.num_relations = num_relations #3
        self.num_bases = num_bases  #3

        self.basis = Param(torch.Tensor(num_bases, in_channels, out_channels))
        self.att = Param(torch.Tensor(num_relations, num_bases))
        self.root = Param(torch.Tensor(in_channels, out_channels))

        if bias:
            self.bias = Param(torch.Tensor(out_channels))
        else:
            self.register_parameter('bias', None)

        self.reset_parameters()

    def reset_parameters(self):
        torch.nn.init.xavier_uniform_(self.basis)
        torch.nn.init.xavier_uniform_(self.att)
        torch.nn.init.xavier_uniform_(self.root)

    def forward(self, x, edge_index, edge_attr, edge_norm=None):
        """"""
        return self.propagate(
            edge_index, x=x, edge_attr=edge_attr, edge_norm=edge_norm)

    def message(self, x_j, edge_index_j, edge_attr, edge_norm):
        w = torch.matmul(self.att, self.basis.view(self.num_bases, -1))
        w = w.view(self.num_relations, self.in_channels, self.out_channels)
        out = torch.einsum('bi,rio->bro', x_j, w)
        out = (out * edge_attr.unsqueeze(2)).sum(dim=1)
        # print(out.size(), edge_attr.unsqueeze(2).size())
        # out = torch.bmm(x_j.unsqueeze(1), w).squeeze(-2)

        return out if edge_norm is None else out * edge_norm.view(-1, 1)

    def update(self, aggr_out, x):
        if x is None:
            out = aggr_out + self.root
        else:
            out = aggr_out + torch.matmul(x, self.root)

        if self.bias is not None:
            out = out + self.bias
        return out

    def __repr__(self):
        return '{}({}, {}, num_relations={})'.format(
            self.__class__.__name__, self.in_channels, self.out_channels,
            self.num_relations)

class KStepRGCN(nn.Module):
    """docstring for KStepRGCN"""

    def __init__(
            self,
            in_channels,
            out_channels,
            num_relations,
            num_bases,
            K,
            bias,
    ):
        super(KStepRGCN, self).__init__()
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.num_relations = num_relations
        self.num_bases = num_bases
        self.K = K
        self.rgcn_layers = nn.ModuleList([
            RGCNConv(in_channels,
                     out_channels,
                     num_relations,
                     num_bases,
                     bias)
        ] + [
            RGCNConv(out_channels,
                     out_channels,
                     num_relations,
                     num_bases,
                     bias) for _ in range(self.K - 1)
        ])

    def forward(self, x, edge_index, edge_attr):
        edge_index=edge_index.to(x.device)
        edge_attr=edge_attr.to(x.device)

        for i in range(self.K):
            x = self.rgcn_layers[i](x=x,
                                    edge_index=edge_index,
                                    edge_attr=edge_attr,
                                    edge_norm=None)
            # not final layer, add relu
            if i != self.K - 1:
                x = torch.relu(x)

        return x

class Mlp(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = nn.Linear(in_features, hidden_features)
        self.act = act_layer()
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(drop)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = self.drop(x)
        return x

class Attention(nn.Module):
    def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
        super().__init__()
        self.num_heads = num_heads
        head_dim = dim // num_heads
        # NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
        self.scale = qk_scale or head_dim ** -0.5

        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)

    def forward(self, x):
        B, N, C = x.shape
        qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
        q, k, v = qkv[0], qkv[1], qkv[2]

        attn = (q @ k.transpose(-2, -1)) * self.scale

        attn = attn.softmax(dim=-1)

        attn = self.attn_drop(attn)

        x = (attn @ v).transpose(1, 2).reshape(B, N, C)

        x = self.proj(x)

        x = self.proj_drop(x)
        return x

class Block(nn.Module):

    def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
                 drop_path=0., act_layer=nn.GELU, norm_layer=partial(nn.LayerNorm, eps=1e-6)):
        super().__init__()
        self.norm1 = norm_layer(dim)
        self.attn = Attention(
            dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
        # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
        self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
        self.norm2 = norm_layer(dim)
        mlp_hidden_dim = int(dim * mlp_ratio)
        self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)

    def forward(self, x):

        x = x + self.drop_path(self.attn(self.norm1(x)))

        x = x + self.drop_path(self.mlp(self.norm2(x)))

        return x

class GRU(nn.Module):
    def __init__(self,device):
        super(GRU, self).__init__()
        self.device=device
        c_in=69
        c_out=256
        self.node_num=69
        self.gru = nn.GRU(c_in, c_out, batch_first=True)  # b*n,l,c
        self.c_out = c_out
        self.bn = BatchNorm2d(c_in, affine=False)

    def forward(self, x1):##

        # print('h')
        shape = x1.shape
        B=shape[0]
        h = Variable(torch.zeros(1, shape[0] * shape[2], self.c_out,dtype=x1.dtype,device=x1.device))
        hidden = h
        x = x1.permute(0, 2, 3, 1).contiguous().view(shape[0] * shape[2], shape[3], shape[1])
        x, hidden = self.gru(x, hidden)
        x = x.view(shape[0], shape[2], shape[3], self.c_out).permute(0, 3, 1, 2).contiguous()
        return x

class Model(nn.Module):
    def __init__(self, device,numT,edge_index,edge_attr):
        super(Model, self).__init__()
        c_in=69
        num_nodes=69
        self.device=device
        self.bn = BatchNorm2d(c_in, affine=False)
        C = 256  # C是channel
        D = 256  # D是hidden dimension
        self.GRU=GRU(device)
        self.with_vertical=True
        self.with_horizontal=True
        self.union = "cat"

        self.rnn_v=nn.LSTM(numT,D,num_layers=1,batch_first=True,bias=True,bidirectional=True)
        self.rnn_h = nn.LSTM(numT, D, num_layers=1, batch_first=True, bias=True, bidirectional=True)

        self.fc = nn.Linear(4*D, D)

        # self.f1 = nn.Linear(30,D)
        self.f2 = nn.Linear(D, numT)
        self.D=D

        #加入transformer
        self.conv = nn.Conv2d(numT, 256, kernel_size=7, stride=2, padding=2, bias=False)
        self.bn1 = nn.BatchNorm2d(256)
        self.act1 = nn.ReLU(inplace=True)
        # self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.trans_patch_conv = nn.Conv2d(256, 768, kernel_size=2, stride=2, padding=0)
        self.cls_token = nn.Parameter(torch.zeros(1, 1, 768))
        # trans_block
        embed_dim = 768
        num_heads = 6
        mlp_ratio = 4
        qkv_bias = True
        qk_scale = None
        drop_rate = 0.0
        attn_drop_rate = 0.0
        drop_path_rate = 0.0
        self.trans_block = Block(
            dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
            drop=drop_rate, attn_drop=attn_drop_rate, drop_path=drop_path_rate)
        patch_size = 2
        self.unconv1 = nn.ConvTranspose2d(768, 256, patch_size, patch_size)
        self.unconv2 = nn.ConvTranspose2d(256, 256, patch_size, patch_size)
        self.conv_shape = nn.Conv2d(256, 256, kernel_size=2, padding=1)
        # self.fc_1 = nn.Linear(80, 256)
        self.mlpatt = nn.Linear(2 * D, D)
        #额外加的
        self.edge_index=edge_index
        self.edge_attr=edge_attr
        self.numT=numT
        c_out = 69
        self.node_num = 69
        self.cheb_v = KStepRGCN(69,  # 80
                                c_out,  # 256
                                num_relations=3,  # 3
                                num_bases=3,  # 3
                                K=1,  # 1
                                bias=False)
        self.gcn_v_fc=nn.Linear(numT, 2*D)
        self.mlp_v = nn.Linear(4 * D, 2*D)
        self.cheb_h = KStepRGCN(69,  # 80
                                c_out,  # 256
                                num_relations=3,  # 3
                                num_bases=3,  # 3
                                K=1,  # 1
                                bias=False)
        self.gcn_h_fc = nn.Linear(numT, 2 * D)
        self.mlp_h = nn.Linear(4 * D, 2 * D)

        self.fc_toweek = nn.Linear(numT*7, 768)
        self.fc_tohour = nn.Linear(numT*24 , 768)
        self.simformer_1 = nn.Linear(numT, D)
        self.norm2 = nn.LayerNorm(D)

    def forward(self, x_f,external_toweek, external_tohour):
        external_toweek=external_toweek.flatten(1)#

        external_toweek = self.fc_toweek(F.relu(external_toweek))  #
        B,E=external_toweek.shape
        external_toweek = external_toweek.expand(289,B,E)  #
        external_toweek=external_toweek.permute(1,0,2)#

        external_tohour=external_tohour.flatten(1)
        external_tohour = self.fc_tohour(F.relu(external_tohour))  #

        external_tohour = external_tohour.expand(289,B,E)

        external_tohour=external_tohour.permute(1,0,2)
        x=x_f
        B,H,W,C=x.shape#

        if self.with_vertical:
            # print('vvvv')
            v = x.permute(0, 2, 1, 3)
            # print(v.shape)
            v1 = v.reshape(-1, H, C)
            # print(v.shape)
            v, _ = self.rnn_v(v1)
            v = v.reshape(B, W, H, -1)
            v = v.permute(0, 2, 1, 3)

            #加入图卷积去更新
            need_concat_v = []
            for i in range(self.numT):
                h_v = self.cheb_v(v1[:, :, i], edge_index=self.edge_index,edge_attr=self.edge_attr)
                need_concat_v.append(h_v)
            gcn_v = torch.stack(need_concat_v, dim=-1)

            gcn_v = gcn_v.reshape(B, W, H, -1)

            gcn_v = gcn_v.permute(0, 2, 1, 3)
            gcn_v=self.gcn_v_fc(gcn_v)#

            #融合双向lstm和gcn
            combine_v= torch.cat([v, gcn_v], dim=-1)  #

            v = v+v * torch.tanh(self.mlp_v(combine_v))

        if self.with_horizontal:

            h1 = x.reshape(-1, W, C)
            # print(h.shape)
            h, _ = self.rnn_h(h1)
            # h, _ = self.rnn_h1(h)
            # print(h.shape)
            h = h.reshape(B, H, W, -1)#
            # print(h.shape)
            # 加入图卷积去更新
            need_concat_h = []
            for i in range(self.numT):  # 12
                h_h = self.cheb_h(h1[:, :, i], edge_index=self.edge_index,edge_attr=self.edge_attr)

                need_concat_h.append(h_h)
            gcn_h = torch.stack(need_concat_h, dim=-1)  #
            gcn_h= gcn_h.reshape(B, H,W, -1)
            gcn_h = self.gcn_h_fc(gcn_h)
            # 融合双向lstm和gcn
            combine_h = torch.cat([h, gcn_h], dim=-1)

            h = h+h * torch.tanh(self.mlp_h(combine_h))
            # print(h.shape)
        if self.with_vertical and self.with_horizontal:
            if self.union == "cat":
                x = torch.cat([v, h], dim=-1)
                # print('cat')
                # print(x.shape)
            else:
                x = v + h
        elif self.with_vertical:
            x = v
        elif self.with_horizontal:
            x = h
        # print('76890')
        # print(x.shape)
        x_bilstm = self.fc(x)
        # print(x_bilstm.shape)
        #在这里我感觉可以进行一下空间transformer
        x1 = x_f.permute(0, 3, 1, 2)
        x = self.act1(self.bn1(self.conv(x1)))
        x = self.trans_patch_conv(x).flatten(2).transpose(1, 2)
        x_t = x+F.relu(external_toweek+external_tohour)
        x_t = self.trans_block(x_t)
        x_t = x_t.view(-1, 17, 17, 768).permute(0, 3, 1, 2)
        x_t = self.unconv1(x_t)
        x_t = self.unconv2(x_t)
        x_t = self.conv_shape(x_t)
        x_t = x_t.permute(0, 2, 3, 1)
        x_t = self.simformer_1(x_f) + x_t
        x_t = self.norm2(x_t)
        #融合双向lstm和全局transformer
        combine_hidden = torch.cat([x_bilstm,x_t], dim=-1)
        next_hidden = x_bilstm * torch.tanh(self.mlpatt(combine_hidden))
        x = self.f2(next_hidden)
        # 加入GRU
        x = self.GRU(x)
        return x

class Net_block(torch.nn.Module):

    def __init__(self,device,edge_index,edge_attr):
        super(Net_block, self).__init__()
        self.bn = BatchNorm2d(69, affine=False)
        self.submodule=Model(device,6,edge_index,edge_attr)
        # self.DEVICE = DEVICE
        # self.to(DEVICE)
        D=256
        num_nodes=69
        self.conv1 = Conv2d(D, num_nodes, kernel_size=(1, 1), padding=(0, 0),
                            stride=(1, 1), bias=True)
        self.conv2 = Conv2d(D, num_nodes, kernel_size=(1, 1), padding=(0, 0),
                            stride=(1, 1), bias=True)
        self.conv3 = Conv2d(D, num_nodes, kernel_size=(1, 1), padding=(0, 0),
                            stride=(1, 1), bias=True)
        self.conv4 = Conv2d(D, num_nodes, kernel_size=(1, 2), padding=(0, 0),
                            stride=(1, 2), bias=True)

    def forward(self,x_list,external_list):
        # 加载data数据
        x_w, x_d, x_r = x_list[0], x_list[1], x_list[
            2]
        ext_w_toweek, ext_w_tohour,ext_d_toweek, ext_d_tohour,ext_r_toweek, ext_r_tohour= \
            external_list[0], external_list[1],external_list[2], external_list[3],external_list[4], external_list[5]
        x_w = self.bn(x_w)
        x_d = self.bn(x_d)
        x_r = self.bn(x_r)
        x = torch.cat((x_w, x_d, x_r), -1)

        ext_toweek=torch.cat((ext_w_toweek,ext_d_toweek,ext_r_toweek),1)#
        ext_tohour=torch.cat((ext_w_tohour,ext_d_tohour,ext_r_tohour),1)#

        y = self.submodule(x,ext_toweek, ext_tohour)
        y1 = y[:, :, :, 0:1]
        y2 = y[:, :, :, 1:2]
        y3 = y[:, :, :, 2:3]
        y4 = y[:, :, :, 3:6]

        y1 = self.conv1(y1)
        y2 = self.conv2(y2)
        y3 = self.conv3(y3)
        y4 = self.conv4(y4)

        return y1+y2+y3+y4


import os,sys

def installmaps(options,buildout):
    # adding maps files
    os.system("""
cd %s/nad
tar xzvf %s/maps/proj-datumgrid-1.3.tar.gz
cd .. """ %( options['compile-directory'], buildout['buildout']['directory']))


import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
from mpl_toolkits.mplot3d import Axes3D
import glob
from tqdm import *

import math

# video init
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
video = cv2.VideoWriter()

# get list of frames
files = glob.glob("test_flow.0.*")
files.sort()

b = np.load(files[0])
shape = b.f.rho.shape

# make video
success = video.open('flow_video.mov', fourcc, 8, ((shape[1]-2), (shape[0]-2)), True)

# get list of frames
files = glob.glob("test_flow.0.*")
files.sort()

# generate video
for f in files:
  x = np.load(f)
  if len(x.f.v.shape) == 4:
    frame = np.sqrt(np.square(x.f.v[0,1:-1,shape[2]/2,1:-1]) + np.square(x.f.v[1,1:-1,shape[2]/2,1:-1]) + np.square(x.f.v[2,1:-1,shape[2]/2,1:-1]))
    #frame = x.f.rho[:,shape[2]/2,:]
    frame[np.where(np.isnan(frame))] = 1.0
    frame = frame - .5
  elif len(x.f.v.shape) == 3:
    frame = np.sqrt(np.square(x.f.v[0,:,:]) + np.square(x.f.v[1,:,:]))

  frame = np.nan_to_num(frame)
  print(np.max(frame))
  frame = np.uint8(255 * (frame - np.min(frame))/(np.max(frame) - np.min(frame)))
  frame = cv2.applyColorMap(frame, 2)
  #frame = cv2.reshape(frame, (frame.shape[1]/2, frame.shape[0]/2))

  video.write(frame)

# release video
video.release()
cv2.destroyAllWindows()


import autosar.package
import autosar.parser.package_parser
import autosar.writer
from autosar.base import (parseXMLFile, getXMLNamespace, removeNamespace, parseAutosarVersionAndSchema, prepareFilter, parseVersionString)
import json
import os
import ntpath
import collections
import re
from autosar.parser.datatype_parser import (DataTypeParser, DataTypeSemanticsParser, DataTypeUnitsParser)
from autosar.parser.portinterface_parser import (PortInterfacePackageParser,SoftwareAddressMethodParser,ModeDeclarationGroupPackageParser)
#default parsers
from autosar.parser.constant_parser import ConstantParser
from autosar.parser.behavior_parser import BehaviorParser
from autosar.parser.component_parser import ComponentTypeParser
from autosar.parser.system_parser import SystemParser
from autosar.parser.signal_parser import SignalParser
#default writers
from autosar.writer.datatype_writer import XMLDataTypeWriter, CodeDataTypeWriter
from autosar.writer.constant_writer import XMLConstantWriter, CodeConstantWriter
from autosar.writer.portinterface_writer import XMLPortInterfaceWriter, CodePortInterfaceWriter
from autosar.writer.component_writer import XMLComponentTypeWriter, CodeComponentTypeWriter
from autosar.writer.behavior_writer import XMLBehaviorWriter, CodeBehaviorWriter
from autosar.writer.signal_writer import SignalWriter

_validWSRoles = ['DataType', 'Constant', 'PortInterface', 'ComponentType', 'ModeDclrGroup', 'CompuMethod', 'Unit',
                 'BaseType', 'DataConstraint']

class Workspace(object):
    def __init__(self, version, patch, schema, attributes = None, useDefaultWriters=True):
        self.packages = []
        if isinstance(version, str):
            (major, minor, patch) = parseVersionString(version)
            self._version=float("%s.%s"%(major, minor))
            self.patch=patch
        elif isinstance(version, float):
            self._version=version
            self.patch=int(patch)
        self.schema=schema
        self.packageParser=None
        self.packageWriter=None
        self.xmlroot = None
        self.attributes = attributes
        self.useDefaultWriters = bool(useDefaultWriters)
        self.roles = {'DataType': None,
                      'Constant': None,
                      'PortInterface': None,
                      'ModeDclrGroup': None,
                      'ComponentType': None,
                      'CompuMethod': None,
                      'Unit': None,
                      'BaseType': None,        #AUTOSAR 4 only
                      'DataConstraint': None }  #AUTOSAR 4 only
        self.map = {'packages': {}}
        self.errorHandlingOpt = False
        self.defaultPackages = {'DataType':'DataType',
                                  'CompuMethod':'DataTypeSemantics',
                                  'Unit':'DataTypeUnits',
                                'Constant':'Constant',
                                'PortInterface':'PortInterface',
                                'ModeDclrGroup':'ModeDclrGroup',
                                'ComponentType':'ComponentType',
                                }

    @property
    def version(self):
        return self._version

    @version.setter
    def version(self, version):
        if isinstance(version, str):
            (major, minor, patch) = parseVersionString(version)
            self._version=float("%s.%s"%(major, minor))
            self.patch=patch
        elif isinstance(version, float):
            self._version=version

    def __getitem__(self,key):
        if isinstance(key,str):
            return self.find(key)
        else:
            raise ValueError('expected string')

    def _adjustFileRef(self,fileRef,basedir):
        basename = ntpath.basename(fileRef['path'])
        dirname=ntpath.normpath(ntpath.join(basedir,ntpath.dirname(fileRef['path'])))
        retval=ntpath.join(dirname,basename)
        if os.path.sep == '/': #are we running in cygwin/Linux?
            retval = retval.replace(r'\\','/')
        return retval

    def getRole(self, role):
        return self.roles[role]

    def setRole(self, ref, role):
        if (role is not None) and (role not in _validWSRoles):
            raise ValueError('invalid role name: '+role)
        if ref is None:
            self.roles[role]=None
        else:
            package = self.find(ref)
            if package is None:
                raise ValueError('invalid reference: '+ref)
            if not isinstance(package, autosar.package.Package):
                raise ValueError('invalid type "%s"for reference "%s", expected Package type'%(str(type(package)),ref))
            package.role=role
            self.roles[role]=package.ref

    def openXML(self,filename):
        xmlroot = parseXMLFile(filename)
        namespace = getXMLNamespace(xmlroot)

        assert (namespace is not None)
        (major, minor, patch, schema) = parseAutosarVersionAndSchema(xmlroot)
        removeNamespace(xmlroot,namespace)
        self.version=float('%s.%s'%(major,minor))
        self.major=major
        self.minor=minor
        self.patch=patch
        self.schema=schema
        self.xmlroot = xmlroot
        if self.packageParser is None:
            self.packageParser = autosar.parser.package_parser.PackageParser(self.version)
        self._registerDefaultElementParsers(self.packageParser)

    def loadXML(self, filename, roles=None):
        global _validWSRoles
        self.openXML(filename)
        self.loadPackage('*')
        if roles is not None:
            if not isinstance(roles, collections.Mapping):
                raise ValueError('roles parameter must be a dictionary or Mapping')
            for ref,role in roles.items():
                self.setRole(ref,role)

    def loadPackage(self, packagename, role=None):
        found=False
        result=[]
        if self.xmlroot is None:
            raise ValueError("xmlroot is None, did you call loadXML() or openXML()?")
        if self.version >= 3.0 and self.version < 4.0:
            if self.xmlroot.find('TOP-LEVEL-PACKAGES'):
                for xmlPackage in self.xmlroot.findall('./TOP-LEVEL-PACKAGES/AR-PACKAGE'):
                    if self._loadPackageInternal(result, xmlPackage, packagename, role):
                        found = True

        elif self.version>=4.0:
            if self.xmlroot.find('AR-PACKAGES'):
                for xmlPackage in self.xmlroot.findall('.AR-PACKAGES/AR-PACKAGE'):
                    if self._loadPackageInternal(result, xmlPackage, packagename, role):
                        found = True

        else:
            raise NotImplementedError('Version %s of ARXML not supported'%version)
        if found==False:
            raise KeyError('package not found: '+packagename)
        return result

    def _loadPackageInternal(self, result, xmlPackage, packagename, role):
        name = xmlPackage.find("./SHORT-NAME").text
        found = False
        if packagename=='*' or packagename==name:
            found=True
            package = self.find(name)
            if package is None:
                package = autosar.package.Package(name, parent=self)
                self.packages.append(package)
                result.append(package)
                self.map['packages'][name] = package
            self.packageParser.loadXML(package,xmlPackage)
            if (packagename==name) and (role is not None):
                self.setRole(package.ref, role)
        return found

#BEGIN DEPRECATED
    # def loadJSON(self, filename):
    #    with open(filename) as fp:
    #       basedir = ntpath.dirname(filename)
    #       data = json.load(fp)
    #       if data is not None:
    #          for item in data:
    #             if item['type']=='fileRef':
    #                adjustedPath = self._adjustFileRef(item, basedir)
    #                if adjustedPath.endswith('.arxml'):
    #                   self.loadXML(adjustedPath)
    #                else:
    #                   raise NotImplementedError(adjustedPath)
    #             else:
    #                raise ValueError('Unknown type: %s'%item['type'])
#END DEPRECATED

    def find(self, ref, role=None):
        global _validWSRoles
        if ref is None: return None
        if (role is not None) and ( ref[0] != '/'):
            if role not in _validWSRoles:
                raise ValueError("unknown role name: "+role)
            if self.roles[role] is not None:
                ref=self.roles[role]+'/'+ref #appends the role packet name in front of ref

        if ref[0]=='/': ref=ref[1:] #removes initial '/' if it exists
        ref = ref.partition('/')
        if ref[0] in self.map['packages']:
            pkg = self.map['packages'][ref[0]]
            if len(ref[2])>0:
                return pkg.find(ref[2])
            return pkg
        return None

    def findall(self,ref):
        """
        experimental find-method that has some rudimentary support for globs.
        """
        if ref is None: return None
        if ref[0]=='/': ref=ref[1:] #removes initial '/' if it exists
        ref = ref.partition('/')
        if ref[0]=='*' and len(ref[2])==0:
            result=list(self.packages)
        else:
            result=[]
            for pkg in self.packages:
                if pkg.name == ref[0] or ref[0]=='*':
                    if len(ref[2])>0:
                        result.extend(pkg.findall(ref[2]))
                    else:
                        result.append(pkg)
        return result

    def asdict(self,packages=None):
        retval = {'type': self.__class__.__name__, 'packages':[]}
        for package in self.packages:
            if (isinstance(packages,list) and package.name in packages) or (packages is None):
                retval['packages'].append(package.asdict())
        return retval

    def findRolePackage(self,roleName):
        """
        finds a package with role set to roleName
        """
        if roleName is None: return None
        for pkg in self.packages:
            if pkg.role == roleName:
                return pkg
            elif len(pkg.subPackages)>0:
                for childPkg in pkg.subPackages:
                    if childPkg.role == roleName:
                        return childPkg
        return None

    def createPackage(self,name,role=None):
        if name not in self.map['packages']:
            package = autosar.package.Package(name,self)
            self.packages.append(package)
            self.map['packages'][name] = package
            if role is not None:
                self.setRole(package.ref, role)
            return package
        else:
            return self.map['packages'][name]

    def dir(self,ref=None,_prefix='/'):
        if ref is None:
            return [x.name for x in self.packages]
        else:
            if ref[0]=='/':
                ref=ref[1:]
            ref = ref.partition('/')
            result=self.find(ref[0])
            if result is not None:
                return result.dir(ref[2] if len(ref[2])>0 else None,_prefix+ref[0]+'/')
            else:
                return None

    def findWS(self):
        return self

    def rootWS(self):
        return self

    def saveXML(self, filename, filters=None, packages=None, ignore=None, version=None, patch=None, schema=None):
        if version is None:
            version = self.version
        if patch is None:
            patch = self.patch
        if schema is None:
            schema = self.schema
        if self.packageWriter is None:
            self.packageWriter = autosar.writer.package_writer.PackageWriter(version, patch)
            if self.useDefaultWriters:
                self._registerDefaultElementWriters(self.packageWriter)
        writer=autosar.writer.WorkspaceWriter(version, patch, schema, self.packageWriter)
        with open(filename, 'w', encoding="utf-8") as fp:
            if isinstance(filters,str): filters=[filters]
            if isinstance(packages,str): packages=[packages]
            if isinstance(ignore,str): filters=[ignore]
            if packages is not None:
                if filters is None:
                    filters = []
                for package in packages:
                    if package[-1]=='/':
                        filters.append(package+'*')
                    else:
                        filters.append(package+'/*')
            if filters is not None:
                filters = [prepareFilter(x) for x in filters]
            writer.saveXML(self, fp, filters, ignore)

    def toXML(self, filters=None, packages=None, ignore=None, version=None, patch=None, schema=None):
        if version is None:
            version = self.version
        if patch is None:
            patch = self.patch
        if schema is None:
            schema = self.schema
        if self.packageWriter is None:
            self.packageWriter = autosar.writer.package_writer.PackageWriter(version, patch)
            if self.useDefaultWriters:
                self._registerDefaultElementWriters(self.packageWriter)
        writer=autosar.writer.WorkspaceWriter(version, patch, schema, self.packageWriter)
        if isinstance(filters,str): filters=[filters]
        if isinstance(packages,str): packages=[packages]
        if isinstance(ignore,str): filters=[ignore]
        if packages is not None:
            if filters is None:
                filters = []
            for package in packages:
                if package[-1]=='/':
                    filters.append(package+'*')
                else:
                    filters.append(package+'/*')
        if filters is not None:
            filters = [prepareFilter(x) for x in filters]
        return writer.toXML(self, filters, ignore)

    def append(self,elem):
        if isinstance(elem,autosar.package.Package):
            self.packages.append(elem)
            elem.parent=self
        else:
            raise ValueError(type(elem))

    # def toJSON(self,packages=None,indent=3):
    #    data=ws.asdict(packages)
    #    return json.dumps(data,indent=indent)
    #
    # def saveJSON(self,filename,packages=None,indent=3):
    #    data=self.asdict(packages)
    #    with open(filename,'w') as fp:
    #       json.dump(data,fp,indent=indent)

    def toCode(self, filters=None, packages=None, header=None, version=None, patch=None):
        if version is None:
            version = self.version
        if patch is None:
            patch = self.patch
        writer=autosar.writer.WorkspaceWriter(version, patch, None, self.packageWriter)
        if isinstance(filters,str): filters=[filters]
        if isinstance(packages,str): packages=[packages]
        if packages is not None:
            if filters is None:
                filters = []
            for package in packages:
                if package[-1]=='/':
                    filters.append(package+'*')
                else:
                    filters.append(package+'/*')
        if filters is not None:
            filters = [prepareFilter(x) for x in filters]
        return writer.toCode(self, filters ,str(header), ws.noDefault)

    def saveCode(self, filename, filters=None, packages=None, ignore=None, head=None, tail=None, module=False, template=False, version=None, patch=None):
        """
        saves the workspace as python code so it can be recreated later
        """
        if version is None:
            version = self.version
        if patch is None:
            patch = self.patch
        if self.packageWriter is None:
            self.packageWriter = autosar.writer.package_writer.PackageWriter(version, patch)
            if self.useDefaultWriters:
                self._registerDefaultElementWriters(self.packageWriter)
        writer=autosar.writer.WorkspaceWriter(version, patch, None, self.packageWriter)
        if isinstance(packages,str): packages=[packages]
        if isinstance(filters,str): filters=[filters]
        if isinstance(ignore,str): ignore=[ignore]
        if packages is not None:
            if filters is None:
                filters = []
            for package in packages:
                if package[-1]=='/':
                    filters.append(package+'*')
                else:
                    filters.append(package+'/*')
        if filters is not None:
            filters = [prepareFilter(x) for x in filters]

        with open(filename,'w', encoding="utf-8") as fp:
            writer.saveCode(self, fp, filters, ignore, head, tail, module, template)

    @property
    def ref(self):
        return ''

    def listPackages(self):
        """returns a list of strings containg the package names of the opened XML file"""
        packageList=[]
        if self.xmlroot is None:
            raise ValueError("xmlroot is None, did you call loadXML() or openXML()?")
        if self.version >= 3.0 and self.version < 4.0:
            if self.xmlroot.find('TOP-LEVEL-PACKAGES'):
                for xmlPackage in self.xmlroot.findall('./TOP-LEVEL-PACKAGES/AR-PACKAGE'):
                    packageList.append(xmlPackage.find("./SHORT-NAME").text)
        elif self.version>=4.0:
            if self.xmlroot.find('AR-PACKAGES'):
                for xmlPackage in self.xmlroot.findall('.AR-PACKAGES/AR-PACKAGE'):
                    packageList.append(xmlPackage.find("./SHORT-NAME").text)
        else:
            raise NotImplementedError('Version %s of ARXML not supported'%version)
        return packageList

    def delete(self, ref):
        if ref is None: return
        if ref[0]=='/': ref=ref[1:] #removes initial '/' if it exists
        ref = ref.partition('/')
        for i,pkg in enumerate(self.packages):
            if pkg.name == ref[0]:
                if len(ref[2])>0:
                    return pkg.delete(ref[2])
                else:
                    del self.packages[i]
                    del self.map['packages'][ref[0]]
                    break

    def createAdminData(self, data):
        return autosar.base.createAdminData(data)

    # def fromDict(self, data):
    #    for item in data:
    #       if item['type'] == 'FileRef':
    #          if os.path.isfile(item['path']):
    #             roles = item.get('roles',None)
    #             self.loadXML(item['path'],roles=roles)
    #          else:
    #             raise ValueError('invalid file path "%s"'%item['path'])

    def apply(self, template, **kwargs):
        """
        Applies template to this workspace
        """
        if len(kwargs) == 0:
            rv = template.apply(self)
        else:
            rv = template.apply(self, **kwargs)
        template.usageCount+=1
        return rv

    #---DEPRECATED CODE, TO BE REMOVED ---#
    @classmethod
    def _createDefaultDataTypes(cls, package):
        package.createBooleanDataType('Boolean')
        package.createIntegerDataType('SInt8', -128, 127)
        package.createIntegerDataType('SInt16', -32768, 32767)
        package.createIntegerDataType('SInt32', -2147483648, 2147483647)
        package.createIntegerDataType('UInt8', 0, 255)
        package.createIntegerDataType('UInt16', 0, 65535)
        package.createIntegerDataType('UInt32', 0, 4294967295)
        package.createRealDataType('Float', None, None, minValType='INFINITE', maxValType='INFINITE')
        package.createRealDataType('Double', None, None, minValType='INFINITE', maxValType='INFINITE', hasNaN=True, encoding='DOUBLE')

    def getDataTypePackage(self):
        """
        Returns the current data type package from the workspace. If the workspace doesn't yet have such package a default package will be created and returned.
        """
        package = self.find(self.defaultPackages["DataType"])
        if package is None:
            package=self.createPackage(self.defaultPackages["DataType"], role="DataType")
            package.createSubPackage(self.defaultPackages["CompuMethod"], role="CompuMethod")
            package.createSubPackage(self.defaultPackages["Unit"], role="Unit")
            Workspace._createDefaultDataTypes(package)
        return package

    def getPortInterfacePackage(self):
        """
        Returns the current port interface package from the workspace. If the workspace doesn't yet have such package a default package will be created and returned.
        """
        package = self.find(self.defaultPackages["PortInterface"])
        if package is None:
            package=self.createPackage(self.defaultPackages["PortInterface"], role="PortInterface")
        return package

    def getConstantPackage(self):
        """
        Returns the current constant package from the workspace. If the workspace doesn't yet have such package, a default package will be created and returned.
        """
        package = self.find(self.defaultPackages["Constant"])
        if package is None:
            package=self.createPackage(self.defaultPackages["Constant"], role="Constant")
        return package

    def getModeDclrGroupPackage(self):
        """
        Returns the current mode declaration group package from the workspace. If the workspace doesn't yet have such package, a default package will be created and returned.
        """
        package = self.find(self.defaultPackages["ModeDclrGroup"])
        if package is None:
            package=self.createPackage(self.defaultPackages["ModeDclrGroup"], role="ModeDclrGroup")
        return package

    def getComponentTypePackage(self):
        """
        Returns the current component type package from the workspace. If the workspace doesn't yet have such package, a default package will be created and returned.
        """
        if self.roles["ComponentType"] is not None:
            packageName = self.roles["ComponentType"]
        else:
            packageName = self.defaultPackages["ComponentType"]
        package = self.find(packageName)
        if package is None:
            package=self.createPackage(packageName, role="ComponentType")
        return package

    #--- END DEPCRECATED CODE ---#

    def registerElementParser(self, elementParser):
        """
        Registers a custom element parser object
        """
        if self.packageParser is None:
            self.packageParser = autosar.parser.package_parser.PackageParser(self.version)
            self._registerDefaultElementParsers(self.packageParser)
        self.packageParser.registerElementParser(elementParser)

    def registerElementWriter(self, elementWriter):
        """
        Registers a custom element parser object
        """
        if self.packageWriter is None:
            self.packageWriter = autosar.writer.package_writer.PackageWriter(self.version, self.patch)
            if self.useDefaultWriters:
                self._registerDefaultElementWriters(self.packageWriter)
        self.packageWriter.registerElementWriter(elementWriter)

    def _registerDefaultElementParsers(self, parser):
        parser.registerElementParser(DataTypeParser(self.version))
        parser.registerElementParser(DataTypeSemanticsParser(self.version))
        parser.registerElementParser(DataTypeUnitsParser(self.version))
        parser.registerElementParser(PortInterfacePackageParser(self.version))
        parser.registerElementParser(SoftwareAddressMethodParser(self.version))
        parser.registerElementParser(ModeDeclarationGroupPackageParser(self.version))
        parser.registerElementParser(ConstantParser(self.version))
        parser.registerElementParser(ComponentTypeParser(self.version))
        parser.registerElementParser(BehaviorParser(self.version))
        parser.registerElementParser(SystemParser(self.version))
        parser.registerElementParser(SignalParser(self.version))

    def _registerDefaultElementWriters(self, writer):
        writer.registerElementWriter(XMLDataTypeWriter(self.version, self.patch))
        writer.registerElementWriter(XMLConstantWriter(self.version, self.patch))
        writer.registerElementWriter(XMLPortInterfaceWriter(self.version, self.patch))
        writer.registerElementWriter(XMLComponentTypeWriter(self.version, self.patch))
        writer.registerElementWriter(XMLBehaviorWriter(self.version, self.patch))
        writer.registerElementWriter(CodeDataTypeWriter(self.version, self.patch))
        writer.registerElementWriter(CodeConstantWriter(self.version, self.patch))
        writer.registerElementWriter(CodePortInterfaceWriter(self.version, self.patch))
        writer.registerElementWriter(CodeComponentTypeWriter(self.version, self.patch))
        writer.registerElementWriter(CodeBehaviorWriter(self.version, self.patch))
        writer.registerElementWriter(SignalWriter(self.version, self.patch))


def get_answer_groups(file_path):
    with open(file_path) as f:
        return f.read().split('\n\n')

def count_unique_group_answers(groups):
    return sum([len(''.join(set(group.replace('\n', '')))) for group in groups])

def count_everyones_answer(groups):
    all_matching_group = 0
    for group in groups:
        unique_letters = ''.join(set(group.replace('\n', '')))
        letters_in_group = group.replace('\n', '')
        people_in_group =  len(group.replace('\n', ' ').split(' '))
        all_matching_group += len([unique_letter for unique_letter in unique_letters if letters_in_group.count(unique_letter) == people_in_group])

    return all_matching_group

if __name__ == '__main__':
    print(count_unique_group_answers(get_answer_groups('./data')))
    print(count_everyones_answer(get_answer_groups('./data')))


class Solution(object):

  def __init__(self, nums):
    """

    :type nums: List[int]
    :type numsSize: int
    """
    self.nums = nums

  def pick(self, target):
    """
    :type target: int
    :rtype: int
    """
    count = 0
    ans = -1
    for i in range(0, len(self.nums)):
      if self.nums[i] == target:
        count += 1
        if random.randrange(0, count) == 0:
          ans = i
    return ans

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)


import sys
sys.stdin = open("in1.txt", "rt")
n = int(input())
nlist = []
for i in range(n):
    nlist.append(list(map(int,input().split())))

dx = [0,0,1,-1,1,-1]
dy = [1,-1,0,0,1,-1]

result = 0
for i in range(n):
    sum = 0
    for j in range(6):
        nx = i
        ny = 0
        sum = 0
        while True:
            if nx >= n or ny >= n or nx < 0 or ny < 0:
                break
            sum += nlist[nx][ny]
            nx += dx[j]
            ny += dy[j]
        result = max(result,sum)
    sum = 0
    for j in range(6):
        nx = 0
        ny = i
        sum = 0
        while True:
            if nx >= n or ny >= n or nx < 0 or ny < 0:
                break
            sum += nlist[nx][ny]
            nx += dx[j]
            ny += dy[j]
        result = max(result, sum)

print(result)


from random import shuffle

def carte():
    L_couleurs = ['coeur', 'carreau', 'pique', 'trèfle']
    L_figures = ['as', 'roi', 'dame', 'valet',2,3,4,5,6,7,8,9,10]
    pioche = []
    for couleur in L_couleurs:
        for elt in L_figures:
            pioche.append([elt, couleur])
    shuffle(pioche)
    nb = int(input("Combien de cartes voulez-vous tirer ?"))
    for i in range (nb):
        print(pioche[0])
        pioche.remove(pioche[0])


'''
This script take the 'data.json' source file from `dirData` and parse it.
It will create geojson file as output.
'''
import geopandas as gpd
import json
import os

########################
# Parameters
########################
dirData = '2023-01-29'

########################
# Constantes
########################
dirAsset = 'assets'
dirRegion = 'regions'
baseUrl = 'https://delivrez.fr/public/posts/'

gpxNs = 'osmand'
gpxNsUrl = 'https://osmand.net'

edibleFile = 'edibles'
giveboxFile = 'giveboxes'
bookcasesFile = 'bookcases'

def newGeojsonStruct():
    return {
        'type': 'FeatureCollection',
        'features': []
    }

def convertJsonToGeoJson():
    print('Read source file data.json in folder: ' + dirData)
    with open(dirData + '/data.json') as file:
        data = json.load(file)

    attrs = []
    types = []

    bookcases = newGeojsonStruct()
    giveboxes = newGeojsonStruct()
    edibles = newGeojsonStruct()

    for d in data:
        attrs.extend(list(d.keys()))
        type = d['type']
        types.append(type)
        feature = {
            'type': 'Feature',
            'properties': {
                'name': d['title'],
                'codetype': d['type'],
                'type': 'Delivrez',
                'desc': d['observation'],
                'color': '#00842b',
                'background': 'square'
            },
            'geometry': {
                'type': 'Point',
                'coordinates': [
                    float(d['lon']),
                    float(d['lat'])
                ]
            }
        }
        if d['picture'] is not None:
            feature['properties']['website'] = baseUrl + d['picture']
        if 'INE' in type:
            feature['properties']['type'] += ' edible'
            edibles['features'].append(feature)
        if 'DSB' in type:
            feature['properties']['type'] += ' givebox'
            giveboxes['features'].append(feature)
        if 'BSB' in type:
            feature['properties']['type'] += ' bookcase'
            feature['properties']['amenity_subtype'] = 'public_bookcase'
            feature['properties']['icon'] = 'public_bookcase'
            bookcases['features'].append(feature)

    attrs = set(attrs)
    types = set(types)
    print('Dataset attributes: ' + ', '.join(attrs))
    print('Dataset types: ' + ', '.join(types))
    print('Objects found :')
    print('- ' + str(len(edibles['features'])) + ' INE: Incredible Edible')
    print('- ' + str(len(giveboxes['features'])) + ' DSB: give box (not only books)')
    print('- ' + str(len(bookcases['features'])) + ' BSB: public bookcase')

    dumpGeojsonToFile(edibles, os.path.join(dirData, edibleFile + '.geojson'))
    dumpGeojsonToFile(giveboxes, os.path.join(dirData, giveboxFile + '.geojson'))
    dumpGeojsonToFile(bookcases, os.path.join(dirData, bookcasesFile + '.geojson'))

    print('Geojson files created in folder: ' + dirData)

def dumpGeojsonToFile(data, path):
    with open(path, 'w') as out:
        json.dump(data, out, indent=2, ensure_ascii=True)

def dumpToGpx(data, path):
    data.to_file(path, driver='GPX', GPX_USE_EXTENSIONS=True, GPX_EXTENSIONS_NS=gpxNs, GPX_EXTENSIONS_NS_URL=gpxNsUrl)

def convertGeojsonToGpx(file):
    print('Convert ' + file + ' from geojson to GPX')
    path = os.path.join(dirData, file + '.geojson')
    bookcases = gpd.read_file(path)
    path = os.path.join(dirData, file + '.gpx')
    dumpToGpx(bookcases, path)

def filterBookcasesByArea():
    print('Start of filtering bookcases by region')
    pathRegion = os.path.join(dirAsset, dirRegion)
    pathBookcase = os.path.join(dirData, bookcasesFile + '.geojson')
    areaFilename = os.listdir(pathRegion)

    print('Filter bookcases by region:')
    for areaName in areaFilename:
        areaFile = os.path.join(dirAsset, dirRegion, areaName)
        if os.path.isfile(areaFile):
            region = gpd.read_file(areaFile)
            regionName = os.path.basename(areaName)
            regionName = os.path.splitext(regionName)[0]
            bookcases_filtered = gpd.read_file(pathBookcase, mask=region)
            bookcases_filtered['type'] += ' ' + regionName
            print(' - ' + str(bookcases_filtered.size) + ' bookcases in ' + regionName)
            bookcases_filtered.to_file(os.path.join(dirData, dirRegion, areaName), driver='GeoJSON')
            filepath = os.path.join(dirData, dirRegion, regionName + '.gpx')
            dumpToGpx(bookcases_filtered, filepath)

    print('End of filtering bookcases by region')

print('Start parsing data.json from folder: ' + dirData)

pathRegion = os.path.join(dirData, dirRegion)
if not os.path.exists(pathRegion):
    print('Create folder: ' + pathRegion)
    os.makedirs(pathRegion)

convertJsonToGeoJson()
convertGeojsonToGpx(bookcasesFile)
convertGeojsonToGpx(edibleFile)
convertGeojsonToGpx(giveboxFile)
filterBookcasesByArea()

print('End of parsing')


#what am I even trying to do??

#I want the user to guess a number the computer has randomly selected and calculate how many times
#it takes the user to guess the correct number.
import random

def guess_number(x):
    random_number = random.randrange(x+1)
    count = 0
    guess = 0

    while guess != random_number:
        guess = int(input("Guess a number: "))
        count = count + 1
        if guess != random_number:
            print("Wrong, try again")
        else:
            print (f"You guessed correctly! It only took you {count} times to do so!")

guess_number(10)


#!/usr/bin/env python
# encoding: utf-8
"""
@author: HuRuiFeng
@file: 095_sequence-restore.py
@time: 2023/8/11 18:41
@project: huawei-od-python
@desc: 095 数列还原
"""

def solve_method(n):
    prev_chars = "1"

    # 从第2项开始生成
    for _ in range(1, n + 1):
        # 获取前一项
        current = prev_chars
        # 计数器初始化为1
        count = 1
        description = ""

        for i in range(1, len(current)):
            if current[i] == current[i - 1]:
                # 如果当前数字与前一个数字相同，计数器加1
                count += 1
            else:
                # 将计数和数字添加到描述中，重置计数器为1
                description += str(count) + current[i - 1]
                count = 1

        # 处理最后一个数字，得到前一个数的描述
        description += str(count) + current[-1]
        # 将描述保存到prev_chars变量中
        prev_chars = description

    return prev_chars

if __name__ == '__main__':
    assert solve_method(0) == "1"
    assert solve_method(4) == "111221"