"""
Conversion script for refractiveindex.info data.

Converts refractiveindex.info data stored in yaml files into JSON format for the Raysect library.
This script must be run from the root of a copy of the refractiveindex.info database.

Only a subset of the database is exported, as required for Raysect.

* RefractiveIndex.INFO website: © 2008-2016 Mikhail Polyanskiy
* refractiveindex.info database: public domain via CC0 1.0
* NO GUARANTEE OF ACCURACY - Use on your own risk
"""

import yaml
import json

def parse_tabulated_nk(d):

    # check type
    dtype = d['type']
    if dtype != 'tabulated nk':
        raise ValueError('File does not contain tabulated nk data.')

    table = d['data']

    # convert string table to values (wavelength in nm)
    wavelength = []
    index_re = []
    index_im = []
    lines = table.strip().split('\n')
    for line in lines:
        wl, n, k = tuple(line.strip().split(' '))
        wavelength.append(float(wl) * 1000)
        index_re.append(float(n))
        index_im.append(float(k))

    return wavelength, index_re, index_im

def yaml_to_json(input_filename, output_filename):

    with open(input_filename) as f:
        d = yaml.load(f)

    wl, ir, ii = parse_tabulated_nk(d['DATA'][0])

    content = {
        'reference': d['REFERENCES'],
        'wavelength': wl,
        "index": ir,
        "extinction": ii
    }

    with open(output_filename, 'w') as f:
        json.dump(content, f, indent=4)

materials = [
    ('database/main/Ag/Rakic', 'silver'),
    ('database/main/Al/Rakic', 'aluminium'),
    ('database/main/Au/Rakic', 'gold'),
    ('database/main/Be/Rakic', 'beryllium'),
    # ('database/main/C/Hagemann', 'carbon'),
    ('database/main/Co/Johnson', 'cobolt'),
    ('database/main/Cu/Rakic', 'copper'),
    ('database/main/Fe/Johnson', 'iron'),
    ('database/main/Hg/Inagaki', 'mercury'),
    ('database/main/Li/Rasigni', 'lithium'),
    ('database/main/Mg/Hagemann', 'magnesium'),
    ('database/main/Mn/Johnson', 'manganese'),
    ('database/main/Na/Inagaki', 'sodium'),
    ('database/main/Ni/Rakic', 'nickel'),
    ('database/main/Pd/Rakic', 'palladium'),
    ('database/main/Pt/Rakic', 'platinum'),
    ('database/main/Si/Jellison', 'silicon'),
    ('database/main/Ti/Rakic', 'titanium'),
    ('database/main/W/Rakic', 'tungsten'),
]

# convert data
for input, output in materials:
    yaml_to_json(input + ".yml", output + ".json")


from absl.testing import absltest
from absl.testing import parameterized
from tracr.compiler import basis_inference
from tracr.compiler import nodes
from tracr.compiler import rasp_to_graph
from tracr.rasp import rasp

class InferBasesTest(parameterized.TestCase):

  def test_arithmetic_error_logs_warning(self):
    program = rasp.numerical(rasp.Map(lambda x: 1 / x, rasp.tokens))
    extracted = rasp_to_graph.extract_rasp_graph(program)
    vocab = {0, 1, 2}
    with self.assertLogs(level="WARNING"):
      basis_inference.infer_bases(
          extracted.graph,
          extracted.sink,
          vocab,
          max_seq_len=1,
      )

  @parameterized.parameters(({1, 2, 3}, {2, 3, 4}), ({0, 5}, {1, 6}))
  def test_one_edge(self, vocab, expected_value_set):
    program = rasp.categorical(rasp.Map(lambda x: x + 1, rasp.tokens))
    extracted = rasp_to_graph.extract_rasp_graph(program)

    basis_inference.infer_bases(
        extracted.graph,
        extracted.sink,
        vocab,
        max_seq_len=1,
    )

    self.assertSetEqual(
        extracted.graph.nodes[program.label][nodes.VALUE_SET],
        expected_value_set,
    )

  def test_primitive_close_to_tip(self):
    intermediate = rasp.categorical(rasp.tokens + 1)
    intermediate = rasp.categorical(intermediate + intermediate)
    program = rasp.categorical(intermediate + rasp.indices)
    extracted = rasp_to_graph.extract_rasp_graph(program)

    basis_inference.infer_bases(
        extracted.graph,
        extracted.sink,
        {0, 1},
        max_seq_len=2,
    )

    self.assertSetEqual(
        extracted.graph.nodes[program.label][nodes.VALUE_SET],
        {2, 3, 4, 5},
    )
    self.assertSetEqual(
        extracted.graph.nodes[intermediate.label][nodes.VALUE_SET],
        {2, 3, 4},
    )

  def test_categorical_aggregate(self):
    program = rasp.categorical(
        rasp.Aggregate(
            rasp.Select(rasp.tokens, rasp.indices, rasp.Comparison.EQ),
            rasp.indices,
        ))

    extracted = rasp_to_graph.extract_rasp_graph(program)

    basis_inference.infer_bases(
        extracted.graph,
        extracted.sink,
        {0, 1},
        max_seq_len=3,
    )

    self.assertSetEqual(
        extracted.graph.nodes[program.label][nodes.VALUE_SET],
        {0, 1, 2},
    )

  def test_numerical_aggregate(self):
    program = rasp.numerical(
        rasp.Aggregate(
            rasp.Select(rasp.tokens, rasp.indices, rasp.Comparison.EQ),
            rasp.indices,
        ))

    extracted = rasp_to_graph.extract_rasp_graph(program)

    basis_inference.infer_bases(
        extracted.graph,
        extracted.sink,
        {0, 1},
        max_seq_len=2,
    )

    self.assertSetEqual(
        extracted.graph.nodes[program.label][nodes.VALUE_SET],
        {0, 1, 1 / 2},
    )

  def test_selector_width(self):
    program = rasp.SelectorWidth(
        rasp.Select(rasp.tokens, rasp.indices, rasp.Comparison.EQ))

    extracted = rasp_to_graph.extract_rasp_graph(program)

    basis_inference.infer_bases(
        extracted.graph,
        extracted.sink,
        {0, 1},
        max_seq_len=2,
    )

    self.assertSetEqual(
        extracted.graph.nodes[program.label][nodes.VALUE_SET],
        {0, 1, 2},
    )

if __name__ == "__main__":
  absltest.main()


import cv2
import debugpy

cat = cv2.imread('cat.jpg')
print(cat.shape)
#399,600,3 이렇게 나오는데 399줄에 600열이나 되는 데이터 3면이 겹쳐져 있다. 3차원으로 라는 뜻
#print(cat[::100])

cv2.imshow('cat',cat)
cv2.waitKey(0) #사용자 입력을 받는키 그런데 0을 주면 무한대기

dog = cv2.imread('dog.jpg')
dog  =cv2.resize(dog,(600,399))
print(dog.shape)
#399,600,3 이렇게 나오는데 399줄에 600열이나 되는 데이터 3면이 겹쳐져 있다. 3차원으로 라는 뜻
#print(cat[::100])

cv2.imshow('dog',dog)
key = cv2.waitKey(0)
print(key)

shark = cv2.imread('shark.jpg')
shark =cv2.resize(shark,(600,399))
print(shark.shape)
#399,600,3 이렇게 나오는데 399줄에 600열이나 되는 데이터 3면이 겹쳐져 있다. 3차원으로 라는 뜻
#print(cat[::100])

cv2.imshow('shark',shark)
key = cv2.waitKey(0)
print(key)


# Constant current
import pandas as pd
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from scipy.optimize import curve_fit

N = 130

df = pd.read_csv("4.csv") # Read data

#Getting Current for the Helmholtz Coils V=IR => I=V/R
cur = []
for i in range(len(df.index)):
    r = df.iloc[i,4]/df.iloc[i,5]
    cur.append(r)
df['Current (A)']=cur

# Getting the radius
rad = []
for i in range(len(df.index)):
    r = 16E-2
    rad.append(r)
df['Radius of Solenoids (m)'] = rad

#Averaging the left and right radius
ave = []
for i in range(len(df.index)):
    a = (df.iloc[i,6] + df.iloc[i,7])/2
    ave.append(a**-2)
df['Average Radius of beam (cm)'] = ave

#Calculating Magnetic field
mag_f = []
for i in range(len(df.index)):
    a = 4 * math.pi * 10**(-7) #𝜇
    a = a * 0.16**2 #𝜇𝑅^2
    a = a * N * df.iloc[i,8] #𝜇𝑅^2𝑁𝐼
    b = 0.16**2 + (0.16/2)**2 #
    b = b**(3/2)
    a = a/b
    mag_f.append(a)
df['Magnetic Field'] = mag_f

# Calculating e/m
ratio = []
for i in range(len(df.index)):
    a = (2 * df.iloc[i,2])/( (df.iloc[i,10])**2  *   (df.iloc[i,11])**2)
    ratio.append(a)
df['e/m'] = ratio

df.to_csv('DF.csv')

print(df)

x = []
for i in range(len(df.index)):
    a = df.iloc[i,2]
    x.append(a)

y = []
for i in range(len(df.index)):
    a = df.iloc[i,10]**2
    y.append(a)

m,b = np.polyfit(x, y, 1)
print(m)
print(b)

p, res, _, _, _ = np.polyfit(x, y, 1, full=True)
print(p)
print(res)

print(len(x))

slopes = []
for i in range(len(x)):
    slopes.append( m*x[i] + b)

plt.xlabel("Accelerating Voltage")
plt.ylabel("Radius Squared")
error = [1E-3,1E-3,1E-3,1E-3,1E-3,1E-3,]

plt.title("Radius Square as a function of V (A=1.11A$\pm$0.01A)")
plt.xlabel("Accelerating Voltage (B)")
plt.ylabel("Radius Squared (r^2)")
plt.plot(x, slopes)
plt.scatter(x, y)
plt.errorbar(x,y,yerr=error,ls='none')
#plt.errorbar(x,y,yerr=np.power(error,2),ls='none')
plt.show()


"""Test the field discovery functions for various targets."""
import typing
from pathlib import Path

import pytest
from hopscotch import Registry
from hopscotch.field_infos import FieldInfo
from hopscotch.field_infos import get_dataclass_field_infos
from hopscotch.field_infos import get_field_origin
from hopscotch.field_infos import get_non_dataclass_field_infos
from hopscotch.field_infos import get_operator
from hopscotch.field_infos import get_stdlib_module_names
from hopscotch.fixtures import dataklasses
from hopscotch.fixtures import DummyOperator
from hopscotch.fixtures import functions
from hopscotch.fixtures import named_tuples
from hopscotch.fixtures import plain_classes
from hopscotch.fixtures.dataklasses import Customer
from hopscotch.fixtures.dataklasses import GreeterFirstName
from hopscotch.fixtures.dataklasses import Greeting
from hopscotch.fixtures.dataklasses import GreetingOperator
from hopscotch.fixtures.dataklasses import GreetingPath
from hopscotch.fixtures.dataklasses import GreetingTuple
from hopscotch.operators import Get
from hopscotch.operators import Operator

def test_get_stdlib_module_names() -> None:
    """Test the helper function which runs at startup."""
    module_names = get_stdlib_module_names()
    assert "contextlib" in module_names
    assert "builtins" in module_names

