#!/usr/bin/env pybricks-micropython

#  This file is part of hugbug ev3 repository. See <https://github.com/hugbug/ev3>.
#
#  This is a program to use Xbox or PS controller to remotely control the
#  LEGO EV3 Model Rov3r+ MOC-20177 (https://rebrickable.com/mocs/MOC-20177).
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

from pybricks.ev3devices import (Motor)
from pybricks.parameters import (Port, SoundFile, Stop, Direction)
from pybricks import ev3brick as brick
from pybricks.tools import print
import time
import struct
import sys
import random
import uselect

random.seed(0)

# Defining stick dead zone which is a minimum amount of stick movement
# from the center position to start motors.
stick_deadzone = 5  # deadzone 5%

# Max steering angle for steering motor (in degrees).
# It is computed automatically during motor calibratation process.
# Here initialized with default value for debug purposes.
max_steering_angle = 300

# One of these can be disabled if you have connected both gamepads and want to use a particular one.
enable_xbox_detection = True
enable_ps_detection = True

# Constants for gamepad type.
gamepad_xbox = 1
gamepad_ps = 2

# Gamepad state.
gamepad_device = None
gamepad_type = 0 # gamepad_xbox or gamepad_ps
xbox = None # True if Xbox or False if PlayStation

# Constants for gearbox mode.
gearbox_manual = 1
gearbox_auto_sport = 2
gearbox_auto_comfort = 3

# Gearbox mode, initialized to default gearbox mode upon start.
gearbox_mode = gearbox_auto_sport

# Constants for automatic sport gearbox.
# Four gears. For each gear:
#  A) maximum RPM of the gear
#  B) Motor Power to gear up
#  C) RPM to gear up
#  D) gear up when the Motor-Power and RPM both are above B/C for as long seconds
#  E) Motor Power to gear down
#  F) RPM to gear down
#  G) gear down when the Motor-Power or RPM go below E/F for as long seconds
automatic_sport_gearbox = (
    (900, 70, 600, 0.6, 0, 0, 0), # Gear 1
    (900, 80, 650, 0.6, 50, 400, 0.3), # Gear 2
    (870, 90, 700, 0.7, 60, 500, 0.3), # Gear 3
    (820, 110, 10000, 1.0, 70, 550, 0.3)) # Gear 4

# Constants for automatic comfort gearbox.
# Four gears. For each gear:
#  A) maximum RPM of the gear
#  B) Motor Power to gear up
#  C) RPM to gear up
#  D) gear up when the Motor-Power and RPM both are above B/C for as long seconds
#  E) Motor Power to gear down
#  F) RPM to gear down
#  G) gear down when the Motor-Power or RPM go below E/F for as long seconds
#  H) gear up ratio compensation
#  I) gear up compensation time
#  J) gear down ratio compensation
#  K) gear down compensation time
automatic_comfort_gearbox = (
    (900, 70, 500, 0.7, 0, 0, 0, 0.8, 0, 0, 0), # Gear 1, 1:1 ratio
    (900, 80, 550, 1.0, 50, 400, 0.3, 0.8, 1.0, 1.2, 0), # Gear 2, 1:1.67 ratio
    (870, 90, 600, 1.0, 50, 450, 0.3, 0.8, 1.0, 1.2, 0.3), # Gear 3, 1:3 ratio
    (820, 110, 10000, 1.0, 50, 450, 0.3, 0, 0, 1.2, 0.3)) # Gear 4, 1:5 ratio

# Assuming sticks are in the middle and triggers are not pressed when starting
gear = 1 # Current gear (1..4)
power_pos = 0 # Current motor power (controlled by Y-axis of gamepad left stick) (-100..100)
power_bump = 0 # Power bump (controller by right trigger)
power_compensation = 1.0 # Power compensation after switching gears in comfort automatic mode
steering_pos = 0 # Steering position (-100..100)
motors = 2 # Use two motors

# An events read from the virtual device file consists of the following elements:
# long int, long int, unsigned short, unsigned short, long int
gamepad_event_format = 'llHHl'
gamepad_event_size = struct.calcsize(gamepad_event_format)

# Clear program title.
brick.display.clear()
brick.display.text("Rov3r+", (60, 20))

# Declare motors and check their connections.
try:
    first_motor = Motor(Port.A, Direction.COUNTERCLOCKWISE)
    second_motor = Motor(Port.D, Direction.COUNTERCLOCKWISE)
    steering_motor = Motor(Port.B)
    gearbox_motor = Motor(Port.C)
    second_motor.stop(Stop.COAST)
except:
    brick.display.text("Check motor cables", (0, 80))
    brick.sound.file(SoundFile.ERROR_ALARM)
    time.sleep(10)
    sys.exit(1)

def find_gamepad():
    """
    Checks device list by reading content of virtual file "/proc/bus/input/devices"
    looking for gamepad device.
    """
    global gamepad_type
    with open("/proc/bus/input/devices", "r") as fp:
        line = fp.readline()
        while line:
            if enable_xbox_detection and line.startswith("N: Name=") and line.find("Xbox") > -1:
                gamepad_type = gamepad_xbox
            if enable_ps_detection and line.startswith("N: Name=") and line.find("PLAYSTATION") > -1 and line.find("Motion") == -1:
                gamepad_type = gamepad_ps
            if gamepad_type > 0 and line.startswith("H: Handlers="):
                line = line[len("H: Handlers="):]
                pb = line.find("event")
                pe = line.find(" ", pb)
                return line[pb:pe]
            line = fp.readline()
    return None

def transform_stick(value):
    """
    Transforms range 0..max to -100..100, removes deadzone from the range.
    """
    max = 65535 if xbox else 255
    half = int((max + 1) / 2)
    deadzone = int((max + 1) / 100 * stick_deadzone)
    value -= half
    if abs(value) < deadzone:
        value = 0
    elif value > 0:
        value = (value - deadzone - 1) / (half - deadzone) * 100
    else:
        value = (value + deadzone) / (half - deadzone) * 100
    return value

def play_horn():
    """
    Plays a horn sound randomly selected from two available sounds.
    """
    if random.randint(1, 2) == 1:
        brick.sound.file(SoundFile.HORN_1)
    else:
        brick.sound.file(SoundFile.HORN_2)

def play_sound_effect():
    """
    Plays a random sound effect.
    """
    effect = random.randint(1, 4)
    if effect == 1:
        brick.sound.file(SoundFile.AIR_RELEASE)
    elif effect == 2:
        brick.sound.file(SoundFile.AIRBRAKE)
    elif effect == 3:
        brick.sound.file(SoundFile.LASER)
    elif effect == 4:
        brick.sound.file(SoundFile.SONAR)

def calibrate_motors():
    """
    Calibrates gearbox motor: switches to first gear.
    Calibrates steering motor: finds the range by steering full to the left
    and full to the right, then centers the steering.
    """
    global max_steering_angle

    gearbox_motor.run_until_stalled(360, Stop.COAST, 50)
    gearbox_motor.run_angle(100, -20) # unstress the switcher
    gearbox_motor.reset_angle(0)

    steering_motor.run_until_stalled(720, Stop.COAST, 80)
    steering_motor.reset_angle(0)
    steering_motor.run_until_stalled(-720, Stop.COAST, 80)
    max_steering_angle = abs(steering_motor.angle()) / 2
    steering_motor.run_target(720, -max_steering_angle)
    steering_motor.reset_angle(0)
    max_steering_angle *= 0.90  # limit max steering angle a little

def print_help():
    """
    Prints program info and gamepad mapping to the brick display.
    Also prints current gearbox mode in the status line.
    """
    brick.display.clear()
    brick.display.text("Rov3r+", (60, 10))
    brick.display.text(("Xbox" if xbox else "PS") + " gamepad functions:", (0, 30))
    brick.display.text("Left Stick: movement", (0, 45))
    brick.display.text(("RB/LB" if xbox else "R1/L1") + ": gear up/down", (0, 55))
    brick.display.text(("A" if xbox else "X") + ": auto comfort/sport", (0, 65))
    brick.display.text(("B" if xbox else "O") + ": one/two motors", (0, 75))
    brick.display.text(("RT" if xbox else "R2") + ": steer. speed bump", (0, 85))
    brick.display.text(("X" if xbox else "/\\") + ": horn", (0, 95))
    brick.display.text(("Y" if xbox else "[]") + ": sound effect", (0, 105))
    brick.display.text((("manual" if gearbox_mode == gearbox_manual
        else "auto comfort" if gearbox_mode == gearbox_auto_comfort else "auto sport")) +
        ", " + str(motors) + " motor" + ("s" if motors > 1 else ""), (0, 125))

def drive(_power_pos, _power_bump, _power_compensation):
    """
    Sets current power settings for driving motors.
    """
    global power_pos, power_bump, power_compensation
    if _power_pos == None:
        _power_pos = power_pos
    if _power_bump == None:
        _power_bump = power_bump
    if _power_compensation == None:
        _power_compensation = power_compensation
    #print("Drive: ", _power_pos, _power_bump, _power_compensation)
    if power_pos != _power_pos or power_bump != _power_bump or power_compensation != _power_compensation:
        power_pos = _power_pos
        power_bump = _power_bump
        power_compensation = _power_compensation
        propulsion_power = power_pos * (1 + power_bump) * power_compensation
        first_motor.dc(propulsion_power)
        if motors == 2:
            second_motor.dc(propulsion_power)
        else:
            second_motor.stop(Stop.COAST)

def steer(_steering_pos):
    """
    Sets steering position.
    Computes required motor angle and rotates the steering motor there.
    """
    global steering_pos
    if steering_pos != _steering_pos:
        steering_pos = _steering_pos
        steering_angle = - steering_pos * max_steering_angle / 100
        steering_motor.track_target(steering_angle)

def switch_gear(_gear):
    """
    Switches gear of the gearbox.
    Computes required angle of the gearbox motor and rotates it to that position.
    """
    global gear
    if gear != _gear:
        gear = _gear
        gearing_angle = - (gear - 1) * 20 / 12 * 90
        gearbox_motor.track_target(gearing_angle)
        reset_automatic_gearbox()

def select_gearbox_mode(mode):
    """
    Sets current steering mode (automatic comfort, automatic sport or manual).
    Indicates current mode via beeps (one, two or three).
    """
    global gearbox_mode
    if mode != gearbox_mode:
        gearbox_mode = mode
        print_help()
        if gearbox_mode == gearbox_auto_comfort:
            brick.sound.beeps(1)
        elif gearbox_mode == gearbox_auto_sport:
            brick.sound.beeps(2)
        elif gearbox_mode == gearbox_manual:
            brick.sound.beeps(3)

def select_motors(motor_count):
    global motors
    if motors != motor_count:
        motors = motor_count
        print_help()
        brick.sound.beeps(motors)
        # Start or stop second motor.
        # We increase current power a little so that function "drive" see some changes to process.
        drive(power_pos + 1, None, None)

# Variables to hold state of the automatic gearbox.
gear_up_time = 0
gear_down_time = 0
comfort_time = 0
comfort_factor = 0
comfort_duration = 0

def reset_automatic_gearbox():
    """
    Aborts power compensation process and resets power compensation.
    This is for automtic comfort gearbox mode only.
    """
    gear_up_time = 0
    gear_down_time = 0
    power_compensation = 1.0

