import numpy as np
import cv2
import matplotlib.pyplot as plt
import helpers
import time

def detect_face(img):
  # img = img.copy()

  face_cas = cv2.CascadeClassifier('data/haarcascades/haarcascade_frontalface_default.xml')

  face_recs = face_cas.detectMultiScale(img, scaleFactor=1.2 , minNeighbors=9)

  for (x,y,w,h) in face_recs:
    # cv2.rectangle(img, (x,y), (x+w,y+h), (255), 1)
    # separate face to blur
    # face_rec = img[y:y+h,x:x+w]
    # blur face
    # face_rec = cv2.medianBlur(face_rec, 19)
    # replace face with blurred face
    # img[y:y+h,x:x+w] = face_rec

    return [x,y,x+w,y+h]

tracker = cv2.TrackerTLD_create()
tracker_name = str(tracker).split()[0][1:]

# Read video
cap = cv2.VideoCapture(0)

# Read first frame.
ret, frame = cap.read()

# Special function allows us to draw on the very first frame our desired ROI
roi = cv2.selectROI(frame, False)
roi2 = tuple(detect_face(frame))
print(roi)
print(roi2)
# roi = tuple(detect_face(frame))

# Initialize tracker with first frame and bounding box
ret = tracker.init(frame, roi)

print(type(roi))

while True:
    # Read a new frame
    ret, frame = cap.read()

    # Update tracker
    success, roi = tracker.update(frame)

    # roi variable is a tuple of 4 floats
    # We need each value and we need them as integers
    (x,y,w,h) = tuple(map(int,roi))

    # Draw Rectangle as Tracker moves
    if success:
        # Tracking success
        p1 = (x, y)
        p2 = (x+w, y+h)
        cv2.rectangle(frame, p1, p2, (0,255,0), 3)
    else :
        # Tracking failure
        cv2.putText(frame, "Cannot see a face :(", (100,200), cv2.FONT_HERSHEY_SIMPLEX, 1,(0,0,255),3)

    # Display tracker type on frame
    cv2.putText(frame, tracker_name, (20,400), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0),3)

    # Display result
    cv2.imshow(tracker_name, frame)

    # Exit if ESC pressed
    k = cv2.waitKey(1) & 0xff
    if k == 27 :
        break

cap.release()
cv2.destroyAllWindows()


# Functional test for uart module
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import Timer,RisingEdge,FallingEdge,ClockCycles,ReadWrite
from cocotb.result import TestFailure
import random
from cocotb_coverage.coverage import CoverPoint,coverage_db

covered_valued = []

g_sys_clk = int(cocotb.top.g_sys_clk)
period_ns = 10**9 / g_sys_clk
g_word_width = int(cocotb.top.g_data_width)

full = False
def notify():
	global full
	full = True

async def connect_tx_rx(dut):
	while full != True:
		await RisingEdge(dut.i_clk)
		dut.i_rx.value = dut.o_tx.value

# at_least = value is superfluous, just shows how you can determine the amount of times that
# a bin must be hit to considered covered
@CoverPoint("top.i_data",xf = lambda x : x.i_data.value, bins = list(range(2**g_word_width)), at_least=1)
def number_cover(dut):
	covered_valued.append(int(dut.i_data.value))

async def reset(dut,cycles=1):
	dut.i_arstn.value = 0
	dut.i_we.value = 0
	dut.i_stb.value = 0
	dut.i_data.value = 0
	dut.i_rx.value = 0

	await ClockCycles(dut.i_clk,cycles)
	dut.i_arstn.value = 1
	await RisingEdge(dut.i_clk)
	dut._log.info("the core was reset")

@cocotb.test()
async def test(dut):
	"""Check results and coverage for UART"""

	cocotb.start_soon(Clock(dut.i_clk, period_ns, units="ns").start())
	await reset(dut,5)
	cocotb.start_soon(connect_tx_rx(dut))

	expected_value = 0
	rx_data = 0

	# configure UART core via interface
	# set databits(8), stopbits(1), parity_en(1), parity_type etc..
	dut.i_stb.value = 1
	dut.i_addr.value = 1
	dut.i_we.value = 1
	dut.i_data.value = 11

	await RisingEdge(dut.i_clk)

	while(full != True):
		data = random.randint(0,2**g_word_width-1)
		while(data in covered_valued):
			data = random.randint(0,2**g_word_width-1)
		expected_value = data

		dut.i_stb.value = 1
		dut.i_we.value = 1
		dut.i_addr.value = 0
		dut.i_data.value = data

		await RisingEdge(dut.i_clk)
		dut.i_stb.value = 0
		await FallingEdge(dut.o_rx_done)

		dut.i_stb.value = 1
		dut.i_we.value = 0
		dut.i_addr.value = 0

		await ClockCycles(dut.i_clk,2)	#1 cycle to register read rd_rbr command, 1 cycle to copy rbr to o_data

		assert not (expected_value != int(dut.o_data.value)),"Different expected to actual read data"
		coverage_db["top.i_data"].add_threshold_callback(notify, 100)
		number_cover(dut)

	coverage_db.report_coverage(cocotb.log.info,bins=True)
	coverage_db.export_to_xml(filename="coverage.xml")


from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

try:
    driver.get(url='https://www.youtube.com')
    input_element = driver.find_element(By.XPATH, '//input[@id="search"]')
    time.sleep(3)
    input_element.send_keys('запрос')
    time.sleep(3)
    search_button = driver.find_element(By.XPATH, '//button[@id="search-icon-legacy"]')
    search_button.click()
    time.sleep(3)
    driver.get(url='https://ru.wikipedia.org/')
    wiki_search = driver.find_element(By.CLASS_NAME, 'vector-search-box-input').send_keys('Польша')
    # search_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, 'searchButton')))
    time.sleep(3)
    search_button = driver.find_element(By.CLASS_NAME, 'searchButton').click()
    time.sleep(3)
    driver.get(url='https://www.google.com')
    google_search = driver.find_element(By.CSS_SELECTOR, '#input')
except Exception as ex:
    print(ex)
finally:
    driver.close()
    driver.quit()


import rospy
import rospkg
import os
import sys
import traceback
import json
from stable_baselines3 import PPO
from stable_baselines3.common.utils import get_device

from rosnav.srv import GetAction, GetActionResponse
from rosnav.rosnav_space_manager.rosnav_space_manager import RosnavSpaceManager

from rosnav import *
sys.modules["rl_agent"] = sys.modules["rosnav"]
sys.modules["rl_utils.rl_utils.utils"] = sys.modules["rosnav.utils"]

class RosnavNode:
    def __init__(self):
        # Agent name and path
        self.agent_name = rospy.get_param("agent_name")
        self.agent_path = self._get_model_path(self.agent_name)

        assert os.path.isdir(self.agent_path), f"Model cannot be found at {self.agent_path}"

        # Load hyperparams
        self._hyperparams = self._load_hyperparams(self.agent_path)
        # rospy.set_param("/actions_in_obs", self._hyperparams.get("actions_in_observationspace", False))

        self._obs_structure = self._get_observation_space_structure(self._hyperparams)

        # Set RosnavSpaceEncoder as Middleware
        self._encoder = RosnavSpaceManager()

        # Load the model
        self._agent = self._get_model(self.agent_path)

        self._get_next_action_srv = rospy.Service(
            "rosnav/get_action", GetAction, self._handle_next_action_srv
        )

    def _handle_next_action_srv(self, request):
        observation = self._encoder.encode_observation({
            "goal_in_robot_frame": request.goal_in_robot_frame,
            "laser_scan": request.laser_scan,
            "last_action": request.last_action
        }, self._obs_structure)

        action = self._agent.predict(observation, deterministic=True)[0]

        decoded_action = self._encoder.decode_action(action)

        response = GetActionResponse()
        response.action = decoded_action

        return response

    def _get_model(self, agent_path):
        action_state_sizes = [0, 3]

        for size in action_state_sizes:
            rospy.set_param(rospy.get_namespace() + "action_state_size", size)
            try:
                return PPO.load(os.path.join(agent_path, "best_model.zip")).policy
            except:
                pass

        rospy.signal_shutdown("")

    def _get_model_path(self, model_name):
        return os.path.join(
            rospkg.RosPack().get_path("rosnav"),
            "agents",
            model_name
        )

    def _load_hyperparams(self, agent_path):
        with open(os.path.join(agent_path, "hyperparameters.json")) as file:
            return json.load(file)

    def _get_observation_space_structure(self, hyperparams):
        structure = hyperparams.get("observation_space", ["laser_scan", "goal_in_robot_frame"])

        return structure

if __name__ == "__main__":
    rospy.init_node("rosnav_node")

    node = RosnavNode()

    while not rospy.is_shutdown():
        rospy.spin()


import dataset

if __name__ == "__main__":
    print("DataSet version: ", dataset.__version__)
    db = dataset.connect('sqlite:///:memory:')  # use 'sqlite:///sensors.db' to persist ...

    sensor_table = db['sensors']

    sensor_table.insert(dict(name='SHT711', type="spi", bus_no=3, cs_num=6, alias="RHT-1A"))
    sensor_table.insert(dict(name='SHT711', type="i2c", bus_no=1, i2c_addr=78, alias="RHT-1B"))
    sensor_table.insert(dict(name='SHT711', type="i2c", bus_no=1, i2c_addr=71, alias="RHT-1C"))

    rht1b = sensor_table.find_one(alias='RHT-1B')
    print(repr(rht1b))
    rht1a = sensor_table.find_one(alias='RHT-1A')
    print(repr(rht1a))
    # Find many
    i2c_sensors = sensor_table.find(type="i2c")
    print("I2C-sensors:")
    print("============")
    for sensor in i2c_sensors:
        print(repr(sensor))


from selenium import webdriver
import platform

class BrowserInt():

    def test(self):
        baseUrl = "https://learn.letskodeit.com/p/practice"
        os_platform = platform.system()
        if os_platform == 'Linux':
            driver_path = webdriver.Firefox(executable_path='./geckodriver')
        elif os_platform == 'Darwin':
            driver_path = webdriver.Chrome()

        driver = driver_path

        driver.maximize_window()
        driver.get(baseUrl)

        title = driver.title
        print('Title of webpage is {}'.format(title))
        currentUrl = driver.current_url
        print('Current URL of page is {}'.format(currentUrl))

        driver.refresh()
        print('Browser refreshed 1st time')
        driver.get(driver.current_url)
        print('Browser refreshed 2nd time')

        driver.get('https://www.google.com')
        print('Current URL of page is {}'.format(driver.current_url))
        driver.back()
        print('Browser went one step back in history')
        print('Current URL of page is {}'.format(driver.current_url))
        driver.forward()
        print('Browser went one step forward in history')

        source = driver.page_source
        driver.close()
        driver.quit()