@pytest.mark.parametrize(
    "target, expected",
    [
        (dataklasses.Greeter, dataklasses.Greeting),
        (functions.Greeter, str),
        (named_tuples.Greeter, named_tuples.Greeting),
        (plain_classes.Greeter, plain_classes.Greeting),
    ],
)
def test_get_field_origin_no_generic(target: object, expected: object) -> None:
    """Find correct type with *no* generic involved."""
    th = typing.get_type_hints(target, globalns=None, localns=None)
    param1_annotation = th["greeting"]
    actual = get_field_origin(param1_annotation)
    assert expected is actual

@pytest.mark.parametrize(
    "target, expected",
    [
        (dataklasses.GreeterOptional, dataklasses.Greeting),
        (functions.GreeterOptional, str),
        (named_tuples.GreeterOptional, named_tuples.Greeting),
        (plain_classes.GreeterOptional, plain_classes.Greeting),
    ],
)
def test_get_field_origin_generic(target: object, expected: object) -> None:
    """Find correct type with a generic involved."""
    th = typing.get_type_hints(target, globalns=None, localns=None)
    param1_annotation = th["greeting"]
    result = get_field_origin(param1_annotation)
    assert expected is result

@pytest.mark.parametrize(
    "target, expected",
    [
        (dataklasses.GreeterAnnotated, dataklasses.Greeting),
        (named_tuples.GreeterAnnotated, named_tuples.Greeting),
        (plain_classes.GreeterAnnotated, plain_classes.Greeting),
    ],
)
def test_get_field_origin_annotated(target: object, expected: object) -> None:
    """Find correct type with an ``Annotated`` involved."""
    th = typing.get_type_hints(target, globalns=None, localns=None)
    param1_annotation = th["greeting"]
    result = get_field_origin(param1_annotation)
    assert expected is result

@pytest.mark.parametrize(
    "target, expected",
    [
        (functions.GreeterAnnotated, str),
    ],
)
def test_get_field_origin_annotated_function(target: object, expected: object) -> None:
    """Find correct type with an ``Annotated`` involved."""
    th = typing.get_type_hints(target, globalns=None, localns=None)
    param1_annotation = th["customer_name"]
    result = get_field_origin(param1_annotation)
    assert expected is result

@pytest.mark.parametrize(
    "target",
    [
        dataklasses.Greeting,
        functions.Greeting,
        named_tuples.Greeting,
        plain_classes.Greeting,
    ],
)
def test_get_field_origin_primitive_type(target: type) -> None:
    """Find correct type with a primitive type like ``str``."""
    th = typing.get_type_hints(target, globalns=None, localns=None)
    param1_annotation = th["salutation"]
    result = get_field_origin(param1_annotation)
    assert str is result

def test_parameter_no_hint() -> None:
    """A function parameter with no type hint should be None."""
    target = functions.GreetingDefaultNoHint
    field_infos = get_non_dataclass_field_infos(target)
    field_type = field_infos[0].field_type
    assert None is field_type

def test_dummy_get_operator() -> None:
    """See if we can get the annotation to get the operator."""
    aa = getattr(typing, "_AnnotatedAlias")
    field_type = aa(str, (DummyOperator("some_arg"),))
    field_type, operator = get_operator(field_type)
    assert str is field_type
    registry = Registry()
    if operator is not None:
        assert "some_arg" == operator(registry)

def test_get_operator_no_annotated() -> None:
    """A field with no ``Annotated`` shouldn't fail on get_operator.

    This simulates a field like ``title: str`` with no ``Annotated`` nor
    operator.
    """
    field_type, operator = get_operator(str)
    assert str is field_type
    assert None is operator

@pytest.mark.parametrize(
    "target, extractor",
    [
        (dataklasses.GreetingNoDefault, get_dataclass_field_infos),
        (functions.GreetingNoDefault, get_non_dataclass_field_infos),
        (named_tuples.GreetingNoDefault, get_non_dataclass_field_infos),
        (plain_classes.GreetingNoDefault, get_non_dataclass_field_infos),
    ],
)
def test_target_field_info_str(
    target: type, extractor: typing.Callable[..., list[FieldInfo]]
) -> None:
    """Variations of field_info extraction."""
    field_infos = extractor(target)
    assert field_infos[0].field_name == "salutation"
    assert field_infos[0].field_type == str
    assert field_infos[0].default_value is None
    assert field_infos[0].default_factory is None
    assert field_infos[0].has_annotated is False

@pytest.mark.parametrize(
    "target, extractor",
    [
        (dataklasses.GreeterChildren, get_dataclass_field_infos),
        (functions.GreeterChildren, get_non_dataclass_field_infos),
        (named_tuples.GreeterChildren, get_non_dataclass_field_infos),
        (plain_classes.GreeterChildren, get_non_dataclass_field_infos),
    ],
)
def test_field_info_children(
    target: type, extractor: typing.Callable[..., list[FieldInfo]]
) -> None:
    """Look for the magic-named ``children`` argument."""
    field_infos = extractor(target)
    assert field_infos[0].field_name == "children"
    assert field_infos[0].field_type is None
    assert field_infos[0].default_value is None

def test_field_info_default_value() -> None:
    """Confirm a default value."""
    field_infos = get_dataclass_field_infos(dataklasses.GreetingFieldDefault)
    assert field_infos[0].default_value == "Default Argument"

def test_field_info_default_factory() -> None:
    """Confirm a default factory."""
    field_infos = get_dataclass_field_infos(dataklasses.GreetingFieldDefaultFactory)
    assert field_infos[0].default_factory is list

def test_dataclass_field_info_init_false() -> None:
    """Look for the field constructor and init false."""
    field_infos = get_dataclass_field_infos(dataklasses.GreetingInitFalse)
    assert field_infos[0].field_name == "salutation"
    assert field_infos[0].field_type == str
    assert field_infos[0].default_value is None
    assert field_infos[0].has_annotated is False
    assert field_infos[0].is_builtin is True

def test_field_info_more_generic() -> None:
    """Look up a field that is a generic using ``tuple``."""
    field_infos = get_dataclass_field_infos(GreetingTuple)
    assert field_infos[0].field_name == "salutation"
    assert "GenericAlias" in str(type(field_infos[0].field_type))
    assert field_infos[0].default_value is None
    assert field_infos[0].is_builtin is True

def test_field_info_builtin() -> None:
    """Look up a field that is a a builtin ``Path``."""
    field_infos = get_dataclass_field_infos(GreetingPath)
    assert field_infos[0].field_name == "location"
    assert field_infos[0].field_type is Path
    assert field_infos[0].default_value is None
    assert field_infos[0].is_builtin is True

def test_dataclass_field_info_annotation() -> None:
    """Resolve an ``Annotated`` that uses an operator."""
    field_infos = get_dataclass_field_infos(GreetingOperator)
    assert field_infos[0].field_name == "greeter"
    assert field_infos[0].field_type is Greeting
    assert field_infos[0].default_value is None
    assert field_infos[0].is_builtin is False
    assert isinstance(field_infos[0].operator, Get)
    assert field_infos[0].has_annotated is True
    operator: Operator = field_infos[0].operator
    assert getattr(operator, "lookup_key") is Greeting

def test_dataclass_field_operator() -> None:
    """Field operators should result in same field info as annotated."""
    field_infos = get_dataclass_field_infos(GreeterFirstName)
    customer_name = field_infos[0]
    operator = customer_name.operator
    assert isinstance(operator, Get)
    assert operator.lookup_key == Customer
    assert operator.attr == "first_name"


def f(st):
    if len(st) == 20:
        return st[-1] != 'Г'
    summ = 0

    for i in 'ГОЛ':
        if st[-1] != i:
            if st[-1] == 'Г':
                summ += f(st + i) if i != st[-2] else 0
            else:
                summ += f(st + i)
    return summ
print(sum(f(let) for let in 'ОЛ'))


#!/usr/bin/env python3
'''
# --------------------------------------- #
# MARV Remote Network Steering Scenario   #
# By Linus Johansson and                  #
# Joakim Osterman, Spring 2022            #
# Chalmers University of Technology       #
# --------------------------------------- #
'''

# System imports
import time
import numpy as np
import os

import json

# Custom libraries
from timer import Timer
from scenario import Scenario
from thrust_controller import ThrustController
from heading_controller import HeadingController

# ROS Imports
import rclpy
from rclpy.node import Node
from rclpy.executors import MultiThreadedExecutor
from rclpy.parameter import Parameter

# Messages
from std_msgs.msg import Bool
from std_msgs.msg import String
from marv_msgs.msg import CmdSteering

