__docformat__ = "restructuredtext"

# -*- coding: utf-8 -*-
# in case o 'unicode error':
# export PYTHONIOENCODING=UTF-8

# get an OS name
import platform

# open URL in browser
import webbrowser

# run shell cmdlet
from os import system
from sys import exit

# freeze program for specified time
from time import sleep
from typing import Optional

# clear IDLE window
def clear():
    """Clear the standard output."""

    # for Windows
    if system_name == "Windows":
        system("cls")

    # for Mac and Linux
    else:
        system("clear")

def open_URL() -> None:
    """Open hardcoded url in the default browser."""

    # webbrowser.open(strURL_bu, new=1) # to use unhash both lines
    # sleep(3*time)
    webbrowser.open(strURL_sense_fear, new=1)
    sleep(3 * time)

def begin_a_game() -> None:
    """First part of the game."""

    clear()
    input(f"Hi there {system_name} user.\n> ")
    sleep(time)
    clear()

    print("Nice to see you.")
    print("Welcome to this simple text adventure game.\n")
    sleep(2 * time)

    ready = input("Are you ready?\n> ")
    sleep(time)

    # user is ready to play
    if "yes" in ready or "Yes" in ready:
        clear()
        sleep(time)
    # user is not ready to play
    elif "no" in ready or "No" in ready:
        print("Take your time.")
        sleep(5 * time)
        print("Ok. The time is over.")
        sleep(time)
        clear()
    else:
        print("Hm, I take it for yes.")
        sleep(2 * time)
        clear()

    print("Let's play a game...")
    sleep(2 * time)
    clear()

    for i in range(3, 0, -1):
        print(f"Let's play a game.\n{i}...")
        sleep(time)
        clear()

    print("Bu.")
    sleep(2 * time)
    open_URL()

    clear()
    print("Didn't mean to scare you.")
    sleep(3 * time)
    print("It's a peaceful game. Hope you'll enjoy it.\n")
    sleep(3 * time)
    print("Imagine you're in a dark room with 3 doors.\n")
    sleep(2 * time)

def main_game() -> None:
    """Main part of the game. Game engine function."""

    # ask for a door number
    door_picked = pick_the_door()

    # ask whether to knock or not
    knock = ask_to_knock()

    # user wants to knock
    if knock:
        knock_the_door(door_picked)

    # user want don't want to knock
    else:
        open_the_door(door_picked)

# ask a user for a door number
def pick_the_door() -> int:
    """Ask user to pick the door.

    :return: picked door number
    :rtype: int
    """

    global first_choice
    clear()
    print("Which door do you choose?\n> ")

    if first_choice:
        sleep(time / 2)
        print("WAIT!")
        sleep(time)
        print("Pick wisely...\n> ", end="")
        sleep(time)
        first_choice = False

    bad_pick = True
    while bad_pick:
        try:
            door_picked = int(input())
            if door_picked in range(1, 4):
                bad_pick = False
        except ValueError:
            print("Give me number 1, 2 or 3:\n> ")

    return door_picked

# ask whether to knock the door or not
def ask_to_knock() -> Optional[bool]:
    """Ask user whether to knock the door or not.

    :return: user decision - to knock or not
    :rtype: bool
    """

    knock = None
    while knock is None:
        # get user answer
        knock_decision = input(" Do you want to knock or open it right away?\n> ")
        knock_decision_list = knock_decision.split(" ")

        knock_list = ("knock", "Knock", "yes")
        open_list = ("open", "Open")

        for i in knock_list:
            # user want to knock
            if i in knock_decision_list:
                knock = True
                break
        for i in open_list:
            # user wants to open
            if i in knock_decision_list:
                knock = False
                print("So rude...")
                sleep(2 * time)
                clear()
                break

        return knock

def knock_the_door(door_picked: int) -> None:
    """A knock-kncok joke scene.

    :param door_picked: picked door number
    :type door_picked: int
    """

    # knock-knock joke
    clear()
    print("> Knock, knock\n> ", end="")
    sleep(2 * time)
    answer_first = input("Who's there?\n> ")
    sleep(2 * time)
    input(f"> {answer_first} who?\n> ")
    sleep(1 * time)
    print("\nHaha\nGood one!\nYou can enter the door.")
    sleep(4 * time)

    open_the_door(door_picked)

def open_the_door(door_picked: int) -> None:
    """Open the picked door.

    :param door_picked: picked door number
    :type door_picked: int
    """

    clear()
    print("(Unfortunately. This part will be covered in Polish.)")
    sleep(4 * time)
    clear()

    if door_picked == 1:
        clear()
        print("Wchodzisz do pierwszego pokoju.")
        sleep(time)
        print("W pokoju widzisz kota,  który leci w Twoim kierunku.")
        sleep(2 * time)

        input("Jak nazywa się ten kot?\n> ")
        sleep(1 * time)
        clear()
        sleep(2 * time)
        print("Kotlecik!")
        sleep(3 * time)
        print("\nThe cat is too busy.")

    elif door_picked == 2:
        clear()
        print("Wchodzisz do drugiego pokoju.")
        sleep(time)
        print("Jesteś na VI Miedzyregionalnych Zawodach Jeździeckich.")
        sleep(2 * time)
        print("W Cieszynie.\n")
        sleep(2 * time)
        print("Następna konkurencja to wyścig z przekodami.")
        sleep(1 * time)
        print(
            "W konkurencji bierze udział ślepy koń, ",
            "który udziela wywiadu tuż przed rozpoczęciem wyścigiem.",
        )
        sleep(4 * time)

        input("\nCo mówi ślepy koń na wyścigach z przeszkodami?\n> ")
        sleep(1 * time)
        clear()
        sleep(2 * time)
        print("Nie widzę przeszkód!")
        sleep(3 * time)

    elif door_picked == 3:
        clear()
        print("Wchodzisz do trzeciego pokoju.")
        sleep(2 * time)
        print("Nie wiem gdzie jesteś.")
        sleep(2 * time)
        print("Przed sobą widzisz złomiarza ", "ciągnącego za sobą worek z puszkami.")
        sleep(2 * time)
        print("Za złomiarzem podąża jego pies.")
        sleep(4 * time)

        input("\nJak nazywa się pies złomiarza?\n> ")
        sleep(1 * time)
        clear()
        sleep(1 * time)
        print("Puszek.")
        sleep(3 * time)

    print(
        "\n(If you don't know Polish. Just so you know, " "this part was realy funny.)"
    )
    sleep(4 * time)
    clear()

    print("\nYou have to leave the room now.")
    sleep(4 * time)
    clear()

    decision = input(
        "Do you want to visit another room?\n"
        "You can quit the game - just type 'leave'\n> "
    )

    if "leave" in decision or "Leave" in decision:
        clear()
        print("Hope you enjoyed the game\n")
        print("Have a nice day! :)\n")
        exit()
    else:
        # play again
        main_game()

# get an OS name
system_name = platform.system()

try:
    print("załółć gęślą jaźń")
    clear()
except UnicodeEncodeError:
    clear()
    print(
        "To run the game set default encoding to UTF-8"
        "by typing the following in the command line:\n"
        "export PYTHONIOENCODING=UTF-8"
    )
    exit()

# assign URLs to be opened
# strURL_bu = "https://drive.google.com/file/d/1dae-FJTJnbZ_xQmmsFFRUh5kZUalkFqc/view?usp=sharing"
strURL_sense_fear = (
    "https://drive.google.com/file/d/1xkDTRZA3Fsm1gGJVFFlNfFq_851aKQlh/view?usp=sharing"
)

# define a time increment [seconds]
# set to 0 for the faster debugging
time = 1

first_choice = True
begin_a_game()
main_game()


#!/usr/bin/env python
from settings.db_config import config as db_config
from ops import db, utilities, image_parser
from tqdm import tqdm
from argparse import ArgumentParser
from settings import credentials
import os

def main(
        experiment_name,
        parent_experiment=None,
        force_channels=True
        ):
    dbc = db_config()
    config = dict(credentials.postgresql_connection(), **vars(dbc))
    if dbc.experiment_names is None:
        raise RuntimeError(
            'Ya need to provide a list of experiment names in the config!')
    with db.db(config) as db_conn:
        for f, en, ln in zip(
                dbc.image_paths, dbc.experiment_names, dbc.label_names):
            exp_id = db_conn.add_experiment(  # add a new experiment
                experiment_name=en,
                parent_experiment=parent_experiment
            )
            files = utilities.get_files(f, dbc.image_file_filter)
            for fid in tqdm(
                    files,
                    desc='Inserting experiment %s %s ' % (en, ln)):
                w, h = image_parser.get_image_size(fid)
                if dbc.relative_path_pointer is not None:
                    fid = os.path.relpath(fid, start=dbc.relative_path_pointer)
                label, synset_parent, class_index = image_parser.get_image_label(
                    fid, dbc.image_key)
                if dbc.force_channels is not None:
                    ch = dbc.force_channels  # need to figure out how to extract channels in image_parser
                if dbc.child_dataset is not None:
                    parent_label_id = dbc.child_dataset  # need to implement
                else:
                    parent_label_id = None
                db_conn.add_images(
                    filename=fid,
                    encoding=dbc.encoding,
                    height=h,
                    width=w,
                    experiment_id=exp_id,
                    parent_image_id=synset_parent,
                    channels=ch)
                db_conn.add_labels(
                    name=label,
                    experiment_id=exp_id,
                    class_index=class_index,
                    parent_label_id=parent_label_id)
                if dbc.skip_label_order:
                    label_order = None
                db_conn.add_image_label_join(
                    filename=fid,
                    image_experiment_name=en,
                    label_name=label,
                    label_experiment_name=ln,
                    label_order=label_order)

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument(
        "--experiment_name", type=str, dest="experiment_name",
        default=None, help="Experiment name.")
    parser.add_argument(
        "--parent_experiment", type=str, dest="parent_experiment",
        default=None, help="Parent experiment name.")
    args = parser.parse_args()
    main(**vars(args))


import sys
import tempfile
import textwrap
import unittest
import shutil
import subprocess