ff = BrowserInt()
ff.test()


from collections import namedtuple

import torch
from torch import nn
import lpips
import torch.nn.functional as F

def make_image_processor(config):
    type = config.get("type", "RGB").lower()
    if type == "rgb":
        ip = RGBProcessor()
    elif type == "perceptual":
        ip = PerceptualProcessor(config.get("layers", 1))
    elif type == "patch":
        ip = PatchProcessor(config.get("patch_size", 3))
    else:
        raise NotImplementedError(f"Unsupported image processor type: {type}")
    return ip

class RGBProcessor(nn.Module):
    def __init__(self):
        super().__init__()
        self.channels = 3

    def forward(self, images):
        images = images * .5 + .5
        return images

class PerceptualProcessor(nn.Module):
    def __init__(self, layers=1) -> None:
        super().__init__()
        self.lpips_module = lpips.LPIPS(net="vgg")
        self._layers = layers
        self.channels = sum(self.lpips_module.chns[:self._layers])

    def forward(self, images):
        n, v, c, h, w = images.shape
        images = images.view(n*v, c, h, w)

        in_input = self.lpips_module.scaling_layer(images)

        x = self.lpips_module.net.slice1(in_input)
        h_relu1_2 = x
        x = self.lpips_module.net.slice2(x)
        h_relu2_2 = x
        x = self.lpips_module.net.slice3(x)
        h_relu3_3 = x

        vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3'])
        outs = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3)

        feats = []

        for kk in range(self._layers):
            f = lpips.normalize_tensor(outs[kk])
            f = F.interpolate(f, (h, w))
            feats.append(f)

        feats = torch.cat(feats, dim=1)

        feats = feats.view(n, v, self.channels, h, w)

        return feats