class Remote_Network_Steering(Scenario):

    ##################################### INIT #############################################################

    def __init__(self):
        '''The Init function is run on node start. Should not subscribe, publish or start any timers
            except for the "run_setup_check_timer". This is because we don't want anything running in the
            background when this scenario is not running.
        '''
        # Scenario name parameter (this needs to be added/same as the name in /marv_driver/config/scenarios.yaml)
        __scenario_name = "RNS"
        # Scenario data variable headers, set to "" if not used, max 7 characters
        __data_var_1_header = "SPEED"
        __data_var_2_header = "ANGLE"

        # Initialize Scenario Wrapper (handles the logic for starting and stopping scenarios)
        super().__init__('remote_network_steering',__scenario_name,__data_var_1_header,__data_var_2_header)

        self.get_logger().info("Initializing Scenario Node: " + __scenario_name)

        # Declare rosparams
        self.declare_parameters(
            namespace='',
            parameters=[
                ('thrust_controller_gain', None),
                ('thrust_anti_windup_gain', None),
                ('aps_signal_limit_min', None),
                ('aps_signal_limit_max', None),
                ('surge_rate_limit', None),
                ('heading_controller_gain', None),
                ('heading_anti_windup_gain', None),
                ('steering_angle_limit', None),
                ('steering_angle_rate_limit', None),
                ('u_min', None),
                ('delta_t', None),
                ('vel_diff_ang', None),
                ('ref_pos', None),
                ('wp_file_name', None),
                ('update_freq', None),
                ('wait_time', None),
                ('start_sound_time', None),
            ])

        # ------- Global variables -------
        self.run_setup = True # Whenever to run the setup method when in INITIALIZING mode

        # Timers
        self.node_start_delay_timer = Timer()
        self.u_vel_update_timeout = 1 # second before counting the velocity input data as too outdated, signaling fault

        # State variables
        #self.u_vel = 0.0 # Current velocity
        #self.r_vel = 0.0 # Current angular velocity
        #self.eta = np.array([0, 0, 0]) # Current position state: x,y,psi

        # Controller signal
        self.aps_signal = 0.0
        self.steering_angle = 0.0
        # --------------------------------

        # ------- Constants --------------
        # Thrust, APS and surge constants
        self.thrust_controller_gain = self.get_parameter('thrust_controller_gain').value
        self.thrust_anti_windup_gain = self.get_parameter('thrust_anti_windup_gain').value
        self.aps_signal_limit_min = self.get_parameter('aps_signal_limit_min').value
        self.aps_signal_limit_max = self.get_parameter('aps_signal_limit_max').value
        self.surge_rate_limit = self.get_parameter('surge_rate_limit').value

        # Heading and steering constants
        self.heading_controller_gain = self.get_parameter('heading_controller_gain').value
        self.heading_anti_windup_gain = self.get_parameter('heading_anti_windup_gain').value
        self.steering_angle_limit = self.get_parameter('steering_angle_limit').value
        self.steering_rate_limit = self.get_parameter('steering_angle_rate_limit').value

        # Other parameters
        self.u_min = self.get_parameter('u_min').value
        self.delta_t = self.get_parameter('delta_t').value
        self.vel_diff_ang = self.get_parameter('vel_diff_ang').value
        self.ref_pos = self.ref_pos = self.get_parameter('ref_pos').value
        self.wp_file_name = self.get_parameter('wp_file_name').value
        self.update_freq = self.get_parameter('update_freq').value
        self.wait_time = self.get_parameter('wait_time').value
        self.start_sound_time = self.get_parameter('start_sound_time').value
        # --------------------------------

        # Configuration parameters
        self.main_loop_update_period = 1/self.update_freq # seconds update time for the main loop, where the controller should be
        self.get_new_params_period = 5.0 # seconds update time for updating with new rosparams

        # Load heading refshape fir coefficients
        hrf_file_path = os.getcwd() + '/colcon_ws/src/marv_scenarios/resource/heading_fir.csv'
        self.heading_ref_fir_coefficients = np.loadtxt(hrf_file_path, delimiter = ',')

        # Load heading yaw fir coefficients
        hyf_file_path = os.getcwd() + '/colcon_ws/src/marv_scenarios/resource/yaw_fir.csv'
        self.heading_yaw_fir_coefficients = np.loadtxt(hyf_file_path, delimiter = ',')

        # Load thrust fir coefficients
        tf_file_path = os.getcwd() + '/colcon_ws/src/marv_scenarios/resource/thrust_fir.csv'
        self.thrust_fir_coefficients = np.loadtxt(tf_file_path, delimiter = ',')

        # Other variables
        self.start_sound_sent = False
        self.start_sound_signal_id = 4
        self.controllers_created = False # Run controller setup once per run

        ### RNS Init stuff ###
        self.gamepad = {}

        self.killswitch = 0
        self.reset_killswitch = 0

        self.speed = 0.0   #self.aps_signal = 0.0
        self.angle = 0.0      #self.steering_angle = 0.0

        self.setSpeed = 0.0

        self.dt = 0.03

        # Check setup timer config
        self.__run_setup_check_timer_period = 0.1 # seconds between checking if the setup should be run (which should be done when the scenario is running)

        # Check setup timer
        self.__run_setup_check_timer = self.create_timer(self.__run_setup_check_timer_period,self.__run_setup_check_callback)

        self.get_logger().info("Started Scenario Node: " + __scenario_name)

    ########################################################################################################

    ##################################### SETUP, TEARDOWN AND CHECK ########################################

    def __run_setup_check_callback(self):
        # If scenario is being initialized, run setup
        if self.run_setup and self.get_scenario_state() == "INITIALIZING":
            self.run_setup = False # Prevent the setup from being run several times
            self.__setup() # Call setup
        elif not self.run_setup and self.get_scenario_state() == "STOPPED":
            self.__teardown()
            self.run_setup = True

    def __setup(self):
        '''Setup configuration parameters, global variables, subscriptions, publishes and timers.
            This function is run when the scenario is initializing, i.e. requested to start but not
            yet runnung (we are still in manual mode which needs to be changed to external to start)
        '''

        # Subscriptions (subscribe to for example sensor data)
        self.gamepad_input = self.create_subscription(String, 'web_ui/gamepad/msg', self.receive_input, 10)

        # Publishes
        #self.marv_sys_ctrl_cmdSteering_publisher = self.create_publisher(CmdSteering, '/marv/sys/ctrl/cmd_steering', 10)

        # Allow time for subscriptions and publishes to be set up
        time.sleep(1.0)

        # Custom timers
        self.node_start_delay_timer.stop()

        # Other variables
        self.start_sound_sent = False
        self.controllers_created = False

        # Timers
        # Set a timer for the main_loop_callback (where the scenario is running)
        self.main_loop_timer = self.create_timer(self.main_loop_update_period, self.main_loop_callback)
        #self.get_new_params_timer = self.create_timer(self.get_new_params_period, self.update_params_callback)

    def __teardown(self):
        '''Teardown timers, publishers and subscriptions when the scenario is no longer running'''

        self.destroy_subscription(self.gamepad_input)
        self.destroy_subscription(self.marv_sys_ctrl_cmdSteering_publisher)

        self.main_loop_timer.cancel()
        #self.get_new_params_timer.cancel()

    ########################################################################################################

    ##################################### MAIN LOOP CALLBACK ###############################################

    # Main program loop
    def main_loop_callback(self):
        '''When the external mode is activated, get_scenario_running() will turn true. After that
            the steering commands needs to be updated with at least 10 Hz, using self.update_cmd_steering(), otherwise there will be
            a system error since the PDU will sense that the updates has stopped.
        '''

        if self.get_scenario_running():
            # Start timer to wait before starting
            if self.node_start_delay_timer.elapsed() == 0:
                self.node_start_delay_timer.start()
                self.aps_signal = 0.0
                self.steering_angle = 0.0
                self.get_logger().info("Timer started")

            # Wait
            elif self.node_start_delay_timer.elapsed() > 0 and self.node_start_delay_timer.elapsed() <= self.wait_time:
                if self.wait_time - self.node_start_delay_timer.elapsed() > 0:
                    self.set_progress(str(round(self.wait_time - self.node_start_delay_timer.elapsed(),2))) # Show start countdown
                else:
                    self.set_progress(str(0.00))

                self.set_data_var_1(str("--"))
                self.set_data_var_2(str("--"))

                # Send the buzzer start signal
                if self.start_sound_sent == False and (self.wait_time - self.node_start_delay_timer.elapsed() < self.start_sound_time) and self.start_sound_time != 0:
                    self.start_sound_sent = True
                    self.set_buzzer_signal(self.start_sound_signal_id)
                    self.update_buzzer_signal()
                    self.get_logger().info("Buzzer signal sent")

            # Start
            elif self.node_start_delay_timer.elapsed() > self.wait_time:

                if self.gamepad.get("button0"):
                    self.killswitch = 1
                if self.gamepad.get("button3"):
                    self.reset_killswitch = 0
                if not self.gamepad.get("button0"):
                    self.killswitch = 0
                    self.reset_killswitch = 1

                if self.killswitch and not self.reset_killswitch:
                    self.steering_angle = -self.gamepad.get("lJoy") * 22     # Jetski positive angle = left steer

                    #lTrigVal = abs(-round(float(self.gamepad.get("lTrig")), 2)) / 2
                    #rTrigVal = (round(float(self.gamepad.get("rTrig")), 2)) / 2 + 0.5

                    #if lTrigVal >= rTrigVal:
                    #    self.setSpeed = lTrigVal - rTrigVal
                    #else:
                    #    self.setSpeed = rTrigVal - lTrigVal

                    #if self.setSpeed < self.speed and self.speed > 0.01:
                    #    if self.speed >= 0.52:
                    #        self.speed -= 0.02
                    #    else:
                    #        self.speed -= 0.01
                    #elif self.setSpeed > self.speed:
                    #    if self.speed < 0.52:
                    #        self.speed += 0.02
                    #    else:
                    #        self.speed += 0.01

                    #print(f"Speed: {self.speed}, Angle: {self.angle}")
                    #self.send_cmdSteering(self.speed, 0.0, self.angle)

                #if not self.killswitch:
                #    self.setSpeed = 0.52
                #    while not(self.speed > 0.5 and self.speed < 0.56):
                #        if self.speed < 0.54:
                #            self.speed += 0.04
                #        elif self.speed > 0.50:
                #            self.speed -= 0.04

                #        print(f"Speed: {self.speed}, Angle: {self.angle}")
                #        self.send_cmdSteering(self.speed, 0.0, self.angle)

                #        sleep(self.dt)

                # Get new control signals
                self.aps_signal = 0.0

                # Set steering commands
                self.set_cmd_steering_aps(self.aps_signal)
                self.set_cmd_steering_angle(self.steering_angle)

            self.update_cmd_steering() # Send the complete steering command to the system
            self.update_all_variables() # Send the updated variables to the system

    ########################################################################################################

    ##################################### CALLBACKS ########################################################

    def receive_input(self, msg):
        self.gamepad = json.loads(msg.data)

    # Get current velocity from INS
    def marv_velocity_callback(self,ros_msg):
        self.u_vel = ros_msg.x # Surge

    def marv_angular_velocity_callback(self,ros_msg):
        self.r_vel = ros_msg.z # Yaw

    # Get current pose from INS
    def marv_pose_callback(self,ros_msg):
        self.eta[0] = ros_msg.pose.position.x
        self.eta[1] = ros_msg.pose.position.y
        eta_pose_quat = self.quaternion_to_euler_deg(ros_msg.pose.orientation.x, ros_msg.pose.orientation.y, ros_msg.pose.orientation.z, ros_msg.pose.orientation.w)
        self.eta[2] = eta_pose_quat[2]

    # Set reference position
    def marv_ref_pos_state_callback(self,ros_msg):
        if ros_msg.data == False:
            ref_pos_message = Vector3()
            ref_pos_message.x = float(self.ref_pos[0])
            ref_pos_message.y = float(self.ref_pos[1])
            ref_pos_message.z = float(self.ref_pos[2])
            self.ref_pos_publisher_.publish(ref_pos_message)

    def update_params_callback(self):
        # Thrust, APS and surge constants
        self.thrust_controller_gain = self.get_parameter('thrust_controller_gain').value
        self.thrust_anti_windup_gain = self.get_parameter('thrust_anti_windup_gain').value
        self.aps_signal_limit_min = self.get_parameter('aps_signal_limit_min').value
        self.aps_signal_limit_max = self.get_parameter('aps_signal_limit_max').value
        self.surge_rate_limit = self.get_parameter('surge_rate_limit').value

        # Heading and steering constants
        self.heading_controller_gain = self.get_parameter('heading_controller_gain').value
        self.heading_anti_windup_gain = self.get_parameter('heading_anti_windup_gain').value
        self.steering_angle_limit = self.get_parameter('steering_angle_limit').value
        self.steering_rate_limit = self.get_parameter('steering_angle_rate_limit').value

        # Other parameters
        self.u_min = self.get_parameter('u_min').value
        self.delta_t = self.get_parameter('delta_t').value
        self.vel_diff_ang = self.get_parameter('vel_diff_ang').value
        self.ref_pos = self.get_parameter('ref_pos').value
        self.wp_file_name = self.get_parameter('wp_file_name').value
        self.update_freq = self.get_parameter('update_freq').value
        self.wait_time = self.get_parameter('wait_time').value
        self.start_sound_time = self.get_parameter('start_sound_time').value

    ########################################################################################################

    ##################################### OTHER FUNCTIONS ##################################################

    ########################################################################################################

def main(args=None):
    rclpy.init(args=args)

    remote_network_steering = Remote_Network_Steering()

    rclpy.spin(remote_network_steering)

    remote_network_steering.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()


from __future__ import division
from unittest import TestCase

import numpy as np

import DigitRecognition.data.bounding_boxes_to_target as script