def automatic_gearbox_control():
    """
    This function is called very often (many times for second) and is active
    only for automatic gearbox modes.
    Checks current power and speed of the driving motors and switches to
    the next or previous gear of the gearbox when necessary.
    For automatic comfort gearbox: decreases motor power after gearing up or
    increases motor power after gearing down, to compensate for changed gear
    ratio in order to prevent jerky linear movement. The motor power is then
    smoothly correctd back to its original value within 0.5-2 seconds.
    """
    global gear_up_time, gear_down_time
    global comfort_time, comfort_factor, comfort_duration

    speed = abs(first_motor.speed())
    current_time = time.time()

    # Did we stop?
    if abs(power_pos) == 0 and speed == 0 and gear > 1:
        #print("Reset gear to", 1)
        switch_gear(1)

    comfort = gearbox_mode == gearbox_auto_comfort
    gearbox = automatic_comfort_gearbox if comfort else automatic_sport_gearbox
    gear_data = gearbox[gear - 1]
    power_compensation_in_progress = abs(power_compensation - 1.0) > 0.01

    # Can we gear up?
    if abs(power_pos) >= gear_data[1] and speed >= gear_data[2] and not power_compensation_in_progress:
        if gear_up_time == 0:
            gear_up_time = current_time
        elif current_time - gear_up_time >= gear_data[3] and gear < len(gearbox):
            # It's time to switch to the next gear
            #print("Gear up to", gear + 1)
            switch_gear(gear + 1)
            if comfort:
                comfort_time = current_time
                comfort_factor = gear_data[7]
                comfort_duration = gear_data[8]
                #print("Compensate drive power", comfort_factor, comfort_duration, comfort_time)
                drive(None, None, comfort_factor)
            gear_up_time = 0
    else:
        gear_up_time = 0

    # Should we gear down?
    if abs(power_pos) <= gear_data[4] or speed <= gear_data[5] and not power_compensation_in_progress:
        if gear_down_time == 0:
            gear_down_time = current_time
        elif current_time - gear_down_time >= gear_data[6] and gear > 1:
            # It's time to switch to the previous gear
            #print("Gear down to", gear - 1)
            switch_gear(gear - 1)
            if comfort:
                comfort_time = current_time
                comfort_factor = gear_data[9]
                comfort_duration = gear_data[10]
                #print("Compensate drive power", comfort_factor, comfort_duration, comfort_time)
                drive(None, None, comfort_factor)
            gear_down_time = 0
    else:
        gear_down_time = 0

    # Comfort gearbox: gradually adjust power factor compensation after switching to a higher gear
    if comfort_time > 0 and current_time > comfort_time:
        duration = current_time - comfort_time
        if duration < comfort_duration:
            if comfort_factor < 1.0:
                # Gear up
                compensation = comfort_factor + (1.0 - comfort_factor) * duration / comfort_duration
            else:
                # Gear down
                compensation = comfort_factor - (comfort_factor - 1.0) * duration / comfort_duration
            #print("Compensate drive power", compensation, comfort_factor, comfort_duration, comfort_time, current_time, duration)
        else:
            #print("Reset drive power")
            compensation = 1.0
            comfort_time = 0
        drive(None, None, compensation)

def process_gamepad_event(device_file):
    """
    Reads events from the gamepad device virtual file and processes them.
    """
    # Read from the gamepad device virtual file
    event = device_file.read(gamepad_event_size)

    (tv_sec, tv_usec, ev_type, code, value) = struct.unpack(gamepad_event_format, event)

    if ev_type == 3 or ev_type == 1:

        if ev_type == 3 and code == 0: # Left Stick Horz. Axis
            steer(transform_stick(value))

        elif ev_type == 3 and code == 1: # Left Stick Vert. Axis
            drive(-transform_stick(value), None, None)

        elif xbox and ev_type == 3 and code == 9: # Xbox Right Trigger
            drive(None, value / 1024, None)

        elif not xbox and ev_type == 3 and code == 5: # PS R2 paddle
            drive(None, value / 256, None)

        elif ev_type == 1 and code == 311 and value == 1: # RB pressed
            switch_gear(min(gear + 1, 4))
            select_gearbox_mode(gearbox_manual)

        elif ev_type == 1 and code == 310 and value == 1: # LB pressed
            switch_gear(max(gear - 1, 1))
            select_gearbox_mode(gearbox_manual)

        elif ev_type == 1 and code == 304 and value == 1: # A pressed
            select_gearbox_mode(gearbox_auto_comfort if gearbox_mode == gearbox_auto_sport else gearbox_auto_sport)

        elif ev_type == 1 and code == 305 and value == 1: # B pressed
            select_motors(2 if motors == 1 else 1)

        elif ev_type == 1 and code == 307 and value == 1: # X pressed
            play_horn()

        elif ev_type == 1 and code == 308 and value == 1: # Y pressed
            play_sound_effect()

# Find the gamepad
gamepad_device = find_gamepad()
xbox = gamepad_type == gamepad_xbox
#print("Gamepad device:", gamepad_device, ", type:", gamepad_type)

if gamepad_device is None:
    brick.display.text("Gamepad not found", (0, 80))
    brick.sound.file(SoundFile.ERROR_ALARM)
    time.sleep(10)
    sys.exit(1)

gamepad_infile_path = "/dev/input/" + gamepad_device
gamepad_infile = open(gamepad_infile_path, "rb")

print_help()

calibrate_motors()

# We use event polling mechanism to read from gamepad virtual device file.
# This allows us to check if there are new data in the file before attempting
# to read from it. As a result the "read from file"-function never blocks
# and we can do some other work when there are no gamepad events.
event_selector = uselect.poll()
event_selector.register(gamepad_infile, uselect.POLLIN)

while True:
    events = event_selector.poll(0)
    if (len(events) > 0 and events[0][1] & uselect.POLLIN):
        process_gamepad_event(gamepad_infile)
    else:
        # This code is executed when there are no gamepad events to proceed.
        # Here we can check sensors or do some other work.
        if gearbox_mode != gearbox_manual:
            automatic_gearbox_control()
        time.sleep(0.010) # sleep a little to reduce CPU load and power consumption

gamepad_infile.close() # will never executed actually, due to endless while loop


# Move all negative numbers to beginning and positive to end with constant extra space
# Difficulty Level : Easy
# Last Updated : 09 Jun, 2021
# An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers.

# Examples :

# Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
# Output: -12 -13 -5 -7 -3 -6 11 6 5

arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
print(arr)
start = 0
end = len(arr)-1
while(start < end):

    while(arr[end] < 0 and end >  start):
        end -= 1
    if(arr[start] < 0):
        arr[start],arr[end] = arr[end],arr[start]
        start += 1
    if(arr[start] >= 0):
        start += 1

print(arr)


"""Producer base-class providing common utilites and functionality"""
import logging
import time
import socket

#from confluent_kafka import avro
from confluent_kafka.admin import AdminClient, NewTopic
from confluent_kafka.avro import AvroProducer

logger = logging.getLogger(__name__)

class Producer:
    """Defines and provides common functionality amongst Producers"""

    # Tracks existing topics across all Producer instances
    existing_topics = set(list())
    client_id = socket.gethostname()

    def __init__(
        self,
        topic_name,
        key_schema,
        value_schema=None,
        num_partitions=1, #single node broker?
        num_replicas=1,
    ):
        """Initializes a Producer object with basic settings"""
        self.topic_name = topic_name
        self.key_schema = key_schema
        self.value_schema = value_schema
        self.num_partitions = num_partitions
        self.num_replicas = num_replicas

        self.broker_properties = {
            "bootstrap.servers": "PLAINTEXT://localhost:9092",
            "schema.registry.url": "http://localhost:8081",
            "client.id": self.client_id
        }

        # If the topic does not already exist, try to create it
        #print(len(self.existing_topics))
        if self._topic_exists(self.topic_name) == False:
            #print(self.topic_name)
            ret = self.create_topic()
            if ret == 1:
                #print(len(self.existing_topics))
                Producer.existing_topics.add(self.topic_name)

        self.producer = AvroProducer(self.broker_properties,
                                     default_key_schema=self.key_schema,
                                     default_value_schema=self.value_schema)

    def _topic_exists(self, topic_name: str) -> bool:
         if topic_name in Producer.existing_topics:
            return True
         return False

    def create_topic(self) -> int:
        """Creates the producer topic if it does not already exist"""
        try:
            client = AdminClient({"bootstrap.servers": self.broker_properties["bootstrap.servers"]})
            topic_metadata = client.list_topics(timeout=200)
            topic_check = self.topic_name in set(t.topic for t in iter(topic_metadata.topics.values()))
            if  topic_check == True:
                 return -1

            futures = client.create_topics(
                [
                    NewTopic(
                        topic=self.topic_name,
                        num_partitions=self.num_partitions,
                        replication_factor=self.num_replicas
                        #config={
                           # "cleanup.policy": "delete",
                          #  "compression.type": "lz4",
                          #  "delete.retention.ms": "2000",
                         #   "file.delete.delay.ms": "2000",
                        #}
                    )
                ]
            )
            status = 1
            for topic, future in futures.items():
                try:
                    future.result()
                    logger.debug("topic created")
                except Exception as e:
                    logger.fatal(f"failed to create topic {self.topic_name}: {e}")
                    status = -1
        except Exception as ex:
            logger.warn(f"Error in create topic {self.topic_name}: {ex}")
            status = -1
        return status

    def time_millis(self) -> int:
        return int(round(time.time() * 1000))

    def close(self):
        """Prepares the producer for exit by cleaning up the producer"""
        if self.producer is not None:
            self.producer.flush()


import tensorflow as tf
from tensorflow import keras

from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder, MinMaxScaler
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
import pickle

import pandas as pd

class PredictingManager:
    def __init__(self):
        self.model = keras.models.load_model("my_keras_model.h5")
        self.num_pipeline = Pipeline([
            ('imputer', SimpleImputer(strategy="mean")),
            ('std_scaler', StandardScaler()),
        ])
        self.num_attribs = ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare']
        self.cat_attribs = ['Sex', 'Embarked']

        filename = '/app/full_pipeline.pkl'
        #filename = 'full_pipeline.pkl'
        with open(filename, 'rb') as f:
            self.full_pipeline = pickle.load(f)

    def do_predict(self,data):
        data = [[data['passengerClass'], data['age'], data['sibSp'], data['parCh'], data['fare'], data['sex'], data['embarked']]]
        df = pd.DataFrame(data, columns=['Pclass', 'Age', 'SibSp', 'Parch', 'Fare','Sex', 'Embarked'])
        print(df.head())
        X_data_prepared = self.full_pipeline.transform(df)
        print(X_data_prepared)
        predicted_class = self.model.predict_classes(X_data_prepared)
        predicted_prob = self.model.predict(X_data_prepared)
        predicted_class_str = str(predicted_class[0][0])
        predicted_prob_str = str(round(predicted_prob[0][0] * 100))
        print(predicted_class_str)
        print(predicted_prob_str)
        predict_data = [predicted_class_str, predicted_prob_str]
        return predict_data


import os
from string import Template

from pyven.reporting.html_utils import HTMLUtils
from pyven.utils.utils import str_to_file, file_to_str
from pyven.reporting.content.content import Content
from pyven.reporting.style import Style

class Properties(Content):
	TEMPLATE = os.path.join(Content.TEMPLATE_DIR, 'properties-template.html')

	def __init__(self, properties=[]):
		super(Properties, self).__init__()
		self.properties = properties
		self.div_style = Style.get().properties['div_style']

	def write(self):
		Properties.generate_template()
		return self.write_properties()

	def write_properties(self):
		result = ''
		if len(self.properties) > 0:
			for property in self.properties:
				result += property.write()
			template = Template(file_to_str(Properties.TEMPLATE))
			result = template.substitute(VALUE=result, DIV_STYLE=self.div_style)
		return result

	@staticmethod
	def generate_template():
		if not os.path.isdir(Content.TEMPLATE_DIR):
			os.makedirs(Content.TEMPLATE_DIR)
		if not os.path.isfile(Properties.TEMPLATE):
			str_to_file(Properties.generate_template_properties(), Properties.TEMPLATE)

	@staticmethod
	def generate_template_properties():
		html_str = HTMLUtils.ltag('div', {'class' : '$DIV_STYLE'})
		try:
			html_str += '$VALUE'
		finally:
			html_str += HTMLUtils.rtag('div')
		return html_str