class PatchProcessor(nn.Module):
    def __init__(self, patch_size) -> None:
        super().__init__()
        self.patch_size = patch_size
        self.channels = 3 * (patch_size ** 2)

        self._hps = self.patch_size // 2

    def forward(self, images):
        n, v, c, h, w = images.shape
        images = images.view(n*v, c, h, w) * .5 + .5

        images = F.pad(images, pad=(self.patch_size // 2,)*4, mode="replicate")
        h_, w_ = images.shape[-2:]

        parts = []

        for y in range(0, self.patch_size):
            for x in range(0, self.patch_size):
                parts.append(images[:, :, y:h_-(self.patch_size - y - 1), x:w_-(self.patch_size - x - 1)])

        patch_images = torch.cat(parts, dim=1)
        patch_images = patch_images.view(n, v, self.channels, h, w)

        return patch_images

class AutoMaskingWrapper(nn.Module):

    # Adds the corresponding color from the input frame for reference
    def __init__(self, image_processor):
        super().__init__()
        self.image_processor = image_processor

        self.channels = self.image_processor.channels + 1

    def forward(self, images, threshold):
        n, v, c, h, w = images.shape
        processed_images = self.image_processor(images)
        thresholds = threshold.view(n, 1, 1, h, w).expand(n, v, 1, h, w)
        processed_images = torch.stack((processed_images, thresholds), dim=2)
        return processed_images


import pytest

_ = pytest.importorskip("duckdb.experimental.spark")

from duckdb.experimental.spark.sql.types import (
    LongType,
    StructType,
    BooleanType,
    StructField,
    StringType,
    IntegerType,
    LongType,
    Row,
    ArrayType,
    MapType,
)
from duckdb.experimental.spark.sql.functions import col, struct, when, lit, array_contains
import duckdb
import re

class TestDataFrameFilter(object):
    def test_dataframe_filter(self, spark):
        data = [
            (("James", "", "Smith"), ["Java", "Scala", "C++"], "OH", "M"),
            (("Anna", "Rose", ""), ["Spark", "Java", "C++"], "CA", "F"),
            (("Julia", "", "Williams"), ["CSharp", "VB"], "OH", "F"),
            (("Maria", "Anne", "Jones"), ["CSharp", "VB"], "NY", "M"),
            (("Jen", "Mary", "Brown"), ["CSharp", "VB"], "NY", "M"),
            (("Mike", "Mary", "Williams"), ["Python", "VB"], "OH", "M"),
        ]

        schema = StructType(
            [
                StructField(
                    'name',
                    StructType(
                        [
                            StructField('firstname', StringType(), True),
                            StructField('middlename', StringType(), True),
                            StructField('lastname', StringType(), True),
                        ]
                    ),
                ),
                StructField('languages', ArrayType(StringType()), True),
                StructField('state', StringType(), True),
                StructField('gender', StringType(), True),
            ]
        )

        df = spark.createDataFrame(data=data, schema=schema)

        # --- Tests ---

        # Using equals condition
        df2 = df.filter(df.state == "OH")
        res = df2.collect()
        assert res[0].state == 'OH'

        # not equals condition
        df2 = df.filter(df.state != "OH")
        df2 = df.filter(~(df.state == "OH"))
        res = df2.collect()
        for item in res:
            assert item.state == 'NY' or item.state == 'CA'

        df2 = df.filter(col("state") == "OH")
        res = df2.collect()
        assert res[0].state == 'OH'

        df2 = df.filter("gender == 'M'")
        res = df2.collect()
        assert res[0].gender == 'M'

        df2 = df.filter("gender != 'M'")
        res = df2.collect()
        assert res[0].gender == 'F'

        df2 = df.filter("gender <> 'M'")
        res = df2.collect()
        assert res[0].gender == 'F'

        # Filter multiple condition
        df2 = df.filter((df.state == "OH") & (df.gender == "M"))
        res = df2.collect()
        assert len(res) == 2
        for item in res:
            assert item.gender == 'M' and item.state == 'OH'

        # Filter IS IN List values
        li = ["OH", "NY"]
        df2 = df.filter(df.state.isin(li))
        res = df2.collect()
        for item in res:
            assert item.state == 'OH' or item.state == 'NY'

        # Filter NOT IS IN List values
        # These show all records with NY (NY is not part of the list)
        df2 = df.filter(~df.state.isin(li))
        res = df2.collect()
        for item in res:
            assert item.state != 'OH' and item.state != 'NY'

        df2 = df.filter(df.state.isin(li) == False)
        res2 = df2.collect()
        assert res2 == res

        # Using startswith
        df2 = df.filter(df.state.startswith("N"))
        res = df2.collect()
        for item in res:
            assert item.state == 'NY'

        # using endswith
        df2 = df.filter(df.state.endswith("H"))
        res = df2.collect()
        for item in res:
            assert item.state == 'OH'

        # contains
        df2 = df.filter(df.state.contains("H"))
        res = df2.collect()
        for item in res:
            assert item.state == 'OH'

        data2 = [(2, "Michael Rose"), (3, "Robert Williams"), (4, "Rames Rose"), (5, "Rames rose")]
        df2 = spark.createDataFrame(data=data2, schema=["id", "name"])

        # like - SQL LIKE pattern
        df3 = df2.filter(df2.name.like("%rose%"))
        res = df3.collect()
        assert res == [Row(id=5, name='Rames rose')]

        # rlike - SQL RLIKE pattern (LIKE with Regex)
        # This check case insensitive
        df3 = df2.filter(df2.name.rlike("(?i)^*rose$"))
        res = df3.collect()
        assert res == [Row(id=2, name='Michael Rose'), Row(id=4, name='Rames Rose'), Row(id=5, name='Rames rose')]

        df2 = df.filter(array_contains(df.languages, "Java"))
        res = df2.collect()
        assert res == [
            Row(
                name={'firstname': 'James', 'middlename': '', 'lastname': 'Smith'},
                languages=['Java', 'Scala', 'C++'],
                state='OH',
                gender='M',
            ),
            Row(
                name={'firstname': 'Anna', 'middlename': 'Rose', 'lastname': ''},
                languages=['Spark', 'Java', 'C++'],
                state='CA',
                gender='F',
            ),
        ]

        df2 = df.filter(df.name.lastname == "Williams")
        res = df2.collect()
        assert res == [
            Row(
                name={'firstname': 'Julia', 'middlename': '', 'lastname': 'Williams'},
                languages=['CSharp', 'VB'],
                state='OH',
                gender='F',
            ),
            Row(
                name={'firstname': 'Mike', 'middlename': 'Mary', 'lastname': 'Williams'},
                languages=['Python', 'VB'],
                state='OH',
                gender='M',
            ),
        ]


# got from https://gist.github.com/enigmaticape/4254054
#!/usr/bin/env python

import sys
import collections

# Bag em
# cipher_file  = open( sys.argv[ 1 ], 'rb')

def get_IC(c_text):
    cipher_text  = c_text

    # remove all non alpha and whitespace and force uppercase
    # SOTHATCIPHERTEXTLOOKSLIKETHIS
    cipher_flat  = "".join(
                            [x.upper() for x in cipher_text.split() \
                                       if  x.isalpha() ]
                         )

    # Tag em
    N            = len(cipher_flat)
    freqs        = collections.Counter( cipher_flat )
    alphabet     =  map(chr, range( ord('A'), ord('Z')+1))
    freqsum      = 0.0

    # Do the math
    for letter in alphabet:
        freqsum += freqs[ letter ] * ( freqs[ letter ] - 1 )

    IC = freqsum / ( N*(N-1) )

    print("IC of the cipher text %.3f" % IC, "({})".format( IC ))
    return IC


from flask import Flask, render_template, request
from os import listdir
from os.path import isfile, join

app = Flask(__name__)

@app.route('/')
def index():
    deck_themes = get_img_dirs()
    return render_template('index.html', deck_themes=deck_themes)

def get_files(deck_theme):
    my_path = f'static/images/{deck_theme}'
    files = [join(my_path, f) for f in listdir(my_path) if isfile(join(my_path, f))]
    return files

def get_img_dirs():
    my_path = 'static/images/'
    decks_data = []
    for dir_name in listdir(my_path):
        icons = get_files(dir_name)
        icons.sort()
        first_img = icons[0]
        deck_data = {'name': dir_name, 'img': first_img}
        decks_data.append(deck_data)
    return decks_data

@app.route('/game', methods=['POST', 'GET'])
def game():
    deck_themes = request.form.getlist('deck_theme')
    if not deck_themes:
        deck_themes = [d for d in listdir('static/images/')]

    files = []
    for deck_theme in deck_themes:
        img_list = get_files(deck_theme)
        for img in img_list:
            files.append(img)

    player_1_keys = ["Q", "W", "E", "R", "F"]
    player_2_keys = ["U", "I", "O", "P", "J"]

    difficulty = int(request.form.get('difficulty', 4))
    player_1_keys_by_difficulty = player_1_keys[:difficulty]
    player_2_keys_by_difficulty = player_2_keys[:difficulty]

    player_1 = request.form.get('player_1', "Player 1")
    player_2 = request.form.get('player_2', "Player 2")

    return render_template('game.html',
                           player_1=player_1,
                           player_2=player_2,
                           player_1_keys=player_1_keys_by_difficulty,
                           player_2_keys=player_2_keys_by_difficulty,
                           files=files)

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


import sys
import time
import string
import random
import requests
import html.parser
from bs4 import BeautifulSoup

class IndeedSalaryFinder(object):
    '''
    Scrapes Indeed to find the Salary associated with the job in question.
    '''

    def __init__(self, query):
        '''
        query - a query to find the job, better queries are better
        '''
        self.query = query

    def find(self, job_id, city='Seattle', state='WA'):
        '''
        Actual scrape function
        '''
        self.no = []
        self.yes = []
        salary = 100
        go = 'yes'
        while go == 'yes':
            new = int(salary/2)
            if new == 0:
                new = 1
            time.sleep(random.randint(0,1))
            if salary <= 25:
                # poverty level...
                go = 'no'
            n = self.get_search(salary, job_id, city, state)
            # print(salary, n)
            if n >= 0:
                try:
                    self.yes.index(salary)
                    go = 'no'
                except:
                    self.yes.append(salary)
                    if len(self.no) >= 1:
                        new = int((min(self.no) - salary)/2)
                    if new <= 0:
                        new = 1
                    salary = salary + new
            else:
                try:
                    self.no.index(salary)
                    go = 'no'
                except:
                    self.no.append(salary)
                    if len(self.yes) >= 1:
                        new = int((salary - max(self.yes))/2)
                    if new <= 0:
                        new = 1
                    salary = salary - new
        print('{}K to {}k by Indeed'.format(max(self.yes), min(self.no)))

    def get_search(self, salary, job_id, city='Seattle', state='WA'):
        '''
        Searches for the job in Indeed... using the search function,
        finds the job_id in the html, or not.
        '''
        r = requests.get('https://www.indeed.com/jobs?q=' + self.query + '+' +
                         '%24' + str(salary) + '%2C000&l=' + city + '%2C+' +
                         state)
        soup = BeautifulSoup(r.content, 'html.parser')
        tags  = soup.find_all()
        return str(tags).find(job_id)

if __name__ == '__main__':
    if len(sys.argv) <= 1:
        print('Type in a query, such as: "data+science+galvanize" and ')
        print('the job_id.')
        print()
        print('job_id -> Make sure the search reveals 2-10 jobs.' )
        print('view source')
        print('find: jobmap')
        print('grab the long string after rd for your job.')
    else:
        finder = IndeedSalaryFinder(sys.argv[1])
        finder.find(sys.argv[2])


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""MergeResults.py:
    Gather all the information from the json files obtained in the tests and create a table in a csv file
"""
__author__ = "Jorge de la Peña García"
__version__ = "1.0"
__maintainer__ = "Jorge"
__email__ = "jpena@ucam.edu"
__status__ = "Production"

import glob
import json
import sys
from os.path import splitext, basename, join

class MergeResults:
    F_RESUME_CSV = 'Resume_analysis.csv'
    SEPARATOR_CSV = ';'
    MAX_TEST = 100  # maximum number of tests allowed per model

    def __init__(self, folder_experiment):
        self.folder = folder_experiment

        self.results = {}
        self.create_csv()

    def get_key_name(self, filename):
        key_name = splitext(basename(filename))[0].split('_')[0]

        if key_name in self.results:
            for i in range(2, self.MAX_TEST):
                if key_name+"_"+str(i) not in self.results:
                    key_name = key_name+"_"+str(i)
                    break;
        return key_name

    def read_data(self):

        for i in glob.glob(join(self.folder, '*.json')):
            key_name = self.get_key_name(i)
            with open(i) as file_in:
                self.results[key_name] = json.load(file_in)

    def create_csv(self):
        self.read_data()
        csv_header = list(self.results.keys())
        csv_header.sort()

        lst_lines = [self.SEPARATOR_CSV + '{} '.format(self.SEPARATOR_CSV).join(csv_header)]
        lst_lines += self.analysis(csv_header)
        lst_lines.append("")
        lst_lines += self.config(csv_header)

        f = open(join(self.folder, self.F_RESUME_CSV), 'w')
        for i in lst_lines:
            f.write('{}\n'.format(i))
        f.close()

    def config(self, csv_header):

        lst_keys_config = []
        lst_lines = []
        for i in csv_header:
            for k, v in self.results[i]['Config']['Model_params']['params'].items():
                if k not in lst_keys_config:
                    lst_keys_config.append(k)

        for k in lst_keys_config:
            line = k
            for key in csv_header:
                if k in self.results[key]['Config']['Model_params']['params']:
                    line += self.SEPARATOR_CSV+" " + str(self.results[key]['Config']['Model_params']['params'][k])
                else:
                    line += self.SEPARATOR_CSV + "-"
            lst_lines.append(line)
        return lst_lines

    def analysis(self, csv_header):
        lst_lines = []
        keys_analysis = self.results[csv_header[0]]['Analysis'].keys()
        for key in keys_analysis:
            if key != "Confusion matrix":
                line = key
                for header in csv_header:
                    line += self.SEPARATOR_CSV + ' ' + str(self.results[header]['Analysis'][key]).replace('.',',')
                lst_lines.append(line)
        return lst_lines

if __name__ == '__main__':
    folder = sys.argv[1]
    MergeResults(folder)


import math
import time
import _pyinstaller_hooks_contrib
import pygame
import os
import sys
import json
pygame.font.init()
pygame.mixer.init()

def getResourcePath(relative_path):
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
        base_path = os.path.abspath(".")
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

FPS = 60
ScreenWidth = 1280
ScreenHeight = 720
Title = "Basic Mario 2"
icon : pygame.surface = pygame.image.load(getResourcePath(str.__add__('Assets/', "icon.png")))
windowColor = (39, 21, 13)
pygame.init()
run = True
entities = []
BGs = []

window = pygame.display.set_mode((ScreenWidth, ScreenHeight))
pygame.display.set_caption(Title)
pygame.display.set_icon(icon)

bulletChance = 20
IsGameOver = False

import pickle

GameStarted = False
Highscore = 0
game_state = {
    'highscore' : Highscore,
}

def save_game_state(game_state, file_name):
    try:
        with open(file_name, 'wb') as file:
            pickle.dump(game_state, file)
            print("Game state saved successfully!")
    except IOError:
        print("Error: Unable to save game state.")

# Load game state
def load_game_state(file_name):
    try:
        if os.path.getsize(file_name) > 0:
            with open(file_name, 'rb') as file:
                game_state = pickle.load(file)
                print("Game state loaded successfully!")
                return game_state
        else:
            return {'highscore': Highscore}
    except (IOError, pickle.UnpicklingError):
        print("Error: Unable to load game state.")
        return {'highscore': Highscore}

def main():
    global run
    global entities
    global Highscore
    global game_state
    global GameStarted
    GameStarted = False
    run = True
    entities = []
    clock = pygame.time.Clock()

    pygame.mixer.music.load(getResourcePath(str.__add__('Assets/', "music1.mp3")))
    pygame.mixer.music.set_volume(.5)
    pygame.mixer.music.play(9999, 0, 2000)

    window.fill((0,0,0))

    addTEXT("text", "a game made by DEVENILLA", (ScreenWidth/2, ScreenHeight/2-50), 5, 7, (255, 255, 255), (0,0,0))

    for ENTITY in entities:
        ENTITY.draw()

    pygame.display.update()

    time.sleep(2.7)

    entities = []

    game_state = load_game_state('save_game.pickle')
    Highscore = game_state['highscore']

    addHIGHSCORE_TIMER("name", (640, 100), 0, 5,  (0, 255, 255), (0,0,0))

    while run:
        clock.tick(FPS)

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

            if event.type == pygame.KEYDOWN:
                start()

        for ENTITY in entities:
            if not BGs.__contains__(ENTITY):
                ENTITY.fixedUpdate(player, entities)

        surface: pygame.surface = pygame.image.load(getResourcePath(str.__add__('Assets/', "start_screen.png")))
        window.blit(surface, (0, 0))

        for ENTITY in entities:
            ENTITY.draw()

        pygame.display.update()

    quit()

def playSound(name : str, volume : float):
    soundPath = getResourcePath(str.__add__('Assets/', name+".wav"))
    sound: pygame.mixer.Sound = pygame.mixer.Sound(soundPath)
    sound.set_volume(volume)
    sound.play(0)

def start():
    global run
    global IsGameOver
    global bulletChance
    global entities
    global BGs
    global GameStarted
    playSound("select", 1)
    GameStarted = True
    run = True
    IsGameOver = False
    entities = []
    clock = pygame.time.Clock()
    bulletChance = 120
    vignette = addBG("vignette", ["vignette"])
    BGs.append(vignette)
    BG = addBG("background", ["bg1", "bg2"])
    BG.converted = True
    BGs.append(BG)
    addHPBG("hp", ["health_0", "health_1", "health_2", "health_3"])
    addTIMER("name", (78, 37), 0, 3,  (255, 255, 255), (0,0,0))
    addHIGHSCORE_TIMER("name", (78, 60), 0, 3,  (0, 255, 255), (0,0,0))
    player = addPlayer("player", ["dev", "dev_run1", "dev_run2", "dev_run3"], (0, 0), (1, 1), (0, 0), 0)
    groundChecker = addEntity("checker", ["ground_checker"], (0, 0), (1, 12), (0, 0), 0)
    platform = addPlatform("platform", ["platform"], (0, 0), (5, 3), (0, 0), 0)

    player.platform = platform
    player.checker = groundChecker
    platform.player = player

    while run:
        clock.tick(FPS)

        player.platform = platform
        player.checker = groundChecker
        platform.player = player

        handleOrbs()
        bulletChance = handleBullets(player, bulletChance)

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

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and IsGameOver:
                    reset()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and not player.isGrounded():
                    player.tryJump()

        for ENTITY in entities:
            if not BGs.__contains__(ENTITY):
                ENTITY.fixedUpdate(player, entities)

        BG.animate(.05)

        if not IsGameOver:
            render(vignette)
        else:
            renderWithoutVignette()

        save_game_state(game_state, 'save_game.pickle')

    quit()

def quit():
    tick = 9

def hurtPlayer(play):
    p : player = play
    if p.tick >= 30:
        playSound("hit", .3)
        p.hp -= 1
        if p.hp <= 0:
            gameOver()
            return

        for ENTITY in entities:
            if ENTITY.name == "bullet": entities.remove(ENTITY)
            else : ENTITY.onPlayerDamage(player)

    p.rect.centerx = ScreenWidth / 2
    p.rect.centery = ScreenHeight / 2 - 100
    p.platform.alpha = 255
    pygame.mouse.set_pos(ScreenWidth / 2, ScreenHeight / 2)

def gameOver():
    global IsGameOver
    IsGameOver = True
    clock = pygame.time.Clock()

    playSound("death", 1)
    for i in range(7):
        BG = addBG("end", [str.__add__("end_screen_", str(int(i + 1)))])
        BG.converted = False
        BGs.append(BG)
        renderWithoutVignette()

def handleOrbs():
    if IsGameOver: return
    if random.randrange(0, 50) == 5:
        addOrb("orb", ["orb"], (random.randrange(-600, 600), random.randrange(-300, 300)), (2, 2), (0, 0), 0,
               player, platform)

def handleBullets(p, bb):
    if IsGameOver: return
    b = bb
    if random.randrange(0, b) == 5:
        addBullet(p)
        if b > 35:
            b -= random.randrange(1, 3)
    return b

def addEntity(name, image, position, scale, flipped, angle):
    ENTITY = entity(name, image, position, scale, flipped, angle, len(entities) - 1)
    entities.append(ENTITY)
    return ENTITY

def addBG(name, image):
    ENTITY = bg(name, image, True, len(entities) - 1)
    entities.append(ENTITY)
    return ENTITY

def addHPBG(name, image):
    ENTITY = healthBg(name, image, len(entities) - 1)
    entities.append(ENTITY)
    return ENTITY

def addTEXT(name, string, pos, angle, size, color, bgColor):
    ENTITY = text(name, string, pos, angle, size, len(entities) - 1, color, bgColor)
    entities.append(ENTITY)
    return ENTITY
def addTIMER(name, pos, angle, size, color, bgColor):
    ENTITY = timer(name, "", pos, angle, size, len(entities) - 1, color, bgColor)
    entities.append(ENTITY)
    return ENTITY
def addHIGHSCORE_TIMER(name, pos, angle, size, color, bgColor):
    ENTITY = hstimer(name, "", pos, angle, size, len(entities) - 1, color, bgColor)
    entities.append(ENTITY)
    return ENTITY

def addPlayer(name, image, position, scale, flipped, angle):
    ENTITY = player(name, image, position, scale, flipped, angle, len(entities) - 1)
    entities.append(ENTITY)
    return ENTITY

def addOrb(name, image, position, scale, flipped, angle, _player, _platform):
    ENTITY = orb(name, image, position, scale, flipped, angle, len(entities) - 1)
    entities.append(ENTITY)
    ENTITY.player = _player
    ENTITY.platform = _platform
    return ENTITY

def addBullet(_player):
    c = random.randrange(0, 4)
    s = 2
    playSound("laser", .1)
    if c == 0:  # up
        pos = (random.randrange(-600, 600), 400)
        ENTITY = beam("bullet", ["beam", "beam_1", "beam_2", "beam_3"], (pos.__getitem__(0), -400), (s, 50), (0, 0), 0, len(entities) - 1)
        ENTITY.pos = pos
        ENTITY.ang = 0
        ENTITY.f = (0, 0)
        entities.append(ENTITY)
        ENTITY.player = _player
    elif c == 1:  # down
        pos = (random.randrange(-600, 600), -400)
        ENTITY = beam("bullet", ["beam", "beam_1", "beam_2", "beam_3"], pos, (s, 50), (0, 0), 0, len(entities) - 1)
        ENTITY.pos = pos
        ENTITY.ang = 180
        ENTITY.f = (0, 0)
        entities.append(ENTITY)
        ENTITY.player = _player
    elif c == 2:  # right
        pos = (800, random.randrange(-350, 350))
        ENTITY = beam("bullet", ["beam", "beam_1", "beam_2", "beam_3"], (-800, pos.__getitem__(1)), (s, 50), (0, 0), 270, len(entities) - 1)
        ENTITY.pos = pos
        ENTITY.ang = 270
        ENTITY.f = (1, 1)
        entities.append(ENTITY)
        ENTITY.player = _player
    elif c == 3:  # left
        pos = (-800, random.randrange(-350, 350))
        ENTITY = beam("bullet", ["beam", "beam_1", "beam_2", "beam_3"], pos, (s, 50), (0, 0), 90, len(entities) - 1)
        ENTITY.pos = pos
        ENTITY.ang = 90
        ENTITY.f = (1, 1)
        entities.append(ENTITY)
        ENTITY.player = _player

def addPlatform(name, image, position, scale, flipped, angle):
    ENTITY = platform(name, image, position, scale, flipped, angle, len(entities) - 1)
    entities.append(ENTITY)
    return ENTITY

def render(vignette):
    # ADD BACKGROUND
    window.fill(windowColor)

    # RENDER OBJECTS
    for ENTITY in entities:
        if ENTITY != vignette:
            ENTITY.draw()

    #vignette.draw()

    pygame.display.update()

def renderWithoutVignette():
    # ADD BACKGROUND
    window.fill(windowColor)

    # RENDER OBJECTS
    for ENTITY in entities:
        ENTITY.draw()

    pygame.display.update()

def reset():
    start()

import random

import pygame
import os

class entity:
    name = "new entity"
    images: list = ["template"]
    imageIndex = 0
    flipped = [0, 0]
    angle = 0
    rect: pygame.Rect = None
    idx = 0

    # when we create a mew Entity
    def __init__(self, name, images, position, scale, flipped, angle, idx):
        self.name = name
        self.images = images
        self.idx = idx
        surface: pygame.surface = pygame.image.load(
            getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[self.imageIndex]), ".png")))))
        scale = (surface.get_width() * scale.__getitem__(0), surface.get_height() * scale.__getitem__(1))

        xpos = position.__getitem__(0) + ScreenWidth / 2 - surface.get_width() / 2
        ypos = position.__getitem__(1) + ScreenHeight / 2 - surface.get_height() / 2

        self.rect = pygame.Rect(xpos, ypos, scale.__getitem__(0), scale.__getitem__(1))
        self.flipped = [flipped.__getitem__(0), flipped.__getitem__(1)]
        self.angle = angle
        self.start()
        self.update()

    def update(self):
        if not run: return
        tick = 0

    def onPlayerDamage(self, player):
        tick=0

    def start(self):
        if not run: return
        self.angle = self.angle

    # runs without a fixed number of times
    def draw(self):
        if not run: return
        surface: pygame.surface = pygame.image.load(
            getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[self.imageIndex]), ".png")))))
        # scale
        surface = pygame.transform.scale(surface, self.rect.size)
        surface = pygame.transform.flip(surface, self.flipped.__getitem__(0), self.flipped.__getitem__(1))

        # rotation
        surface = pygame.transform.rotate(surface, self.angle)

        # draw
        window.blit(surface, (self.rect.x, self.rect.y))

    # runs with a fixed number of times
    def fixedUpdate(self, player, entities):
        if not run: return
        tick = 0

    def animate(self, amount = 1):
        if int(self.imageIndex + amount) >= len(self.images):
            self.imageIndex = 0
        else:
            self.imageIndex += amount

class bg(entity):
    name = "new entity"
    images: list = ["template"]
    tick = 0
    idx = 0
    converted = True

    # when we create a mew Entity
    def __init__(self, name, images, converted, idx):
        self.name = name
        self.images = images
        self.idx = idx
        self.converted = converted

    # runs without a fixed number of times
    def draw(self):
        if not run: return
        surface: pygame.surface = pygame.image.load(
            getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[int(self.imageIndex)]), ".png")))))

        # draw
        if self.converted:
            surface = surface.convert(surface)

        window.blit(surface, (0, 0))

class healthBg(bg):
    name = "new entity"
    images: list = ["template"]
    tick = 0
    idx = 0

    # when we create a mew Entity
    def __init__(self, name, images, idx):
        self.name = name
        self.images = images
        self.idx = idx

    def fixedUpdate(self, player, entities):
        if player.hp >= 3:
            self.imageIndex = 3
        else:
            self.imageIndex = player.hp

    # runs without a fixed number of times
    def draw(self):
        if not run: return
        surface: pygame.surface = pygame.image.load(
            getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[self.imageIndex]), ".png")))))

        surface = pygame.transform.scale_by(surface, 10)

        # draw
        window.blit(surface.convert_alpha(), (0, 0))

class player(entity):
    speed = 5
    sprintSpeed = 10
    jumpForce = -15
    gravity = 1
    xVelocity = 0
    yVelocity = 0
    wasGrounded = False
    checker: entity = None
    platform: platform = None
    animationTick = 0
    jumpTimes = 1
    hp = 3
    tick = 0

    prevX = 0
    prevY = 0

    def start(self):
        self.hp = 3

    def onPlayerDamage(self, player):
        self.tick = 0

    def fixedUpdate(self, player, entities):
        if not run: return

        self.tick += .5

        keys_pressed = pygame.key.get_pressed()

        if keys_pressed[pygame.K_a]:
            self.flipped[0] = True
            if keys_pressed[pygame.K_LSHIFT]:
                self.xVelocity = -self.sprintSpeed
            else:
                self.xVelocity = -self.speed
        elif keys_pressed[pygame.K_d]:
            self.flipped[0] = False
            if keys_pressed[pygame.K_LSHIFT]:
                self.xVelocity = self.sprintSpeed
            else:
                self.xVelocity = self.speed
        elif not keys_pressed[pygame.K_d] and not keys_pressed[pygame.K_a]:
            if self.xVelocity > 0:
                self.xVelocity -= 1
            elif self.xVelocity < 0:
                self.xVelocity += 1

        if keys_pressed[pygame.K_SPACE] and self.isGrounded():
            self.tryJump()

        if not self.isGrounded():
            self.yVelocity += self.gravity
            self.wasGrounded = False
        elif self.isGrounded():
            self.jumpTimes = 1
            if self.yVelocity > 0: self.yVelocity = 0

        self.moveSteps(self.xVelocity, 0)
        self.moveSteps(0, self.yVelocity)

        if self.xVelocity != 0:
            if self.animationTick >= 2:
                self.animate()
                self.animationTick = 0
            else:
                self.animationTick += 1
        else:
            self.imageIndex = 0

        if self.rect.centerx > ScreenWidth + self.rect.size.__getitem__(
                0) / 2 or self.rect.centerx < 0 - self.rect.size.__getitem__(
            0) / 2 or self.rect.y > ScreenHeight:
            hurtPlayer(player)

    def tryJump(self):
        if not run: return
        if self.jumpTimes > 0:
            playSound("jump", .3)
            self.yVelocity = self.jumpForce
            self.jumpTimes -= 1

    def isGrounded(self):
        if not run: return
        self.checker.rect.x = self.rect.x + self.rect.size.__getitem__(0) / 2
        self.checker.rect.y = self.rect.y + self.rect.size.__getitem__(1) / 2
        if self.checker.rect.colliderect(self.platform.rect):
            return True
        return False

    def moveSteps(self, xSteps, ySteps):
        if not run: return
        self.rect.x += xSteps
        # if self.rect.colliderect(self.platform.rect):
        #    self.rect.x -= xSteps

        self.rect.y += ySteps
        while self.rect.colliderect(self.platform.rect) and self.isGrounded():
            self.rect.y -= 1

    def draw(self):
        if not run: return
        surface: pygame.surface = pygame.image.load(
            getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[self.imageIndex]), ".png")))))
        # scale
        surface = pygame.transform.scale(surface, self.rect.size)
        surface = pygame.transform.flip(surface, self.flipped.__getitem__(0), self.flipped.__getitem__(1))

        # rotation
        surface = pygame.transform.rotate(surface, self.angle)

        if self.tick < 30 and (self.tick % 5 == 0 or self.tick % 5 == 1 or self.tick % 5 == 2):
            surface = self.create_white_surf(surface, 255)

        # draw
        window.blit(surface, (self.rect.x, self.rect.y))

    def create_white_surf(self, surf, alpha):
        mask = pygame.mask.from_surface(surf)
        white_surface = mask.to_surface()
        white_surface.set_colorkey((0, 0, 0))
        white_surface.set_alpha(alpha)
        return white_surface

class platform(entity):
    player = None
    alpha = 255

    def start(self):
        if not run: return
        self.alpha = 255
        pygame.mouse.set_pos(self.rect.center)

    def fixedUpdate(self, player, entities):
        if not run: return
        if self.alpha <= 0:
            self.rect.x = 1000000
            return
        self.rect.x = pygame.mouse.get_pos().__getitem__(0) - self.rect.size.__getitem__(0) / 2
        self.rect.y = pygame.mouse.get_pos().__getitem__(1) - self.rect.size.__getitem__(1) / 2
        self.alpha -= 1

    def reset(self):
        self.alpha = 255

    def draw(self):
        if not run: return
        if self.alpha <= 0:
            return
        surface: pygame.surface = pygame.image.load(
            getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[self.imageIndex]), ".png")))))
        # scale
        surface = pygame.transform.scale(surface, self.rect.size)
        surface = pygame.transform.flip(surface, self.flipped.__getitem__(0), self.flipped.__getitem__(1))

        # rotation
        surface = pygame.transform.rotate(surface, self.angle)

        # alpha
        surface.fill((255, 255, 255, self.alpha), None, pygame.BLEND_RGBA_MULT)

        # draw
        window.blit(surface, (self.rect.x, self.rect.y))

class orb(entity):
    player = None
    platform = None
    dir = 0

    def __init__(self, name, images, position, scale, flipped, angle, idx):
        self.name = name
        self.images = ["orb1", "orb2","orb3","orb4","orb5"]
        self.idx = idx
        surface: pygame.surface = pygame.image.load(
            getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[4]), ".png")))))
        scale = (surface.get_width() * scale.__getitem__(0), surface.get_height() * scale.__getitem__(1))

        xpos = position.__getitem__(0) + ScreenWidth / 2 - surface.get_width() / 2
        ypos = position.__getitem__(1) + ScreenHeight / 2 - surface.get_height() / 2

        self.rect = pygame.Rect(xpos, ypos, scale.__getitem__(0), scale.__getitem__(1))
        self.flipped = [flipped.__getitem__(0), flipped.__getitem__(1)]
        self.angle = angle
        self.imageIndex = 0
        self.start()
        self.update()

    def start(self):
        self.dir = random.randrange(-2, 3)

    def fixedUpdate(self, player, entities):
        if not run: return
        if self.rect.colliderect(player.rect):
            player.platform.reset()
            playSound("pickup", .3)
            entities.remove(self)
        self.rect.y += self.dir

        self.rect.scale_by(1, 1)

        if self.imageIndex < 4:
            self.imageIndex+=.2

        if self.rect.centerx > ScreenWidth + self.rect.size.__getitem__(
                0) / 2 or self.rect.centerx < 0 - self.rect.size.__getitem__(
            0) / 2 or self.rect.y + self.rect.size.__getitem__(1) < 0 or self.rect.y > ScreenHeight:
            entities.remove(self)

    def animate(self):
        if self.imageIndex + 1 >= len(self.images):
            self.imageIndex = 0
        else:
            self.imageIndex += 1

    def draw(self):
        if not run: return
        image = getResourcePath(str.__add__('Assets/', str(str.__add__(str(self.images[int(self.imageIndex)]), ".png"))))

        surface: pygame.surface = pygame.image.load(image)
        # scale
        surface = pygame.transform.scale(surface, self.rect.size)
        surface = pygame.transform.flip(surface, self.flipped.__getitem__(0), self.flipped.__getitem__(1))

        # rotation
        surface = pygame.transform.rotate(surface, self.angle)

        # draw
        window.blit(surface, (self.rect.x, self.rect.y))

class text(entity):
    t: str = "new text"
    pos = (0, 0)
    color = (240, 240, 240)
    size = 1
    bgColor = (115, 117, 117)

    def __init__(self, name, text, position, angle, size, idx, color=(240, 240, 240), bgColor=(115, 117, 117)):
        self.name = name
        self.t = text
        self.pos = position
        self.angle = angle
        self.idx = idx
        self.size = size

    def fixedUpdate(self, player, entities):
        if not run: return

    def draw(self):
        if not run: return
        fontPath = getResourcePath(str.__add__('Assets/', "small_bold_pixel-7.ttf"))
        fontObj = pygame.font.Font(fontPath, 16*self.size)
        textSurfaceObj = fontObj.render(self.t, True, self.color)
        textRectObj = textSurfaceObj.get_rect()
        textRectObj.center = self.pos
        textSurfaceObj = pygame.transform.rotate(textSurfaceObj, self.angle)
        window.blit(textSurfaceObj, textRectObj)

def setHighscore(var : int):
    global Highscore
    Highscore = var
    game_state["highscore"] = var
    save_game_state(game_state, 'save_game.pickle')

class timer(text):
    ticks = 0

    def start(self):
        self.ticks = 0

    def time_convert(self, sec):
        mins = sec // 60
        sec = sec % 60
        hours = mins // 60
        mins = mins % 60
        return "{0}:{1}:{2}".format(int(hours), int(mins), int(sec))

    def fixedUpdate(self, player, entities):
        if not run: return
        if IsGameOver: return
        global Highscore
        global game_state
        self.ticks += 1
        time_lapsed = int(self.ticks/FPS)
        if Highscore <= time_lapsed:
            setHighscore(time_lapsed)
        self.t = self.time_convert(time_lapsed)
class hstimer(text):

    def time_convert(self, sec):
        mins = sec // 60
        sec = sec % 60
        hours = mins // 60
        mins = mins % 60
        return "{0}:{1}:{2}".format(int(hours), int(mins), int(sec))

    def fixedUpdate(self, player, entities):
        if not run: return
        global Highscore
        global game_state
        game_state = load_game_state('save_game.pickle')
        Highscore = game_state['highscore']
        if GameStarted:
            self.color = (255, 230, 0)
        else:
            self.color = (0, 255, 255)

        if GameStarted:
            self.t = self.time_convert(Highscore)
        else:
            self.t = "HIGHSCORE => " + str(self.time_convert(Highscore))

# Save game state
class bullet(entity):
    player = None
    speed = 15
    tick = 0

    def onPlayerDamage(self, player):
        entities.remove(self)

    def fixedUpdate(self, player, entities):
        if not run: return
        if not entities.__contains__(self): return
        self.player = player
        if self.tick > 5 * FPS:
            entities.remove(self)
        else:
            self.tick += 1
        if self.rect.colliderect(self.player):
            hurtPlayer(player)
            if entities.__contains__(self): entities.remove(self)
        if self.angle == 0:
            self.rect.y -= self.speed
        elif self.angle == 90:
            self.rect.x += self.speed
        elif self.angle == 180:
            self.rect.y += self.speed
        elif self.angle == 270:
            self.rect.x -= self.speed

class beam(entity):
    tick = 0
    max = 50

    pos = (0, 0)
    f = (0, 0)
    ang = 0

    summoned = False

    def onPlayerDamage(self, player):
        entities.remove(self)

    def fixedUpdate(self, player, entities):
        if not run: return
        if not entities.__contains__(self): return
        if self.tick >= self.max/2:
            if not self.summoned:
                playSound("shoot", .1)
                entities.append(bullet("bullet", ["crow"], self.pos, (2, 2), self.f, self.ang,
                                len(entities) - 1))
                self.summoned = True
            if self.tick >= self.max:
                entities.remove(self)
            else:
                if (self.tick > self.max-4):
                    self.imageIndex+=1
                self.tick+=1
        else:
            self.tick += 1
            self.summoned = False

if __name__ == "__main__":
    main()


"""Redact it yaml module.

This module contains the core logic to redact data from yaml files.
"""
import glob
from typing import Any

from redact_it.redact_it import RedactIt

class RedactItYaml(RedactIt):
    """Redact it yaml class."""

    def __init__(self, config_file: str, file_path: str, dry_run: bool) -> None:
        """Constructor.

        :param config_file: the redact it configuration file
        :param file_path: the file path of where to glob for files
        :param dry_run: toggle on/off dry run
        """
        super().__init__(config_file, file_path, dry_run)

    def redact(self) -> int:
        """Redact data from files."""
        self.load_config_file()
        if not self.config:
            return 1

        for file in glob.glob(self.file_path, recursive=True):
            if file == self.config_file:
                continue

            try:
                with open(file) as f:
                    file_content: dict[str, Any] = self.yaml.load(f)
            except FileNotFoundError as e:
                print(f"Failed to load {file}, error: {e}")
                continue

            count: int = 0

            for key, value in self.config.items():
                if isinstance(value, dict):
                    for nested_key, nested_value in value.items():
                        if (
                            nested_key in file_content[key]
                            and file_content[key][nested_key] != nested_value
                        ):
                            file_content[key][nested_key] = nested_value
                            count += 1
                else:
                    if key in file_content and file_content[key] != value:
                        file_content[key] = value
                        count += 1

            if count > 0:
                if self.dry_run:
                    print(
                        f"File {file} would be redacted, disable --dry-run to redact it"
                    )
                    continue

                print(f"Redacted {file}")

                with open(file, "w") as f:
                    self.yaml.dump(file_content, f)
        return 0


import spacy
from spacy.matcher import Matcher
from spacy.lang.en import English
from lib.custom_nlp.patterns import cse_pattern, tsx_pattern, stock_phrases
import re
from spacytextblob.spacytextblob import SpacyTextBlob
try:
    from lib.custom_nlp.curr_tickers import stocks as stock_names
except ImportError as e:
    print(e)
    stock_names = []

# All NLP logic is encompassed in this object
class NLPLogic:
    def __init__(self):
        nlp = spacy.load('en_core_web_sm')
        nlp.add_pipe("spacytextblob")
        self.nlp = nlp

    def get_text_matches(self, text):
        matches = []
        matched_strings = []

        temp_matched_strings, temp_matches = self.phrases_of_interest(text)
        matched_strings = [*matched_strings, *temp_matched_strings]
        matches = [*matches, *temp_matches]

        temp_matched_strings, temp_matches = self.stocks_of_interest(text)
        matched_strings = [*matched_strings, *temp_matched_strings]
        matches = [*matches, *temp_matches]

        temp_matched_strings, temp_matches = self.stocks_from_exchange(text)
        matched_strings = [*matched_strings, *temp_matched_strings]
        matches = [*matches, *temp_matches]

        return matched_strings, matches

    def phrases_of_interest(self, text):
        matcher = Matcher(self.nlp.vocab, validate=True)
        matcher.add(
            "Phrases",
            stock_phrases
        )
        doc = self.nlp(text)
        matches = matcher(doc)
        # Iterate and add stocks to the matcher, one by one
        matched_strings = []
        for match_id, start, end in matches:
            string_id = self.nlp.vocab.strings[match_id]  # Get string representation
            span = doc[start:end]  # The matched span
            matched_strings.append(span.text)
        return matched_strings, matches

    def stocks_of_interest(self, text):
        """
        Description: Checks a given sentence for stocks of interest

        Returns:
          matched_strings: String matches from text
          matches: spacy matches
        """
        stock_patterns = [{"TEXT": {"REGEX": f"{stock}"}} for stock in stock_names if len(stock) > 1]
        matcher = Matcher(self.nlp.vocab)
        matcher.add("stocks_patterns", [stock_patterns])
        doc = self.nlp(text)

        matches = matcher(doc)
        # Iterate and add stocks to the matcher, one by one
        matched_strings = []
        # for match_id, start, end in matches:
        #     string_id = self.nlp.vocab.strings[match_id]  # Get string representation
        #     span = doc[start:end]  # The matched span
        #     print(match_id, string_id, start, end, span.text)

        # https://spacy.io/usage/rule-based-matching
        for stock in stock_names:
            for match in re.finditer(stock, doc.text, flags=re.IGNORECASE):
                start, end = match.span()
                span = doc.char_span(start, end)
                # This is a Span object or None if match doesn't map to valid token sequence
                if span is not None:
                    matched_strings.append(span.text)
        # for match_id, start, end in matches:
        #     string_id = self.nlp.vocab.strings[match_id]  # Get string representation
        #     span = doc[start:end]  # The matched span
        #     matched_strings.append(span.text)
        return matched_strings, matches

    def stocks_from_exchange(self, text):
        """
        Description: Checks a given sentence for tickers from exchanges

        Returns:
          matched_strings: String matches from text
          matches: spacy matches
        """
        matcher = Matcher(self.nlp.vocab)
        doc = self.nlp(text)
        matcher.add("CSE_TICKERS", [cse_pattern])
        matcher.add("TSX_TICKERS", [tsx_pattern])
        matches = matcher(doc)

        matched_strings = []
        for match_id, start, end in matches:
            string_id = self.nlp.vocab.strings[match_id]  # Get string representation
            span = doc[start:end]  # The matched span
            matched_strings.append(span.text)
            print(matches)
        print(matched_strings)
        return matched_strings, matches

    def __exit__(self, exc_type, exc_value, traceback):
        self.nlp = None

if __name__ == "__main__":
    nlpLogic = NLPLogic()


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
from scrapy import Request
from scrapy.pipelines.images import ImagesPipeline
class B(ImagesPipeline):

    default_headers = {
        'accept': 'image/webp,image/*,*/*;q=0.8',
        'accept-encoding': 'gzip, deflate, sdch, br',
        'accept-language': 'zh-CN,zh;q=0.8,en;q=0.6',
        'referer': 'http://search.jumei.com',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
    }

    def get_media_requests(self, item, info):
        """
        :param item: 上一个管道中返回的item
        :param info:
        :return:
        """
        print('info------------',info)
        # referer = item['img_url']
        # self.default_headers['referer'] = referer
        yield Request(item['img_url'], headers=self.default_headers, meta={'item': item})

    def file_path(self, request, response=None, info=None):
        """
        :param request: 每一个图片下载管道请求
        :param response:
        :param info:
        :param strip :清洗Windows系统的文件夹非法字符，避免无法创建目录
        :return: 每套图的分类目录
        """
        item = request.meta['item']
        print('item================================>',item)
        folder = item['title']
        # folder_strip = self.strip(folder)
        image_guid = request.url.split('/')[-1]
        filename = u'full/{0}/{1}'.format(folder, image_guid)
        return filename

    def item_completed(self, results, item, info):
        print('?????????????????????????result????????????')
        print('item-------------',item)
        print('info-------------',info)
        print('results',results)
        image_paths = [x['path'] for ok, x in results if ok]
        print('imge_paths==========>',image_paths)
        if not image_paths:
            raise DropItem("Item contains no images")
        return item


# Licensed under a 3-clause BSD style license - see LICENSE.rst

from astropy import units
import numpy as np
import pytest

from sofia_redux.scan.filters.filter import Filter
from sofia_redux.scan.filters.kill_filter import KillFilter

class NoFilter(Filter):  # pragma: no cover

    def __init__(self, integration=None, data=None):
        super().__init__(integration=integration, data=data)
        self.variable = False

    def get_id(self):
        return 'N'

    def get_config_name(self):
        return 'filter.none'

    def response_at(self, fch):
        if not self.variable:
            return np.ones_like(fch).astype(float)
        else:
            return np.ones((self.channel_size, np.asarray(fch).size))

    def get_mean_point_response(self):
        if not self.variable:
            return 1.0
        else:
            return np.ones(self.channel_size)

class VariedKill(KillFilter):

    def response_at(self, fch):
        response = super().response_at(fch)
        if response.ndim == 2:
            return response.T
        return response

@pytest.fixture
def initialized_filter(populated_integration):
    return NoFilter(integration=populated_integration)

@pytest.fixture
def configured_filter(initialized_filter):
    f = initialized_filter
    f.set_integration(f.integration.copy())
    f.configuration.parse_key_value(f.get_config_name(), 'True')
    f.configuration.parse_key_value(f'{f.get_config_name()}.level', '2.0')
    return f

@pytest.fixture
def kill_filter(populated_integration):
    integration = populated_integration.copy()
    f = VariedKill(integration=integration)
    integration.configuration.parse_key_value('filter.kill', 'True')
    integration.configuration.parse_key_value('filter.kill.bands', '0.5:0.6')
    f.update_config()
    f.make_temp_data()
    f.load_time_streams()
    return f

def test_init(populated_integration):

    f = NoFilter()
    for attr in ['integration', 'channels', 'parms', 'frame_parms', 'data',
                 'points']:
        assert getattr(f, attr) is None

    for attr in ['is_sub_filter', 'dft', 'pedantic', 'enabled']:
        assert not getattr(f, attr)

    for attr in ['nt', 'nf', 'df']:
        assert getattr(f, attr) == 0

    data = np.ones(1024)
    f = NoFilter(data=data)
    assert f.data is data

    integration = populated_integration
    f = NoFilter(integration=integration)
    assert f.integration is integration
    assert f.nt == 2048
    assert f.nf == 1024
    assert np.isclose(f.df, 0.0048828125)
    assert f.channels.data is integration.channels.data

def test_copy(initialized_filter):
    f = initialized_filter
    f.data = np.zeros(1024)
    f2 = f.copy()
    assert f2 is not f
    assert np.allclose(f2.data, f.data)
    assert f2.integration is f.integration
    assert f2.channels is f.channels

def test_referenced_attributes():
    f = NoFilter()
    assert 'integration' in f.referenced_attributes
    assert 'channels' in f.referenced_attributes

def test_channel_dependent_attributes():
    f = NoFilter()
    assert 'points' in f.channel_dependent_attributes

def test_size(initialized_filter):
    assert NoFilter().size == 0
    assert initialized_filter.size > 0

def test_channel_size(initialized_filter):
    assert NoFilter().channel_size == 0
    assert initialized_filter.channel_size > 0

def test_frames(initialized_filter):
    assert NoFilter().frames is None
    assert initialized_filter.frames.__class__.__name__.endswith('Frames')

def test_info(initialized_filter):
    assert NoFilter().info is None
    assert initialized_filter.info.__class__.__name__.endswith('Info')

def test_configuration(initialized_filter):
    assert NoFilter().configuration is None
    assert initialized_filter.configuration.__class__.__name__.endswith(
        'Configuration')

def test_flagspace(initialized_filter):
    assert NoFilter().flagspace is None
    assert initialized_filter.flagspace.__name__.endswith('FrameFlags')

def test_channel_flagspace(initialized_filter):
    assert NoFilter().channel_flagspace is None
    assert initialized_filter.channel_flagspace.__name__.endswith(
        'ChannelFlags')

def test_valid_filtering_frames(initialized_filter):
    f = initialized_filter.copy()
    f.set_integration(f.integration.copy())
    f.integration.frames.set_flags('MODELING_FLAGS', np.arange(5))
    f.integration.frames.valid[5] = False
    v = f.valid_filtering_frames
    assert not v[:6].any()
    assert v[6:].all()
    assert NoFilter().valid_filtering_frames.size == 0

def test_reindex(initialized_filter):
    f = NoFilter()
    f.reindex()
    assert f.channels is None

    f = initialized_filter.copy()
    # Set a copy of the integration
    f.set_integration(f.integration.copy())
    # Set dependents to actual values
    f.parms = f.integration.get_dependents(f.get_config_name())
    f.points = np.arange(f.channels.data.size)

    # Set some dead channels
    f.integration.channels.data.set_flags('DEAD', np.arange(5))
    # Slim the integration channels, but not the filter
    s1 = f.integration.channels.size
    f.integration.slim()
    s2 = f.integration.channels.size
    assert s1 - s2 == 5

    f.reindex()
    assert f.data is None
    assert f.parms.for_channel.size == s2
    assert np.allclose(f.points, np.arange(5, s1))
    assert np.allclose(f.channels.fixed_index, np.arange(5, s1))

    # Try again with no points
    f.points = None
    f.reindex()
    assert f.points is None
    assert f.channels.size == s2

def test_has_option(configured_filter):
    assert not NoFilter().has_option('level')
    assert configured_filter.has_option('level')

def test_option(configured_filter):
    assert NoFilter().option('level') is None
    assert configured_filter.option('level') == '2.0'

def test_make_temp_data(initialized_filter):
    f = initialized_filter
    f.make_temp_data()
    assert f.data.shape == (121, 2048) and np.allclose(f.data, 0)
    assert f.points.shape == (121,) and np.allclose(f.points, 0)
    f.make_temp_data()  # Do again with existing data and points...
    assert f.data.shape == (121, 2048) and np.allclose(f.data, 0)
    assert f.points.shape == (121,) and np.allclose(f.points, 0)

def test_discard_temp_data(initialized_filter):
    f = initialized_filter
    f.make_temp_data()
    f.discard_temp_data()
    assert f.data is None and f.points is None

def test_is_enabled(initialized_filter):
    f = initialized_filter
    assert not f.is_enabled()
    f.enabled = True
    assert f.is_enabled()

def test_get_temp_data(initialized_filter):
    f = initialized_filter
    f.make_temp_data()
    assert f.get_temp_data() is f.data

def test_set_temp_data(initialized_filter):
    f = initialized_filter
    x = np.zeros(20)
    f.set_temp_data(x)
    assert f.data is x

def test_rejection_at():
    f = NoFilter()
    assert np.allclose(f.rejection_at(np.arange(10)), 0)

def test_count_parms(initialized_filter):
    f = initialized_filter
    assert f.count_parms() == 0
    f.variable = True
    assert np.allclose(f.count_parms(), np.zeros(f.channel_size))

def test_get_channels(initialized_filter):
    f = initialized_filter
    assert f.get_channels().data is f.integration.channels.data

def test_set_channels(initialized_filter):
    channels = initialized_filter.integration.channels.copy()
    f = NoFilter()
    assert f.channels is None
    f.set_channels(None)
    assert f.channels is None

    f.set_channels(channels)
    assert f.channels.data is channels.data
    f.set_integration(initialized_filter.integration.copy())

    f.set_channels(channels.data)
    assert f.channels.data is channels.data
    group = f.channels

    f.set_channels(group)
    assert f.channels is not group and f.channels.data is channels.data

    with pytest.raises(ValueError) as err:
        f.set_channels(1)
    assert "Channels must be" in str(err.value)

def test_set_integration(initialized_filter):
    f = NoFilter()
    integration = initialized_filter.integration.copy()
    f.set_integration(integration)
    assert f.integration is integration
    assert f.nt == 2048
    assert f.nf == 1024
    assert f.df == 0.0048828125
    assert f.channels.data is integration.channels.data

def test_update_config(configured_filter):
    f = NoFilter()
    f.update_config()
    assert not f.enabled and not f.pedantic
    f = configured_filter.copy()
    assert not f.enabled
    assert not f.pedantic
    f.update_config()
    assert f.enabled
    assert not f.pedantic
    f.configuration.parse_key_value('filter.mrproper', 'True')
    f.update_config()
    assert f.enabled
    assert f.pedantic

def test_apply(configured_filter):
    f = NoFilter()
    assert not f.apply()
    assert f.frame_parms is None
    f = configured_filter
    assert f.apply(report=True)
    assert f.integration.comments == ['N', '(1.0)']

def test_apply_to_channels(configured_filter):
    integration = configured_filter.integration.copy()
    f = configured_filter.copy()
    f.set_integration(integration.copy())
    d1 = f.integration.frames.data.copy()
    f.apply_to_channels()
    d2 = f.integration.frames.data.copy()
    assert not np.allclose(d1, d2)
    f = configured_filter.copy()
    f.set_integration(integration.copy())
    f.pedantic = True
    f.dft = True
    f.apply_to_channels()
    d3 = f.integration.frames.data.copy()
    assert np.allclose(d3, d2)
    f = configured_filter.copy()
    f.set_integration(integration.copy())
    f.data = np.zeros((0, 0))
    f.apply_to_channels()
    assert f.data.shape == (121, 2048)

def test_pre_filter(configured_filter):
    f = configured_filter.copy()
    integration = f.integration.copy()
    i1 = integration.copy()
    f.set_integration(i1)
    parms = i1.get_dependents(f.get_config_name())
    parms.for_channel[:] += 1
    parms.for_frame[:] += 2
    assert np.allclose(i1.frames.dependents, 0)
    assert np.allclose(i1.channels.data.dependents, 0)
    f.pre_filter()
    assert np.allclose(i1.frames.dependents, -2)
    assert np.allclose(parms.for_frame, 0)
    assert np.allclose(i1.channels.data.dependents, -1)
    assert np.allclose(parms.for_channel, 0)

    i2 = integration.copy()
    f = configured_filter.copy()
    f.set_integration(i2)
    f.is_sub_filter = True
    parms = i2.get_dependents(f.get_config_name())
    parms.for_channel[:] += 1
    parms.for_frame[:] += 2
    assert np.allclose(i2.frames.dependents, 0)
    assert np.allclose(i2.channels.data.dependents, 0)
    f.pre_filter()
    assert np.allclose(i2.frames.dependents, 0)
    assert np.allclose(parms.for_frame, 0)
    assert np.allclose(i2.channels.data.dependents, 0)
    assert np.allclose(parms.for_channel, 0)

def test_post_filter(configured_filter):
    f = configured_filter.copy()
    integration = f.integration.copy()
    f.set_integration(integration)
    parms = integration.get_dependents(f.get_config_name())
    parms.for_frame[:] = 1
    parms.for_channel[:] = 2
    f.parms = parms
    f.is_sub_filter = True
    f.post_filter()
    assert np.allclose(integration.frames.dependents, 0)
    assert np.allclose(integration.channels.data.dependents, 0)
    f.is_sub_filter = False
    f.post_filter()
    assert np.allclose(integration.frames.dependents, 1)
    assert np.allclose(integration.channels.data.dependents, 2)

def test_remove(configured_filter):
    f = configured_filter.copy()
    f.make_temp_data()
    f.data.fill(1.0)
    d0 = f.integration.frames.data.copy()
    f.remove()
    assert np.allclose(d0, f.integration.frames.data + 1)

def test_remove_from_frames(configured_filter):
    f = configured_filter.copy()
    frames = f.integration.frames
    channels = f.channels
    f.make_temp_data()
    f.data.fill(1)
    d0 = frames.data.copy()
    NoFilter.remove_from_frames(
        rejected_signal=f.data,
        frames=frames,
        channels=channels)
    assert np.allclose(d0, frames.data + 1)

def test_report(configured_filter):
    f = configured_filter.copy()
    integration = f.integration.copy()
    assert len(integration.comments) == 0
    i1 = integration.copy()
    f.set_integration(i1)
    f.report()
    assert i1.comments == ['(1.0)']
    i2 = integration.copy()
    i2.channels.n_mapping_channels = 0
    f.set_integration(i2)
    f.report()
    assert i2.comments == ['(---)']

def test_load_time_streams(configured_filter):
    f = configured_filter.copy()
    assert f.data is None
    f.load_time_streams()
    df = f.data[:, :1100].T
    df0 = f.data.copy()
    di = f.integration.frames.data
    diff = di - df
    assert np.allclose(diff, diff[0, None])  # Just the mean
    assert np.allclose(f.points, 1100)  # no invalid points

    f.data = np.zeros((0, 0))
    f.load_time_streams()
    assert np.allclose(f.data, df0)

def test_fft_filter(kill_filter, configured_filter):
    f = configured_filter
    f.load_time_streams()
    d0 = f.integration.frames.data.copy()
    f0 = f.data.copy()
    f.fft_filter()
    # Nothing happens because no rejection...
    assert np.allclose(f.integration.frames.data, d0)
    assert np.allclose(f.data, f0)

    f = kill_filter.copy()
    integration = f.integration.copy()
    d0 = integration.frames.data.copy()
    f0 = f.data.copy()
    f.fft_filter()
    assert not np.allclose(f.data, f0)
    assert np.allclose(f.integration.frames.data, d0)
    assert np.allclose(f.data[f.integration.size:], 0)  # Zeroed
    f1 = f.data.copy()

    reject = f.reject.copy()
    varied_reject = np.empty((reject.size, f0.shape[0]), dtype=bool)
    varied_reject[...] = reject[:, None].copy()
    f.reject = varied_reject
    f.load_time_streams()
    f.fft_filter()
    assert np.allclose(f.data, f1)  # Should be the same, but 2-D processing.

def test_dft_filter(kill_filter, configured_filter):
    f = configured_filter
    f.load_time_streams()
    d0 = f.integration.frames.data.copy()
    f0 = f.data.copy()
    f.dft_filter()
    # Nothing happens because no rejection...
    assert np.allclose(f.integration.frames.data, d0)
    assert np.allclose(f.data, f0)

    f = kill_filter.copy()
    f0 = f.integration.frames.data.copy()
    freq_channels = np.arange(f.nf + 1)
    f.rejection_at(freq_channels)
    f.dft_filter()
    d1 = f.data.copy()
    # Check that the integration data is unmodified
    assert np.allclose(f0, f.integration.frames.data)

    f = kill_filter.copy()
    f.load_time_streams()
    f.fft_filter()
    d2 = f.data.copy()
    # Check that the DFT is consistent with the FFT
    assert np.allclose(d1, d2)

def test_calc_point_response(kill_filter):
    f = kill_filter.copy()
    # Infinite integration filter time scale
    assert np.isclose(f.calc_point_response(), 0.9723746209)

    # About half way through the filter rejection block
    f.integration.filter_time_scale = 0.9 * units.Unit('second')
    assert np.isclose(f.calc_point_response(), 0.9874574061)

def test_get_high_pass_index(kill_filter):
    f = kill_filter.copy()
    ts = f.integration.filter_time_scale
    assert np.isinf(ts) and ts > 0
    assert f.get_high_pass_index() == 0

    f.integration.filter_time_scale = 0.9 * units.Unit('second')
    assert f.get_high_pass_index() == 114

    f.integration.filter_time_scale = np.nan * units.Unit('second')
    assert f.get_high_pass_index() == 1

def test_level_data_for_channels(kill_filter):
    f = kill_filter.copy()
    f.data += 1
    d0 = f.data.copy()
    f.level_data_for_channels()
    d1 = f.data.copy()
    diff = d0 - d1
    n = f.integration.size
    assert np.allclose(diff[:, :n], 1)
    assert np.allclose(diff[:, n:], 0)

def test_level_for_channels(kill_filter):
    f = kill_filter.copy()
    f.data += 1
    d0 = f.data.copy()
    d1 = d0.copy()
    f.level_for_channels(d1, channels=f.channels)
    diff = d0 - d1
    n = f.integration.size
    assert np.allclose(diff[:, :n], 1)
    assert np.allclose(diff[:, n:], 0)

    d1 = d0.copy()
    f.level_for_channels(d1, channels=f.channels.copy())
    diff = d0 - d1
    assert np.allclose(diff[:, :n], 1)
    assert np.allclose(diff[:, n:], 0)

def test_level_data(kill_filter):
    f = kill_filter.copy()
    f.data += 1
    d0 = f.data.copy()
    f.level_data()
    d1 = f.data.copy()
    diff = d0 - d1
    n = f.integration.size
    assert np.allclose(diff[:, :n], 1)
    assert np.allclose(diff[:, n:], 0)

def test_level(kill_filter):
    f = kill_filter.copy()
    signal = np.ones(f.integration.size)
    f.level(signal)
    assert np.allclose(signal, 0)
    signal = (np.arange(3) + 1)[:, None] * np.ones(f.integration.size)[None]
    f.level(signal)
    assert np.allclose(signal, 0) and signal.shape == (3, f.integration.size)

def test_set_dft(kill_filter):
    f = kill_filter.copy()
    assert f.dft
    f.set_dft(False)
    assert not f.dft


from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import numpy as np

iris = load_iris()
atributos = iris.data
classes = iris.target

atributos_do_conjunto = atributos[classes != 0]
classes_conjunto = classes[classes != 0]
classes_conjunto = np.where(classes_conjunto == 1, 1, -1)

#População inicial
def inicializar_populacao(tamanho_populacao, dimensao_individuo):
    populacao = []
    for j in range(tamanho_populacao):
        individuo = np.random.uniform(-1, 1, dimensao_individuo)
        populacao.append(individuo)
    return populacao

# Mutação do filho
def mutacao(individuo, taxa_mutacao):
    #Verifica numero aleatório gerado e compara com a taxa de mutação para mutar o filho
    for i in range(len(individuo)):
        if np.random.uniform(-1, 1) < taxa_mutacao:
            individuo[i] = np.random.uniform(-1, 1)
    return individuo

# Para cada individuo calcula a aptidao EMQ
def aptidao(individuo):
    pesos = individuo[:-1]
    viés = individuo[-1]
    erro_quadrado_total = 0
    for i in range(atributos_treinamento.shape[0]):
        entrada = atributos_treinamento[i]
        alvo = classes_treinamento[i]
        soma_ponderada = np.dot(entrada, pesos) + viés
        previsao = 1 if soma_ponderada >= 0 else 0
        erro = alvo - previsao
        erro_quadrado_total += erro ** 2
    emq = erro_quadrado_total / atributos_treinamento.shape[0]
    return emq

# Cruzamento dos pais selecionados
def crossover(pai1, pai2):
    ponto_corte = np.random.randint(0, len(pai1))
    #Une pais de acordo com o ponto de corte definido
    filho = np.concatenate((pai1[:ponto_corte], pai2[ponto_corte:]))
    return filho

for cont in range(3):
    if cont == 0:
        proporcao_conn_teste = 0.1
    if cont == 1:
        proporcao_conn_teste = 0.3
    if cont == 2:
        proporcao_conn_teste = 0.5
    # Divisão entre treinamento e teste
    atributos_treinamento, atributos_teste, classes_treinamento, classes_teste = train_test_split(atributos_do_conjunto, classes_conjunto, test_size=proporcao_conn_teste, random_state=42)
    tamanho_conjunto = atributos_teste.shape[0]
    #Inicialização pesos/bias
    np.random.seed(0)
    pesos = np.random.rand(atributos_treinamento.shape[1])
    viés = np.random.rand()

    #Genético
    tamanho_populacao = 100
    dimensao_individuo = atributos_treinamento.shape[1] + 1  #Adiciona o viés na ultima posição
    taxa_mutacao = 0.2
    num_geracoes = 200
    populacao = inicializar_populacao(tamanho_populacao, dimensao_individuo)

    for geracao in range(num_geracoes):
        aptidoes = []
        for individuo in populacao:
            apt = aptidao(individuo)
            aptidoes.append(apt);
        melhor_individuo = populacao[np.argmin(aptidoes)]
        # populacao que contem apenas o melhor indivíduo, será a próxima populacao
        populacao_selecionada = [melhor_individuo]
        #Gera filhos
        while len(populacao_selecionada) < tamanho_populacao:
            #seleciona dois indices da populacao para serem os pais
            indices = np.random.choice(len(populacao), size=2, replace=False)
            pai1 = populacao[indices[0]]
            pai2 = populacao[indices[1]]
            filho = crossover(pai1, pai2)
            filho = mutacao(filho, taxa_mutacao)
            populacao_selecionada.append(filho)
        populacao = populacao_selecionada

    melhor_pesos = melhor_individuo[:-1]
    melhor_bias = melhor_individuo[-1]

    pesos = melhor_pesos;
    viés = melhor_bias;

    # Execução de testes do classificador
    corretos = 0
    for i in range(tamanho_conjunto): #Tamanho conjunto de testes
        entrada = atributos_teste[i]
        objetivo = classes_teste[i]
        soma_ponderada = np.dot(entrada, pesos) + viés
        ativação = np.sign(soma_ponderada)
        if ativação == objetivo:
            corretos += 1

    acuracia = (corretos / tamanho_conjunto) * 100 #Quantidade de acertos/tamanho do conjunto

    print("Teste "+str(cont+1))
    print("     Tamanho conjunto de teste:", proporcao_conn_teste)
    print("     Acurácia obtida no conjunto de teste %:", acuracia)


import serial
import RPi.GPIO as GPIO
import os, time

textnumber = '8327978415'
textmessage = 'Please return to your car immediately!'
GPIO.setmode(GPIO.BOARD)

GSMpower = 11
GPIO.setup(GSMpower,GPIO.OUT)
GPIO.output(GSMpower,1) #Turn on GSM

# Enable Serial Communication
print("Begin SMS procedure")
port = serial.Serial("/dev/serial0", baudrate=9600, timeout=1) #Declare what serial port to use

#Flush Serial
port.flushInput()
time.sleep(.5)
port.flushOutput()
time.sleep(.5)

# Transmitting AT Commands to the Modem
def GSMconvo(message):
    sendGSM = message + '\r' #Change original message into GSM message format
    print(sendGSM.encode('utf-8')) #encode message and print to terminal
    port.write(sendGSM.encode('utf-8')) #encode message and send to serial port
    port.readline() #This WILL be '\r\n'. Need line to read GSM response on next line
    print (port.readline()) #Read and print GSM response to terminal
    time.sleep(.5)

GSMconvo('AT')
GSMconvo('ATE0') # Disable the Echo
GSMconvo('ATE0') # Disable the Echo
GSMconvo('AT+CVHU=0')
GSMconvo('ATI')
GSMconvo('AT+GMM')
GSMconvo('AT+CPMS="SM","SM","SM"')
GSMconvo('AT+CSCS="GSM"')
GSMconvo('AT+CMGF=1') # Select Message format as Text mode
GSMconvo('AT+CNMI=2,1,0,0,0') # New SMS Message Indications
GSMconvo('AT+CMGS="1'+ textnumber +'"') # Determine what number to text
GSMconvo(textmessage) #Determine content of text
GSMconvo("\x1A") # Enable to send SMS
port.close()