class TestBoundingBoxesToTarget(TestCase):
    def test_bounding_boxes_to_target_computes_correct_boxes_for_example(self):
        target = script.bounding_boxes_to_target(bounding_boxes=[(3, 31, 13, 10, 38), (0, 45, 15, 10, 38),
                                                                 (5, 59, 17, 10, 38), (5, 73, 19, 10, 38)],
                                                 anchor_boxes=[(10, 20), (20, 40)],
                                                 image_size=(100, 100),
                                                 grid_rows=10)

        # Is object?
        expected = np.zeros((10, 10))
        expected[3, 3] = 1
        expected[3, 4] = 1
        expected[3, 6] = 1
        expected[3, 7] = 1
        self.assertTrue(all(target[:, :, 0] == expected))

        # Object location (x)
        expected = np.zeros((10, 10))
        expected[3, 3] = .31
        expected[3, 4] = .45
        expected[3, 6] = .59
        expected[3, 7] = .73
        self.assertTrue(all(target[:, :, 1] == expected))

        # Object width
        expected = np.zeros((10, 10))
        expected[3, 3] = .38
        expected[3, 4] = .38
        expected[3, 6] = .38
        expected[3, 7] = .38
        self.assertTrue(all(target[:, :, 3] == expected))

    def test_intersection_over_union_for_simple_examples(self):
        result = script.intersection_over_union((10, 20), (10, 10))
        self.assertEqual(result, 0.5)

        result = script.intersection_over_union((20, 20), (30, 30))
        self.assertEqual(result, 4/9)

    def test_intersection_over_union_provides_same_result_for_random_boxes_but_switched_order(self):
        box_1 = np.random.randint(0, 100, size=2)
        box_2 = np.random.randint(0, 100, size=2)
        result1 = script.intersection_over_union(tuple(box_1), tuple(box_2))
        result2 = script.intersection_over_union(tuple(box_2), tuple(box_1))
        self.assertEqual(result1, result2)

    def test_anchor_boxes_chooses_correct_box_with_sample_data(self):
        anchor_boxes = [(10, 10), (20, 20), (30, 30)]
        index = script.get_anchor_box_index(anchor_boxes, (10, 10))
        self.assertEqual(index, 0)

        index = script.get_anchor_box_index(anchor_boxes, (10, 15))
        self.assertEqual(index, 0)

        index = script.get_anchor_box_index(anchor_boxes, (50, 50))
        self.assertEqual(index, 2)

    def test_get_index_in_range_works_correctly_with_sample_data(self):
        result = script.get_index_in_range(1, 10, 5)
        self.assertEqual(result, 0)

        result = script.get_index_in_range(5, 10, 5)
        self.assertEqual(result, 3)


# coding: utf-8

import sys
string = sys.stdin.readlines(64)

result = 0
for i in range(8):
    for j in range(8):
        if i % 2 == 0:
            if j % 2 == 0 and string[i][j] == 'F':
                result += 1
        else:
            if j % 2 == 1 and string[i][j] == 'F':
                result += 1

print(result)


testmark = []
quizmark = []                                 #Varibles
assignmentmark = []
quiztotal = 0
testtotal = 0
assignmenttotal = 0

print(75 * "*")    #Discription
print("This calculator helps you determine your final course grade without needing your current grade.")
print("You enter your number of quizes and the marks recived on them, number of tests and the marks recived on them, number of assignments and the marks recived on them, and finally your summative or exam mark which is worth 30% of your final grade.")
print("If you don't have tests, assignments, or quizes, just type 0 when prompted. But you need to have at least two of these three components or it would be harder (and impossible for this program)to determine your final grade.")
print("Keep in mind that all these weights are based on the actual course marking weights and that the teacher could have thier own mark weighting system.")

print(75 * "*")

quizes = int(input("How many quizes did you have?> "))
if (quizes > 0):

    for a in range(quizes):
            print("What was your mark for quiz",a+1,"?")
            q = int(input(">"))
            quizmark.append(q)                                     #Gets Input from user for each componet calculates the average for each
    for b in range(quizes):
            quiztotal = quiztotal + quizmark[b]

    quizmarks = len(quizmark)
    quizaverage = quiztotal/quizmarks
tests = int(input("How many unit tests did you have?> "))
if (tests > 0):

    for c in range(tests):
        print("What was your mark for unit test",c+1,"?")
        t = int(input(">"))
        testmark.append(t)
    for d in range(tests):
        testtotal = testtotal + testmark[d]
    testmarks = len(testmark)
    testaverage = testtotal/testmarks
assignments = int(input("How many assignments did you have?> "))
if (assignments > 0):

    for e in range(assignments):
        print("What was your mark for assignment",e+1,"?")
        a = int(input(">"))
        assignmentmark.append(a)
    for f in range(assignments):
       assignmenttotal = assignmenttotal + assignmentmark[f]
    assignmentmarks = len(assignmentmark)
    assignmentaverage = assignmenttotal/assignmentmarks

final = int(input("What was your mark for the summative or exam (30%)?> "))
if (quizes == 0):
    finalgrade = (0.30*assignmentaverage + 0.40*testaverage + 0.30*final)/1
    finalgrade = float(finalgrade)                                                          #Calculates the final grade accoding to the wieghts and what user inputted, then outputs the grade
    finalgrade = round(finalgrade,1)
    testaverage = round(testaverage,1)
    assignmentaverage = round(assignmentaverage,1)

    print(75*"*")
    print("Your test average is "+str(testaverage)+"%")
    print("Your assignment average is "+str(assignmentaverage)+"%")
    print("Your Final Course Grade is " + str(finalgrade) +"%")

    print(75*"*")
elif (assignments == 0):
    finalgrade = (0.20*quizaverage + 0.50*testaverage + 0.30*final)/1
    finalgrade = float(finalgrade)
    finalgrade = round(finalgrade,1)

    testaverage = round(testaverage,1)
    quizaverage = round(quizaverage,1)

    print(75*"*")
    print("Your test average is "+str(testaverage)+"%")
    print("Your quiz average is "+str(quizaverage)+"%")
    print("Your Final Course Grade is " + str(finalgrade) +"%")
    print(75*"*")
elif (tests == 0):
    finalgrade = (0.50*assignmentaverage + 0.20*quizaverage + 0.30*final)/1
    finalgrade = float(finalgrade)
    finalgrade = round(finalgrade,1)
    assignmenttaverage = round(assignmentaverage,1)
    quizaverage = round(quizaverage,1)

    print(75*"*")
    print("Your assignment average is "+str(assignmentaverage)+"%")
    print("Your quiz average is "+str(quizaverage)+"%")
    print("Your Final Course Grade is " + str(finalgrade) +"%")

    print(75*"*")
else:
    finalgrade = (0.20*assignmentaverage + 0.15*quizaverage + 0.35*testaverage + 0.30*final)/1
    finalgrade = float(finalgrade)
    finalgrade = round(finalgrade,1)
    testaverage = round(testaverage,1)
    quizaverage = round(quizaverage,1)
    assignmentaverage = round(assignmentaverage,1)
    print(75*"*")
    print("Your test average is "+str(testaverage)+"%")
    print("Your quiz average is "+str(quizaverage)+"%")
    print("Your assignment average is "+str(assignmentaverage)+"%")
    print("Your Final Course Grade is " + str(finalgrade) +"%")

    print(75*"*")


#!/usr/bin/env python
#_*_coding:utf-8_*_
#@author :yinzhengjie
#blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/
#EMAIL:y1053419035@qq.com

end = int(input("你想要打印乘法表是:"))

row = 1
while row <= end:
    col = 1
    while col <= row:
      print(str(col) + "x" + str(row) + "=" + str(row * col) + "\t",)
    print()
    row += 1

#print("shijie,你好")

# for i in range(1,10):
#     for j in range(1,i+1):
#         print(i,'*',j,'=',i*j,"\t",end="")
#     print("")


import sys
sys.path.append('../REFPROP')

from xml.dom import minidom
import numpy as np
from refprop import RefPropInterface

#from multiprocessing import Pool
import multiprocessing
import multiprocessing.pool

class NoDaemonProcess(multiprocessing.Process):
    @property
    def daemon(self):
        return False

    @daemon.setter
    def daemon(self, value):
        pass

class NoDaemonContext(type(multiprocessing.get_context())):
    Process = NoDaemonProcess

class MyPool(multiprocessing.pool.Pool):
    def __init__(self, *args, **kwargs):
        kwargs['context'] = NoDaemonContext()
        super(MyPool, self).__init__(*args, **kwargs)