import tkinter as tk

def solve():
    # get the values from the Entry widgets
    a = int(entry1.get())
    b = int(entry2.get())
    c = int(entry3.get())

    # solve the equation
    x = (b**2 - 4*a*c) / (2*a)

    # display the result
    label4.config(text="Result: " + str(x))

# create the main window
root = tk.Tk()
root.title("Math Problem Solver")

# create the Entry widgets
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
entry3 = tk.Entry(root)

# create the labels
label1 = tk.Label(root, text="a:")
label2 = tk.Label(root, text="b:")
label3 = tk.Label(root, text="c:")
label4 = tk.Label(root, text="")

# place the Entry widgets and labels in the window
entry1.grid(row=0, column=1)
entry2.grid(row=1, column=1)
entry3.grid(row=2, column=1)
label1.grid(row=0, column=0)
label2.grid(row=1, column=0)
label3.grid(row=2, column=0)
label4.grid(row=3, column=0, columnspan=2)

# create the solve button
button = tk.Button(root, text="Solve", command=solve)
button.grid(row=4, column=0, columnspan=2, pady=10)

# start the main loop
root.mainloop()


# Funcionalidad relacionada con el menú

"""
    Autores: Nicolás Olabarría
    Fecha: 9 de Junio de 2021
    Tema: Menú
"""

import pandas as pd

def menu():
    """
    The menu() function asks for a route and stores it in a string variable.
    :return: A list of strings with the routes to the files
    """

    # Mensajes utilizados en el menú
    message_option = '¿Cómo quiere leer las direcciones de los datasets?[man/txt]: '
    message_not_valid = 'Opción no válida. Introdúzcalo de nuevo\n'

    print(
        'Puedes introducir los datos manualmente (man), o si los tienes en un .txt hacerlo de manera automática (txt)')
    option = input(message_option)

    while option.upper() != 'MAN' and option.upper() != 'TXT':
        print(message_not_valid)
        option = input(message_option)

    route = []

    if option.upper() == 'MAN':
        route = lectura_manual()
    elif option.upper() == 'TXT':
        route = lectura_txt()

    return route

def lectura_manual():
    """
    Lectura de las rutas de manera manual.
    :return: Devuelve una lista de rutas introducidas de manera manual.
    """
    message_done = 'Si quiere terminar el proceso escribe "Done"\n'
    message_route = 'Introduzca la dirección del archivo: '
    print(message_done)
    command = input(message_route)

    route = []

    if command.upper() != 'DONE':
        while command.upper() != 'DONE':

            while True:
                try:
                    data = pd.read_csv(command)
                    break
                except FileNotFoundError:
                    print('La dirección no es correcta')
                    command = input(message_route)

            route.append(command)
            command = input(message_route)

    return route

def lectura_txt():
    """
    Función para la lectura de las rutas de manera automática.
    :return: Devuelve una lista de rutas sacadas de un archivo .txt.
    """
    txt_route = input('Introduzca la ruta del archivo: ')
    while True:
        try:
            with open(txt_route, 'r') as route_file:
                route = []
                i = 1
                for line in route_file.readlines():
                    print('Ruta ', i, ':', line)
                    i+=1
                    line = line.replace("\n", "")
                    route.append(line)
            break
        except FileNotFoundError:
            txt_route = input('La ruta no es válida, introdúzcala de nuevo: ')

    return route


import logging
from typing import Optional, Union

from df_engine.core.keywords import TRANSITIONS, RESPONSE
from df_engine.core import Context, Actor
import df_engine.conditions as cnd

logger = logging.getLogger(__name__)

# First of all, to create a dialog agent, we need to create a dialog script.
# Below, `script` is the dialog script.
# A dialog script is a flow dictionary that can contain multiple script .
# Script are needed in order to divide a dialog into sub-dialogs and process them separately.
# For example, the separation can be tied to the topic of the dialog.
# In our example, there is one flow called greeting_flow.

# Inside each flow, we can describe a sub-dialog.
# Here we can also use keyword `LOCAL`, which we have considered in other examples.

# Flow describes a sub-dialog using linked nodes, each node has the keywords `RESPONSE` and `TRANSITIONS`.

# `RESPONSE` - contains the response that the dialog agent will return when transitioning to this node.
# `TRANSITIONS` - describes transitions from the current node to other nodes.
# `TRANSITIONS` are described in pairs:
#      - the node to which the agent will perform the transition
#      - the condition under which to make the transition
script = {
    "greeting_flow": {
        "start_node": {  # This is an initial node, it doesn't need an `RESPONSE`
            RESPONSE: "",
            TRANSITIONS: {"node1": cnd.exact_match("Hi")},  # If "Hi" == request of user then we make the transition
        },
        "node1": {
            RESPONSE: "Hi, how are you?",  # When the agent goes to node1, we return "Hi, how are you?"
            TRANSITIONS: {"node2": cnd.exact_match("i'm fine, how are you?")},
        },
        "node2": {
            RESPONSE: "Good. What do you want to talk about?",
            TRANSITIONS: {"node3": cnd.exact_match("Let's talk about music.")},
        },
        "node3": {
            RESPONSE: "Sorry, I can not talk about music now.",
            TRANSITIONS: {"node4": cnd.exact_match("Ok, goodbye.")},
        },
        "node4": {RESPONSE: "bye", TRANSITIONS: {"node1": cnd.exact_match("Hi")}},
        "fallback_node": {  # We get to this node if an error occurred while the agent was running
            RESPONSE: "Ooops",
            TRANSITIONS: {"node1": cnd.exact_match("Hi")},
        },
    }
}

# An actor is an object that processes user input replicas and returns responses
# To create the actor, you need to pass the script of the dialogue `script`
# And pass the initial node `start_label`
# and the node to which the actor will go in case of an error `fallback_label`
# If `fallback_label` is not set, then its value becomes equal to `start_label` by default
actor = Actor(script, start_label=("greeting_flow", "start_node"), fallback_label=("greeting_flow", "fallback_node"))

# turn_handler - a function is made for the convenience of working with an actor
def turn_handler(
    in_request: str, ctx: Union[Context, str, dict], actor: Actor, true_out_response: Optional[str] = None
):
    # Context.cast - gets an object type of [Context, str, dict] returns an object type of Context
    ctx = Context.cast(ctx)
    # Add in current context a next request of user
    ctx.add_request(in_request)
    # pass the context into actor and it returns updated context with actor response
    ctx = actor(ctx)
    # get last actor response from the context
    out_response = ctx.last_response
    # the next condition branching needs for testing
    if true_out_response is not None and true_out_response != out_response:
        msg = f"in_request={in_request} -> true_out_response != out_response: {true_out_response} != {out_response}"
        raise Exception(msg)
    else:
        logging.info(f"in_request={in_request} -> {out_response}")
    return out_response, ctx

# testing
testing_dialog = [
    ("Hi", "Hi, how are you?"),  # start_node -> node1
    ("i'm fine, how are you?", "Good. What do you want to talk about?"),  # node1 -> node2
    ("Let's talk about music.", "Sorry, I can not talk about music now."),  # node2 -> node3
    ("Ok, goodbye.", "bye"),  # node3 -> node4
    ("Hi", "Hi, how are you?"),  # node4 -> node1
    ("stop", "Ooops"),  # node1 -> fallback_node
    ("stop", "Ooops"),  # fallback_node -> fallback_node
    ("Hi", "Hi, how are you?"),  # fallback_node -> node1
    ("i'm fine, how are you?", "Good. What do you want to talk about?"),  # node1 -> node2
    ("Let's talk about music.", "Sorry, I can not talk about music now."),  # node2 -> node3
    ("Ok, goodbye.", "bye"),  # node3 -> node4
]

def run_test():
    ctx = {}
    for in_request, true_out_response in testing_dialog:
        _, ctx = turn_handler(in_request, ctx, actor, true_out_response=true_out_response)

# interactive mode
def run_interactive_mode(actor):
    ctx = {}
    while True:
        in_request = input("type your answer: ")
        _, ctx = turn_handler(in_request, ctx, actor)

if __name__ == "__main__":
    logging.basicConfig(
        format="%(asctime)s-%(name)15s:%(lineno)3s:%(funcName)20s():%(levelname)s - %(message)s",
        level=logging.INFO,
    )
    # run_test()
    run_interactive_mode(actor)


from PyQt5 import QtWidgets, QtCore
import numpy as np
import pyqtgraph as pg
from modules.slicevolume import get_oblique_slice
import math
from shapely import Polygon

pg.setConfigOption('imageAxisOrder', 'row-major')