class PabotArgumentsOutputsTest(unittest.TestCase):
    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.tmpdir)

    def _run_tests_with(self, testfile, arg1file, arg2file):
        robot_file = open("{}/test.robot".format(self.tmpdir), "w")
        robot_file.write(textwrap.dedent(testfile))
        robot_file.close()
        with open("{}/arg1.txt".format(self.tmpdir), "w") as f:
            f.write(textwrap.dedent(arg1file))
        with open("{}/arg2.txt".format(self.tmpdir), "w") as f:
            f.write(textwrap.dedent(arg2file))
        process = subprocess.Popen(
            [
                sys.executable,
                "-m" "pabot.pabot",
                "--processes",
                "2",
                "--argumentfile1",
                "{}/arg1.txt".format(self.tmpdir),
                "--argumentfile2",
                "{}/arg2.txt".format(self.tmpdir),
                "--outputdir",
                self.tmpdir,
                "--output",
                "test.xml",
                "{}/test.robot".format(self.tmpdir),
            ],
            cwd=self.tmpdir,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        return process.communicate(), process.returncode

    def test_argumentfile_outputs(self):
        (stdout, stderr), rc = self._run_tests_with(
            """
        *** Test Cases ***
        Test 1
            Log     ${VALUE}
            Should Be True  ${VALUE} == 2
        """,
            """
        --variable VALUE:1
        """,
            """
        --variable VALUE:2
        """,
        )
        self.assertEqual(rc, 1)
        if sys.version_info < (3, 0):
            self.assertIn("PASSED", stdout, stderr)
            self.assertIn("failed", stdout, stderr)
        else:
            self.assertIn(b"PASSED", stdout, stderr)
            self.assertIn(b"failed", stdout, stderr)


'''
# 每日一题 # 第3题：
统计一个文件中每个单词出现的次数，列出出现频率最多的5个单词。
'''
def countWords(File):
    try:
        f = open(File, 'r')
        words = {}
        for line in f.readlines():
            begin = 0
            end = 0
            length = len(line)
            while end < length:
                while line[end].isalpha():
                    end += 1
                word = line[begin:end]
                if word in words:
                    words[word] += 1
                else:
                    words[word] = 1
                begin = end
                while begin < length and not line[begin].isalpha():
                    begin += 1
                end = begin
    except:
        print("Open File failed.")
    finally:
        f.close()
        sortedWords = sorted(words.items(), key=lambda d:d[1], reverse=True)
        print("The 5 words with highest frequency:",sortedWords[:5])

File = "import_this.txt"
countWords(File)


import random
import time
from intelliJo.fellow.fellow import Fellow
from intelliJo.staff.staff import Staff
from intelliJo.living_space.living_space import LivingSpace
from intelliJo.office.office import Office

class Amity:
    living_spaces = []
    office_rooms = []
    fellows = []
    staff = []
    data = {}

    # please do note that add_person and add_room are being called from intelli_dojo.py file

    # add_person method checks the docopt args <type> to see if the value is staff|fellow
    # and calls the appropriate method depending on the type value

    def add_person(self, args):
        # the "who variable will be assigned the value of fellow or staff"
        who = args["<type>"]

        # i just use who.lower() to make the string lowercase just to make my life easy
        if who.lower() == "staff":
            # if true call the add_staff method
            self.add_staff(args)
        # an else because i don't need to check if the "who" is a fellow
        else:
            # call the add_fellow method
            self.add_fellow(args)

    # add_room method checks the docopt args <room_type> to see if the value is livingspace|office
    # and calls the appropriate method depending on the room_type value
    def add_room(self, args):
        # gets the room_type  value
        room_type = args["<room_type>"]

        # convert the string to lowercase because the user might enter something like this LivInGspAce
        if room_type.lower() == "livingspace":
            # if the room_type return the value livingspace call the create_living_space method
            self.create_living_space(args)

        # else call the create_office method
        else:
            self.create_office(args)

    # this method will be responsible for for creating staff user when completed
    def add_staff(self, args):
        # create an instance of Staff by passing the values we got from docopt.
        staff = Staff(args['<first_name>'], args["<last_name>"])

        # gives a feedback to the user if the staff was created.
        print("Staff {} {} has been successfully added.".format(staff.first_name, staff.last_name))
        self.store_data(self.give_me_an_office(), "Office", staff)

        # gives a feedback to the user if the office was created.
        print("{} has been allocated the office {}".format(staff.first_name, self.give_me_an_office().room_name))

    # this method is responsible for creating a new fellow
    def add_fellow(self, args):

        toon_names = ["mickey mouse", "donald duck"]
        firstname_lastname = args['<first_name>'] + " " + args['<first_name>']
        print(firstname_lastname)

        if firstname_lastname in toon_names:
            print("TIA, maybe you're looking for Walt Disney")
            return
        # create an instance of class Fellow
        fellow = Fellow(args['<first_name>'], args["<last_name>"], args["<accommodation>"])
        office = self.give_me_an_office()

        self.store_data(office.room_name, "Office", fellow)

        if args["<accommodation>"] is None:

            self.store_data(office.room_name, "Office", fellow)
            # gives a feedback to the user if the fellow was created.
            print("Fellow {} {} has been successfully added.".format(fellow.first_name, fellow.last_name))
            print("{} has been allocated the office {}".format(fellow.first_name, office.room_name))

        # checks if the fellow wants accommodation
        elif args["<accommodation>"].lower() == "y":
            # if yes get a random room from the list

            # and call the allocate_a_living_space method passing it a room and a fellow object
            self.store_data(office.room_name, "Office", fellow)

            self.allocate_a_living_space(self.give_me_a_living_space().room_name, fellow, True)

    # this method is responsible for creating a new offices.
    def create_office(self, args):
        # loop over all the office or offices the user entered
        if isinstance(args, str):
            Amity.office_rooms.append(Office(args))

        else:
            for i in args["<room_name>"]:
                # create some instance of Office class and append them to the temp_office list variable
                Amity.office_rooms.append(Office(i))
                print("An office called {} has been successfully created!".format(i))

    # this method creates a new livingspace.
    def create_living_space(self, args):
        if isinstance(args, str):
            Amity.living_spaces.append(LivingSpace(args))
        else:
            for i in args["<room_name>"]:
                Amity.living_spaces.append(LivingSpace((i)))
                print("A LivingSpace called {} has been successfully created!".format(i))

    # this method allocates a living space
    def allocate_a_living_space(self, room_name, fellow, want_living_space=False):
        # gives a feedback to the user if the fellow was created.
        print("Fellow {} {} has been successfully added.".format(fellow.first_name, fellow.last_name))
        print("{} has been allocated the office {}".format(fellow.first_name, self.query_data(fellow)))
        if isinstance(fellow, Fellow) and want_living_space:
            print("{} has been allocated the LivingSpace {}".format(fellow.first_name, room_name))

    # When i call this function it will first check if there is a living space, if there is a living space,
    # It will return a random living space, else
    # It will call the create_living_space to
    def give_me_a_living_space(self):

        # Edge case for checking if there are rooms.
        if len(Amity.living_spaces) == 0:
            time.sleep(4)
            print("Hey Amity, what's the big idea?")
            print()
            time.sleep(2)
            print("OOPS this is embarrassing there is no Living Space")
            print("just enter the name room you want: ")
            print()
            time.sleep(3)
            print("oh and since your are the first person you get to chose the top deck")
            print()
            time.sleep(2)
            name = input("Enter living space name: ")
            self.create_living_space(name)
            return Amity.living_spaces[0]
        # Returns a random room
        return random.choice(Amity.living_spaces)

    # Returns a random Office
    def give_me_an_office(self):
        if len(Amity.office_rooms) == 0:
            time.sleep(2)
            print("What now ?")
            print()
            time.sleep(2)
            print("OOPS this is embarrassing there are no office rooms")
            print("just enter the office name you want: ")
            print()
            time.sleep(2)
            print("oh and since your are the first person you get to chose the corner you want")
            print()
            time.sleep(2)
            name = input("Enter Office name: ")
            self.create_office(name)
            return Amity.office_rooms[0]

        return random.choice(Amity.office_rooms)

    # Stores Data to a Dictionary
    def store_data(self, room_name, room_type, person_type):
        if room_name in Amity.data:

            Amity.data[room_name][room_type].append(person_type)
        else:
            Amity.data[room_name] = {room_type: []}
            Amity.data[room_name][room_type].append([person_type])

    # Gets Data from a Dictionary
    def query_data(self, user):
        for key, value in self.data.items():
            for room, occupants in value.items():
                if user in occupants and room == "Office":
                    return key


import pandas as pd
import matplotlib.pyplot as plt

# Change names of the files accordingly

df1 = pd.read_csv('training_log_f32.csv')
df2 = pd.read_csv('training_log_f64.csv')
df3 = pd.read_csv('training_log_mpt.csv')

acc_f32 = df1.loc[:, 'Accuracy']
acc_f64 = df2.loc[:, 'Accuracy']
acc_mpt = df3.loc[:, 'Accuracy']
batch_index = df1.loc[:, 'Batch']

fig = plt.figure()
plt.plot(batch_index, acc_f32)
plt.plot(batch_index, acc_f64)
plt.plot(batch_index, acc_mpt)
plt.xlabel('Batch Index')
plt.ylabel('Accuracy')
plt.legend(["Float32", "Float64", "MPT"])
plt.show()


import justpy as jp

# Every justpy app will have a main object
# It is known as the quasar page.
# This is because justpy uses the quasar framework.

def app():
    wp = jp.QuasarPage()
    h1 = jp.QDiv(a=wp, text="Analysis Of Course Reviews", classes="text-h3 text-weight-bold text-center q-pa-md inset-shadow-down shadow-1 bg-positive")
    p1 = jp.QDiv(a=wp, text="These graphs represent course review analysis!!!", classes="text-h3")
    return wp

jp.justpy(app)


# -*- coding: utf-8 -*-
"""
Created on Mon Nov  8 19:23:46 2021

@author: sroqu
"""

import paqueteEjercicios.moduloEj11 as Ej11
import paqueteEjercicios.moduloEj12 as Ej12
import paqueteEjercicios.moduloEj21 as Ej21
import paqueteEjercicios.moduloEj22 as Ej22
import paqueteEjercicios.moduloEj30 as Ej30

#opciones de ejecucion
#1 ejecuta programa 1
#2 ejecuta programa 2
#3 ejecuta programa 3
#4 Ejecuta programa 4
#5 Salir

opcion=1
cuentas=0
cuentas_tot=0

while opcion!=6:
        a=input("Seleccione una opción de ejecución\
              \n1) Ejecute un programa que genera varios mensajes en pantalla\
              \n2) Ejecute un programa que intenta determinar el tipo de dato ingresado\
              \n   por el usuario\
              \n3) Ejecuta un programa que separa valores pares e impares de una lista\
              \n4) Ejecuta un programa que valida una contraseña 4\
              \n5) Ejecuta un programa que clasifica un conjuto de valores de un\
              \n   de un diccionario\
              \n6) Salir de la ejecución \ningrese el número ")

        try:
            b=int(a)
            opcion=b
            if opcion==6:
                break
            elif opcion==1:
                Ej11.programa1()
            elif opcion==2:
                Ej12.programa2()
            elif opcion==3:
                Ej21.programa3()
            elif opcion==4:
                Ej22.programa4()
            elif opcion==5:
                Ej30.programa5()
            else:
                print("Debe escoger un número de 1 a 6")
        except:
              print("No es un dígito. Debes ingresar un dígito de 1 a 6")
        else:
           print("Escribiste un número")
           cuentas+=1
        finally:
           cuentas_tot+=1

print("El codigo se ejecuto correctamente ",cuentas," veces")
print("El codigo se ejecuto incorrectamente ",cuentas_tot - cuentas," veces")
print("El codigo se ejecuto en total ",cuentas_tot," veces")


# %% [markdown]
# # About
# This code reports the LST time series over a rock site in Ladakh in all the four categories of QA see [https://www.youtube.com/watch?v=JPjkjjhj5rk]

# %% [markdown]
## Libs
import xarray as xr, pandas as pd, numpy as np, time
from tqdm.notebook import tqdm as td
start = time.time()

# %% [markdown]
## Read files
df1 = pd.read_csv("../../004_RishiGanga/05_CSVs/16_Rock-Terra-MOD11A1-006-results.csv")
df2 = pd.read_csv("../../004_RishiGanga/05_CSVs/17_Rock-Aqua-MYD11A1-006-results.csv")

# %% [markdown]
## List of cols to be chosen
cols1 = ['Latitude', 'Longitude', 'Date','MOD11A1_006_LST_Day_1km','MOD11A1_006_QC_Day_LST_Error_Flag_Description', 'MOD11A1_006_LST_Night_1km','MOD11A1_006_QC_Night_LST_Error_Flag_Description']
cols2 = ['Date', 'MYD11A1_006_LST_Day_1km', 'MYD11A1_006_QC_Day_LST_Error_Flag_Description', 'MYD11A1_006_LST_Night_1km','MYD11A1_006_QC_Night_LST_Error_Flag_Description']

# %% [markdown]
## Subset cols as per above list
df1 = df1[cols1]
df2 = df2[cols2]

# %% [markdown]
## Merge
# [1] Set dates as index in df1
df1.set_index('Date', inplace=True)
df1.index.names = [None]
df1.index = pd.to_datetime(df1.index)  # data type of date chanegd

# [2] Set dates as index in df2
df2.set_index('Date', inplace=True)
df2.index.names = [None]
df2.index = pd.to_datetime(df2.index)

# [3] Merge
df = pd.concat([df1, df2],axis=1)

# [4] Shorten the column names
cols = ['Latitude', 'Longitude', 'Terra_Day', 'Terra_Day_Error','Terra_Night_Error','Terra_Night_Error', 'Aqua_Day', 'Aqua_Day_Error', 'Aqua_Night', 'Aqua_Night_Error']
df.columns = cols

# %% [markdown]
## Save to csv
df.to_csv("../../004_RishiGanga/05_CSVs/18_Rock_Terra_Aqua.csv")
print('Time elapsed: ', np.round(time.time()-start,2), 'secs')

# %%


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS

from flask_restful import Resource, Api
import os

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
    os.path.join(basedir, 'group-finance.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

api = Api(app)

def load_resources():
    from resources import GroupResource, MemberResource
    api.add_resource(GroupResource, '/groups', '/groups/<int:group_id>')
    api.add_resource(MemberResource, '/members/<int:group_id>',
                     '/members/<int:group_id>/<int:member_id>')

def init_db(app):
    with app.app_context():
        from models import db
        db.init_app(app)
        db.create_all()

if __name__ == '__main__':
    CORS(app)
    init_db(app)
    load_resources()
    app.run(debug=True)


from src import *

if __name__ == '__main__':
    model_yaml = 'configs/cvt-21-384x384.yaml'
    path2pretrained = 'pretrained/CvT-21-384x384-IN-22k.pth'

    model = build_model(model_yaml, path2pretrained, num_classes = 10)

    print(model)

    with torch.no_grad():
        model.eval()
        x = torch.randn(10, 3, 512, 512)
        y = model(x)
        print(y.shape)
        # print(y)


"""
Maximum Sum in a Circular Array
Given a "circular array" nums containing integers, return the sum of the subarray with the largest sum.

A subarray is an array within another array. Unlike subsequences, they are contiguous meaning that there are no "gaps" in the subarray taken from the overarching array.

Here, we define a circular array to be an array whose start is connected to its end.

Example:
Input: [20, -100, 20]
Output: 40
Explanation: We can take the subarray [20, 20] whose sum is 20 + 20 = 40. Note that this is possible since our array is circular and we can loop around the back (index 2 to index 0).
"""

class Solution:
    def maxCircularSubarraySum(self, nums):
        """
        Interface
        ----
        :type nums: list of int
        :rtype: int

        Approach
        ----
        Use Kadane's algorithm

        1. There are two collectively exhaustive cases together:
            a) Our maximum sum subarray can either consist of only contiguous elements in our original array
            b) Or it can "wrap around" the end of the subarray We can compute the maximum sum of a subarray under both of these conditions,
            and the maximum of the two values we find will be our overall answer.
            NOTE: we need hold a subproblem competition

        2. First of all, we can compute the maximum sum of a circular subarray by using Kadane's algorithm. This is discussed in the solution to the
        problem "Max Contiguous Subarray Sum" (if you need a refresher view that first).

        3. The only other case to consider is when our subarray wraps around the end of our original array.

        4. However, the maximum sum in a circular subarray is simply :
        the sum of the entire array minus the sum of a minimum sum contiguous subarray (which can potentially be empty).

        5. By subtracting the minimum sum contiguous subarray, we are essentially "excluding" this portion from what we are taking to form a circular subarray.
        NOTE: The reason why we exclude the minimum subarray to form a maximum circular subarray is because we are required to remove something, so it is optimal to
        remove the part of our array that contributes the least (or a negative amount) to our sum.

        6. For example, the minimum contiguous subarray in the array [20, -100, 20] is -100. Thus, the maximum sum circular subarray is the sum of the entire array
        (which is 20 + -100 + 20 = -60) minus the sum of the minimum contiguous subarray. This leads us to an answer of -60 - (-100) = 40.

        7. The minimum contiguous subarray sum can be found by negating the elements of the original array, applying Kadane's algorithm to find the maximum contiguous subarray sum,
        and finally negating the final answer.
        NOTE: There is one special case: our minimum subarray cannot include every element in the array because, otherwise, our array would be empty.

        Complexity
        ----
        Time : O(N)
        Space : O(1)
        """

        # First, we compute the max contiguous sum and total sum.
        max_sum = nums[0]
        total_sum = 0
        curr_sum = 0
        for i in range(0, len(nums)):
            value = nums[i]
            # reset the maximum contiguous sum if we have sum less then zero
            if curr_sum < 0:
                curr_sum = 0

            curr_sum += value
            total_sum += value
            max_sum = max(max_sum, curr_sum)

            # Negate elements in the array to find minimum contiguous sum next.
            nums[i] = -value

        # Next, we find the minimum contiguous sum.
        # NOTE: we run kadane's algorithm on an array with every element negated
        min_sum = nums[0]
        curr_sum = 0
        for value in nums:
            if curr_sum < 0:
                curr_sum = 0

            curr_sum += value
            min_sum = max(min_sum, curr_sum)
        # the min_sum will be the negation
        min_sum = -min_sum

        # Now, we return the best of our two cases.
        return max(total_sum - min_sum, max_sum)

arr = [20, -100, 20]
s = Solution()
print(s.maxCircularSubarraySum(arr))


from tkinter import *
from tkinter import filedialog
from tkinter import messagebox as MessageBox
import tkinter as tk
from tkinter import ttk
from xml.dom import minidom
import xml.etree.ElementTree as ET
import webbrowser
import os
from lista_circular import ListaCircular
from lista_orto import ListaOrtogonal
from datetime import datetime

###########INTERFAZ############
Ventana = Tk()
Ventana.title("Principal") #Titulo
Ventana.geometry("1000x500") #AnchoxAlto
Ventana.configure(background = "#17202A") #Color
ori = Label(Ventana,text="Original", fg = "#E74C3C")
ori.place(x=25, y=390)
mod = Label(Ventana,text="Modificada", fg = "#E74C3C")
mod.place(x=495, y=390)
image1 = tk.PhotoImage(file="inicio.png")
image2 = tk.PhotoImage(file="inicio.png")
label = tk.Label(Ventana, image = image1)
label2 = tk.Label(Ventana, image = image2)
label.place(x=20, y=20)
label2.place(x=490, y=20)
ori.config(bg = "#17202A")
mod.config(bg = "#17202A")
###########INTERFAZ############

html = False
datosRepo = ""
nombres = ""
nombre = ""
ListaC = ListaCircular()
def cargarArchivo():
    global datosRepo, html, nombres, ListaC
    ruta = filedialog.askopenfilename (title = "Abrir")
    try:
        tree = ET.parse(ruta)
        root = tree.getroot()
        i = 0
        names = tree.findall("matriz")
        for elem in root:
            nueva = True
            if elem.tag == "matriz":
                #nombre
                nombre = names[i].find("nombre").text
                a = nombres.split(sep = ",")
                for nom in range(0,len(a)):
                    if a[nom] == nombre:
                        now = datetime.now()
                        datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Cargar Archivo - Error la matriz "+ nombre +" ya existe,"
                        nueva = False
                        i = i + 1
                if nueva == True:
                    #filas
                    n = names[i].find("fila").text
                    #columnas
                    m = names[i].find("columna").text
                    #imagen
                    imagen = names[i].find("imagen").text
                    lineas = imagen.split(sep = None, maxsplit = -1)
                    j = 0
                    mas = False
                    if len(lineas) == int(n):
                        while j < int(n):
                            columnas = list(lineas[j])
                            if len(columnas) != int(m):
                                mas = True
                                now = datetime.now()
                                datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Cargar Archivo - Error la matriz "+ nombre +" exede el numeo de columnas indicado,"
                                break
                            j = j + 1
                        if mas == False:
                            nombres = nombres + nombre +","
                            caracter = ""
                            l = 0
                            vacio = 0
                            lleno = 0
                            for linea in lineas:
                                l = l + 1
                                columnas = list(linea)
                                c = 0
                                for col in columnas:
                                    c = c + 1
                                    if l == len(lineas) and c == len(columnas):
                                        if col == "-":
                                            caracter = caracter +" "
                                            vacio += 1
                                        elif col == "*":
                                            caracter = caracter +"*"
                                            lleno += 1
                                    else:
                                        if col == "-":
                                            caracter = caracter +" ,"
                                            vacio += 1
                                        elif col == "*":
                                            caracter = caracter +"*,"
                                            lleno += 1
                            Datos = caracter.split(",")
                            ListaO = ListaOrtogonal()
                            ListaO.CrearMatriz(int(n),int(m),Datos)
                            ListaC.Agregar(ListaO,nombre)
                            now = datetime.now()
                            datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - "+ nombre +" - Espacios llenos: "+str(lleno)+" - Espacios vacíos: " +str(vacio) + ","
                    else:
                        now = datetime.now()
                        datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Cargar Archivo - Error la matriz "+ nombre +" exede el numeo de filas indicado,"
                    i = i + 1
        MessageBox.showinfo("Cargar Archivo", "El archivo se termino de cargar")
        html = True
    except:
        MessageBox.showerror("Error", "Carge el archivo de nuevo")
def dos(lista,lista2):
    global datosRepo, nombre, image1, image2, label, label2, ListaC
    nombre = lista.get()
    nombre2 = lista2.get()
    ListaC.buscarMat4(nombre)
    ListaC.buscarMat4(nombre2)
    image2 = tk.PhotoImage(file=nombre+".png")
    image1 = tk.PhotoImage(file=nombre2+".png")
    image1 = image1.subsample(2,2)
    image2 = image2.subsample(2,2)
    label = tk.Label(Ventana, image = image1)
    label2 = tk.Label(Ventana, image = image2)
    label.place(x=20, y=20)
    label2.place(x=20, y=300)
def elegir(lista,a):
    global datosRepo, nombre, image1, image2, label, label2, ListaC
    nombre = lista.get()

    if a == 1:
        ListaC.buscarMat(nombre,a)
        image2 = tk.PhotoImage(file=nombre+"rotH.png")
        now = datetime.now()
        datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Rotacion horizontal de una imagen - Matriz (o matrices) usadas: " +nombre + ","
    elif a == 2:
        ListaC.buscarMat(nombre,a)
        image2 = tk.PhotoImage(file=nombre+"rotV.png")
        now = datetime.now()
        datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Rotacion vertical de una imagen - Matriz (o matrices) usadas: " +nombre + ","
    elif a == 3:
        ListaC.buscarMat(nombre,a)
        image2 = tk.PhotoImage(file=nombre+"tran.png")
        now = datetime.now()
        datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Transpuesta de una imagen - Matriz (o matrices) usadas: " +nombre + ","
    image1 = tk.PhotoImage(file=nombre+".png")
    image1 = image1.subsample(1,1)
    image2 = image2.subsample(1,1)
    label = tk.Label(Ventana, image = image1)
    label2 = tk.Label(Ventana, image = image2)
    label.place(x=20, y=20)
    label2.place(x=490, y=20)

def linea(lista,f1,c1,ca,accion):
    global datosRepo, nombre, image1, image2, label, label2, ListaC
    nombre = lista.get()
    f = f1.get()
    c = c1.get()
    cant = ca.get()
    if str(f) != "" and str(c) != "" and str(cant) != "":

        if accion == 5:
            ListaC.buscarMat2(nombre, int(f), int(c), int(cant), accion)
            image2 = tk.PhotoImage(file=nombre+"agreH.png")
            now = datetime.now()
            datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Agregar línea horizontal a una imagen - Matriz (o matrices) usadas: " +nombre + ","
        elif accion == 6:
            ListaC.buscarMat2(nombre, int(f), int(c), int(cant), accion)
            image2 = tk.PhotoImage(file=nombre+"agreV.png")
            now = datetime.now()
            datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Agregar línea vertical a una imagen - Matriz (o matrices) usadas: " +nombre + ","
        elif accion == 8:
            ListaC.buscarMat2(nombre, int(f), int(c), int(cant), accion)
            image2 = tk.PhotoImage(file=nombre+"agreT.png")
            now = datetime.now()
            datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Agregar triangulo a una imagen - Matriz (o matrices) usadas: " +nombre + ","
        image1 = tk.PhotoImage(file=nombre+".png")
        image1 = image1.subsample(1,1)
        image2 = image2.subsample(1,1)
        label = tk.Label(Ventana, image = image1)
        label2 = tk.Label(Ventana, image = image2)
        label.place(x=20, y=20)
        label2.place(x=490, y=20)
    else:
        MessageBox.showerror("Error", "Debe llenarse todos los campos")

def limYr(lista,f1,c1,f2,c2,accion):
    global datosRepo, nombre, image1, image2, label, label2, ListaC
    nombre = lista.get()
    f = f1.get()
    c = c1.get()
    ff = f2.get()
    cc = c2.get()
    if str(f) != "" and str(c) != "" and str(ff) != "" and str(cc) != "":
        if accion == 4:
            ListaC.buscarMat3(nombre, int(f),int(c) ,int(ff),int(cc), accion)
            image2 = tk.PhotoImage(file=nombre+"limp.png")
            now = datetime.now()
            datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Limpiar zona de una imagen - Matriz (o matrices) usadas: " +nombre + ","
        elif accion == 7:
            ListaC.buscarMat3(nombre, int(f),int(c) ,int(ff),int(cc), accion)
            image2 = tk.PhotoImage(file=nombre+"agreR.png")
            now = datetime.now()
            datosRepo = datosRepo + str(now.day)+"/" + str(now.month)+"/" + str(now.year) +" - "+ str(now.time())  + " - Agregar rectángulo - Matriz (o matrices) usadas: " +nombre + ","
        image1 = tk.PhotoImage(file=nombre+".png")
        image1 = image1.subsample(1,1)
        image2 = image2.subsample(1,1)
        label = tk.Label(Ventana, image = image1)
        label2 = tk.Label(Ventana, image = image2)
        label.place(x=20, y=20)
        label2.place(x=490, y=20)
    else:
        MessageBox.showerror("Error", "Debe llenarse todos los campos")

def destruir(ventana):
    ventana.destroy()

def rotar(op):
    global datosRepo, html
    a = int(op)
    if html:
        ventana = Toplevel()
        ventana.title("Operaciones")
        ventana.geometry("300x90")
        ventana.configure(background = "#17202A")
        op = Label(ventana,text="Seleccione una matriz para realizar la operación", fg = "white")
        op.pack()
        op.configure(background = "#17202A")
        lista = ttk.Combobox(ventana,width=17, state="readonly")
        nom = ListaC.Nombres().split(",")
        lista["values"] = nom
        lista.set(nom[0])
        lista.place(x=30, y=40)
        button = Button(ventana,text="Aceptar", fg = "white",bg="#E74C3C",command=lambda:[elegir(lista,a),destruir(ventana)])
        button.place(x=170,y=40)
        ventana.mainloop()
    else:
        MessageBox.showinfo("Operaciones", "Debe cargar un archivo de entrada")
def validate_entry(text):
    return text.isdecimal()
def limpiar():
    global datosRepo, html
    if html:
        ventana = Toplevel()
        ventana.title("Operaciones")
        ventana.geometry("300x170")
        ventana.configure(background = "#17202A")
        a = Label(ventana,text="Seleccione una matriz para realizar la operación", fg = "white")
        a.pack()
        a.config(bg = "#17202A")
        lista = ttk.Combobox(ventana,width=17, state="readonly")
        nom = ListaC.Nombres().split(",")
        lista["values"] = nom
        lista.set(nom[0])
        lista.pack()
        b = Label(ventana,text="Coordenada inicial", fg = "white")
        b.pack()
        b.config(bg = "#17202A")
        c = Label(ventana,text="Fila", fg = "#E74C3C")
        c.place(x=60,y=60)
        c.config(bg = "#17202A")
        f1 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        f1.place(x=90,y=60)
        d = Label(ventana,text="Columna", fg = "#E74C3C")
        d.place(x=145,y=60)
        d.config(bg = "#17202A")
        c1 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        c1.place(x=205,y=60)
        e = Label(ventana,text="Coordenada final", fg = "white")
        e.place(x=103,y=80)
        e.config(bg = "#17202A")
        f = Label(ventana,text="Fila", fg = "#E74C3C")
        f.place(x=60,y=100)
        f.config(bg = "#17202A")
        f2 = tk.Entry(ventana, validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        f2.place(x=90,y=100)
        g = Label(ventana,text="Columna", fg = "#E74C3C")
        g.place(x=145,y=100)
        g.config(bg = "#17202A")
        c2 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        c2.place(x=205,y=100)
        button = Button(ventana,text="Aceptar",fg = "white",bg="#E74C3C",command=lambda:[limYr(lista,f1,c1,f2,c2,4),destruir(ventana)])
        button.place(x=125,y=130)
        ventana.mainloop()
    else:
        MessageBox.showinfo("Operaciones", "Debe cargar un archivo de entrada")

def agregarF(accion):
    global datosRepo, html
    if html:
        ventana = Toplevel()
        ventana.title("Operaciones")
        ventana.geometry("300x170")
        ventana.configure(background = "#17202A")
        a = Label(ventana,text="Seleccione una matriz para realizar la operación", fg = "white")
        a.pack()
        a.config(bg = "#17202A")
        lista = ttk.Combobox(ventana,width=17, state="readonly")
        nom = ListaC.Nombres().split(",")
        lista["values"] = nom
        lista.set(nom[0])
        lista.pack()
        b = Label(ventana,text="Coordenada inicial", fg = "white")
        b.pack()
        b.config(bg = "#17202A")
        c = Label(ventana,text="Fila", fg = "#E74C3C")
        c.place(x=60,y=60)
        c.config(bg = "#17202A")
        f1 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        f1.place(x=90,y=60)
        d = Label(ventana,text="Columna", fg = "#E74C3C")
        d.place(x=145,y=60)
        d.config(bg = "#17202A")
        c1 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        c1.place(x=205,y=60)
        e = Label(ventana,text="Cantidad de Elementos", fg = "white")
        e.place(x=85,y=80)
        e.config(bg = "#17202A")
        cant= tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=10,justify=tk.LEFT)
        cant.place(x=117,y=100)
        button = Button(ventana,text="Aceptar",fg = "white",bg="#E74C3C",command=lambda:[linea(lista,f1,c1,cant,accion),destruir(ventana)])
        button.place(x=125,y=130)
        ventana.mainloop()
    else:
        MessageBox.showinfo("Operaciones", "Debe cargar un archivo de entrada")

def agregarR():
    global datosRepo, html
    if html:
        ventana = Toplevel()
        ventana.title("Operaciones")
        ventana.geometry("300x170")
        ventana.configure(background = "#17202A")
        a = Label(ventana,text="Seleccione una matriz para realizar la operación", fg = "white")
        a.pack()
        a.config(bg = "#17202A")
        lista = ttk.Combobox(ventana,width=17, state="readonly")
        nom = ListaC.Nombres().split(",")
        lista["values"] = nom
        lista.set(nom[0])
        lista.pack()
        b = Label(ventana,text="Coordenada inicial", fg = "white")
        b.pack()
        b.config(bg = "#17202A")
        c = Label(ventana,text="Fila", fg = "#E74C3C")
        c.place(x=60,y=60)
        c.config(bg = "#17202A")
        f1 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        f1.place(x=90,y=60)
        d = Label(ventana,text="Columna", fg = "#E74C3C")
        d.place(x=145,y=60)
        d.config(bg = "#17202A")
        c1 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        c1.place(x=205,y=60)
        e = Label(ventana,text="Cantidad", fg = "white")
        e.place(x=120,y=80)
        e.config(bg = "#17202A")
        f = Label(ventana,text="Filas", fg = "#E74C3C")
        f.place(x=60,y=100)
        f.config(bg = "#17202A")
        f2 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        f2.place(x=95,y=100)
        g = Label(ventana,text="Columnas", fg = "#E74C3C")
        g.place(x=140,y=100)
        g.config(bg = "#17202A")
        c2 = tk.Entry(ventana,validate = "key", validatecommand=(ventana.register(validate_entry),"%S"),width=5,justify=tk.LEFT)
        c2.place(x=205,y=100)
        button = Button(ventana,text="Aceptar",fg = "white",bg="#E74C3C",command=lambda:[limYr(lista,f1,c1,f2,c2,7),destruir(ventana)])
        button.place(x=125,y=130)
        ventana.mainloop()
    else:
        MessageBox.showinfo("Operaciones", "Debe cargar un archivo de entrada")

def agregarT():
    global datosRepo, html
    if html:
        ventana = Toplevel()
        ventana.title("Operaciones")
        ventana.geometry("300x170")
        ventana.configure(background = "#17202A")
        a = Label(ventana,text="Seleccione una matriz para realizar la operación", fg = "white")
        a.pack()
        a.config(bg = "#17202A")
        lista = ttk.Combobox(ventana,width=17, state="readonly")
        nom = ListaC.Nombres().split(",")
        lista["values"] = nom
        lista.set(nom[0])
        lista.pack()
        b = Label(ventana,text="Coordenada inicial", fg = "white")
        b.pack()
        b.config(bg = "#17202A")
        c = Label(ventana,text="Fila", fg = "#E74C3C")
        c.place(x=60,y=60)
        c.config(bg = "#17202A")
        f1 = tk.Entry(ventana,width=5,justify=tk.LEFT)
        f1.place(x=90,y=60)
        d = Label(ventana,text="Columna", fg = "#E74C3C")
        d.place(x=145,y=60)
        d.config(bg = "#17202A")
        c1 = tk.Entry(ventana,width=5,justify=tk.LEFT)
        c1.place(x=205,y=60)
        e = Label(ventana,text="Numero de filas y columnas", fg = "white")
        e.place(x=75,y=80)
        e.config(bg = "#17202A")
        cant= tk.Entry(ventana,width=10,justify=tk.LEFT)
        cant.place(x=117,y=100)
        button = Button(ventana,text="Aceptar",fg = "white",bg="#E74C3C",command=lambda:[linea(lista,f1,c1,cant,8),destruir(ventana)])
        button.place(x=125,y=130)
        ventana.mainloop()
    else:
        MessageBox.showinfo("Operaciones", "Debe cargar un archivo de entrada")

def dosMat(accion):
    global datosRepo, html
    if html:
        ventana = Toplevel()
        ventana.title("Operaciones")
        ventana.geometry("300x150")
        ventana.configure(background = "#17202A")
        a = Label(ventana,text="Matriz A", fg = "white")
        a.pack()
        a.config(bg = "#17202A")
        lista = ttk.Combobox(ventana,width=17, state="readonly")
        nom = ListaC.Nombres().split(",")
        lista["values"] = nom
        lista.set(nom[0])
        lista.pack()
        b = Label(ventana,text="Matriz B", fg = "white")
        b.pack()
        b.config(bg = "#17202A")
        lista2 = ttk.Combobox(ventana,width=17, state="readonly")
        lista2["values"] = nom
        lista2.set(nom[0])
        lista2.pack()
        button = Button(ventana,text="Aceptar",fg = "white",bg="#E74C3C",command=lambda:[dos(lista,lista2),destruir(ventana)])
        button.pack()
        ventana.mainloop()
    else:
        MessageBox.showinfo("Operaciones", "Debe cargar un archivo de entrada")

def reporte():
    global datosRepo, html
    if html:
        datos = datosRepo.split(",")
        fichero = open("Reporte.html","w")
        fichero.write("""<!doctype html>
                    <html lang="en">
                    <head>
                    <meta charset="utf-8">
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                    <meta charset="UTF-8"/>
                    <meta name="viewport" content="width=device-width, initial-scale=1">
                    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
                    <title>Reporte</title>
                    </head>
                    <body  style="background-color:#17202A;">

                     <h1 style="color:white">Reporte</h1>
                    <table class="table">
                    <tbody>""")
        for s in datos:
            fichero.write("<tr><td> <font color=\"#E74C3C\">"+s+"</font></td></tr>\n")
        fichero.write("""</tbody>
                    </table>
                    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
                    </body>
                    </html>""")
        fichero.close()
        webbrowser.open_new_tab("Reporte.html")
    else:
        MessageBox.showinfo("Reporte HTML", "Debe cargar un archivo de entrada")

def datosEstudiante():
    Ventana = Tk()
    Ventana.title("Información del estudiante") #Titulo
    Ventana.geometry("200x110") #AnchoxAlto
    nombre = Label(Ventana,text="Katheryn Darleny Yuman Oscal")
    nombre.pack()
    carnet = Label(Ventana,text="201902209")
    carnet.pack()
    carrera = Label(Ventana,text="Ingenieria en ciencias y sistemas")
    carrera.pack()
    semestre = Label(Ventana,text="5to. semestre")
    semestre.pack()
    curso = Label(Ventana,text="IPC - 2, \"B\"")
    curso.pack()
    Ventana.mainloop()

def Docu():
    webbrowser.open_new_tab("Documentación\Ensayo.pdf")

###########INTERFAZ############
Barra = Menu(Ventana, bg = "#E74C3C",fg = "white")
Barra.config(bg = "#E74C3C",fg = "white")
#Cargar Archivo
CargarArchivo = Menu(Barra)
CargarArchivo.config(bg = "#E74C3C",fg = "white")
CargarArchivo.add_command(label = "Cargar archivo de entrada",command=cargarArchivo)

#Operaciones
Operaciones = Menu(Barra)
Operaciones.config(bg = "#E74C3C",fg = "white")
Operaciones.add_command(label = "Rotacion horizontal de una imagen",command=lambda:[rotar(1)])
Operaciones.add_command(label = "Rotacion vertical de una imagen",command=lambda:[rotar(2)])
Operaciones.add_command(label = "Transpuesta de una imagen",command =lambda:[rotar(3)])
Operaciones.add_command(label = "Limpiar zona de una imagen",command=limpiar)
Operaciones.add_command(label = "Agregar línea horizontal a una imagen",command=lambda:[agregarF(5)])
Operaciones.add_command(label = "Agregar línea vertical a una imagen",command=lambda:[agregarF(6)])
Operaciones.add_command(label = "Agregar rectángulo",command=agregarR)
Operaciones.add_command(label = "Agregar triángulo rectángulo",command=agregarT)
Operaciones.add_command(label = "Unión A, B",command=lambda:[dosMat(9)])
Operaciones.add_command(label = "Intersección A, B",command=lambda:[dosMat(10)])
Operaciones.add_command(label = "Diferencia A, B",command=lambda:[dosMat(11)])
Operaciones.add_command(label = "Diferencia simétrica A, B",command=lambda:[dosMat(12)])

#Reportes
Reportes = Menu(Barra)
Reportes.config(bg = "#E74C3C",fg = "white")
Reportes.add_command(label = "Reporte HTML",command=reporte)

#Ayuda
Ayuda = Menu(Barra)
Ayuda.config(bg = "#E74C3C",fg = "white")
Ayuda.add_command(label = "Información del estudiante",command=datosEstudiante)
Ayuda.add_command(label = "Documentación del programa",command=Docu)

Barra.add_cascade(label = "Cargar archivo", menu = CargarArchivo)
Barra.add_cascade(label = "Operaciones", menu = Operaciones)
Barra.add_cascade(label = "Reportes", menu = Reportes)
Barra.add_cascade(label = "Ayuda", menu = Ayuda)

Ventana.config(menu = Barra)
Ventana.mainloop()


from flask import render_template, request, redirect, flash, url_for, Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, Integer, String,  create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base    #雖然沒有import pymysql 但是還是要裝喔!

Base = declarative_base()
engine = create_engine('mysql+pymysql://root:root@localhost:3306/ques_data') # mysql+pymysql://帳號:密碼@localhost:3306/資料庫

app = Flask(__name__)
app.secret_key = "super secret key"
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root@localhost:3306/ques_data"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)

class USER(Base):
    __tablename__ = 'user2' #這邊是要連線的資料庫名稱

    #id = Column(String(10), primary_key=True, autoincrement=True)
    username = Column(String(10), nullable=False)
    email = Column(String(120), primary_key=True, nullable=False)
    gender = Column(String(3), default=None)
    age = Column(String(3), default=None)
    height = Column(Integer, default=None)
    weight = Column(Integer, default=None)
    disliked = Column(String(120), default=False)
    health = Column(String(3), default=None)
    fried = Column(String(3), default=None)
    vegetable = Column(String(3), default=None)
    activity = Column(String(3), default=None)

    def __init__(self, username, email, gender, age, height, weight, disliked, health, fried, vegetable, activity):
        self.username = username
        self.email = email
        self.gender = gender
        self.age = age
        self.height = height
        self.weight = weight
        self.disliked = disliked
        self.health = health
        self.fried = fried
        self.vegetable = vegetable
        self.activity = activity

@app.route('/', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template('Questionnaire.html')

    elif request.method == 'POST':
        try:
            username = request.form['username']
            email = request.form['email']
            gender = request.form['gender']
            age = request.form['age']
            height = request.form['height']
            weight = request.form['weight']
            disliked = request.form['disliked']
            health = request.form['health']
            fried = request.form['fried']
            vegetable = request.form['vegetable']
            activity = request.form['activity']

            Session = sessionmaker(bind=engine)
            session = Session()
            ed_user = USER(username = username, email = email, gender = gender, age = age, height = height, weight = weight, disliked = disliked, health = health, fried = fried, vegetable = vegetable, activity = activity)
            session.add(ed_user)
            session.commit()
            session.close()
            flash('Item Created.')
            return render_template('End_screen.html')

        except:
            flash('Invalid input.')
            return redirect(url_for('register'))

if __name__ == '__main__':
    app.debug = True
    app.run()


from flask import jsonify, current_app
from cenotes_lib.exceptions import InvalidUsage

def craft_response(enote, error, key, dkey, payload, plaintext, success):
    return {"success": success if not error else False,
            "error": error,
            "key": key,
            "duress_key": dkey,
            "plaintext": plaintext,
            "payload": payload,
            "expiration_date": enote.iso_expiration_date if enote else "",
            "max_visits": enote.max_visits if enote else ""}

def craft_json_response(success=True, error="", enote=None,
                        plaintext="", key="", payload="", dkey=""):

    return jsonify(
        craft_response(enote, error, key, dkey, payload, plaintext, success))

def get_request_params(request_params):
    try:
        return CENParams(**request_params)
    except TypeError:
        raise InvalidUsage("Wrong format of parameters given. Could not parse")

class CENParams(object):
    def __init__(self, plaintext="", key=None, expiration_date=None,
                 visits_count=None, max_visits=None, no_store=False,
                 payload=None, algorithm=None, hardness=None,
                 **kwargs):
        self.plaintext = plaintext
        self.key = key
        self.payload = payload
        self.expiration_date = expiration_date
        self.visits_count = visits_count
        self.max_visits = max_visits
        self.no_store = no_store
        self.algorithm, self.hardness = self.enforce_correct_encr_options(
            algorithm, hardness)

    @staticmethod
    def enforce_correct_encr_options(algorithm, hardness):
        supported = current_app.config["SUPPORTED_ALGORITHM_PARAMS"]
        fallback = current_app.config["FALLBACK_ALGORITHM_PARAMS"]

        matched_algorithm = (algorithm if algorithm in supported.keys()
                             else fallback["algorithm"])

        if hardness not in supported[matched_algorithm]["hardness"]:
            return tuple(map(
                lambda x: current_app.config["FALLBACK_ALGORITHM_PARAMS"][x],
                ("algorithm", "hardness")))
        else:
            return matched_algorithm, hardness


import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time

# 화면 스크롤(#1)
def drop_down():
    '''执行页面滚动操作'''  # javascript
    for x in range(1, 30, 4):  # 在你不断地下拉过程中,页面高度会变
        time.sleep(1)
        j = x / 9
        # document.documentElement.scrollTop 指定滚动条的位置
        # document.documentElement.scrollHeight 获取浏览器页面的最大高度
        js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
        browser.execute_script(js)

browser = webdriver.Chrome('D:\Downloads\coding\chromedriver.exe')
#브라우저 최대화
# browser.maximize_window()

# 페이지 이동
url = "https://play.google.com/store/books/collection/cluster?clp=sgIoCiAKGnByb21vdGlvbl9lYm9va190b3BzZWxsaW5nEEQYASIECAUILA%3D%3D:S:ANO1ljLtPtQ&gsr=CiuyAigKIAoacHJvbW90aW9uX2Vib29rX3RvcHNlbGxpbmcQRBgBIgQIBQgs:S:ANO1ljJFgfM"
browser.get(url)
time.sleep(3)
drop_down()   #화면 스크롤(#1)

# # 화면 스크롤(#2)
# interval = 2    # 2초에 한번씩 스크롤 내림

# # # 지정 위치로 스크롤 내리기
# # # 모니터(해상도) 높이인 2160 위치로 스크롤 내리기
# # browser.execute_script("window.scrollTo(0,1080)")   # 1920 x 1080
# # browser.execute_script("window.scrollTo(0,2160)")   # 3840 x 2160

# # 현재 문서 높이를 가져와서 저장
# prev_height = browser.execute_script("return document.body.scrollHeight")

# # 반복 수행
# while True:
#     #스크롤을 가장 아래로 내림
#     browser.execute_script("window.scrollTo(0,document.body.scrollHeight)")

#     # 페이지 로딩 대기
#     time.sleep(interval)

#     # 현재 문서 높이를 가져와서 저장
#     curr_height = browser.execute_script("return document.body.scrollHeight")
#     if curr_height == prev_height:
#         break
#     prev_height=curr_height

print("스크롤 완료")

soup = BeautifulSoup(browser.page_source,"lxml")

movies = soup.find_all("div",attrs={"class":["Vpfmgd"]})
# print(len(movies))
# print(movies)

# 타이틀 가져오기
for movie in movies:
    title = movie.find("div",attrs={"class":"WsMG1c nnK0zc"}).get_text()
    # print(title)

    # 할인 전 가격
    original_price = movie.find("span",attrs={"class":"SUZt4c djCuy"})
    if original_price:
        original_price = original_price.get_text()
    else:
        # print(title,"<할인되지 않은 영화 제외>")
        continue

    # 할인 후 가격
    price = movie.find("span",attrs={"class":"VfPpfd ZdBevf i5DZme"}).get_text()

    # 링크
    link = movie.find("a",attrs={"class":"JC71ub"})["href"]
    # 올바른 링크: https://play.google.com/ + link

    print(f"제목:{title}")
    print(f"할인 전 금액:{original_price}")
    print(f"할인 후 금액:{price}")
    print("링크:","https://play.google.com" + link)
    print("-" *120)


# Transportation Cipher

# original: this_is_a_secret_message_that_i_want_to_transmit
# encrypted version: hsi__ertmsaeta__att_rnmtti_sasce_esg_htiwn_otasi

def scramble2Encrypt(plainText):
    evenChars = ""
    oddChars = ""
    charCount = 0
    for ch in plainText:
        if charCount % 2 == 0:
            evenChars = evenChars + ch
        else:
            oddChars = oddChars + ch
        charCount = charCount + 1
    cipherText = oddChars + evenChars
    return cipherText

def scramble2Decrypt(cipherText):
    halfLength = lent(cipherText) // 2
    evenChars = cipherText[halfLength:]
    oddchars = cipherText[:halfLength]
    plainText = ""

    for i in range(halfLength):
        plainText = plainText + evenChars[i]
        plainText = plainText + oddChars[i]

        if len(oddChars) < len(evenChars):
            plainText = plainText + evenChars[-1]

        return plainText

# write a stripSpace(text) function here:

def encryptMessage():
    msg = input("Enter the message to encrypt: ")
    cipherText = scramble2Encrypt(msg)
    print("The encrypted message is:", cipherText)

# write a ceaserEncrypt(plainText, shift)

def encrypt(text,s):
    result = ""
    # transverse the plain text
    for i in range(len(text)):
        char = text[i]
        # encrypt uppercase charecters in plain text
        if (char.isupper()):
            result += chr((ord(char) + s-65) % 26 + 65)
        # Encrypt lowercase characters in plain text
        else:
            result += chr((ord(char) + s - 97) % 26 + 97)
        return result
# Time to see if it works...
text = "I HOPE IT WORKS"
s = 4

print("plain Text : ") + text
print("shift pattern : ") + str(s)
print ("cipher: ") + encrypt(text,s)

# write a ceaserDecrypter(cipherText, shift)

Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

for key in range(len(letters)):
    translated = ''
    for symbol in message:
        if symbol in letters:
            num = letters.find(symbol)
            num = num - key
            if num < 0:
                num = num + len(letters)
            translated = translated + letters[num]
        else:
            translated = translated + symbol


from typing import Any, Callable

from casadi import MX, SX, vertcat

from ..dynamics.ode_solver import OdeSolver
from ..misc.enums import ControlType, PhaseDynamics
from ..misc.mapping import BiMapping
from ..optimization.non_linear_program import NonLinearProgram
from ..optimization.optimization_variable import OptimizationVariableList, OptimizationVariable

class PenaltyController:
    """
    A placeholder for the required elements to compute a penalty (all time)
    For most of the part, PenaltyController will behave like NLP with the major difference that it will always
    return the states and controls form the current node_index (instead of all of them). If for some reason,
    one must access specific node that is not the current node_index, they can directly access the _nlp.
    Please note that this will likely result in free variables, which can be a pain to deal with...
    """

    def __init__(
        self,
        ocp,
        nlp: NonLinearProgram,
        t: list,
        x: list,
        u: list,
        x_scaled: list,
        u_scaled: list,
        p: MX | SX | list,
        s: list,
        s_scaled: list,
        node_index: int = None,
    ):
        """
        Parameters
        ----------
        ocp: OptimalControlProgram
            A reference to the ocp
        nlp: NonLinearProgram
            A reference to the current phase of the ocp
        t: list
            Time indices, maximum value being the number of shooting point + 1
        x: list
            References to the state variables
        u: list
            References to the control variables
        x_scaled: list
            References to the scaled state variables
        u_scaled: list
            References to the scaled control variables
        p: MX | SX | list
            References to the parameter variables
        s: list
            References to the stochastic variables
        s_scaled: list
            References to the scaled stochastic variables
        node_index: int
            Current node index if nlp.phase_dynamics is SHARED_DURING_THE_PHASE,
            then node_index is expected to be set to 0
        """

        self._ocp: Any = ocp
        self._nlp: NonLinearProgram = nlp
        self.t = t
        self.x = x
        self.u = u
        self.x_scaled = x_scaled
        self.u_scaled = u_scaled
        self.s = s
        self.s_scaled = s_scaled
        self.p = vertcat(p) if p is not None else p
        self.node_index = node_index
        self.cx_index_to_get = 0

    def __len__(self):
        return len(self.t)

    @property
    def ocp(self):
        return self._ocp

    @property
    def get_nlp(self):
        """
        This method returns the underlying nlp. Please note that acting directly with the nlp is not want you should do.
        Unless you see no way to access what you need otherwise, we strongly suggest that you use the normal path
        """
        return self._nlp

    @property
    def cx(self) -> MX | SX | Callable:
        return self._nlp.cx

    @property
    def to_casadi_func(self) -> Callable:
        return self._nlp.to_casadi_func

    @property
    def control_type(self) -> ControlType:
        return self._nlp.control_type

    @property
    def ode_solver(self) -> OdeSolver:
        return self._nlp.ode_solver

    @property
    def phase_idx(self) -> int:
        return self._nlp.phase_idx

    @property
    def ns(self) -> int:
        return self._nlp.ns

    @property
    def tf(self) -> int:
        return self._nlp.tf

    @property
    def mx_to_cx(self):
        return self._nlp.mx_to_cx

    @property
    def model(self):
        return self._nlp.model

    @property
    def time(self) -> OptimizationVariable:
        """
        Return the time associated with the current node index

        Returns
        -------
        The time at node node_index
        """

        tp = OptimizationVariableList(self._nlp.cx, self._nlp.phase_dynamics == PhaseDynamics.SHARED_DURING_THE_PHASE)
        tp.append(
            "time",
            mx=self._nlp.time_mx,
            cx=[self._nlp.time_cx, self._nlp.time_cx, self._nlp.time_cx],
            bimapping=BiMapping(to_second=[0], to_first=[0]),
        )
        return tp["time"]

    @property
    def states(self) -> OptimizationVariableList:
        """
        Return the states associated with the current node index

        Returns
        -------
        The states at node node_index
        """
        self._nlp.states.node_index = self.node_index
        out = self._nlp.states.unscaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def controls(self) -> OptimizationVariableList:
        """
        Return the controls associated with the current node index

        Returns
        -------
        The controls at node node_index
        """
        self._nlp.controls.node_index = self.node_index
        out = self._nlp.controls.unscaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def states_dot(self) -> OptimizationVariableList:
        """
        Return the states_dot associated with the current node index

        Returns
        -------
        The states_dot at node node_index
        """
        self._nlp.states_dot.node_index = self.node_index
        out = self._nlp.states_dot.unscaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def stochastic_variables(self) -> OptimizationVariableList:
        """
        Return the stochastic_variables associated with the current node index
        Returns
        -------
        The stochastic_variables at node node_index
        """
        # TODO: This variables should be renamed to "algebraic"
        self._nlp.stochastic_variables.node_index = self.node_index
        out = self._nlp.stochastic_variables.unscaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def integrated_values(self) -> OptimizationVariableList:
        """
        Return the values associated with the current node index
        Returns
        -------
        The integrated_values at node node_index
        """
        self._nlp.integrated_values.node_index = self.node_index
        out = self._nlp.integrated_values
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def integrate(self):
        return self._nlp.dynamics[self.node_index]

    def integrate_extra_dynamics(self, dynamics_index):
        return self._nlp.extra_dynamics[dynamics_index][self.node_index]

    @property
    def dynamics(self):
        return self._nlp.dynamics_func[0]

    def extra_dynamics(self, dynamics_index):
        # +1 - index so "integrate_extra_dynamics" and "extra_dynamics" share the same index.
        # This is a hack which should be dealt properly at some point
        return self._nlp.dynamics_func[dynamics_index + 1]

    @property
    def states_scaled(self) -> OptimizationVariableList:
        """
        Return the scaled states associated with the current node index.

        Warning: Most of the time, the user does not want that states but the normal `states`, that said, it can
        sometime be useful for very limited number of use case.

        Returns
        -------
        The scaled states at node node_index
        """
        self._nlp.states.node_index = self.node_index
        out = self._nlp.states.scaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def controls_scaled(self) -> OptimizationVariableList:
        """
        Return the scaled controls associated with the current node index.

        Warning: Most of the time, the user does not want that controls but the normal `controls`, that said, it can
        sometime be useful for very limited number of use case.

        Returns
        -------
        The scaled controls at node node_index
        """
        self._nlp.controls.node_index = self.node_index
        out = self._nlp.controls.scaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def states_dot_scaled(self) -> OptimizationVariableList:
        """
        Return the scaled states_dot associated with the current node index.

        Warning: Most of the time, the user does not want that states but the normal `states_dot`, that said, it can
        sometime be useful for very limited number of use case.

        Returns
        -------
        The scaled states_dot at node node_index
        """
        self._nlp.states_dot.node_index = self.node_index

        out = self._nlp.states_dot.scaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def stochastic_variables_scaled(self) -> OptimizationVariableList:
        """
        Return the scaled stochastic variables associated with the current node index.

        Warning: Most of the time, the user does not want that stochastic variables but the normal
        `stochastic_variables`, that said, it can sometime be useful for very limited number of use case.

        Returns
        -------
        The scaled stochastic variables at node node_index
        """
        self._nlp.stochastic_variables.node_index = self.node_index
        out = self._nlp.stochastic_variables.scaled
        out.current_cx_to_get = self.cx_index_to_get
        return out

    @property
    def parameters(self) -> OptimizationVariableList:
        """
        Return the parameters

        Returns
        -------
        The parameters
        """
        return self._nlp.parameters

    @property
    def parameters_scaled(self) -> OptimizationVariableList:
        """
        Return the scaled parameters

        Warning: Most of the time, the user does not want that parameters but the normal `parameters`, that said, it can
        sometime be useful for very limited number of use case.

        Returns
        -------
        The scaled parameters
        """
        return self._nlp.parameters.scaled

    def get_time_parameter_idx(self):
        time_idx = None
        for i in range(self.parameters.cx.shape[0]):
            param_name = self.parameters.cx[i].name()
            if param_name == "time_phase_" + str(self.phase_idx):
                time_idx = self.phase_idx
        if time_idx is None:
            raise RuntimeError(
                f"Time penalty can't be established since the {self.phase_idx}th phase has no time parameter. "
                f"\nTime parameter can be added with : "
                f"\nobjective_functions.add(ObjectiveFcn.[Mayer or Lagrange].MINIMIZE_TIME) or "
                f"\nwith constraints.add(ConstraintFcn.TIME_CONSTRAINT)."
            )
        return time_idx


from room import Room
from character import Character,Enemy,Friend

kitchen = Room("Kitchen")
kitchen.set_description("A dank and dirty room buzzing with flies.")

dining_hall = Room("Dining Hall")
dining_hall.set_description("A large room with ornate decorations.")

ballroom = Room("Ballroom")
ballroom.set_description("A vast room with a shiny wooden floor.")

# Add an enemy and it's weakness to defeat it
dave = Enemy("Dave","A bad, very smelly Zombie")
dave.set_weakness("cheese")
# Add some conversation for Dave when talked to
dave.set_conversation("Argh, me eat your brains!")

# Add a friend and it's feelings
kati = Friend("Kati","A friendly skeleton")
kati.set_feelings("I'm very happy today!")
# Add some conversation for Kati when talked to
kati.set_conversation("Do you need a hug today?")

kitchen.link_room(dining_hall, "south")
dining_hall.link_room(kitchen, "north")
dining_hall.link_room(ballroom, "west")
ballroom.link_room(dining_hall, "east")

# Add characters to rooms
dining_hall.set_character(dave)
ballroom.set_character(kati)

# Testing the get_details() method
# dining_hall.get_details()
# kitchen.get_details()
# ballroom.get_details()

current_room = kitchen

dead = False

while dead != True:
	print("\n")
	current_room.get_details()

	inhabitant = current_room.get_character()

	if inhabitant is not None:
		inhabitant.describe()

	command = input("> ")

	if command in ["east","west","north","south"]:
		# move in that direction
		current_room = current_room.move(command)
	elif command == "talk":
		# talk with the inhabitant - check if one is there or not
		if current_room.get_character() is not None:
			inhabitant.talk()
		else:
			print("There is no one here to talk with!")
	elif command == "fight":
		if current_room.get_character() is not None:
			print("What will you fight with?")
			fight_with = input()
			# Try to fight
			if inhabitant.fight(fight_with) == True:
				# What happens if you win
				print("You survived!")
			else:
				# What happens if you lose
				print("Game Over!")
				dead = True
		else:
			print("This is no one here to fight!")


"""  ----------------------------顯示包包內物品--------------------------------------- """
def DisplayInventory(Inventory):
    print("Inventory:")
    item_total = 0
    for k,v in Inventory.items():
        print(k ,end=' ')
        print(v)
        item_total = item_total + int(v)
    print("Total number of items: " + str(item_total))

Backpack = {'repe':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
DisplayInventory(Backpack)

print ("------------------------------分隔線----------------------------------------")

""" ----------------------------增加包包內物品---------------------------------------"""
def AddToInventory(Inventory, AddedItems):
    for x in range(5):
        if AddedItems[x] in Inventory.keys():
            Inventory[AddedItems[x]]=Inventory[AddedItems[x]]+1
        else:
            AddedItems[x]={AddedItems[x]:1}
            Inventory.update(AddedItems[x])

inv = {'gold coin': 42, 'rope': 1}

DragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin','ruby']

ivn = AddToInventory(inv, DragonLoot)
DisplayInventory(inv)


import random

play = True

while (play == True):
  win = False
  num = random.randint(1, 10)
  attemps = 5

  while (attemps > 0):
      ask = int(input("guess a number between 1 and 10:"))

      if (ask == num):
         win = True
         break
      else:
            print("wrong, try agian")
            win = False
            attemps -= 1
            print(f"you have {attemps} attemps left")
  if(win == True):
    print("you've got it")
  else:
    print("you've lost")
  ask2 = input("do you want to play again? ")
  if(ask2 == ("no")):
    break
  elif():
    play = True


import heapq
import sys

input = sys.stdin.readline

def dijkstra_heap(s,edge,n):
    #始点sから各頂点への最短距離
    d = [float("inf")] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

def main():
    N = int(input())
    edge = [[] for i in range(N)]
    for i in range(N-1):
        u, v, w = map(int, input().split())
        u -= 1
        v -= 1
        edge[u].append([w,v])
        edge[v].append([w,u])
    d = dijkstra_heap(0,edge,N)
    for i in range(N):
        if d[i] % 2 == 0:
            print(0)
        else:
            print(1)

if __name__ == "__main__":
    main()


import os
import unittest

from maya import cmds
from maya import standalone

from pxr import Usd

import fixturesUtils

def write_usd_source_file(out_file):
    stage = Usd.Stage.CreateNew(out_file)

def build_skel_scene(out_file):
    cmds.file(f=1, new=1)
    cmds.createNode('transform', name='group')
    cmds.joint()
    cmds.joint(p=(0.0, 2.154, 0.0,))

    cmds.select(cl=1)
    cmds.polyPlane(sh=1, sw=1)
    cmds.parent('pPlane1', 'group')
    cmds.skinCluster('joint1', 'pPlane1')

    cmds.setKeyframe('joint1.rx', 'joint1.rz', v=0.0, t=[1])
    cmds.setKeyframe('joint1.rx', 'joint1.rz', v=180.0, t=[2])

    cmds.setKeyframe('joint1.ry', v=-85.968, t=[1])
    cmds.setKeyframe('joint1.ry', v=-85.127, t=[2])

    cmds.mayaUSDExport(file=out_file, skl='auto', skn='auto', fr=[1,2])

def build_xform_scene(out_file):
    cmds.file(f=1, new=1)
    cmds.polyCube()

    cmds.setKeyframe('pCube1.rx', 'pCube1.rz', v=0.0, t=[1])
    cmds.setKeyframe('pCube1.rx', 'pCube1.rz', v=180.0, t=[2])

    cmds.setKeyframe('pCube1.ry', v=-85.968, t=[1])
    cmds.setKeyframe('pCube1.ry', v=-85.127, t=[2])

    cmds.mayaUSDExport(file=out_file, fr=[1,2])

class testUsdImportEulerFilter(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        inputPath = fixturesUtils.setUpClass(__file__)

        tempTestPath = os.environ.get('MAYA_APP_DIR')
        cls.skel_file = os.path.join(tempTestPath, "UsdImportEulerFilterTest", "UsdImportEulerFilterTest_skel.usda")

        build_skel_scene(cls.skel_file)

        cls.xform_file = os.path.join(tempTestPath, "UsdImportEulerFilterTest", "UsdImportEulerFilterTest_xform.usda")
        build_xform_scene(cls.xform_file)

    def test_skel_rotation_fail(self):
        """The original behaviour should not correct euler angles on import"""
        cmds.file(f=1, new=1)
        cmds.mayaUSDImport(file=self.skel_file, ani=1)

        values =  cmds.keyframe('joint1.rx', q=1, vc=1)
        self.assertNotAlmostEqual(0.0, values[-1])

    def test_xform_rotation_fail(self):
        """The original behaviour should not correct euler angles on import"""
        cmds.file(f=1, new=1)
        cmds.mayaUSDImport(file=self.xform_file, ani=1)

        values =  cmds.keyframe('pCube1.rx', q=1, vc=1)
        self.assertNotAlmostEqual(0.0, values[-1])

    def test_skel_rotation(self):
        """Test that the channels on the imported joints have been euler filtered"""
        cmds.file(f=1, new=1)
        cmds.mayaUSDImport(file=self.skel_file, ani=1, aef=1)

        values =  cmds.keyframe('joint1.rx', q=1, vc=1)
        self.assertAlmostEqual(0.0, values[-1])

    def test_xform_rotation(self):
        """Test that the channels on the imported transforms have been euler filtered"""
        cmds.file(f=1, new=1)
        cmds.mayaUSDImport(file=self.xform_file, ani=1, aef=1)

        values =  cmds.keyframe('pCube1.rx', q=1, vc=1)
        self.assertAlmostEqual(0.0, values[-1])

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


#!/usr/bin/env python
import dyna
import pygame
import time
import rospy
from std_msgs.msg import String
import geometry_msgs.msg
import time
import sys
import os

import tf
import math
import TXY as formula
from pid import pid

pygame.init()
pygame.font.init()

width, height = 64*10, 64*8
screen=pygame.display.set_mode((width, height))
screen.fill((255,255,255))

mot = dyna.motors()
yaw_pid = pid(86.05,0.15,28)
# yaw_pid = pid(50,0.05,20)

speed = 250
caps = False
freez_time = 1
error_correction_time = 0.25 #1.4 mm

is_pid = False
yaw = 0

yaw_setpoint = -20

def read_position(data):
    global yaw
    (roll, eu_pitch, yaw) = tf.transformations.euler_from_quaternion(
        [data.pose.orientation.x,
         data.pose.orientation.y,
         data.pose.orientation.z,
         data.pose.orientation.w]
          )
    print(radtodeg(yaw))

def radtodeg(data):
    return data*57.2958

rospy.init_node('farzamsdick_controller', anonymous=False)

rospy.Subscriber("/aruco_single/pose", geometry_msgs.msg.PoseStamped, read_position)
pub = rospy.Publisher('chatter', String, queue_size=10)

while 1:

    for event in pygame.event.get():
        # check if the event is the X button
        if event.type == pygame.QUIT:
            # if it is quit the game
            pygame.quit()
            exit(0)
        if event.type == pygame.KEYDOWN:
            if event.key==pygame.K_UP:
                mot.move(4,0,speed,speed,0)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_DOWN:
                mot.move(4,speed,0,0,speed)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_RIGHT:
                mot.move(4,speed,0,speed,0)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_LEFT:
                mot.move(4,0,speed,0,speed)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_KP8:
                mot.move(4,0,-speed,-speed,0)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_KP2:
                mot.move(4,-speed,0,0,-speed)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_KP6:
                mot.move(4,-speed,0,-speed,0)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_KP4:
                mot.move(4,0,-speed,0,-speed)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_KP_PLUS:
                mot.move(4,-speed,-speed,-speed,-speed)
            elif event.key==pygame.K_KP_MINUS:
                mot.move(4,speed,speed,speed,speed)
            elif event.key==pygame.K_CAPSLOCK:
                if caps == False: caps = True
                elif caps == True: caps = False

            elif event.key==pygame.K_w:
                mot.move(4,-speed,speed,speed,-speed)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_s:
                mot.move(4,speed,-speed,-speed,speed)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_d:
                mot.move(4,speed,-speed,speed,-speed)
                if caps: time.sleep(freez_time)
            elif event.key==pygame.K_a:
                mot.move(4,-speed,speed,-speed,speed)
                if caps: time.sleep(freez_time)

            elif event.key==pygame.K_h:
                mot.home()

            elif event.key==pygame.K_SPACE:
                if is_pid == False: is_pid = True
                elif is_pid == True: is_pid = False
                yaw_pid.resetI()

            elif event.key==pygame.K_RALT or event.key==pygame.K_LALT:
                mot.move(4,speed,-speed,speed,-speed)
                time.sleep(formula.t_yaw(yaw_setpoint))
                mot.move(4,0,0,0,0)

        if event.type == pygame.KEYUP:
            mot.move(5,0,0,0,0)

    if is_pid:
        pid_speed = yaw_pid.update_pid(yaw_setpoint,radtodeg(yaw))
        mot.move(4,pid_speed,-pid_speed,pid_speed,-pid_speed)


import re
import random

def get_word():
    words = ['Charlie', 'Woodstock', 'Snoopy', 'Lucy', 'Linus',
             'Schroeder', 'Patty', 'Sally', 'Marcie']
    return random.choice(words).upper()

def green_glass_door_1():
    word = get_word()
    prev_letter = ''
    for letter in word:
        letter = letter.upper()
        if letter == prev_letter:
            return True
        prev_letter = letter
    return False

def green_glass_door_2():
    word = get_word()
    pattern = re.compile(r'(.)\1')
    return pattern.search(word)


#!/usr/bin/env python
# coding: utf-8

# In[ ]:

# In[ ]:

# In[ ]:

# In[6]:

#Importing Necessary Libraires
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

# Load pre-trained model
model = joblib.load('model.joblib')

vectorizer = joblib.load('vectorizer.joblib')

# In[2]:

#Define a function to clean the tweet
def clean_tweet(tweet):
    # Remove URLs, mentions, and hashtags
    tweet = re.sub(r"http\S+", "", tweet)
    tweet = re.sub(r"@[^\s]+[\s]?", "", tweet)
    tweet = re.sub(r"#([^\s]+[\s]?)+", "", tweet)

    # Remove stopwords and stem the remaining words
    stemmer = PorterStemmer()
    stopwords_english = stopwords.words('english')
    words = nltk.word_tokenize(tweet)
    words = [stemmer.stem(word) for word in words if word not in stopwords_english]

    return " ".join(words)

# In[4]:

#Define streamlit app

def app():
    # Set the title and page icon
    st.set_page_config(page_title='Sentiment Analysis', page_icon=':smiley:')

    # Add a title and subtitle
    st.title('Sentiment Analysis')
    st.write('Enter a tweet below to predict the sentiment.')

    # Add a text input for user input
    tweet_input = st.text_input('Enter a tweet:')
    analyze_button = st.button('Analyze')

    # Check if the user has entered anything
    if tweet_input:
        # Clean the tweet
        cleaned_tweet = clean_tweet(tweet_input)

        # Vectorize the cleaned tweet using your pre-trained vectorizer
        # This step depends on how you vectorized your data during training, so modify it accordingly
        tweet_vectorized = vectorizer.transform([cleaned_tweet])

        # Predict the sentiment of the tweet using your pre-trained model
        sentiment = model.predict(tweet_vectorized)[0]

        # Display the predicted sentiment
        if sentiment == 'positive':
            st.write('The sentiment is positive :smile:')
        elif sentiment == 'negative':
            st.write('The sentiment is negative :disappointed:')
        else:
            st.write('The sentiment is neutral :neutral_face:')

# In[5]:

if __name__ == '__main__':
    app()

# In[ ]:

# In[ ]:


portal = context.getPortalObject()

def isNodeFromLineReceivable(line):
  node_value = line.getSourceValue(portal_type='Account')
  return node_value.getAccountType() == 'asset/receivable'
for line in context.getMovementList(portal.getPortalAccountingMovementTypeList()):
  if isNodeFromLineReceivable(line):
    if not line.hasGroupingReference():
      line.setGroupingReference('FAKEGROUPINGREFERENCE')
      break


from typing import Dict, List, Callable

from autopandas_v2.generators.compilation.ir.arguments import IArg
from autopandas_v2.generators.compilation.ir.signatures import ISignature

class IGenerator:
    def __init__(self, namespace: str, name: str, sig: ISignature,
                 arg_irs: Dict[str, IArg], enum_order: List[str], target: Callable, arity: int,
                 representation: str):

        self.sig = sig
        self.namespace = namespace
        self.name = name
        self.sig = sig
        self.arg_irs = arg_irs
        self.enum_order = enum_order
        self.target = target
        self.arity = arity
        self.representation = representation


from __future__ import unicode_literals

import logging

from asgiref.inmemory import ChannelLayer
from django.core.management import CommandError, call_command
from channels.staticfiles import StaticFilesConsumer
from django.test import TestCase, mock
from six import StringIO

from channels.management.commands import runserver

class FakeChannelLayer(ChannelLayer):
    '''
    Dummy class to bypass the 'inmemory' string check.
    '''
    pass

@mock.patch('channels.management.commands.runworker.Worker')
class RunWorkerTests(TestCase):

    def setUp(self):
        import channels.log
        self.stream = StringIO()
        channels.log.handler = logging.StreamHandler(self.stream)

    def test_runworker_no_local_only(self, mock_worker):
        """
        Runworker should fail with the default "inmemory" worker.
        """
        with self.assertRaises(CommandError):
            call_command('runworker')

    def test_debug(self, mock_worker):
        """
        Test that the StaticFilesConsumer is used in debug mode.
        """
        with self.settings(DEBUG=True, STATIC_URL='/static/'):
            # Use 'fake_channel' that bypasses the 'inmemory' check
            call_command('runworker', '--layer', 'fake_channel')
            mock_worker.assert_called_with(
                only_channels=None, exclude_channels=None, callback=None, channel_layer=mock.ANY)

            channel_layer = mock_worker.call_args[1]['channel_layer']
            static_consumer = channel_layer.router.root.routing[0].consumer
            self.assertIsInstance(static_consumer, StaticFilesConsumer)

    def test_runworker(self, mock_worker):
        # Use 'fake_channel' that bypasses the 'inmemory' check
        call_command('runworker', '--layer', 'fake_channel')
        mock_worker.assert_called_with(callback=None,
                                       only_channels=None,
                                       channel_layer=mock.ANY,
                                       exclude_channels=None)

    def test_runworker_verbose(self, mocked_worker):
        # Use 'fake_channel' that bypasses the 'inmemory' check
        call_command('runworker', '--layer',
                     'fake_channel', '--verbosity', '2')

        # Verify the callback is set
        mocked_worker.assert_called_with(callback=mock.ANY,
                                         only_channels=None,
                                         channel_layer=mock.ANY,
                                         exclude_channels=None)

class RunServerTests(TestCase):

    def setUp(self):
        import channels.log
        self.stream = StringIO()
        # Capture the logging of the channels moduel to match against the
        # output.
        channels.log.handler = logging.StreamHandler(self.stream)

    @mock.patch('channels.management.commands.runserver.sys.stdout', new_callable=StringIO)
    @mock.patch('channels.management.commands.runserver.Server')
    @mock.patch('channels.management.commands.runworker.Worker')
    def test_runserver_basic(self, mocked_worker, mocked_server, mock_stdout):
        # Django's autoreload util uses threads and this is not needed
        # in the test envirionment.
        # See:
        # https://github.com/django/django/blob/master/django/core/management/commands/runserver.py#L105
        call_command('runserver', '--noreload')
        mocked_server.assert_called_with(port=8000, signal_handlers=True, http_timeout=60,
                                         host='127.0.0.1', action_logger=mock.ANY, channel_layer=mock.ANY)

    @mock.patch('channels.management.commands.runserver.sys.stdout', new_callable=StringIO)
    @mock.patch('channels.management.commands.runserver.Server')
    @mock.patch('channels.management.commands.runworker.Worker')
    def test_runserver_debug(self, mocked_worker, mocked_server, mock_stdout):
        """
        Test that the server runs with `DEBUG=True`.
        """
        # Debug requires the static url is set.
        with self.settings(DEBUG=True, STATIC_URL='/static/'):
            call_command('runserver', '--noreload')
            mocked_server.assert_called_with(port=8000, signal_handlers=True, http_timeout=60,
                                             host='127.0.0.1', action_logger=mock.ANY, channel_layer=mock.ANY)

            call_command('runserver', '--noreload', 'localhost:8001')
            mocked_server.assert_called_with(port=8001, signal_handlers=True, http_timeout=60,
                                             host='localhost', action_logger=mock.ANY, channel_layer=mock.ANY)

        self.assertFalse(mocked_worker.called,
                         "The worker should not be called with '--noworker'")

    @mock.patch('channels.management.commands.runserver.sys.stdout', new_callable=StringIO)
    @mock.patch('channels.management.commands.runserver.Server')
    @mock.patch('channels.management.commands.runworker.Worker')
    def test_runserver_noworker(self, mocked_worker, mocked_server, mock_stdout):
        '''
        Test that the Worker is not called when using the `--noworker` parameter.
        '''
        call_command('runserver', '--noreload', '--noworker')
        mocked_server.assert_called_with(port=8000, signal_handlers=True, http_timeout=60,
                                         host='127.0.0.1', action_logger=mock.ANY, channel_layer=mock.ANY)
        self.assertFalse(mocked_worker.called,
                         "The worker should not be called with '--noworker'")

    @mock.patch('channels.management.commands.runserver.sys.stderr', new_callable=StringIO)
    def test_log_action(self, mocked_stderr):
        cmd = runserver.Command()
        test_actions = [
            (100, 'http', 'complete',
             'HTTP GET /a-path/ 100 [0.12, a-client]'),
            (200, 'http', 'complete',
             'HTTP GET /a-path/ 200 [0.12, a-client]'),
            (300, 'http', 'complete',
             'HTTP GET /a-path/ 300 [0.12, a-client]'),
            (304, 'http', 'complete',
             'HTTP GET /a-path/ 304 [0.12, a-client]'),
            (400, 'http', 'complete',
             'HTTP GET /a-path/ 400 [0.12, a-client]'),
            (404, 'http', 'complete',
             'HTTP GET /a-path/ 404 [0.12, a-client]'),
            (500, 'http', 'complete',
             'HTTP GET /a-path/ 500 [0.12, a-client]'),
            (None, 'websocket', 'connected',
             'WebSocket CONNECT /a-path/ [a-client]'),
            (None, 'websocket', 'disconnected',
             'WebSocket DISCONNECT /a-path/ [a-client]'),
            (None, 'websocket', 'something', ''),  # This shouldn't happen
        ]

        for status_code, protocol, action, output in test_actions:
            details = {'status': status_code,
                       'method': 'GET',
                       'path': '/a-path/',
                       'time_taken': 0.12345,
                       'client': 'a-client'}
            cmd.log_action(protocol, action, details)
            self.assertIn(output, mocked_stderr.getvalue())
            # Clear previous output
            mocked_stderr.truncate(0)