class Manifold():

    refpropm = RefPropInterface().refpropm
    def __init__(self, base_path, root, initialMassFlow, initialVaporQuality=None, initialVaporQualitySector = None, setPointTemp=None, parent=None):

        from SingleBranch import SingleBranch
        self.SingleBranch = SingleBranch

        self.Name = base_path+root
        self.Fluid = "CO2" # this has to be determined by the XML... update later.
        self.setPointTemp = setPointTemp
        self.initialVaporQuality = initialVaporQuality #put 1% just to be safe
        self.initialVaporQualitySector = initialVaporQualitySector
        self.initialMassFlow = initialMassFlow
        self.branches = [] #array of manifolds (branches)
        self.xmls = []
        self.base_path = base_path
        self.root = root
        self.parent = parent
        self.series = None
        self.initialize()

    def initialize(self):
        self.branches = [[node.getAttribute('type'), node.getAttribute('loc'), node.getAttribute('vq0'), node.getAttribute('vq0_point')] for node in minidom.parse(self.base_path+self.root).getElementsByTagName("manifold")]
        for branch in self.branches:
            branch[2] = float(branch[2])
            branch[3] = int(branch[3])
        self.series = minidom.parse(self.base_path+self.root).getElementsByTagName("components")[0].getAttribute("type") == "series";
        self.explore()

    def explore(self):
        for b in range(len(self.branches)):
            branch = self.branches[b]
            if branch[0] == 'manifold':
                self.branches[b] = Manifold(self.base_path,
                                            branch[1],
                                            self.initialMassFlow if self.series else self.initialMassFlow/len(self.branches),
                                            0.0, # Manifold never have initial vapor quality, this is defined at the singlebranch level
                                            None,
                                            setPointTemp=self.setPointTemp,
                                            parent=self)
            else:
                self.branches[b] = self.SingleBranch(Fluid=self.Fluid,
                                                     Tsp=self.setPointTemp,
                                                     vq0 = branch[2],
                                                     vq0_point = branch[3] if branch[3]>=0 else None,
                                                     MF = self.initialMassFlow if self.series else self.initialMassFlow/len(self.branches),
                                                     xml = self.base_path+branch[1],
                                                     parent=self)

    def updateMassFlow(self, newMF):
        self.initialMassFlow = newMF
        for branch in self.branches:
            if not self.series:
                branch.updateMassFlow(self.initialMassFlow/len(self.branches))
            else:
                branch.updateMassFlow(self.initialMassFlow)

    def worker(self, branch):
        branch.run(run=True)
        return branch

    def minimize(self):
        N = len(self.branches)
        weights = np.full(N, self.initialMassFlow/N)
        for i in range(N):
            weights[i]=self.initialMassFlow*self.branches[i].getTotalAppliedHeat()/self.getTotalAppliedHeat()

        print("Total mass flow for {}: {} kg/s".format(" ".join(map(str, self.branches)), self.initialMassFlow))
        dPs = np.zeros_like(weights)
        epsilon = 0.1
        gamma = 0.0001
        counts = 0

        while dPs[0] == 0 or dPs.std() > epsilon:

            for b in range(len(self.branches)):
                branch = self.branches[b]
                branch.updateMassFlow(weights[b])
                # branch.run(run=True)

            p = MyPool(len(self.branches))
            self.branches = p.map(self.worker, self.branches)

            for b in range(len(self.branches)):
                branch = self.branches[b]
                dPs[b] = branch.getDP()

            counts+=1
            print("Iteration {}:\n\tmass flows in each branch: {}\n\tdelta pressure in each branch: {}".format(counts, weights, dPs))
            avgDP = dPs.mean()
            diffs = dPs-np.full(N, avgDP)
            weights+=gamma*diffs
        return avgDP

    def getDP(self):
        return self.branches[-1].getFinalPressure() - self.branches[0].getStartPressure()
    def getFinalEnthalpy(self):
        return self.branches[-1].getFinalEnthalpy()
    def getFinalVaporQuality(self):
        return self.branches[-1].getFinalVaporQuality()
    def getInitialTemp(self):
        return self.branches[0].getInitialTemp()
    def getStartEnthalpy(self):
        return self.branches[0].getStartEnthalpy()
    def getStartPressure(self):
        return self.branches[0].getStartPressure()
    def getFinalPressure(self):
        return self.branches[-1].getFinalPressure()
    def getTotalAppliedHeat(self):
        retval = 0
        for b in self.branches:
            retval = retval + b.getTotalAppliedHeat()
        return retval

    def concat(self):

        print('Solving concatenation')

        # logic:
        #   solve each part of the series
        #   from nBranch-1
        #      if it is evaporating
        #            set setPointTemp to initial temp of the next one
        #            set the final guess to the initial vapor quality of the
        #      if not evaporating
        #            set setPointTemp to same temperature as the final branch
        #            set final guess to 0.

        for ibranch, branch in enumerate(self.branches):
            if branch.initialVaporQuality > 0:
                firstEvapBranch = ibranch
                firstVaporQuality = branch.initialVaporQuality
                break
        nEvapBranches = len(self.branches) - firstEvapBranch;

        vaporQualities = np.linspace(self.initialVaporQuality, 0.5, nEvapBranches+1)
        for i in range(firstEvapBranch+1,len(self.branches)):
            vaporQualities[i-firstEvapBranch]=vaporQualities[i-1-firstEvapBranch]+(0.5-self.branches[firstEvapBranch].initialVaporQuality)*self.branches[i-1].getTotalAppliedHeat()/self.getTotalAppliedHeat()
        vaporQualities = np.concatenate(([0]*firstEvapBranch,vaporQualities))
        temperatures = np.ones_like(vaporQualities)
        pressures = np.ones_like(vaporQualities)
        for i in range(len(self.branches)):
            temperatures[i+1] = self.branches[i].setPointTemp
        temperatures[0] = self.branches[0].setPointTemp #getInitialTemp()
        for i in range(len(self.branches)+1):
            pressures[i] = self.refpropm('P','T',temperatures[i]+273.15,'Q',vaporQualities[i],self.Fluid)*1e-2;
        print('Initial guesses')
        print('Vapor qualities: ', vaporQualities)
        print('Temperatures: ', temperatures)

        itt=0;
        converge=10000;
        convlimit=100;
        conv_repeat=0;
        conv_repeat_limit=3;
        ittstop = 400

        while (abs(converge)>convlimit or conv_repeat<conv_repeat_limit+1) and itt<ittstop:
            itt+=1
            print("\nManifold loop")
            print("Iteration Round: {}".format(itt))
            print("Iteration offset: {} (Stops at {})".format(converge, convlimit))

            enthalpies = np.ones(len(self.branches))
            for i in range(len(enthalpies)):
                try:
                    enthalpies[i] = self.branches[i].getStartEnthalpy()
                except:
                    enthalpies[i] = self.refpropm('H','T',self.branches[i].setPointTemp+273.15,'Q',self.branches[i].initialVaporQuality,self.Fluid);

            print("Enthalpy: {} J/kg".format(max(enthalpies)))
            print("Iteration offset: {} (Stops at {})".format(conv_repeat, conv_repeat_limit))
            for ibranch in range(len(self.branches)-1, -1, -1):
               # these will remain unchanged
                self.branches[ibranch].setPointTemp = temperatures[ibranch+1]
                if ibranch >= firstEvapBranch:
                    self.branches[ibranch].finalVaporQualityGuess = vaporQualities[ibranch+1]
                else:
                    self.branches[ibranch].finalUsePressureGuess = True
                    self.branches[ibranch].finalPressureGuess = pressures[ibranch+1]
                # update

            print("Running Children")
            p = MyPool(len(self.branches))
            self.branches = p.map(self.worker, self.branches)

            # update things that actually change
            for ibranch in range(len(self.branches)-1, -1, -1):
                vaporQualities[ibranch+1] = self.branches[ibranch].getFinalVaporQuality()
                temperatures[ibranch] = self.branches[ibranch].getInitialTemp()
                pressures[ibranch] = self.branches[ibranch].getStartPressure()

            prev_enthalpies = np.copy(enthalpies)
            for i in range(len(enthalpies)):
                enthalpies[i] = self.branches[i].getStartEnthalpy()

            diff_enthalpies = np.abs(enthalpies-prev_enthalpies)
            converge = np.amax(diff_enthalpies) #use enthalpy to converge
            if abs(converge) < convlimit:
                conv_repeat+=1
            else:
                conv_repeat = 0

        return vaporQualities[-1]

    def __str__(self):
        return self.root

    def prettyprint(self, i=0, var=None):
        print(i*"\t|"+self.Name, end="    ")
        print(self.initialMassFlow if var == "IMF" else "")
        for b in self.branches:
            if b.__class__ == Manifold:
                b.prettyprint(i=i+1, var=var)
            else:
                print((i+1)*"\t|"+str(b), end="    ")
                print(b.massFlow if var == "IMF" else "")

    def plot(self):
        print("Plotting manifold")
        for b in self.branches:
            b.plot()

    def run(self, ST=None, run=None):

        ST = ST or self.setPointTemp

        if len(self.branches)==1:
            self.branches[0].run(run=True)
            print(self.getDP())
            return
        else:
            if self.series == True:
                print("Concatenating {}".format(" ".join(map(str, self.branches))))
                return self.concat()
            else:
                print("Minimizing {}".format(" ".join(map(str, self.branches))))
                return self.minimize()


class Solution:
    def convertEdgesToAdjMatrix(self, edges, n):
        adjMatrix = {}

        for i in range(n):
            adjMatrix[i] = []

        for a, b in edges:
            adjMatrix[a].append(b)
            adjMatrix[b].append(a)

        return adjMatrix

    def dfs(self, index, edges, visited, adjMatrix):
        visited[index] = 1

        for node in adjMatrix[index]:
            if not visited[node]:
                self.dfs(node, edges, visited, adjMatrix)

    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        components = 0

        adjMatrix = self.convertEdgesToAdjMatrix(edges, n)
        visited = [0] * n

        for i in range(n):
            if not visited[i]:
                components += 1
                self.dfs(i, edges, visited, adjMatrix)

        return components


#!/usr/bin/env python3

"""
We discovered a Jackpot of Youtube URLs, however there is over 9000 of them. We need a script to distill the
list into a solely valid URLS.
"""

__author__ = "Darragh Connaughton"
__copyright__ = "Copyright (c) Darragh Connaughton, 2023"
__license__ = "MIT License"

import csv
import os
import re
import sys
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile

CSV_BANNER = "URL,Views,Length,Subscribers"
OUTPUT_FILE = "./jackpot_valid_urls.txt"
SUBSCRIBERS_PATTERN = r'"subscriberCountText":{"accessibility":{"accessibilityData":{"label":"(.*?) subscribers"}'
TIME_DURATION_PATTERN = r'((?:\d+:)?\d+:\d+)'
VIEWS_PATTERN = r'"views":{"simpleText":"(.*?) views"}'
PROFILE_F = "/Users/darraghconnaughton/Library/Application Support/Firefox/Profiles/m3e7vaoq.default-release-1"

def __launch_browser_() -> webdriver:
    firefox_profile = FirefoxProfile(PROFILE_F)
    firefox_profile.set_preference("browser.cache.disk.enable", False)
    firefox_profile.set_preference("browser.cache.memory.enable", False)
    firefox_profile.set_preference("browser.cache.offline.enable", False)
    firefox_profile.set_preference("network.http.use-cache", False)
    return webdriver.Firefox(firefox_profile)

def __read_from_disk(fpath):
    with open(fpath, "r") as file:
        return file.read().split("\n")

def __handle_match(match):
    if match:
        return match.group(1)

    print(f"[-]WARNING! match not found.")
    return "N/A"

def __valid_url(views):
    view_split = views.split(":")

    if len(view_split) == 3:
        return True

    if len(view_split) == 1:
        return False

    return int(view_split[0]) >= 2

def __continue_where_left_off(urls, output_file):
    if os.path.exists(output_file):
        print(f"[+]{output_file} found. Retrieving last processed URL.")

        with open(output_file, "r") as csv_file:
            t_urls = [row[0] for row in csv.reader(csv_file)]
            if len(t_urls) > 0:
                last_url = t_urls[-1]

                for index in range(len(urls)):
                    if urls[index] == last_url:
                        print(f"[+]URL found {urls[index]} at index {index}")
                        return urls[index:]

    else:
        print(f"[+]Writing CSV Banner: {CSV_BANNER}")
        with open(output_file, "w") as file:
            file.write(f"{CSV_BANNER}\n")

    return urls

BROWSER = __launch_browser_()

if __name__ == "__main__":
    urls = __continue_where_left_off(__read_from_disk("./URLJackpot.txt"), OUTPUT_FILE)
    print(f"len: {len(urls)}")
    with open(OUTPUT_FILE, "a") as file:

        for url in urls:
            trimmed_url = url.strip()

            try:
                session = BROWSER.get(f"https://www.youtube.com/watch?v={trimmed_url}")
                html_snippet = BROWSER.page_source

                time_duration = __handle_match(re.search(TIME_DURATION_PATTERN, html_snippet))
                if __valid_url(time_duration):

                    subscriber_count = __handle_match(re.search(SUBSCRIBERS_PATTERN, html_snippet))
                    views_count = __handle_match(re.search(VIEWS_PATTERN, html_snippet))

                    csv_row = f"{trimmed_url},{views_count},{time_duration},{subscriber_count}"
                    print(f"[+]{csv_row}")
                    file.write(f"{csv_row}\n")

                else:
                    print(f"[-]invalid: {trimmed_url},{time_duration}")

            except Exception as ex:
                print(f"[-]Exception encountered: {ex}. Continuing.")

    print("[+]Finished.")
    BROWSER.quit()


# Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

# You may return the answer in any order.

# Example 1:

# Input: n = 4, k = 2
# Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
# Explanation: There are 4 choose 2 = 6 total combinations.
# Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
# Example 2:

# Input: n = 1, k = 1
# Output: [[1]]
# Explanation: There is 1 choose 1 = 1 total combination.

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        def backtrack(first = 1, curr = []):
            if len(curr) == k:
                output.append(curr[:])
                return
            for i in range(first, n + 1):
                curr.append(i)
                backtrack(i + 1, curr)
                curr.pop()
        output = []
        backtrack()
        return output


"""
2021/03/11
@Yuya Shimzu

P制御（アーム）
"""
import numpy as np
import matplotlib.pyplot as plt
from control import tf, feedback
from control.matlab import step, bode, logspace
from tf_arm import arm_tf       #自作関数
#https://qiita.com/Yuya-Shimizu/items/c7b69b4dfd63fb8facfa
from for_plot import linestyle_generator, plot_set, bodeplot_set      #自作関数
#https://qiita.com/Yuya-Shimizu/items/f811317d733ee3f45623

##パラメータ設定
g    =   9.8                    #重力加速度[m/s^2]
l     =   0.2                    #アームの長さ[m]
M   =   0.5                     #アームの質量[kg]
mu =   1.5e-2                #粘性摩擦係数[kg*m^2/s]
J    =   1.0e-2                 #慣性モーメント[kg*m^2]

#制御対象
P = arm_tf(J, mu, M, g, l)

#目標値(指示値=refference)
ref = 30        #目標角度30[deg]

#比例ゲイン
kp = (0.5, 1, 2)        #比較のために3つ用意

##P制御を用いたときのステップ応答の描画
LS = linestyle_generator()
fig, ax = plt.subplots()
for i in range(len(kp)):
    K = tf([0, kp[i]], [0, 1])  #P制御
    Gyr = feedback(P*K, 1)  #閉ループ系
    y, t = step(Gyr, np.arange(0, 2, 0.01))     #ステップ応答

    pltargs = {'ls':next(LS), 'label':f"$k_P$={kp[i]}"}
    ax.plot(t, y*ref, **pltargs)

ax.set_title('P control')
ax.axhline(ref, color='k', linewidth=0.5)
plot_set(ax, 't', 'y', 'best')

plt.show()

##P制御を用いたときのボード線図
LS = linestyle_generator()
fig, ax = plt.subplots(2, 1)
for i in range(len(kp)):
    K = tf([0, kp[i]], [0, 1])  #P制御
    Gyr = feedback(P*K, 1)  #閉ループ系
    gain, phase, w = bode(Gyr, logspace(-1, 2), Plot=False)     #ボード線図

    pltargs = {'ls':next(LS), 'label':f"$k_P$={kp[i]}"}
    ax[0].semilogx(w, 20*np.log10(gain), **pltargs)
    ax[1].semilogx(w, phase*180/np.pi, **pltargs)

ax[0].set_title('P control - Bode Plot')
bodeplot_set(ax, 'lower left')

plt.show()


"""
This is a text interface for running the simulation
Checking all user input is valid at here
"""
import re
import sys
import traceback
from typing import Union, Tuple

from SimulatorFile.Dynamic import DynamicSimulator
from SimulatorFile.EnergyScan import EnergySimulator
from ExternalIO import *

def getArgument() -> None:
    """
    This function take the setting argument from the user and call Simulation file to run the program
    Check all user input valid at here
    :return: None
    """
    # taking general info

    simulatorType, trail, interval_x, interval_y = getGeneralArgument()

    # taking film info

    filmDomainChargeConcentration, filmDomainCon, filmDomainShape, filmDomainSize, filmSeed, filmSurfaceCharge, \
    filmSurfaceShape, filmSurfaceSize = getFilmArgument()

    # taking bacteria info

    bacteriaDomainChargeConcentration, bacteriaDomainCon, bacteriaDomainShape, bacteriaDomainSize, bacteriaSeed, \
    bacteriaSize, bacteriaSurfaceCharge, bacteriaSurfaceShape = getBacteriaArgument(filmSurfaceSize)

    # take info for simulator
    if simulatorType == 1:
        simulator = EnergySimulator
        # taking info for energy scan simulation
        bacteriaNum, dimension, filmNum, interactType, simulationType = getEnergyScanArgument()
        parameter = {"interactType": interactType, "simulationType": simulationType}

    elif simulatorType == 2:
        simulator = DynamicSimulator
        # set some fixed parameter
        dimension = 3
        filmNum = 1
        # taking info for dynamic simulation
        probabilityType, timestep, bacteriaNum = getDynamicArgument()
        parameter = {"probabilityType": probabilityType, "timestep": timestep}
    else:
        raise RuntimeError("Unknown simulator type")

    # generate simulation program
    showMessage("Start to generate the simulation simulator ......")

    # generate simulator
    sim = simulator(trail, dimension,
                    filmSeed, filmSurfaceSize, filmSurfaceShape, filmSurfaceCharge,
                    filmDomainSize, filmDomainShape, filmDomainCon, filmDomainChargeConcentration,
                    bacteriaSeed, bacteriaSize, bacteriaSurfaceShape, bacteriaSurfaceCharge,
                    bacteriaDomainSize, bacteriaDomainShape, bacteriaDomainCon, bacteriaDomainChargeConcentration,
                    filmNum, bacteriaNum, interval_x, interval_y, parameter)

    showMessage("Simulator generate done")

    # run the simulation
    showMessage("Start to run simulate ......")

    sim.runSimulate()

    # finish whole simulation
    showMessage("Whole simulation done")

def getDynamicArgument() -> [str, int, int]:
    # if this is dynamic simulator, need timestep
    while True:

        timestep = input("Please enter time step want: \n")

        # set the name
        helpName = "TIMESTEP"

        # if enter help
        if timestep.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        # check is it a number
        if not checkNum(timestep):
            errorInput(helpName)
        elif result:
            timestep = int(timestep)
            break
        else:
            errorInput(helpName)

    # if this is dynamic simulator, need probability type
    while True:
        probabilityType = input("Please enter probability type want to use: \n")

        # set the name
        helpName = "PROBABILITYTYPE"

        # if enter help
        if probabilityType.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        # check result
        if result:
            probabilityType = probabilityType.upper()
            break
        else:
            errorInput(helpName)

    # get bacteria number
    while True:

        bacteriaNum = input("Please enter the number of bacteria you want to test or help for more information: ")
        number = bacteriaNum

        # set the name
        helpName = "NUMBER"

        # if type help
        if bacteriaNum.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if not checkNum(bacteriaNum):
            errorInput(helpName)
        elif result:
            bacteriaNum = int(bacteriaNum)
            break
        else:
            errorInput(helpName)

    return probabilityType, timestep, bacteriaNum

def getEnergyScanArgument() -> [int, int, int, str, int]:
    # take simulation type
    while True:
        simulationType = input("Please enter simulation type: \n")

        # set the name
        helpName = "TYPE"

        # if enter help
        if simulationType.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            simulationType = int(simulationType)
            break
        else:
            errorInput(helpName)

    # take interact type
    while True:

        # Take user input
        interactType = input("Please enter the interact type you want to simulate (help for more information): \n")

        # set the name
        helpName = "INTERACTTYPE"

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            break
        elif interactType.upper() == "HELP":
            helpMessage(helpName)
        else:
            errorInput(helpName)

    # take cutoff if needed
    while True:
        if not interactType.upper() in ["CUTOFF", "CUT-OFF"]:
            cutoff = float("INF")
            break

        # Take user input
        cutoff = input("Please enter the cutoff value you want to simulate (help for more information): \n")

        # set the name
        helpName = "CUTOFF"

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if cutoff.upper() == "HELP":
            helpMessage(helpName)
        elif checkNum(cutoff):
            errorInput(helpName)
        elif result:
            break
        else:
            errorInput(helpName)

    # take dimension
    while True:

        # Take user input
        dimension = input("Please enter the dimension you want to simulate (2 for 2D, 3 for 3D, "
                          "help for more information): \n")

        # set the name
        helpName = "DIMENSION"

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            dimension = int(dimension)
            break
        elif dimension.upper() == "HELP":
            helpMessage(helpName)
        else:
            errorInput(helpName)

    # if simulation type is not 1, take in extra info
    while True:

        # check the simulation type
        if simulationType == 1:
            filmNum = "1"
            bacteriaNum = "1"
            break

        elif simulationType == 2:
            filmNum = "1"
            bacteriaNum = input("Please enter the number of bacteria you want to test or help for more information: ")
            number = bacteriaNum

        elif simulationType == 3:
            filmNum = input("Please enter the number of bacteria you want to test or help for more information: ")
            bacteriaNum = "1"
            number = filmNum
        else:
            raise RuntimeError("Wrong simulation type, causes get bacteria/film number error")

        # set the name
        helpName = "NUMBER"

        # if type help
        if bacteriaNum.upper() == "HELP" or filmNum.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if not checkNum(bacteriaNum) or not checkNum(filmNum):
            errorInput(helpName)
        elif result:
            filmNum = int(filmNum)
            bacteriaNum = int(bacteriaNum)
            break
        else:
            errorInput(helpName)
    return bacteriaNum, dimension, filmNum, interactType, simulationType