class Display:
    '''
    This class initializes the all 4 pyqtgraph elements with the desired features and necessary components.
    The self.[plane]_image attribute is the element directly accessed to show/update an image.
    '''

    mw = None
    pen = pg.mkPen(color='g', width=0.5,style=QtCore.Qt.DashLine)

    selected_plot = None
    active = None
    line_start = None
    line_end = None

    poly_arr = []
    items = []

    def __init__(self, mw):
        self.mw = mw
        Display.mw = mw
        Display.init_axial_plot(self.mw)
        Display.init_sagittal_plot(self.mw)
        Display.init_coronal_plot(self.mw)
        Display.init_oblique_plot(self.mw)

        Display.selected_plot = self.mw.axial_box
        Display.active = 'None'

    def setActive(self, active):
        Display.active = active

        if active == 'line':
            self.line_seg = pg.LineSegmentROI([0,0], [0,0])
            self.line_seg.sigRegionChangeFinished.connect(Display.updateLineLength)
            self.axial_box.addItem(self.line_seg)
            Display.items.append(self.line_seg)
        elif active == 'angle':
            self.angle = pg.PolyLineROI([[0,0], [0,0]])
            self.angle.sigRegionChangeFinished.connect(Display.updateLinesAngle)
            self.axial_box.addItem(self.angle)
            Display.items.append(self.angle)
        elif active == 'polygon':
            self.poly = pg.PolyLineROI([[0,0], [0,0]])
            self.poly.sigRegionChangeFinished.connect(Display.updatePolygonArea)
            self.axial_box.addItem(self.poly)
            Display.items.append(self.poly)
        elif active == 'ellipse':
            self.ellipse = pg.EllipseROI([0,0], 0.001)
            self.ellipse.sigRegionChangeFinished.connect(Display.updateEllipseArea)
            self.axial_box.addItem(self.ellipse)
            Display.items.append(self.ellipse)

    def updateLineLength():
        # get the length of the line segment
            handles = Display.mw.line_seg.getHandles()
            length = math.dist((handles[0].x(), handles[0].y()), (handles[1].x(), handles[1].y()))
            Display.mw.statusbar.showMessage(f'Line Length: {round(length, 3)} mm')

    def updateLinesAngle():
        # get the length of the line segment
            handles = Display.mw.angle.getHandles()
            ba = math.dist((handles[0].x(), handles[0].y()), (handles[1].x(), handles[1].y()))
            bc = math.dist((handles[1].x(), handles[1].y()), (handles[2].x(), handles[2].y()))
            angle = math.degrees(math.cos(bc / ba))

            ang = math.degrees(
            math.atan2(handles[2].y()-handles[1].y(), handles[2].x()-handles[1].x()) - math.atan2(handles[0].y()-handles[1].y(), handles[0].x()-handles[1].x()))
            if ang<0:
                ang=ang+360
            Display.mw.statusbar.showMessage(f'Angle: {round(ang, 3)}')

    def updateEllipseArea():
        # get the size of the ellipse
            size = Display.mw.ellipse.size()
            area = np.pi * size[0] * size[1]
            Display.mw.statusbar.showMessage(f'Ellipse Area: {round(area, 3)} mm2')

    def updatePolygonArea():
        # get the area of the polygon
            handles = Display.mw.poly.getHandles()
            area = Polygon([(handles[0].x(),handles[0].y()), (handles[1].x(),handles[1].y()), (handles[2].x(),handles[2].y()), (handles[3].x(),handles[3].y())]).area
            Display.mw.statusbar.showMessage(f'Polygon Area: {round(area, 3)} mm2')

    def clear(self):
        for i in Display.items:
            self.axial_box.scene().removeItem(i)

        Display.items.clear()

    def init_axial_plot(self):
        self.axial_image = pg.ImageItem()

        self.axial_box.setAspectLocked(True)
        self.axial_box.showAxes(False)
        self.axial_box.setMouseEnabled(x=False, y=False)
        self.axial_box.addItem(self.axial_image)

        self.axial_vline = pg.InfiniteLine(angle=90, movable=True, pen=Display.pen, name='axial_vline')
        self.axial_hline = pg.InfiniteLine(angle=0, movable=True, pen=Display.pen, name='axial_hline')
        self.axial_oline = pg.InfiniteLine(angle=135, movable=True, pen=Display.pen, name='axial_oline')
        self.axial_box.addItem(self.axial_vline)
        self.axial_box.addItem(self.axial_hline)
        self.axial_box.addItem(self.axial_oline)

        self.axial_box.scene().sigMouseClicked.connect(Display.line_mouse_clicked)
        self.axial_box.scene().sigMouseClicked.connect(Display.ellipse_mouse_clicked)
        self.axial_box.scene().sigMouseClicked.connect(Display.angle_mouse_clicked)
        self.axial_box.scene().sigMouseClicked.connect(Display.poly_mouse_clicked)

    def line_mouse_clicked(evt):
        if Display.active == 'line':
            vb = Display.selected_plot.plotItem.vb
            scene_coords = evt.pos()
            if Display.selected_plot.sceneBoundingRect().contains(scene_coords):
                mouse_point = vb.mapSceneToView(scene_coords)

                if Display.line_start == None:
                    Display.line_start = (mouse_point.x(), mouse_point.y())
                else:
                    Display.line_end = (mouse_point.x(), mouse_point.y())
                    if Display.line_end:
                        handles = Display.mw.line_seg.getHandles()
                        Display.mw.line_seg.movePoint(handles[0], Display.line_start)
                        Display.mw.line_seg.movePoint(handles[1], Display.line_end)
                    Display.line_start = None
                    Display.line_end = None

    def angle_mouse_clicked(evt):
        if Display.active == 'angle':
            vb = Display.selected_plot.plotItem.vb
            scene_coords = evt.pos()
            if Display.selected_plot.sceneBoundingRect().contains(scene_coords):
                mouse_point = vb.mapSceneToView(scene_coords)

                if len(Display.poly_arr) < 2:
                    Display.poly_arr.append((mouse_point.x(), mouse_point.y()))
                    Display.mw.angle.setPoints(Display.poly_arr, False)
                else:
                    Display.poly_arr.append((mouse_point.x(), mouse_point.y()))
                    Display.mw.angle.setPoints(Display.poly_arr, False)
                    Display.poly_arr.clear()

    def ellipse_mouse_clicked(evt):
        if Display.active == 'ellipse':
            vb = Display.selected_plot.plotItem.vb
            scene_coords = evt.pos()
            if Display.selected_plot.sceneBoundingRect().contains(scene_coords):
                mouse_point = vb.mapSceneToView(scene_coords)

                if Display.line_start == None:
                    Display.line_start = (mouse_point.x(), mouse_point.y())
                else:
                    Display.line_end = (mouse_point.x(), mouse_point.y())
                    if Display.line_end:
                        Display.mw.ellipse.setPos([Display.line_start[0], Display.line_start[1]])
                        Display.mw.ellipse.setSize([Display.line_end[0] - Display.line_start[0], Display.line_end[1] - Display.line_start[1]])
                    Display.line_start = None
                    Display.line_end = None

    def poly_mouse_clicked(evt):
        if Display.active == 'polygon':
            vb = Display.selected_plot.plotItem.vb
            scene_coords = evt.pos()
            if Display.selected_plot.sceneBoundingRect().contains(scene_coords):
                mouse_point = vb.mapSceneToView(scene_coords)

                if len(Display.poly_arr) < 3:
                    Display.poly_arr.append((mouse_point.x(), mouse_point.y()))
                    Display.mw.poly.setPoints(Display.poly_arr, False)
                else:
                    Display.poly_arr.append((mouse_point.x(), mouse_point.y()))
                    Display.mw.poly.setPoints(Display.poly_arr, True)
                    Display.poly_arr.clear()

    def init_sagittal_plot(self):
        self.sagittal_image = pg.ImageItem()

        self.sagittal_box.setAspectLocked(True)
        self.sagittal_box.showAxes(False)
        self.sagittal_box.setMouseEnabled(x=False, y=False)
        self.sagittal_box.addItem(self.sagittal_image)

        self.sagittal_vline = pg.InfiniteLine(angle=90, movable=True, pen=Display.pen, name='sagittal_vline')
        self.sagittal_hline = pg.InfiniteLine(angle=0, movable=True, pen=Display.pen, name='sagittal_hline')
        self.sagittal_box.addItem(self.sagittal_vline)
        self.sagittal_box.addItem(self.sagittal_hline)

    def init_coronal_plot(self):
        self.coronal_image = pg.ImageItem()

        self.coronal_box.setAspectLocked(True)
        self.coronal_box.showAxes(False)
        self.coronal_box.setMouseEnabled(x=False, y=False)
        self.coronal_box.addItem(self.coronal_image)

        self.coronal_vline = pg.InfiniteLine(angle=90, movable=True, pen=Display.pen, name='coronal_vline')
        self.coronal_hline = pg.InfiniteLine(angle=0, movable=True, pen=Display.pen, name='coronal_hline')
        self.coronal_box.addItem(self.coronal_vline)
        self.coronal_box.addItem(self.coronal_hline)

    def init_oblique_plot(self):
        self.oblique_image = pg.ImageItem()
        self.oblique_box.setAspectLocked(True)
        self.oblique_box.showAxes(False)
        self.oblique_box.setMouseEnabled(x=False, y=False)
        self.oblique_box.addItem(self.oblique_image)
        self.oblique_hline = pg.InfiniteLine(angle=0, movable=True, pen=Display.pen, name='oblique_hline')
        self.oblique_box.addItem(self.oblique_hline)

    def center_lines(self, arr):
        self.mw.axial_vline.setValue(arr.shape[1] / 2)
        self.mw.axial_hline.setValue(arr.shape[2] / 2)
        self.mw.axial_oline.setValue((arr.shape[1] / 2, arr.shape[2] / 2))

        self.mw.sagittal_vline.setValue(arr.shape[1] / 2)
        self.mw.sagittal_hline.setValue(arr.shape[0] / 2)

        self.mw.coronal_vline.setValue(arr.shape[2] / 2)
        self.mw.coronal_hline.setValue(arr.shape[0] / 2)

    # quick function to update the image based on axes and sync the remaining lines
    def update_image(self, arr = None, axes = None, angle = 45):
        if arr is None:
            print("No array passed to update_image")
            return
        if axes == 'axial':
            # update lines in other planes
            # vertical moves vertical in coronal plane
            self.coronal_vline.setValue(self.axial_vline.value())
            # horizontal moves vertical in sagittal plane
            self.sagittal_vline.setValue(self.axial_hline.value())

            # update slices in other planes
            #vertical moves sagittal plane
            self.sagittal_image.setImage(arr[:, :, int(self.axial_vline.value())])
            #horizontal moves coronal plane
            self.coronal_image.setImage(arr[:, int(self.axial_hline.value()), :])
            # oblique moves oblique plane
            self.axial_oline.setAngle(angle)
            self.oblique_image.setImage(get_oblique_slice(arr, angle, self.axial_oline.value()))
            # print("axial oline value" + str(self.axial_oline.value()))
            # print("axial oline angle" + str(self.axial_oline.angle()))

        elif axes == 'coronal':
            # update lines in other planes
            # vertical moves vertical in axial plane
            self.axial_vline.setValue(self.coronal_vline.value())
            # horizontal moves horizontal in sagittal plane
            self.sagittal_hline.setValue(self.coronal_hline.value())
            # horizontal moves horizontal in oblique plane
            self.oblique_hline.setValue(self.coronal_hline.value())

            # update slices in other planes
            # horizontal moves axial plane
            self.axial_image.setImage(arr[int(self.coronal_hline.value()), :, :])
            # vertical moves sagittal plane
            self.sagittal_image.setImage(arr[:, :, int(self.coronal_vline.value())])

        elif axes == 'sagittal':
            # update lines in other planes
            # vertical moves horizontal in axial plane
            self.axial_hline.setValue(self.sagittal_vline.value())
            # horizontal moves horizontal in coronal plane
            self.coronal_hline.setValue(self.sagittal_hline.value())
            # horizontal moves horizontal in oblique plane
            self.oblique_hline.setValue(self.sagittal_hline.value())

            # update slices in other planes
            # horizontal moves axial plane
            self.axial_image.setImage(arr[int(self.sagittal_hline.value()), :, :])
            # vertical moves coronal plane
            self.coronal_image.setImage(arr[:, int(self.sagittal_vline.value()), :])

        elif axes == 'oblique':
            # update lines in other planes
            # horizontal moves horizontal in coronal plane
            self.coronal_hline.setValue(self.oblique_hline.value())
            # horizontal moves horizontal in sagittal plane
            self.sagittal_hline.setValue(self.oblique_hline.value())

            # update slices in other planes
            # horizontal moves axial plane
            self.axial_image.setImage(arr[int(self.oblique_hline.value()), :, :])


#!/usr/bin/env python3
'''
Namespace for the ICNS format.
@see https://en.wikipedia.org/wiki/Apple_Icon_Image_format
'''
import os  # path
from typing import Union, Optional, Tuple, Iterator, List, Iterable, Set
from . import PackBytes, RawData

class CanNotDetermine(Exception):
    pass

class Media:
    KeyT = Union[str, bytes]
    __slots__ = ['key', 'types', 'size', 'channels', 'bits', 'availability',
                 'desc', 'compressable', 'retina', 'maxsize', 'ext_certain']

    def __init__(
        self,
        key: KeyT,
        types: List[str],
        size: Union[int, Tuple[int, int], None] = None,
        *,
        ch: Optional[int] = None,
        bits: Optional[int] = None,
        os: Optional[float] = None,
        desc: str = '',
    ) -> None:
        self.key = key
        self.types = types
        self.size = (size, size) if isinstance(size, int) else size
        self.availability = os
        self.desc = desc
        # computed properties
        self.compressable = self.is_type('argb') or self.is_type('rgb')
        self.retina = '@2x' in self.desc
        if self.is_type('rgb'):
            ch = 3
            bits = 8
        if self.is_type('argb'):
            ch = 4
            bits = 8
        self.channels = ch
        self.bits = bits
        self.maxsize = None  # type: Optional[int]
        if self.size and ch and bits:
            self.maxsize = self.size[0] * self.size[1] * ch * bits // 8
        self.ext_certain = all(x in ['png', 'argb', 'plist', 'jp2', 'icns']
                               for x in self.types)

    def is_type(self, typ: str) -> bool:
        return typ in self.types

    def is_binary(self) -> bool:
        return any(x in self.types for x in ['rgb', 'bin'])

    def fallback_ext(self) -> str:
        if self.channels in [1, 2]:
            return self.desc  # guaranteed to be icon, mask, or iconmask
        return self.types[-1]

    def decompress(self, data: bytes, ext: Optional[str] = '-?-') \
            -> Optional[List[int]]:
        ''' Returns None if media is not decompressable. '''
        if self.compressable:
            if ext == '-?-':
                ext = RawData.determine_file_ext(data)
            if ext == 'argb':
                return PackBytes.unpack(data[4:])  # remove ARGB header
            if ext is None or ext == 'rgb':  # RGB files dont have magic number
                if self.key == 'it32':
                    data = data[4:]
                return PackBytes.unpack(data)
        return None

    def filename(self, *, key_only: bool = False, size_only: bool = False) \
            -> str:
        if key_only:
            if os.path.exists(__file__.upper()):  # check case senstive
                if self.key in ['sb24', 'icsb']:
                    return self.key + '-a'  # type: ignore
                elif self.key in ['SB24', 'icsB']:
                    return self.key + '-b'  # type: ignore
            return str(self.key)  # dont return directy, may be b''-str
        else:
            if self.is_type('icns'):
                return self.desc
            if not self.size:
                return str(self.key)  # dont return directy, may be b''-str
            w, h = self.size
            suffix = ''
            if self.retina:
                w //= 2
                h //= 2
                suffix = '@2x'
            if size_only:
                if self.bits == 1:
                    suffix += '-mono'
            else:
                if self.desc in ['icon', 'iconmask']:
                    suffix += '-icon{}b'.format(self.bits)
                if self.desc in ['mask', 'iconmask']:
                    suffix += '-mask{}b'.format(self.bits)
            return '{}x{}{}'.format(w, h, suffix)

    def __repr__(self) -> str:
        return '<{}: {}, {}.{}>'.format(
            type(self).__name__, str(self.key), self.filename(), self.types[0])

    def __str__(self) -> str:
        T = ''
        if self.size:
            T += '{}x{}, '.format(*self.size)
            if self.maxsize:
                T += '{}ch@{}-bit={}, '.format(
                    self.channels, self.bits, self.maxsize)
        if self.desc:
            T += self.desc + ', '
        return '{}: {}macOS {}+'.format(
            str(self.key), T, self.availability or '?')