def getBacteriaArgument(filmSurfaceSize: Tuple[int, int]):
    # take seed of bacteria
    while True:
        bacteriaSeed = input("Please enter bacteria seed number: \n")

        # set the name
        helpName = "SEED"
        seed = bacteriaSeed

        # if type help
        if bacteriaSeed.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if not checkNum(seed):
            errorInput(helpName)
        elif result:
            bacteriaSeed = int(bacteriaSeed)
            break
        else:
            errorInput(helpName)

    # take shape of the bacteria
    while True:
        # Take user input
        bacteriaSurfaceShape = input("Please enter the shape of the bacteria you want to simulate ("
                                     "help for more information): \n")

        # set the name
        helpName = "SURFACESHAPE"

        # if type help
        if bacteriaSurfaceShape.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        shape = bacteriaSurfaceShape

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            break
        else:
            errorInput(helpName)

    # take the area size of bacteria
    while True:
        # Take user input
        bacteriaSize = input("Please enter the bacteria surface area you want to simulate  "
                             "(in format: ###x### (length x width) for 2D, ###x###x### (length x width x height) for "
                             "3D or help for more information): \n")

        # set the name
        helpName = "SIZE"

        # check the validity of input
        if bacteriaSize.upper() == "HELP":
            helpMessage(helpName)
        else:
            # check the format of the input mach 2D format or 3D format
            formatValid = bool(re.match("\d+[x]\d+", bacteriaSize)) or bool(re.match("\d+[x]\d+[x]\d+", bacteriaSize))

            if formatValid:
                # check this input size if valid
                valid = checkSize(bacteriaSurfaceShape, bacteriaSize)

                # if not valid
                if not valid:
                    errorInput(bacteriaSurfaceShape)
                    continue

                # if valid check bacteria size is smaller than surface size
                elif (valid[0] * valid[1]) >= (filmSurfaceSize[0] * filmSurfaceSize[1]):
                    print("BacteriaFile size should smaller than surface size.")

                # if valid, record and break
                else:
                    bacteriaSize = valid
                    break
            else:
                errorInput(helpName)

    # take charge of the bacteria
    while True:
        # Take user input
        bacteriaSurfaceCharge = input("Please enter the charge of the bacteria you want to simulate ("
                                      "help for more information): \n")
        # set the name
        helpName = "CHARGE"

        # if type help
        if bacteriaSurfaceCharge.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        charge = bacteriaSurfaceCharge

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            bacteriaSurfaceCharge = int(bacteriaSurfaceCharge)
            break
        else:
            errorInput(helpName)

    # take the domain concentration of bacteria
    while True:
        # Take user input
        bacteriaDomainCon = input("Please enter the domain concentration of the bacteria you want to simulate ("
                                  "help for more information): \n")
        # set the name
        helpName = "CONCENTRATION"

        # if type help
        if bacteriaDomainCon.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        concentration = bacteriaDomainCon

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            bacteriaDomainCon = float(bacteriaDomainCon)
            break
        else:
            errorInput(helpName)

    # take the domain shape of bacteria
    while True:
        # Take user input
        bacteriaDomainShape = input("Please enter the shape of the domain on the bacteria you want to simulate ("
                                    "help for more information): \n")

        # set the name
        helpName = "DOMAINSHAPE"

        # if type help
        if bacteriaDomainShape.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        shape = bacteriaDomainShape

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            break
        else:
            errorInput(helpName)

    # take the domain size of bacteria
    while True:
        # Take user input
        bacteriaDomainSize = input("Please enter the domain area on the bacteria you want to simulate  "
                                   "(in format: ###x### (length x width) or help for more information): \n")

        # set the name
        helpName = "SIZE"

        # check the validity of input
        if bacteriaDomainSize.upper() == "HELP":
            helpMessage(helpName)
        else:
            # check the format of the input
            if bool(re.match("\d+[x]\d+", bacteriaDomainSize)):
                # check this input size if valid
                valid = checkSize(bacteriaDomainShape, bacteriaDomainSize)

                # if not valid
                if not valid:
                    errorInput(bacteriaDomainShape)
                    continue

                # if valid, record and break
                else:
                    bacteriaDomainSize = valid
                    break
            else:
                errorInput(helpName)

    # take bacteria surface domain charge concentration
    while True:
        # Take user input
        bacteriaDomainChargeConcentration = input(
            "Please enter the domain charge concentration of the bacteria surface you want to "
            "simulate (help for more information): \n")

        # set the name
        helpName = "CONCENTRATION"

        if bacteriaDomainChargeConcentration.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        concentration = bacteriaDomainChargeConcentration

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            bacteriaDomainChargeConcentration = float(bacteriaDomainChargeConcentration)
            break
        else:
            errorInput(helpName)

    return bacteriaDomainChargeConcentration, bacteriaDomainCon, bacteriaDomainShape, bacteriaDomainSize, bacteriaSeed, bacteriaSize, bacteriaSurfaceCharge, bacteriaSurfaceShape

def getFilmArgument():
    # take film seed number
    while True:
        filmSeed = input("Please enter film seed number: \n")

        # set the name
        helpName = "SEED"
        seed = filmSeed

        # if enter help
        if filmSeed.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if not checkNum(seed):
            errorInput(helpName)
        elif result:
            filmSeed = int(filmSeed)
            break
        else:
            errorInput(helpName)

    # take shape of the film surface
    while True:
        # Take user input
        filmSurfaceShape = input("Please enter the shape of the surface you want to simulate ("
                                 "help for more information): \n")

        # set the name
        helpName = "SURFACESHAPE"

        if filmSurfaceShape.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        shape = filmSurfaceShape

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            break
        else:
            errorInput(helpName)

    # take film surface area size
    while True:
        # Take user input
        filmSurfaceSize = input("Please enter the film surface area you want to simulate  "
                                "(in format: ###x### (length x width) or "
                                "help for more information): \n")

        # set the name
        helpName = "SIZE"

        # check the validity of input
        if filmSurfaceSize.upper() == "HELP":
            helpMessage(helpName)
        else:
            # check the format of the input
            if bool(re.match("\d+[x]\d+", filmSurfaceSize)):
                # check this input size if valid
                valid = checkSize(filmSurfaceShape, filmSurfaceSize)

                # if not valid
                if not valid:
                    errorInput(filmSurfaceShape)
                    continue

                # if valid, record and break
                else:
                    filmSurfaceSize = valid
                    break
            else:
                errorInput(helpName)

    # take charge of the surface
    while True:
        # Take user input
        filmSurfaceCharge = input("Please enter the charge of the surface you want to simulate ("
                                  "help for more information): \n")
        # set the name
        helpName = "CHARGE"

        if filmSurfaceCharge.upper() == "HELP":
            helpMessage(helpName)
            continue
        # set the variable for check
        charge = filmSurfaceCharge

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            filmSurfaceCharge = int(filmSurfaceCharge)
            break
        else:
            errorInput(helpName)

    # take domain concentration of film
    while True:
        # Take user input
        filmDomainCon = input("Please enter the domain concentration of the surface you want to simulate ("
                              "help for more information): \n")
        # set the name
        helpName = "CONCENTRATION"

        if filmDomainCon.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        concentration = filmDomainCon

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            filmDomainCon = float(filmDomainCon)
            break
        else:
            errorInput(helpName)

    # take domain shape of film
    while True:
        # Take user input
        filmDomainShape = input("Please enter the shape of the domain on the surface you want to simulate ("
                                "help for more information): \n")

        # check the validity of input
        # set the name
        helpName = "DOMAINSHAPE"

        if filmDomainShape.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        shape = filmDomainShape

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            break
        else:
            errorInput(helpName)

    # take domain size of film
    while True:
        # Take user input
        filmDomainSize = input("Please enter the domain area on the film you want to simulate  "
                               "(in format: ###x### (length x width) or "
                               "help for more information): \n")

        # set the name
        helpName = "SIZE"

        # check the validity of input
        if filmDomainSize.upper() == "HELP":
            helpMessage(helpName)
        else:
            # check the format of the input
            if bool(re.match("\d+[x]\d+", filmDomainSize)):
                # check this input size if valid
                valid = checkSize(filmDomainShape, filmDomainSize)

                # if not valid
                if not valid:
                    errorInput(filmDomainShape)
                    continue

                # if valid, record and break
                else:
                    filmDomainSize = valid
                    break
            else:
                errorInput(helpName)

    # take film surface domain charge concentration
    while True:
        # Take user input
        filmDomainChargeConcentration = input("Please enter the domain charge concentration of the film surface "
                                              "you want to simulate (help for more information): \n")

        # set the name
        helpName = "CONCENTRATION"

        if filmDomainChargeConcentration.upper() == "HELP":
            helpMessage(helpName)
            continue

        # set the variable for check
        concentration = filmDomainChargeConcentration

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            filmDomainChargeConcentration = float(filmDomainChargeConcentration)
            break
        else:
            errorInput(helpName)

    return filmDomainChargeConcentration, filmDomainCon, filmDomainShape, filmDomainSize, filmSeed, \
           filmSurfaceCharge, filmSurfaceShape, filmSurfaceSize

def getGeneralArgument():
    # take simulator type
    while True:
        simulatorType = input("Please enter simulator type: \n")

        # set the name
        helpName = "SIMULATOR"

        # if enter help
        if simulatorType.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        if result:
            simulatorType = int(simulatorType)
            break
        else:
            errorInput(helpName)

    # take trail number
    while True:
        trail = input("Please enter trail number: \n")

        # set the name
        helpName = "TRAIL"

        # if enter help
        if trail.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check the validity of input and do reaction
        result = eval(execDict[helpName])

        # check is it a number
        if not checkNum(trail):
            errorInput(helpName)
        elif result:
            trail = int(trail)
            break
        else:
            errorInput(helpName)

    # get the interval
    while True:
        # Take user input
        interval = input("Please enter the interval on x-direction and y direction you want to simulate, "
                         "enter in format ###x###, first number is x and second number is y"
                         " (type help for more information): \n")

        # set the name
        helpName = "INTERVAL"

        # if type help
        if interval.upper() == "HELP":
            helpMessage(helpName)
            continue

        # check if the format of input
        if not bool(re.match("\d+[x]\d+", interval)):
            print("Wrong format\n")
            errorInput(helpName)

        # check the validity of input and do reaction
        interval = interval.split("x")
        result = eval(execDict[helpName])

        if result:
            interval_x = int(interval[0])
            interval_y = int(interval[1])
            break
        else:
            errorInput(helpName)

    return simulatorType, trail, interval_x, interval_y

def errorInput(helpName: str) -> None:
    """
    This function print the message of user putin not valid input
    """
    print("Invalid input, please enter again.\n")
    print(infoDict[helpName].replace("\\n", "\n"))

def checkSize(shape: str, size: str) -> Union[bool, Tuple[int, int], Tuple[int, int, int]]:
    """
    This function checks the size input is satisfied the restriction of the shape
    return False if not satisfy, else return a Tuple with (length, width)
    """
    # get the size
    size = size.split("x")

    length = int(size[0])
    width = int(size[1])

    # get height, if exist
    if len(size) == 3:
        height = int(size[2])
    else:
        height = 0

    # set the checker
    result = eval(execDict[shape.upper()])

    # check the result
    if not result:
        return False
    else:
        return (length, width, height)

def helpMessage(helpName: str) -> None:
    """
    This function print the help message
    """
    print(helpDict[helpName].replace("\\n", "\n"))
    print(infoDict[helpName].replace("\\n", "\n"))

def checkNum(input: str) -> bool:
    """
    This function take in a string and test does it can be convert to number
    """
    try:
        float(input)
        return True
    except ValueError:
        return False

if __name__ == '__main__':
    # get the help info
    helpDict = getHelp()

    # get special info dict, exec dict
    infoDict, execDict = getRestriction()

    # open log
    write_at_end = True
    write_log = True
    generate_image = True

    message = setIndicator(generate_image, write_log, write_at_end)
    showMessage(message)

    try:
        # call the user input function
        getArgument()

        # close
        closeLog()

    except Exception as e:

        exc_type, exc_value, exc_traceback = sys.exc_info()

        info = ""

        info += str('e.message: {}\t'.format(exc_value))

        info += str(

            "Note, object e and exc of Class %s is %s the same." % (type(exc_value), ('not', '')[exc_value is e]))

        info += str('traceback.print_exc(): {}'.format(traceback.print_exc()))

        info += str('traceback.format_exc():\n%s' % traceback.format_exc())

        writeLog(info)

        closeLog()
        exit(1)


def percentage(a):
    b={}
    for i in a:
        summ=0
        for j in a[i]:
            summ+=j
        percen=summ/4
        b[i]=percen
    maxx=0
    for i in b:
        if(b[i]>=maxx):
            maxx=b[i]
            c={}
            c[i]=maxx
    print("student who have secured highest percentage is ",end=" ")
    for i in c:
        print(i,"with percetage",c[i])

marks={}
ch="Y"
while(ch=="y" or ch=="Y"):
    name=str(input("enter your name :"))
    l=[]
    for i in range(4):
        print("enter marks of subject",i+1,end=" ")
        k=int(input())
        l.append(k)
    marks[name]=l
    ch=input("do you want to insert more data ? Y/N")
percentage(marks)