_TYPES = {x.key: x for x in (
    # Read support for these:
    Media('ICON', ['bin'], 32, ch=1, bits=1, os=1.0, desc='icon'),
    Media('ICN#', ['bin'], 32, ch=2, bits=1, os=6.0, desc='iconmask'),
    Media('icm#', ['bin'], (16, 12), ch=2, bits=1, os=6.0, desc='iconmask'),
    Media('icm4', ['bin'], (16, 12), ch=1, bits=4, os=7.0, desc='icon'),
    Media('icm8', ['bin'], (16, 12), ch=1, bits=8, os=7.0, desc='icon'),
    Media('ics#', ['bin'], 16, ch=2, bits=1, os=6.0, desc='iconmask'),
    Media('ics4', ['bin'], 16, ch=1, bits=4, os=7.0, desc='icon'),
    Media('ics8', ['bin'], 16, ch=1, bits=8, os=7.0, desc='icon'),
    Media('is32', ['rgb'], 16, os=8.5),
    Media('s8mk', ['bin'], 16, ch=1, bits=8, os=8.5, desc='mask'),
    Media('icl4', ['bin'], 32, ch=1, bits=4, os=7.0, desc='icon'),
    Media('icl8', ['bin'], 32, ch=1, bits=8, os=7.0, desc='icon'),
    Media('il32', ['rgb'], 32, os=8.5),
    Media('l8mk', ['bin'], 32, ch=1, bits=8, os=8.5, desc='mask'),
    Media('ich#', ['bin'], 48, ch=2, bits=1, os=8.5, desc='iconmask'),
    Media('ich4', ['bin'], 48, ch=1, bits=4, os=8.5, desc='icon'),
    Media('ich8', ['bin'], 48, ch=1, bits=8, os=8.5, desc='icon'),
    Media('ih32', ['rgb'], 48, os=8.5),
    Media('h8mk', ['bin'], 48, ch=1, bits=8, os=8.5, desc='mask'),
    Media('it32', ['rgb'], 128, os=10.0),
    Media('t8mk', ['bin'], 128, ch=1, bits=8, os=10.0, desc='mask'),
    # Write support for these:
    Media('icp4', ['png', 'jp2', 'rgb'], 16, os=10.7),
    Media('icp5', ['png', 'jp2', 'rgb'], 32, os=10.7),
    Media('icp6', ['png', 'jp2'], 48, os=10.7),
    Media('ic07', ['png', 'jp2'], 128, os=10.7),
    Media('ic08', ['png', 'jp2'], 256, os=10.5),
    Media('ic09', ['png', 'jp2'], 512, os=10.5),
    Media('ic10', ['png', 'jp2'], 1024, os=10.7, desc='or 512x512@2x (10.8)'),
    Media('ic11', ['png', 'jp2'], 32, os=10.8, desc='16x16@2x'),
    Media('ic12', ['png', 'jp2'], 64, os=10.8, desc='32x32@2x'),
    Media('ic13', ['png', 'jp2'], 256, os=10.8, desc='128x128@2x'),
    Media('ic14', ['png', 'jp2'], 512, os=10.8, desc='256x256@2x'),
    Media('ic04', ['argb', 'png', 'jp2'], 16, os=11.0),  # ARGB is macOS 11+
    Media('ic05', ['argb', 'png', 'jp2'], 32, os=11.0),
    Media('icsb', ['argb', 'png', 'jp2'], 18, os=11.0),
    Media('icsB', ['png', 'jp2'], 36, desc='18x18@2x'),
    Media('sb24', ['png', 'jp2'], 24),
    Media('SB24', ['png', 'jp2'], 48, desc='24x24@2x'),
    # ICNS media files
    Media('sbtp', ['icns'], desc='template'),
    Media('slct', ['icns'], desc='selected'),
    Media(b'\xFD\xD9\x2F\xA8', ['icns'], os=10.14, desc='dark'),
    # Meta types:
    Media('TOC ', ['bin'], os=10.7, desc='Table of Contents'),
    Media('icnV', ['bin'], desc='4-byte Icon Composer.app bundle version'),
    Media('name', ['bin'], desc='Unknown'),
    Media('info', ['plist'], desc='Info binary plist'),
)}

def enum_img_mask_pairs(available_keys: Iterable[Media.KeyT]) \
        -> Iterator[Tuple[Optional[str], Optional[str]]]:
    for mask_k, *imgs in [  # list probably never changes, ARGB FTW
        ('s8mk', 'is32', 'ics8', 'ics4', 'icp4'),
        ('l8mk', 'il32', 'icl8', 'icl4', 'icp5'),
        ('h8mk', 'ih32', 'ich8', 'ich4'),
        ('t8mk', 'it32'),
    ]:
        mk = mask_k if mask_k in available_keys else None
        any_img = False
        for img_k in imgs:
            if img_k in available_keys:
                any_img = True
                yield img_k, mk
        if mk and not any_img:
            yield None, mk

def enum_png_convertable(available_keys: Iterable[Media.KeyT]) \
        -> Iterator[Tuple[Media.KeyT, Optional[Media.KeyT]]]:
    ''' Yield (image-key, mask-key or None) '''
    for img in _TYPES.values():
        if img.key not in available_keys:
            continue
        if img.is_type('argb') or img.bits == 1:  # allow mono icons
            yield img.key, None
        elif img.is_type('rgb'):
            mask_key = None
            for mask in _TYPES.values():
                if mask.key not in available_keys:
                    continue
                if mask.desc == 'mask' and mask.size == img.size:
                    mask_key = mask.key
                    break
            yield img.key, mask_key

def supported_extensions() -> Set[str]:
    return set(y for x in _TYPES.values() for y in x.types)

def get(key: Media.KeyT) -> Media:
    try:
        return _TYPES[key]
    except KeyError:
        pass
    raise NotImplementedError('Unsupported icns type "' + str(key) + '"')

def key_from_readable(key: str) -> Media.KeyT:
    key_mapping = {
        'dark': b'\xFD\xD9\x2F\xA8',
        'selected': 'slct',
        'template': 'sbtp',
        'toc': 'TOC ',
    }
    return key_mapping.get(key.lower(), key)  # type: ignore[return-value]

def match_maxsize(total: int, typ: str) -> Media:
    assert(typ == 'argb' or typ == 'rgb')
    ret = [x for x in _TYPES.values() if x.is_type(typ) and x.maxsize == total]
    return _best_option(ret, typ)

def guess(data: bytes, filename: Optional[str] = None) -> Media:
    '''
    Guess icns media type by analyzing the raw data + file naming convention.
    Use:
    - @2x.png or @2x.jp2 for retina images
    - directly name the file with the corresponding icns-key
    - or {selected|template|dark}.icns to select the proper icns key.
    '''
    # Set type directly via filename
    if filename:
        bname = os.path.splitext(os.path.basename(filename))[0]
        if bname in _TYPES:
            return _TYPES[bname]

    # Filter attributes
    desc = None
    size = None
    maxsize = None
    retina = False

    # Guess extension
    ext = RawData.determine_file_ext(data)
    if not ext and filename:
        if filename.endswith('.rgb'):
            ext = 'rgb'
        elif filename.endswith('.mask'):
            maxsize = len(data)
            desc = 'mask'

    # Guess image size
    if ext:
        size = RawData.determine_image_size(data, ext)

    # if filename is set, then bname is also set (see above)
    if filename:
        # Guess retina flag
        retina = bname.lower().endswith('@2x')
        # Guess icns-specific type
        if ext == 'icns':
            for candidate in ['template', 'selected', 'dark']:
                if bname.endswith(candidate):
                    desc = candidate
                    break

    # stupid double usage of ic10, enforce retina flag
    if size == (1024, 1024):
        retina = True

    choices = []
    for x in _TYPES.values():
        if retina != x.retina:  # png + jp2
            continue
        if desc and desc != x.desc:  # icns or rgb-mask
            continue
        if ext:
            if size != x.size or not x.is_type(ext):
                continue
        else:  # not ext
            if x.ext_certain:
                continue
            if maxsize and x.maxsize and maxsize != x.maxsize:  # mask only
                continue
        choices.append(x)

    return _best_option(choices, ext)

def _best_option(choices: List[Media], ext: Optional[str] = None) -> Media:
    '''
    Get most favorable media type.
    If more than one option exists, choose based on order index of ext.
    '''
    if len(choices) == 1:
        return choices[0]
    # Try get most favorable type (sort order of types)
    if ext:
        best_i = 99
        best_choice = []
        for x in choices:
            i = x.types.index(ext)
            if i < best_i:
                best_i = i
                best_choice = [x]
            elif i == best_i:
                best_choice.append(x)
        if len(best_choice) == 1:
            return best_choice[0]
        choices = best_choice

    raise CanNotDetermine('Could not determine type – one of {}.'.format(
        [x.key for x in choices]))


from time import sleep

l = list()
p = dict()
k = m = 0
while True:
    p['Nome'] = str(input('Nome: ')).title().strip()
    s = str(input('Sexo M/F: ')).upper().strip()[0]
    while s not in 'MF':
        s = str(input('Sexo M/F: ')).upper().strip()[0]
    if s == 'M':
        p['Sexo'] = 'Masculino'
    else:
        p['Sexo'] = 'Feminino'
    p['Idade'] = int(input('Idade: '))
    m = m + p['Idade']
    l.append(p.copy())
    r = str(input('Gostaria de continuar S/N: ')).upper().strip()[0]
    while r not in 'SN':
        r = str(input('Gostaria de continuar S/N: ')).upper().strip()[0]
    if r == 'N':
        sleep(1)
        break
print('-'*30)
#print(l)
#for c in l:
    #k += 1
    #for n, i in c.items():
     #   print(f'O {n} ', end='')
      #  print(f'é {i} ', end='')
        #print(p.values(['Idade']))
        #if p['Sexo'] == 'Feminino':
        #    n.append(p.copy(['Sexo']))
    #print('\n')
print(f'Foram cadastrado {len(l)} pessoas')
print(f'A média de idade é {m/len(l)}.')
print(f'As mulheres da lista são ', end='')
for p in l:
    if p['Sexo'] == 'Feminino':
        print(f'{p["Nome"]} ', end='')
print()
print('As pessoas com idade acima dá média são ', end='')
for p in l:
    if p['Idade'] > (m/len(l)):
        print(f'{p["Nome"]} ', end='')
print()


""""
Esse é o jogo dos dados, muito usado em Las Vegas nos cassinos, aposte em um
número que seja o resultado da soma deles e ganhe o seu dinheiro. Crie duas variáveis
para representar os dados e uma para sua aposta, crie uma para armazenar o resultado
e faça a verificação.
"""
import random

dado1= random.randint(1,6)
dado2= random.randint(1,6)
soma = dado1 + dado2

inputNum = int(input("Digite o valor da sua aposta da soma de dois dados (6 faces) "))
print(soma)
if soma == inputNum :
  print("Você venceu!")
else:
  print("Você perdeu!")

Lista de exercícios condicionais/Aula 6/Ex2 - Dados.py


import numpy as np
from monai.networks.layers.factories import Norm
from monai.networks.nets import UNETR, DynUNet, UNet
from torch.optim import lr_scheduler
from typing import List, Optional, Tuple

def convert_df_to_dicts(case_df):
    case_dicts = []
    for idx, row in case_df.iterrows():
        bbox = {
            "filename": row["filename"],
            "label": row["label"],
            "center_w": [row["world_x"], row["world_y"], row["world_z"]],
            "x_axis_local": [row["dx1"], row["dx2"], row["dx3"]],
            "y_axis_local": [row["dy1"], row["dy2"], row["dy3"]],
            "z_axis_local": [row["dz1"], row["dz2"], row["dz3"]],
        }
        for key in ["width", "height", "depth"]:
            bbox.update({key: row[key]})
        case_dicts.append(bbox)
    return case_dicts

def axis_angle_to_rotation_matirx(axis, degree):
    """
    Compute rotation matrix from axis-angle.

    :param axis: array-like, shape (3,), Axis of rotation: (x, y, z)
    :param degree: degree to rotate
    :return: array-like, shape (3, 3), Rotation matrix
    """

    axis = axis / np.linalg.norm(axis)
    ux, uy, uz = axis
    theta = np.deg2rad(degree)
    c = np.cos(theta)
    s = np.sin(theta)
    ci = 1.0 - c
    rotation_matrix = np.array(
        [
            [ci * ux * ux + c, ci * ux * uy - uz * s, ci * ux * uz + uy * s],
            [ci * uy * ux + uz * s, ci * uy * uy + c, ci * uy * uz - ux * s],
            [ci * uz * ux - uy * s, ci * uz * uy + ux * s, ci * uz * uz + c],
        ]
    )
    return rotation_matrix

def get_scheduler(optimizer, opt):
    if opt.lr_policy == "lambda":
        lambda_rule = lambda epoch: 1.0 - max(0, epoch + 1 + opt.epoch_count - opt.niter) / float(
            opt.niter_decay + 1
        )
        scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
    elif opt.lr_policy == "step":
        scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)
    elif opt.lr_policy == "multi_step":
        scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=opt.lr_milestones, gamma=0.1)
    elif opt.lr_policy == "cosine":
        scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.max_iterations)
    elif opt.lr_policy == "plateau":
        scheduler = lr_scheduler.ReduceLROnPlateau(
            optimizer, modee="min", factor=0.2, threshold=0.01, patience=5
        )
    elif opt.lr_policy == "invariant":
        lambda_rule = lambda epoch: 1.0
        scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
    elif opt.lr_policy == "warm_up_multi_step":
        lambda_rule = (
            lambda epoch: (epoch + 1) / opt.warm_up_epochs
            if epoch < opt.warm_up_epochs
            else 0.1 ** len([m for m in opt.lr_milestones if m <= epoch])
        )
        scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
    else:
        return NotImplementedError(f"Learning rate policy {opt.lr_policy} is not implemented")

    return scheduler

def mask_np_bbox(
    mask_np: np.ndarray, mask_value: Optional[int] = None
) -> Tuple[np.ndarray, np.ndarray]:
    """
    get the bounding box of foreground label(s) in voxel coordinate system,
    if foreground label not found in the mask, will return (None, None)

    :param mask: the input ndarray object for mask
    :param mask_value: foreground label value, will use all positive labels if not specified
    :return: the bounding box in voxel coordinate system of numpy, i.e: (vz, vy, vx)!
    """
    if mask_value is not None:
        vz, vy, vx = np.where(mask_np == mask_value)
    else:
        vz, vy, vx = np.where(mask_np > 0)

    min_corner, max_corner = None, None
    if vz.size > 0:
        start = [vz.min(), vy.min(), vx.min()]
        end = [vz.max(), vy.max(), vx.max()]

        coords = list(zip(start, end))
        corners = []
        for i in range(2):
            for j in range(2):
                for k in range(2):
                    corner_coord = [coords[0][i], coords[1][j], coords[2][k]]
                    corners.append(corner_coord)
        corners = np.vstack(corners)
        min_corner = corners.min(axis=0)
        max_corner = corners.max(axis=0)
    return min_corner, max_corner

def get_network(
    net_name, in_channels, num_classes, dimensions, normalization, base=8, downsample=5
):
    if net_name.startswith("unet"):
        norms = {"instancenorm": Norm.INSTANCE, "batchnorm": Norm.BATCH, "groupnorm": Norm.GROUP}
        max_stride = 2 ** downsample
        channels = [base * 2 ** i for i in range(downsample + 1)]
        strides = [2] * downsample
        if net_name.endswith("16"):
            max_stride = max_stride // 2
            strides.pop()
            channels.pop()
        net = UNet(
            dimensions=dimensions,
            in_channels=in_channels,
            out_channels=num_classes,
            channels=channels,
            strides=strides,
            num_res_units=2,
            norm=norms[normalization],
        )
    elif net_name == "unetr":
        max_stride = 16
        norms = {"instancenorm": "instance", "batchnorm": "batch", "groupnorm": "group"}
        net = UNETR(
            in_channels=in_channels,
            out_channels=num_classes,
            img_size=(32, 128, 256),
            feature_size=8,
            num_heads=6,
            norm_name=norms[normalization],
        )
    elif net_name == "dynunet":
        strides = [[1, 2, 2]] * downsample
        kernels = [3] * downsample
        strides.insert(0, 1)
        kernels.insert(0, 3)
        max_stride = 2 ** downsample
        channels = [base * 2 ** i for i in range(downsample + 1)]
        net = DynUNet(
            spatial_dims=dimensions,
            in_channels=in_channels,
            out_channels=num_classes,
            kernel_size=kernels,
            strides=strides,
            upsample_kernel_size=strides[1:],
            filters=channels,
            deep_supervision=True,
            deep_supr_num=2,
        )
    else:
        raise ValueError(f"unsupported network: {net_name}")

    return net, max_stride

def longest_common_prefix_str(names: List[str]) -> str:
    chars_list = []
    for chars in zip(*names):
        if len(set(chars)) == 1:
            chars_list.append(chars[0])
        else:
            break
    return "".join(chars_list)

def longest_common_postfix_str(names: List[str]) -> str:
    reversed_names = map(lambda x: x[::-1], names)
    reversed_lcp = longest_common_prefix_str(reversed_names)
    return reversed_lcp[::-1]


import numpy as np
from prml.nn.optimizer.optimizer import Optimizer

class RMSProp(Optimizer):
    """
    RMSProp optimizer
    initial
    msg = 0
    update rule
    msg = rho * msg + (1 - rho) * gradient ** 2
    param -= learning_rate * gradient / (sqrt(msg) + eps)
    """

    def __init__(self, parameter, learning_rate=1e-3, rho=0.9, epsilon=1e-8):
        super().__init__(parameter, learning_rate)
        self.rho = rho
        self.epsilon = epsilon
        self.mean_squared_grad = []
        for p in self.parameter:
            self.mean_squared_grad.append(np.zeros(p.shape))

    def update(self):
        """
        update parameters
        """
        self.increment_iteration()
        for p, msg in zip(self.parameter, self.mean_squared_grad):
            if p.grad is None:
                continue
            grad = p.grad
            msg *= self.rho
            msg += (1 - self.rho) * grad ** 2
            p.value -= (
                self.learning_rate * grad / (np.sqrt(msg) + self.epsilon)
            )


#!flask/bin/python
from flask import Flask, jsonify, request

from params import pool_fee
import wallet_json_rpc
import mining
import sqlite_handler

app = Flask(__name__)

last_account_transferred_block = 0

class BePatientError(Exception):
    pass

def transfer_account_handler(new_pubkey):
    """
    It will transfer a random empty account to the new_pubkey. One account per block is allowed.
    :param new_pubkey:
    :return:
    """
    global last_account_transferred_block

    try:
        current_block = wallet_json_rpc.get_current_block()
    except wallet_json_rpc.WalletCommError:
        raise wallet_json_rpc.WalletCommError

    if current_block == last_account_transferred_block:
        raise BePatientError

    try:
        acc_number = wallet_json_rpc.get_a_zero_balance_account_number()
    except wallet_json_rpc.WalletCommError:
        raise wallet_json_rpc.WalletCommError
    except wallet_json_rpc.NoEmptyAccountError:
        raise wallet_json_rpc.NoEmptyAccountError

    try:
        wallet_json_rpc.change_key(new_pubkey, acc_number)
    except wallet_json_rpc.WalletCommError:
        raise wallet_json_rpc.WalletCommError
    except wallet_json_rpc.InputParameterError:
        raise wallet_json_rpc.InputParameterError

    last_account_transferred_block = current_block
    return acc_number

@app.route('/pool_data', methods=['GET'])
def get_pool_data():
    network_height = wallet_json_rpc.get_current_block()
    pool_data = {
        "current_block": str(network_height),
        "net_hashrate": str(wallet_json_rpc.get_net_hashrate(network_height)) + " Gh",
        "algorithm": "Pascal",
        "poolhash": str(round(mining.get_pool_hr() / 10**9, 2)) + " Gh",
        "nethash":  0,
        "workers":  str(mining.No_miners()),
        "fee":      str(pool_fee) + "%",
        "period":   "Every block"
    }
    return jsonify({'pool_data': pool_data})

@app.route('/miner_data/<int:account>', methods=['GET'])
def get_miner_data(account):
    miner_data = {
        "account": str(account),
        "hashrate": str(round(mining.get_hr(account) / 10**9, 3)) + " Gh",
        "1hour":            0,
        "24hours":          0,
        "average_mined":    0,
        "payments":         sqlite_handler.db.get_account_payments(account)
    }
    return jsonify({'miner_data': miner_data})

@app.route('/get_account', methods=['POST'])
def get_account():
    pubkey = request.get_json(force=True)['pubkey']
    try:
        acc_number = transfer_account_handler(pubkey)
    except wallet_json_rpc.WalletCommError:
        return jsonify({'result': 'An error occured on the pool side. Please try again. If you see this message multiple times please report it to the team on Discord or Telegram. Thank you!'})
    except BePatientError:
        return jsonify({'result': 'An account was already sent to someone in this block. Please try again in a few minutes. If you see this message multiple times please report it to the team on Discord or Telegram. Thank you!'})
    except wallet_json_rpc.NoEmptyAccountError:
        return jsonify({'result': 'No free account is left on the pool. Please try again in a few minutes. If you see this message multiple times please report it to the team on Discord or Telegram. Thank you!'})
    except wallet_json_rpc.InputParameterError:
        return jsonify({'result': 'Wrong public key! You can export your public key from the wallet. It has to start with "3G". If you see this message multiple times please report it to the team on Discord or Telegram. Thank you!'})

    return jsonify({'result': 'Account ' + str(acc_number) + ' was successfully sent to your public key. You will see it in the next block in appr. 5 minutes.'})

def start_restapi():
    app.run(debug=False, port = 3000)