def translate(fileName):
    import codeWriter
    from codeWriter import CodeWriter
    import stackParser
    from stackParser import Parser
    import os

    files = []
    ext = os.path.splitext(fileName)[1]

    if ext == '':
        outputFile = open(os.path.join(fileName, os.path.basename(os.path.abspath(fileName)) + ".asm"), 'w')
        for currentFile in os.listdir(fileName):
            if os.path.splitext(currentFile)[1] == '.vm':
                files.append(os.path.join(fileName, currentFile))
    elif ext == '.vm':
        outputFile = open(os.path.splitext(fileName)[0] + ".asm", 'w')
        files.append(fileName)
    else:
        raise Exception("File provided doesn't have a .vm extension and is not a directory")

    codeWriter = CodeWriter(outputFile)
    codeWriter.writeInit()
    for currentFile in files:
        file = open(currentFile, 'r')
        parser = Parser(file)
        parse(parser, codeWriter, os.path.basename(currentFile))
    codeWriter.close()

def parse(parser, codeWriter, fileName):
    import stackParser
    from stackParser import Parser
    codeWriter.setFileName(fileName)
    while parser.hasMoreCommands():
        parser.advance()
        print("Command is " + parser.current() + " type is " + str(parser.commandType()))
        if parser.commandType() == Parser.C_ARITHMETIC:
            codeWriter.writeArithmetic(parser.arg1())
        elif (parser.commandType() == Parser.C_PUSH) | (parser.commandType() == Parser.C_POP):
            codeWriter.writePushPop(parser.commandType(), parser.arg1(), parser.arg2())
        elif parser.commandType() == Parser.C_GOTO:
            codeWriter.writeGoto(parser.arg1())
        elif parser.commandType() == Parser.C_LABEL:
            codeWriter.writeLabel(parser.arg1())
        elif parser.commandType() == Parser.C_IF:
            codeWriter.writeIf(parser.arg1())
        elif parser.commandType() == Parser.C_CALL:
            codeWriter.writeCall(parser.arg1(), int(parser.arg2()))
        elif parser.commandType() == Parser.C_RETURN:
            codeWriter.writeReturn()
        elif parser.commandType() == Parser.C_FUNCTION:
            codeWriter.writeFunction(parser.arg1(), int(parser.arg2()))
        else:
            print("Unhandled command type, type is " + str(parser.commandType()))
            print("\tCommand is " + parser.current())


'''
Refer to 'Matching networks for one shot learning'

'''
import torch
import torch.nn as nn
from torch.autograd import Variable

from .base_net import MLP

class CosDistance(nn.Module):
    def __init__(self):
        super(CosDistance, self).__init__()
        self.cos = nn.CosineSimilarity(dim=1)

    def forward(self, support_set, query_set):
        similarities = []
        for query_image in query_set:
            cosine_similarity = self.cos(support_set, query_image)
            similarities.append(cosine_similarity)
        similarities = torch.stack(similarities)
        return similarities

class AttentionalRegressor(nn.Module):
    def __init__(self):
        super(AttentionalRegressor, self).__init__()
        self.softmax = nn.Softmax(dim=1)

    def forward(self, similarities, support_set_y):
        """
        Produces pdfs over the support set classes for the target set image.

        Parameters
        ---------
        similarities:
            A tensor with cosine similarities of size
            [bs_of_query_set, bs_of_support_set]
        support_set_y:
            A tensor with the one hot vectors of the targets for each support set image

        Return
        ------
            Softmax pdf, [sequence_length,  batch_size, num_classes]
        """
        softmax_similarities = self.softmax(similarities)
        preds = torch.matmul(softmax_similarities, support_set_y)
        return preds

class BidirectionalLSTM(nn.Module):
    def __init__(self, layer_sizes, batch_size, vector_dim):
        super(BidirectionalLSTM, self).__init__()
        """
        Initializes a multi layer bidirectional LSTM
        :param layer_sizes: A list containing the neuron numbers per layer
                            e.g. [100, 100, 100] returns a 3 layer, 100
        :param batch_size: The experiments batch size
        """
        self.batch_size = batch_size
        self.hidden_size = layer_sizes[0]
        self.vector_dim = vector_dim
        self.num_layers = len(layer_sizes)

        '''
        input_size: The number of expected features in the input x
        hidden_size: The number of features in the hidden state h
        num_layers: Number of recurrent layers.
        bias: If False, then the layer does not use bias weights b_ih and b_hh. Default: True
        batch_first: If True, then the input and output tensors are provided as (batch, seq, feature)
        dropout: If non-zero, introduces a dropout layer on the outputs of each RNN layer except the last layer
        bidirectional: If True, becomes a bidirectional RNN. Default: False
        '''
        self.lstm = nn.LSTM(input_size=self.vector_dim,
                            num_layers=self.num_layers,
                            hidden_size=self.hidden_size,
                            bidirectional=True)

    def forward(self, inputs):
        """
        Runs the bidirectional LSTM, produces outputs and saves both forward and backward states as well as gradients.
        :param x: The inputs should be a list of shape [sequence_length, batch_size, 64]
        :return: Returns the LSTM outputs, as well as the forward and backward hidden states.
        """
        c0 = Variable(torch.rand(self.lstm.num_layers*2, self.batch_size, self.lstm.hidden_size),
                      requires_grad=False).cuda()
        h0 = Variable(torch.rand(self.lstm.num_layers*2, self.batch_size, self.lstm.hidden_size),
                      requires_grad=False).cuda()
        output, (hn, cn) = self.lstm(inputs, (h0, c0))
        return output, hn, cn

class MatchNet(nn.Module):
    ''' Refer to https://github.com/gitabcworld/MatchingNetworks.git
    '''
    def __init__(self, input_len):
        super(MatchNet, self).__init__()
        self.Embedding = MLP([input_len, 1024, 1024, 1024])
        self.Distance = CosDistance()
        self.Regression = AttentionalRegressor()
        self.bn = nn.BatchNorm1d(1024, affine=False)

    def forward(self, support_x, support_y, query_x):
        ### Embedding
        embedded_support_x = self.bn(self.Embedding(support_x))
        embedded_query_x = self.bn(self.Embedding(query_x))
        attention = self.Distance(embedded_support_x, embedded_query_x)
        preds = self.Regression(attention, support_y)
        return preds


#Fazer um programa para ler um vetor de N números inteiros. Em seguida, mostrar na
# tela a média aritmética somente dos números pares lidos, com uma casa decimal.
# Se nenhum número par for digitado, mostrar a mensagem "NENHUM NUMERO PAR"

n=int(input("Digite p número de valores do vetor: "))
a:[float]=[0 for x in range(n)]
for i in range(n):
    a[i]=float(input("Informe um valor: "))
m_aritimetica=soma=cont=0
print()
for i in range (n):
    if a[i]%2==0:
        cont+=1
        soma += a[i]
        m_aritimetica=soma/cont
if a[i]%2!=0:
    print("NENHUM NUMERO PAR")
else:
    print(f"Os números pares são: {a[i]}")
    print(f"E sua média é: {m_aritimetica:.2f} ")


"""
Utility function for vocabulary
"""
import gzip
import os
import re
import six
import string
import tensorflow as tf
from tensorflow.python.ops import lookup_ops

def convert_to_unicode(text):
    """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
    if six.PY3:
        if isinstance(text, str):
            return text
        elif isinstance(text, bytes):
            return text.decode("utf-8", "ignore")
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    elif six.PY2:
        if isinstance(text, str):
            return text.decode("utf-8", "ignore")
        # In py2, six.text_type = unicode. We use six.text_type to pass the pyflake checking
        elif isinstance(text, six.text_type):
            return text
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    else:
        raise ValueError("Not running on Python2 or Python 3?")

def convert_to_str(text):
    """
    Converts `text` to str (if it's not already).
    Used when writing text to file with `open(filename, 'w')`.
    """
    if six.PY2:  # In python 2, str is byte
        if isinstance(text, str):
            return text
        else:
            return convert_to_unicode(text).encode('utf-8')
    elif six.PY3:  # In python3, str is unicode
        if isinstance(text, str):
            return text
        else:
            return convert_to_unicode(text)
    raise ValueError("Not running on Python2 or Python 3?")

def convert_to_bytes(text):
    """
    Converts `text` to bytes (if it's not already).
    Used when generating tfrecords. More specifically, in function call `tf.train.BytesList(value=[<bytes1>, <bytes2>, ...])`
    """
    if six.PY2:
        return convert_to_str(text)  # In python2, str is byte
    elif six.PY3:
        if isinstance(text, bytes):
            return text
        else:
            return convert_to_unicode(text).encode('utf-8')
    else:
        raise ValueError("Not running on Python2 or Python 3?")

def strip(s):
    """Strips ascii whitespace characters off string s."""
    return s.strip(string.whitespace)

def split(s):
    """Split string s by whitespace characters."""
    whitespace_lst = [re.escape(ws) for ws in string.whitespace]
    pattern = re.compile('|'.join(whitespace_lst))
    return pattern.split(s)

def read_vocab(input_file):
    """Read vocabulary file and return a dict"""
    if input_file is None:
        return None

    vocab = {}
    if input_file.endswith('.gz'):
        f = tf.gfile.Open(input_file, 'r')
        fin = gzip.GzipFile(fileobj=f)
    else:
        fin = tf.gfile.Open(input_file, 'r')
    for line in fin:
        word = split(strip(line))[0]
        vocab[word] = len(vocab)
    fin.close()
    return vocab

def read_tf_vocab(input_file, UNK):
    """Read vocabulary and return a tf hashtable"""
    if input_file is None:
        return None

    keys, values = [], []
    if input_file.endswith('.gz'):
        f = tf.gfile.Open(input_file, 'r')
        fin = gzip.GzipFile(fileobj=f)
    else:
        fin = tf.gfile.Open(input_file, 'r')
    for line in fin:
        word = split(strip(line))[0]
        keys.append(word)
        values.append(len(values))
    fin.close()
    UNK_ID = keys.index(UNK)
    vocab_table = lookup_ops.HashTable(lookup_ops.KeyValueTensorInitializer(
        tf.constant(keys), tf.constant(values)), UNK_ID)
    return vocab_table

def extract_text_data(input_dir, output_file, text_fields):
    """
    Extract text data from tfrecords.  The data will be used for word embedding pretraining.
    """
    with tf.gfile.Open(output_file, 'w') as fout:
        for file in tf.gfile.ListDirectory(input_dir):
            input_file = os.path.join(input_dir, file)
            print(input_file)
            for example in tf.python_io.tf_record_iterator(input_file):
                result = tf.train.Example.FromString(example)
                for field in text_fields:
                    text_values = result.features.feature[field].bytes_list.value
                    for text in text_values:
                        text = convert_to_unicode(text)
                        text = text.strip()
                        if ' ' not in text:
                            continue
                        fout.write(text + '\n')

if __name__ == '__main__':
    input_dir = '/home/wguo/data/people_v6/NAV/train/'
    output_file = '/home/wguo/data/people_v6/NAV/glove/text'
    text_fields = ['query', 'doc_headlines', 'doc_currCompanies', 'doc_pastCompanies', 'doc_currTitles',
                   'doc_pastTitles', 'doc_currSchools', 'doc_pastSchools']
    extract_text_data(input_dir, output_file, text_fields)
    # max_vocab_size = 100000
    # generate_vocab_file(input_dir, output_file, max_vocab_size)