from tkinter import Tk,Menu,scrolledtext,END,filedialog,INSERT,messagebox
import os
import subprocess
from Html_Analyzer import Html_lex
from Js_Analyzer import Js_Lex
from Css_Analyzer import Css_Lex
from Rmt_Analyzer import Rmt_Lex
class Window_app:

    text_area=None
    text_console=None
    type_Analizer=None
    name_file=""
    file_open=None
    def __init__(self,gui_window):
        self.gui_window = gui_window
        self.gui_window.title('HTML, CSS & JS COMPILER')
        self.gui_window.geometry("1200x720")
        self.gui_window.configure(bg='#3d405b')
        self.text_area = scrolledtext.ScrolledText(gui_window, width=80, height=40,bg='#edf2f4')
        self.text_area.grid(column=0,row=0, pady=30,padx=20)

        self.text_console= scrolledtext.ScrolledText(gui_window, width=50, height=40,bg='#000000',foreground='#aacc00')
        self.text_console.grid(column=1,row=0, pady=20,padx=20)
        self.text_area.focus()
        menu_bar=Menu(gui_window)
        self.gui_window.config(menu=menu_bar)

        file_menu=Menu(menu_bar,tearoff=0)
        file_menu.add_command(label="New",command=self.New_Data)
        file_menu.add_command(label="Open",command=self.Open_Data)
        file_menu.add_command(label="Save",command=self.save_file)
        file_menu.add_command(label="Save As",command=self.save_As)
        tools_menu=Menu(menu_bar,tearoff=0)
        help_menu=Menu(menu_bar,tearoff=0)

        #Creating tag for Each Principal Element of the Menu

        tools_menu=Menu(menu_bar, tearoff=0)
        tools_menu.add_command(label="Analyze",command=self.Analyzer)

        help_menu=Menu(menu_bar,tearoff=0)
        help_menu.add_command(label="User guide",command=self.Open_User_Guide)
        help_menu.add_command(label="Tech guide",command=self.Open_Tec_Guide)
        help_menu.add_command(label="About", command=self.About)

        menu_bar.add_cascade(label="File",menu=file_menu)
        menu_bar.add_cascade(label="Tools",menu=tools_menu)
        menu_bar.add_cascade(label="Help",menu=help_menu)

        global temp_htmlAnalyzer,temp_jsAnalizer,temp_CssAnalyzer,temp_RmtAnalyzer
        temp_htmlAnalyzer = Html_lex()
        temp_jsAnalizer = Js_Lex()
        temp_CssAnalyzer = Css_Lex()
        temp_RmtAnalyzer = Rmt_Lex()

        #class instance's

    def New_Data(self):
        self.text_area.delete(1.0,END)
        self.text_console.delete(1.0,END)
        self.file_open=None

    def Open_Data(self):
        try:
            self.name_file=""
            self.file_open = filedialog.askopenfilename(title = "Open File", initialdir = "C:/",filetypes=[("JavaScript Files","*.js"),
            ("Html Files","*.html"),("Css Files","*.css"),("Rmt Files","*.rmt")])
            text_data = open(self.file_open, encoding='windows-1252')
            data_extension=str(text_data.name)
            sub_name=text_data.name.split("/")
            self.name_file=sub_name[len(sub_name)-1]
            print(self.name_file)
            if(data_extension.endswith('.js')):
                self.type_Analizer="js"
                print("JAVASCRIPT ANALYZER ON")
            elif(data_extension.endswith('.html')):
                print("HTML ANALYZER ON")
                self.type_Analizer="html"
            elif(data_extension.endswith('.css')):
                print("CSS ANALYZER ON")
                self.type_Analizer="css"
            elif(data_extension.endswith('.rmt')):
                print("RMT ANALYZER ON")
                self.type_Analizer="rmt"
            else:
                print("THERE'S NO EXTENSION")
                self.type_Analizer=""
        except FileNotFoundError:
            print("File not Found")
            data_extension=""
            text_data=""

        if(data_extension!=""):
            content = text_data.read()
            self.text_area.delete(1.0, END)
            self.text_area.insert(INSERT, content)
            text_data.close()
        else:
            self.text_area.delete(1.0, END)

#save file as data method
    def save_As(self):
        save_a=filedialog.asksaveasfilename(title="Save File", initialdir="C:/")
        open_buffer_save=open(save_a,"w+")
        open_buffer_save.write(self.text_area.get(1.0,END))
        open_buffer_save.close()
        self.file_open=save_a

#save file data method
    def save_file(self):
        if self.file_open is None:
            self.save_As()
        else:
            open_buffer=open(self.file_open,"w+")
            open_buffer.write(self.text_area.get(1.0,END))
            open_buffer.close()

#FOREGROUND CHANGE COLOR:
    def Tokens_Color(self,Array_Tokens):
        print("VA A PINTAR TOKENS")
        for index,Token_List in enumerate(Array_Tokens):
            if (Token_List.get_TypeT()=="Reserved Keyword"):
                self.text_area.tag_add(str(index)+Token_List.get_Token(),str(Token_List.get_Row())+"."+str(Token_List.get_Column()-len(Token_List.get_Token())),str(Token_List.get_Row())+"."+str(Token_List.get_Column()))
                self.text_area.tag_config(str(index)+Token_List.get_Token(), foreground="red")
            elif(Token_List.get_TypeT()=="Double Quote comment" or Token_List.get_TypeT()=="Single Quote comment"):
                self.text_area.tag_add(str(index)+Token_List.get_Token(),str(Token_List.get_Row())+"."+str(Token_List.get_Column()-len(Token_List.get_Token())),str(Token_List.get_Row())+"."+str(Token_List.get_Column()))
                self.text_area.tag_config(str(index)+Token_List.get_Token(), foreground="yellow")
            elif(Token_List.get_TypeT()=="multiline comment"):
                self.text_area.tag_add(str(index)+Token_List.get_Token(),Token_List.get_Index(),str(Token_List.get_Row())+"."+str(Token_List.get_Column()))
                self.text_area.tag_config(str(index)+Token_List.get_Token(), foreground="gray")
            elif(Token_List.get_TypeT()=="single comment"):
                self.text_area.tag_add(str(index)+Token_List.get_Token(),str(Token_List.get_Row())+"."+str(Token_List.get_Column()-len(Token_List.get_Token())),str(Token_List.get_Row())+"."+str(Token_List.get_Column()))
                self.text_area.tag_config(str(index)+Token_List.get_Token(), foreground="gray")
            elif(Token_List.get_TypeT()=="forward-slash"or Token_List.get_TypeT()=="Equality sign" or Token_List.get_TypeT()=="Asterisk" or
            Token_List.get_TypeT()=="Minus-sing" or Token_List.get_TypeT()=="Plus-sign" or Token_List.get_TypeT()=="Percent" or Token_List.get_TypeT()=="Right parentheses" or
            Token_List.get_TypeT()=="Left parentheses" or Token_List.get_TypeT()=="Less-than sign" or Token_List.get_TypeT()=="greater-than sign" or Token_List.get_TypeT()=="or" or
            Token_List.get_TypeT()=="not" or Token_List.get_TypeT()=="and"):
                self.text_area.tag_add(str(index)+Token_List.get_Token(),str(Token_List.get_Row())+"."+str(Token_List.get_Column()-len(Token_List.get_Token())),str(Token_List.get_Row())+"."+str(Token_List.get_Column()))
                self.text_area.tag_config(str(index)+Token_List.get_Token(), foreground="orange")
            elif(Token_List.get_TypeT()=="Int" or Token_List.get_TypeT()=="Float"):
                self.text_area.tag_add(str(index)+Token_List.get_Token(),str(Token_List.get_Row())+"."+str(Token_List.get_Column()-len(Token_List.get_Token())),str(Token_List.get_Row())+"."+str(Token_List.get_Column()))
                self.text_area.tag_config(str(index)+Token_List.get_Token(), foreground="blue")
            elif(Token_List.get_TypeT()=="Identifier"):
                self.text_area.tag_add(str(index)+Token_List.get_Token(),str(Token_List.get_Row())+"."+str(Token_List.get_Column()-len(Token_List.get_Token())),str(Token_List.get_Row())+"."+str(Token_List.get_Column()))
                self.text_area.tag_config(str(index)+Token_List.get_Token(), foreground="green")
            else:
                pass

   #Analyzer call function
    def Analyzer(self):

        #CLEANS ALL VARIABLES OF EACH CLASS
        temp_jsAnalizer.clear_method()
        temp_htmlAnalyzer.clear_method()
        temp_CssAnalyzer.clear_method()
        temp_RmtAnalyzer.clear_method()

    #test js

        if(self.type_Analizer=="js"):
            temp_jsAnalizer.Analyze_text_Js(self.text_area.get(1.0,END),self.name_file)
            self.Tokens_Color(temp_jsAnalizer.Token_Array_Js)
        elif(self.type_Analizer=="html"):
            temp_htmlAnalyzer.Analyze_text(self.text_area.get(1.0, END),self.name_file)
            self.Tokens_Color(temp_htmlAnalyzer.Token_Array)
        elif(self.type_Analizer=="css"):
            temp_CssAnalyzer.Analyze_text_Css(self.text_area.get(1.0, END),self.name_file)
            self.Tokens_Color(temp_CssAnalyzer.Token_Array_Css)
            self.text_console.insert(INSERT, temp_CssAnalyzer.Log_Analyzer)
        elif(self.type_Analizer=="rmt"):
            temp_RmtAnalyzer.Analyze_text_Rmt(self.text_area.get(1.0, END))
            self.Tokens_Color(temp_RmtAnalyzer.Token_Array_Rmt)

        else:
            messagebox.showerror(title="Warning", message="There's no File to Analyze")

    def Open_User_Guide(self):
        subprocess.Popen('user_manual.pdf',shell=True)

    def Open_Tec_Guide(self):
        subprocess.Popen('Tec_manual.pdf',shell=True)

    def About(self):
        messagebox.showinfo(title="Developer Info", message="Alex4191\nId: 201602880")

if __name__ == "__main__":
    gui_window = Tk()
    app = Window_app(gui_window)
    gui_window.mainloop()


import gymnasium as gym

from pcse_gym.envs.winterwheat import WinterWheat
from pcse_gym.envs.sb3 import get_model_kwargs
import pcse_gym.utils.defaults as defaults

def get_action_space(nitrogen_levels=7):
    space_return = gym.spaces.Discrete(nitrogen_levels)
    return space_return

def initialize_env(pcse_env=1, crop_features=defaults.get_default_crop_features(pcse_env=1),
                   costs_nitrogen=10, reward='DEF', nitrogen_levels=7, action_multiplier=1.0,
                   years=defaults.get_default_train_years(), locations=defaults.get_default_location()):
    action_space = get_action_space(nitrogen_levels=nitrogen_levels)
    env_return = WinterWheat(crop_features=crop_features,
                             costs_nitrogen=costs_nitrogen,
                             years=years,
                             locations=locations,
                             action_space=action_space,
                             action_multiplier=action_multiplier,
                             reward=reward,
                             **get_model_kwargs(pcse_env))

    return env_return

def initialize_env_no_baseline():
    return initialize_env(reward='GRO', action_multiplier=2.0)


#import relevant libraries (first streamlit)
import streamlit as st
import pandas as pd
import plotly as py
import plotly.graph_objs as pg
import plotly.express as px

st.title("Data Visualization Tutorial: Interactive Streamlit Dashboard")
st.title("Anandi Gupta")

"""
This tutorial provides users a step-by-step guide for creating their own interactive data visualization dashboards using Streamlit and Plotly.

Note, to insert text blocks as shown here, simply type your text within a doc string.
"""

## URLs - Our world in data github as an example
#Emissions
url = "https://raw.githubusercontent.com/owid/co2-data/master/owid-co2-data.csv"
#read in our world in data github
df_emissions = pd.read_csv(url)

df_emissions = df_emissions[['iso_code', 'country', 'year', 'co2', 'co2_per_capita', 'energy_per_gdp', 'energy_per_capita', 'population']]

#### Create relevant sections and corresponding plots using plotly

if st.sidebar.checkbox("Bar Charts Over Time", key="section1"):
    st.header("Example Bar Chart (Use st.header to include meaningful section header)")
    df_emissions_viz = df_emissions[df_emissions['country'] == "World"]
    df_emissions_viz = df_emissions_viz[df_emissions_viz['year'] > 1980].reset_index()
    fig = px.bar(df_emissions_viz, x=df_emissions_viz['year'], y=df_emissions_viz['co2'], labels={'co2':'Global CO2 Emissions', "year": "Year"},
                 title='CO2 Emissions Over Time')
    st.plotly_chart(fig, use_container_width=True)
    st.write("Use st.write to insert a meaningful takeaway")

if st.sidebar.checkbox("Chloropleth Maps", key="section2"):
    st.header("Example Chloropleth Map: Use st.header to include meaningful section header")

    answer1 = st.selectbox(label="Choose indicator",
    options=("CO2 Emissions Per Capita", "Energy Consumption Per Capita"))
    answer2 = st.slider('Choose time period', 2016, 2020, 2016)

    def cc_causes_maps(var):
        df_emissions2 = df_emissions[df_emissions['year'] == answer2]

        data = dict(type='choropleth',
                locations = df_emissions2['iso_code'],
                z = df_emissions2[var],
                text = df_emissions2['country'])

        layout = dict(title = answer1,
                  geo = dict(showframe = False,
                           projection = {'type':'robinson'},
                           showlakes = True,
                           lakecolor = 'rgb(0,191,255)'))
        x = pg.Figure(data = [data], layout = layout)
        st.plotly_chart(x, use_container_width=True)

    if answer1 == "CO2 Emissions Per Capita":
        cc_causes_maps('co2_per_capita')
        st.write("Use st.write to insert a meaningful takeaway about CO2 Emissions per Capita")

    elif answer1 == "Energy Consumption Per Capita":
        cc_causes_maps('energy_per_capita')
        st.write("Use st.write to insert a meaningful takeaway about Energy Consumption per Capita")

if st.sidebar.checkbox("Text Section", key="section6"):
    st.header("Use st.header to insert meaningful text header")
    """
    Insert any text within doc strings

    To add links use format "[NAME] (LINK)" as seen in the example below:

    1) [Anandi Gupta's Streamlit Dashboard](https://anandigupta-data-science-i-ds2-final-project-streamlit-2-fahu9f.streamlit.app/)
    """


from time import process_time as clock

# Initialize the data
with open("04.txt") as f:
    data = [l.split() for l in f]
    for d in data:
        date = d[0]
        time = d[1]
        del d[1]
        d[0] = tuple(int(i) for i in date[1:].split("-")) + tuple(int(i) for i in time[:-1].split(":"))
        if d[1][0] == "G":
            del d[1]
            del d[2]
            del d[2]
        else:
            d[1] = d[1][0]
            del d[2]
    data.sort()
    for i, d in enumerate(data):
        data[i] = (d[0][3], d[0][4], d[1])

    guards = {}

# Function for solving the first problem
def first ():
    st = clock()

    minute = [0]*60
    i = 0
    while i < len(data):
        label = data[i][2]
        if label[0] == "#":
            if label not in guards:
                guards[label] = minute.copy()
            cur_guard = label
        elif label == "f":
            sta = data[i][1]
            i += 1
            end = data[i][1]
            for j in range(sta, end):
                guards[cur_guard][j] += 1

        i += 1

    m = (0,"#0")
    for k in guards:
        s = sum(guards[k])
        if s > m[0]:
            m = (s, k)

    res = guards[m[1]].index(max(guards[m[1]])) * int(m[1][1:])

    print("First:", res, "Time:", clock() - st)

# Function for solving the second problem
def second ():
    st = clock()

    m = (0,"#0")
    for k in guards:
        s = max(guards[k])
        if s > m[0]:
            m = (s, k)

    res = guards[m[1]].index(m[0]) * int(m[1][1:])

    print("Second:", res, "Time:", clock() - st)

# Solve the problems
if __name__ == "__main__":
    first()
    second()


from typing import List
import math

class Solution:
    def numberOfBoomerangs(self, points: List[List[int]]) -> int:
        graph = dict()
        for point in points:
            graph[(point[0], point[1])] = dict()

        count = len(points)
        for i in range(count):
            for j in range(i + 1, count):
                distance = math.pow(points[i][0] - points[j][0], 2) + \
                           math.pow(points[i][1] - points[j][1], 2)
                dists = graph[(points[i][0], points[i][1])]
                distance=int(distance)
                if distance in dists:
                    dists[distance] += 1
                else:
                    dists[distance] = 1

                dists = graph[(points[j][0], points[j][1])]
                if distance in dists:
                    dists[distance] += 1
                else:
                    dists[distance] = 1

        count = 0
        for point in graph:
            dists = graph[point]
            for dist in dists:
                num = dists[dist]
                if num <= 1:
                    count += 0
                else:
                    count += num * (num - 1)

        return count

print(Solution().numberOfBoomerangs([[0,0],[1,0],[-1,0],[0,1],[0,-1]]))


# from game.objects import Transport, Planet
from game.objects.trade_station import TradeStation
from game.objects.planet import Planet
from game.objects.transport import Transport

class SolarSystem:
    def __init__(self, interface):
        self.interface = interface
        self.objects = interface.init_objects()
        # self.planets = []
        # self.tradestations = []
        # self.transports = []
        self.__init_planets()
        self.__init_transports()
        self.__init_tradestations()

    def debug(self):
        print(self.objects)

    def __init_transports(self):
        self.transports = []
        for tr in self.objects['transportcontrol']:
            self.transports.append(Transport(tr, self.interface))

    def __init_planets(self):
        self.planets = []
        screen_planets = self.interface.get_planets(self.objects['planet'])
        for planet in screen_planets:
            self.planets.append(Planet(planet))

    def __init_tradestations(self):
        self.tradestations = []
        for ts in self.objects['tradestation']:
            self.tradestations.append(TradeStation(ts))


import json
import random

from flask import Flask, redirect, url_for, request, jsonify, make_response

app = Flask(__name__)

data = json.load(open('services.json'))
imeiservicelist = data["IMEISERVICELIST"]
accountinfo = data["ACCOUNTINFO"]

@app.route('/api/index.php', methods=['POST', 'GET'])
def imeiservices():  # put application's code here
    if request.method == 'POST' and request.form['action'] == 'imeiservicelist':
        return imeiservicelist
    elif request.method == 'POST' and request.form['action'] == 'accountinfo':
        return accountinfo
    else:
        return make_response(jsonify({"status": "read documentation"}), 400)

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


import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn import metrics
import pickle
import scipy
from sklearn.datasets import make_classification
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

# Læs og omskriv filen til at have headers.
data = pd.read_csv("SMSSpamCollection", delimiter='\t')
data.to_csv('SMSSpamCollection.csv', header=["Kategori", "SMS"], index=False)

# Læs nye fil data til df
df = pd.read_csv("SMSSpamCollection.csv")

# Tæl froskellige værdier der er i columns.
# print(df.shape)

# Print de første 5 rows.
# print(df.head())

# Tæl hvor mange værdier der er af hver kategori værdi.
# print(df['Kategori'].value_counts())

# Lav en plot graph over antal af kategorier fra Kategori column.
# df['Kategori'].value_counts().plot.bar(rot=50, title='Antal af kategori værdier')
# plt.show()

# Statistik over værdier i hvert row fra filen
# print(df['SMS'].str.split().apply(len).describe())
# Gennemsnit af ord pr. row.
# print("Rows/Ord-per-row forhold er:", round(5571 / 15.59))
# Print det row med den korteste værdi, som er ét ord. "Yup"
# print(df[df['SMS'].str.split().apply(len) == 1]['SMS'].values[0])
# Print det row med fleste værdier, som er 171 ord.
# print(df[df['SMS'].str.split().apply(len) == 171]['SMS'].values[0][:1000])

# Ny colonne med kategori værdien pr. row.
# le = LabelEncoder().fit(df["Kategori"])
# df['Kategori_værdi'] = le.transform(df["Kategori"])
# print(df.head())

# Fjern dupliketter og print de to kategorier spam / ham som er i kategori_værdi
# df_categories = df[['Kategori', 'Kategori_værdi']].drop_duplicates().sort_values('Kategori_værdi')
# print(df_categories)

# Split test data til train og test datasæt.
# x_train, x_test, y_train, y_test = train_test_split(
#    df['SMS'], df['Kategori_værdi'], test_size=.2, stratify=df['Kategori'], random_state=42)

# Print første værdi af x_train data, max 1000 karakterer.
# print(x_train[0][:1000])

# tyvstjålet ..
# def tfidf_transform(x_train, x_test):
#    kwargs = {
#        'ngram_range': (1, 1),  # Use 1-grams + 2-grams.
#        'analyzer': 'word',  # Split text into word tokens.
#        'min_df': 1,
#        'stop_words': "english",
#    }
#    vectorizer = TfidfVectorizer(**kwargs)
# Learn vocabulary from training texts and vectorize training texts.
#    x_train_transformed = vectorizer.fit_transform(x_train)
# Vectorize validation texts.
#    x_test_transformed = vectorizer.transform(x_test)
#    return x_train_transformed, x_test_transformed

# tfidf_train, tfidf_test = tfidf_transform(x_train, x_test)
# print(tfidf_train.shape)  # (4456, 7441)

# Print første test data efter tfidf transformationen
# print(tfidf_train[0].data)  # [0.64582673 0.52647801 0.55292743]

# train_tfidf_dense = scipy.sparse.csr_matrix.todense(tfidf_train)
# print(train_tfidf_dense[0])  # [[0. 0. 0. ... 0. 0. 0.]]
# print(len(train_tfidf_dense))  # 4456
# print(train_tfidf_dense[0][train_tfidf_dense[0] != 0][0])  # [[0.52647801 0.64582673 0.55292743]]

# classification models med sickit library

# print(df.shape, df['Kategori'].nunique())
# df.head(2)  # (5571, 3) 2

X_train, X_test, y_train, y_test = train_test_split(
    df['SMS'], df['Kategori'], test_size=.10, stratify=df['Kategori'], random_state=42)

print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)  # (4456,) (1115,) (4456,) (1115,)

# Tyvstjålet SVC pipeline..
def svc_pipleline():
    return Pipeline(
        [
            (
                "tfidf_vector_com",
                TfidfVectorizer(
                    input="array",
                    norm="l2",
                    max_features=None,
                    sublinear_tf=True,
                    stop_words="english",
                ),
            ),
            (
                "clf",
                SVC(
                    C=10,
                    kernel="rbf",
                    gamma=0.1,
                    probability=True,
                    class_weight=None,
                ),
            ),
        ]
    )

def print_metrics(pred_test, y_test, pred_train, y_train):
    print("test accuracy", str(np.mean(pred_test == y_test)))
    print("train accuracy", str(np.mean(pred_train == y_train)))
    print("\n Metrics and Confusion for SVM \n")
    print(metrics.confusion_matrix(y_test, pred_test))
    print(metrics.classification_report(y_test, pred_test))

# SVM præcision test
print('SVM Precision')
svc_pipe = svc_pipleline()
svc_pipe.fit(X_train, y_train)
pred_test = svc_pipe.predict(X_test)
pred_train = svc_pipe.predict(X_train)
print_metrics(pred_test, y_test, pred_train, y_train)

# Vis prediction af "trained data" i et confusion matrix display
cm = confusion_matrix(y_train, pred_train, labels=svc_pipe.classes_)
disp = ConfusionMatrixDisplay(confusion_matrix=cm,
                              display_labels=svc_pipe.classes_)
disp.plot()
plt.show()