'''
打点钱包获取用户信息
'''
import readConfig
import json
import unittest,paramunittest
from common import common,Log
from common import configHttp

userInfo_xls = common.get_xls('userCase.xlsx','userInfo')
localReadConfig = readConfig.ReadConfig()
configHttp = configHttp.ConfigHttp()
info = ()

@paramunittest.parametrized(*userInfo_xls)
class UserInfo(unittest.TestCase):

    def setParameters(self,case_name,method,code,cn_msg):
        '''
        set params
        :param case_name:
        :param method:
        :param code:
        :param cn_msg:
        :return:
        '''
        self.case_name = str(case_name)
        self.method = str(method)
        self.code = int(code)
        self.cn_msg = str(cn_msg)

    def setUp(self):
        self.log = Log.MyLog.get_log()
        self.logger = self.log.get_logger()

    def testuserInfo(self):
        '''
        用户信息
        :return:
        '''
        self.url = common.get_url_from_xml('userInfo')

        # set url
        configHttp.set_url(self.url)

        # set headers
        configHttp.set_headers()

        # test interface
        self.return_json = configHttp.request_get()

        self.checkResult()

    def checkResult(self):
        '''
        check test result
        :return:
        '''
        self.info = json.loads(self.return_json.text)

        self.assertEqual(self.info['code'],self.code)
        self.assertEqual(self.info['cn_msg'],self.cn_msg)

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


import json

from classes.monster import Monster

monster = Monster(name="Orc", mclass="evil", hitpoints= 32, armor= 12)

#  print(monster)

dicMonster = vars(monster)

print(dicMonster)

f = open("monster.json", "w+")
json.dump(dicMonster, f, indent=2)
f.close()


from textblob import TextBlob
import json, time

def analyzeTweets():
    with open('scraped/'+time.strftime("%Y-%m-%d")+'.json') as inputData:
        tweets = json.load(inputData)

    for tweet in tweets:
        (polarity, subjectivity) = (TextBlob(tweet['text']).sentiment)
        tweet['subjectivity'] = subjectivity
        tweet['polarity'] = polarity

    with open('analyzed/'+time.strftime("%Y-%m-%d")+'.json', 'w', encoding='utf-8') as f:
        json.dump(tweets, f, ensure_ascii=False, indent=4)

    print("Tweets Analyzed: " + str(len(tweets)))


from pathlib import Path

import pandas as pd
import pytest

from ipumspy import ddi, readers

@pytest.fixture(scope="module")
def cps_ddi(fixtures_path: Path) -> ddi.Codebook:
    return readers.read_ipums_ddi(fixtures_path / "cps_00006.xml")

@pytest.fixture(scope="module")
def cps_df(fixtures_path: Path, cps_ddi: ddi.Codebook) -> pd.DataFrame:
    return readers.read_microdata(cps_ddi, fixtures_path / "cps_00006.csv.gz")

def test_get_variable_info(cps_ddi: ddi.Codebook, cps_df: pd.DataFrame):
    # Does it retrieve the appropriate variable?
    assert cps_ddi.get_variable_info("YEAR").id == "YEAR"

    # Even if the name is not UPPERCASE?
    assert cps_ddi.get_variable_info("year").id == "YEAR"

    # does it give the right description
    assert (
        cps_ddi.get_variable_info("year").description
        == "YEAR reports the year in which the survey was conducted.  YEARP is repeated on person records."
    )

    # does it return the name
    assert cps_ddi.get_variable_info("year").name == "YEAR"

    # codes
    assert cps_ddi.get_variable_info("month").codes == {
        "January": 1,
        "February": 2,
        "March": 3,
        "April": 4,
        "May": 5,
        "June": 6,
        "July": 7,
        "August": 8,
        "September": 9,
        "October": 10,
        "November": 11,
        "December": 12,
    }

    # And does it raise a ValueError if the variable does not exist?
    with pytest.raises(ValueError):
        cps_ddi.get_variable_info("foo")


import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.integrate import odeint

# Simulation parameters
duration = 100  # Duration of the simulation in hours
time_step = 1  # Time step size in hours

# Building parameters
layers = 4  # Number of layers
area_room = 3.65 * 4  # Area of the building in square meters
height_room = 3.3

cp = np.array([835, 1317, 835, 835])  # Specific heat capacity of each layer

# Constants and parameters
rho_in = 1.2  # Air density at inlet, kg/m^3
rho_out = 1.2  # Air density at outlet, kg/m^3
alpha_w = [1.7e-7, 1.4e-6, 2.25e-2, 1.7e-7]  # Thermal diffusivity of wall, m^2/s
alpha_r = [1.7e-7, 1.4e-6, 1.8e-7, 4e-7]  # Thermal diffusivity of roof, m^2/s
alpha_f = [4.0e-7, 1.7e-7]  # Thermal diffusivity of floor, m^2/s
alpha_fur = 1.8e-7  # Thermal diffusivity of furniture, m^2/s
l_w = [6e-3, 75e-3, 8.5e-3, 8.5e-3]  # Thickness of wall layers, m
l_r = [6e-3, 100e-3, 11e-3, 6.5e-4]  # Thickness of roof layers, m
l_f = [1e-3, 9e-3]  # Thickness of floor layers, m
K_w = [0.14, 0.038, 0.026, 0.14]
K_r = [0.14, 0.038, 0.12, 0.027]
K_f = [0.027, 0.14]
K_fur = 2
rho_f = [55.0, 615.0]  # Furniture density, kg/m^3
c_p_f = [1210.0, 1317.0]  # Furniture specific heat capacity, J/(kg*K)

# Outside temperature
T_outside = 270.95  # Outside temperature in degrees kelvin

# Furniture parameters
furniture_volume = 1  # Volume of furniture in cubic meters
furniture_alpha = 1.8e-7  # Thermal diffusivity of furniture
furniture_radius = 0.5  # Radius of furniture in meters

# Heat transfer coefficients
h_walls = 2
h_furniture = 2

air_flow = 0.7

num_steps = int(duration / time_step)
T = np.zeros((num_steps, layers))
# Set initial conditions
V_b = area_room * height_room
V_out = air_flow
# Assume V_in = V_out
V_in = V_out
Ventilation_rate = V_in / V_b
# Assume ρ_in = ρ_out
# rho_in = rho_out

h_b_w = 2
h_alpha_w = 1
h_b_r = 2
h_alpha_r = 1
h_b_f = 2
h_b_fur = 2

h_in = h_b_w + h_alpha_w
h_out = h_b_r + h_alpha_r
R = 8.314  # Pa*m^3 /(mol*K)
M_b = 0.02897  # kg/mol
T_b_occupied_initial = 293.15
T_b_unoccupied_initial = 288.15

time = np.arange(0, duration, time_step)
T_b = np.zeros(num_steps)  # Building unit temperature
T_w_occupied = np.zeros((len(l_w), num_steps))  # Wall temperatures
T_r_occupied = np.zeros((len(l_r), num_steps))  # Roof temperatures
T_f_occupied = np.zeros((len(l_f), num_steps))  # Floor temperatures
T_fur_occupied = np.zeros(num_steps)  # Furniture temperature

T_w_unoccupied = np.zeros((len(l_w), num_steps))  # Wall temperatures
T_r_unoccupied = np.zeros((len(l_r), num_steps))  # Roof temperatures
T_f_unoccupied = np.zeros((len(l_f), num_steps))  # Floor temperatures
T_fur_unoccupied = np.zeros(num_steps)  # Furniture temperature

T_b_occupied = np.zeros(num_steps)
T_b_unoccupied = np.zeros(num_steps)
T_b_occupied[0] = T_b_occupied_initial
T_b_unoccupied[0] = T_b_unoccupied_initial
P_atm = 101300  # Pa

# Assume P_b = P_atm
P_b = P_atm
P_in = P_b
rho_b_occupied = (P_b * M_b) / (R * T_b_occupied[0])
rho_b_unoccupied = (P_b * M_b) / (R * T_b_unoccupied[0])
c_p_b = 1005  # J/(kgK)
print(rho_b_occupied)

# Energy
dE_in_dt_occupied = (
    rho_b_occupied * c_p_b * (T_outside - T_b_occupied[0]) * (area_room * h_in)
)
dE_out_dt_occupied = (
    rho_b_occupied * c_p_b * (T_b_occupied[0] - T_outside) * (area_room * h_out)
)

dE_in_dt_unoccupied = (
    rho_b_unoccupied * c_p_b * (T_outside - T_b_unoccupied[0]) * (area_room * h_in)
)
dE_out_dt_unoccupied = (
    rho_b_unoccupied * c_p_b * (T_b_unoccupied[0] - T_outside) * (area_room * h_out)
)

A_window = A_door = A_walls = A_floor = A_roof = area_room  # it's an approximation
U_window = U_door = U_walls = U_floor = U_roof = 1.2  # W/(m^2·K) approximation

dQ_dt_loss_occupied = np.zeros(num_steps)
dT_b_dt_occupied = np.zeros(num_steps)
dQ_dt_supply = np.zeros(num_steps)
T_infinity = T_outside
Insolation = 100  # W/m^2
Appliances = 150  # W
dQ_people_dt = 58.2 * area_room  # W
dQ_people_dt_series = np.zeros(num_steps)
dQ_appliances_dt = Appliances  # W
dQ_solar_dt = Insolation * area_room
Q_heater = 1000  # W]
dQ_heater_dt = np.zeros(num_steps)
# dQ_heater_dt = Q_heater
k1_occupied = np.zeros(num_steps)
k2_occupied = np.zeros(num_steps)
dQ_supply_dt = dQ_appliances_dt + dQ_solar_dt + dQ_people_dt + Q_heater
T_b_occupied_unbiased = np.zeros(num_steps)
T_b_occupied_unbiased[0] = T_b_occupied_initial

for i in range(1, num_steps):
    dQ_window_dt_occupied = U_window * A_window * (T_infinity)
    dQ_door_dt_occupied = U_door * A_door * (T_infinity)
    dQ_walls_dt_occupied = U_walls * A_walls * (T_infinity)
    dQ_floor_dt_occupied = U_floor * A_floor * (T_infinity)
    dQ_roof_dt_occupied = U_roof * A_roof * (T_infinity)

    dQ_dt_loss_occupied = (
        dQ_window_dt_occupied
        + dQ_door_dt_occupied
        + dQ_walls_dt_occupied
        + dQ_floor_dt_occupied
        + dQ_roof_dt_occupied
    )

    rho_in_occupied = (P_in * M_b) / (R * T_b_occupied_initial)
    rho_out_occupied = rho_b_occupied
    drho_b_occupied_dt = 0

    if i <= 50:
        dQ_dt_supply[i] = dQ_supply_dt
        V_in = V_out = 0.7
        h_in = 60179.47996
        h_out = 60587.96

        k1_occupied_0 = 70
        k1_occupied[i] = (
            (V_in * rho_in_occupied * h_in - V_out * rho_out_occupied * h_out)
            + dQ_dt_supply[i]
            + dQ_dt_loss_occupied
        ) / (V_b * rho_b_occupied * (c_p_b - R / M_b))
        k1 = 70
        k2_occupied[i] = dQ_dt_loss_occupied / T_infinity + (
            V_in * rho_in_occupied - V_out * rho_out_occupied
        ) / (rho_b_occupied * V_b)
        k2 = 0.23
        T_b_occupied[i] = (1 / k2) * (
            k1_occupied_0 - (k1 - k2 * T_b_occupied[0]) * math.exp(-k2 * i)
        )

    else:
        V_in = V_out = 0.7
        h_in = 61173.08
        h_out = 60587.96
        dQ_dt_supply[i] = 0
        k1_occupied_50 = 50

        k1_occupied[i] = (
            (V_in * rho_in_occupied * h_in - V_out * rho_out_occupied * h_out)
            + dQ_dt_supply[i]
            + dQ_dt_loss_occupied
        ) / (V_b * rho_b_occupied * (c_p_b - R / M_b))
        k2 = 0.19
        k1 = 50

        k2_occupied[i] = dQ_dt_loss_occupied / T_infinity + (
            V_in * rho_in_occupied - V_out * rho_out_occupied
        ) / (rho_b_occupied * V_b)
        T_b_occupied[i] = (1 / k2) * (
            k1_occupied_50 - (k1 - k2 * T_b_occupied[50]) * math.exp(-k2 * (i - 50))
        )

for i in range(len(l_w)):
    T_w_occupied[i][0] = T_infinity
for i in range(len(l_r)):
    T_r_occupied[i][0] = T_infinity
for i in range(len(l_f)):
    T_f_occupied[i][0] = T_infinity
T_fur_occupied[0] = T_b_occupied[0]

for i in range(len(l_w)):
    T_w_unoccupied[i][0] = T_infinity
for i in range(len(l_r)):
    T_r_unoccupied[i][0] = T_infinity
for i in range(len(l_f)):
    T_f_unoccupied[i][0] = T_infinity
T_fur_unoccupied[0] = T_b_unoccupied[0]
firstPart = np.zeros(num_steps)

for step in range(1, num_steps):
    dT_w_dt_occupied = np.zeros(len(l_w))

    for i in range(len(l_w)):
        if i == 0:
            dT_w_dt_occupied[i] = alpha_w[i] * (
                (
                    T_w_occupied[i + 1][step - 1]
                    - 2 * T_w_occupied[i][step - 1]
                    + T_b_occupied[step - 1]
                )
                / (l_w[i] ** 2)
            )
        elif i == len(l_w) - 1:
            dT_w_dt_occupied[i] = alpha_w[i] * (
                (
                    T_w_occupied[i - 1][step - 1]
                    - 2 * T_w_occupied[i][step - 1]
                    + T_w_occupied[i][step - 1]
                )
                / (l_w[i] ** 2)
            )
        else:
            dT_w_dt_occupied[i] = alpha_w[i] * (
                (
                    T_w_occupied[i + 1][step - 1]
                    - 2 * T_w_occupied[i][step - 1]
                    + T_w_occupied[i][step - 1]
                )
                / (l_w[i] ** 2)
            )

    dT_r_dt_occupied = np.zeros(len(l_r))
    for i in range(len(l_r)):
        if i == 0:
            dT_r_dt_occupied[i] = alpha_r[i] * (
                (
                    T_r_occupied[i + 1][step - 1]
                    - 2 * T_r_occupied[i][step - 1]
                    + T_b_occupied[step - 1]
                )
                / (l_r[i] ** 2)
            )
        elif i == len(l_r) - 1:
            dT_r_dt_occupied[i] = alpha_r[i] * (
                (
                    T_r_occupied[i - 1][step - 1]
                    - 2 * T_r_occupied[i][step - 1]
                    + T_r_occupied[i][step - 1]
                )
                / (l_r[i] ** 2)
            )
        else:
            dT_r_dt_occupied[i] = alpha_r[i] * (
                (
                    T_r_occupied[i + 1][step - 1]
                    - 2 * T_r_occupied[i][step - 1]
                    + T_r_occupied[i][step - 1]
                )
                / (l_r[i] ** 2)
            )

    dT_f_dt_occupied = np.zeros(len(l_f))
    for i in range(len(l_f)):
        if i == 0:
            dT_f_dt_occupied[i] = alpha_f[i] * (
                (
                    T_f_occupied[i + 1][step - 1]
                    - 2 * T_f_occupied[i][step - 1]
                    + T_b_occupied[step - 1]
                )
                / (l_f[i] ** 2)
            ) + (dQ_dt_supply[step] - dQ_dt_loss_occupied) / (rho_f[i] * c_p_f[i])
        elif i == len(l_f) - 1:
            dT_f_dt_occupied[i] = alpha_f[i] * (
                (
                    T_f_occupied[i - 1][step - 1]
                    - 2 * T_f_occupied[i][step - 1]
                    + T_f_occupied[i][step - 1]
                )
                / (l_f[i] ** 2)
            ) + (dQ_dt_supply[step] - dQ_dt_loss_occupied) / (rho_f[i] * c_p_f[i])

    dT_fur_dt_occupied = (
        alpha_fur
        * (
            (T_fur_occupied[0] - 2 * T_fur_occupied[step - 1] + T_b_occupied[step - 1])
            / (0.5**2)
        )
    ) + (alpha_fur / 0.5) * ((T_fur_occupied[0] - T_b_occupied[step - 1]) / (1))

    for i in range(len(l_w)):
        T_w_occupied[i][step] = (
            T_w_occupied[i][step - 1] + time_step * dT_w_dt_occupied[i]
        )
    for i in range(len(l_r)):
        T_r_occupied[i][step] = (
            T_r_occupied[i][step - 1] + time_step * dT_r_dt_occupied[i]
        )
    for i in range(len(l_f)):
        T_f_occupied[i][step] = (
            T_f_occupied[i][step - 1] + time_step * dT_f_dt_occupied[i]
        )
    T_fur_occupied[step] = T_fur_occupied[step - 1] + time_step * dT_fur_dt_occupied

def dydt(y0, time, T_outside):
    for i in range(1, num_steps):
        deltaRhoB = (V_in * rho_in - V_out * rho_b_occupied) / V_b

        firstPart[i] = (
            V_in * rho_in * h_in
            - V_out * rho_b_occupied * h_out
            + dQ_dt_supply[i]
            - dQ_dt_loss_occupied
        ) / (V_b * rho_b_unoccupied * (c_p_b - (R / M_b))) - (
            y0 / rho_b_occupied
        ) * deltaRhoB
    return firstPart[i]

K = 273.15
y0 = 15 + K
tolerance = 1e-5

sol = odeint(dydt, y0, time, args=(T_outside,), rtol=tolerance, atol=tolerance)

plt.figure(figsize=(12, 6))
plt.plot(time, T_b_occupied, label="T building occupied")

for i in range(len(l_w)):
    plt.plot(time, T_w_occupied[i], label=f"Wall Layer {i+1} occupied")
for i in range(len(l_r)):
    plt.plot(time, T_r_occupied[i], label=f"Roof Layer {i+1} occupied")
for i in range(len(l_f)):
    plt.plot(time, T_f_occupied[i], label=f"Floor Layer {i+1} occupied")
plt.plot(time, T_fur_occupied, label="Furniture occupied")
plt.xlabel("Time (hours)")
plt.ylabel("Temperature (°K)")
plt.title("Temperature Variations of Internal Elements - Occupied")
plt.legend(
    bbox_to_anchor=(1.02, 1), loc="upper left", ncol=1, mode="expand", borderaxespad=0.0
)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()


import cv2
import numpy as np
import os
import json
import random
import configparser
import boto3
import shutil
import io

config = configparser.ConfigParser()
config.read('config.ini')

# Read image
positivedir = 'data/frames/positive'
boundaries = [
    'AllMaterial',
    'Wood',
    'Brick',
    'Metal',
    'Weapons Slots',
    'Weapons',
    'HealthShield',
    'Health',
    'Shield',
    'GameStatus',
    'StormClock',
    'PlayersLeft',
    'StormCount',
    'Chat',
    'TeamStats',
    'TeammateHealth',
    'Streamer'
]

multipleSelects = [
    'Weapons',
    'TeammateHealth',
]
if not os.path.exists('data/assets'):
    os.makedirs('data/assets')

assetBoundaries = {}

newFileFound = False
s3client = boto3.client('s3',
                        aws_access_key_id=config['S3_BUCKET']['accesskey'],
                        aws_secret_access_key=config['S3_BUCKET']['accesssecret'],)
positivesList = s3client.get_object(
    Bucket=config['S3_BUCKET']['bucket'], Key='positives.json')
positiveImages = s3client.list_objects(
    Bucket=config['S3_BUCKET']['bucket'], Prefix='frames/positive')
positives = json.load(positivesList['Body'])
while not newFileFound:
    fileIndex = random.randint(0, len(positiveImages['Contents']) - 1)
    filename = os.path.basename(positiveImages['Contents'][fileIndex]['Key'])
    if not filename in positives:
        fileKey = positiveImages['Contents'][fileIndex]['Key']
        newFileFound = True
temppath = os.path.join(config['DIRECTORY']['temp'],
                        'crop')
if not os.path.exists(temppath):
    os.makedirs(temppath)
i = 0
tempfilename = os.path.join(temppath, filename)
s3client.download_file(config['S3_BUCKET']['bucket'], fileKey, tempfilename)

frameWidth = 600
im = cv2.imread(tempfilename)
width, height = im.shape[:2]
# imgScale = frameWidth/width
# newX,newY = im.shape[1]*imgScale, im.shape[0]*imgScale
# resized = cv2.resize(im,(int(newX),int(newY)))

removeImg = False
bail = False

for asset in boundaries:
    mulitpleBounds = []
    # # Select ROI
    font = cv2.FONT_HERSHEY_SIMPLEX
    if removeImg == True or bail == True:
        break
    newimg = im.copy()
    while True:
        cv2.putText(newimg, f'Select {asset}', (int(width/2), 130), font,
                    .8, (200, 255, 155), 2, cv2.LINE_AA)
        cv2.putText(newimg, f'Press enter then d to delete this frame as a positive', (int(width/2), 160), font,
                    .8, (20, 95, 70), 2, cv2.LINE_AA)
        r = cv2.selectROI("Image", newimg)

        if not (asset == 'Weapons' or asset == 'TeammateHealth') or r[2] == 0:
            if r[2] == 0:
                nextCommand = cv2.waitKey()
                if nextCommand == 100:
                    removeImg = True
                if nextCommand == 113:
                    bail = True
            break
        else:
            mulitpleBounds.append(r)
    if r[2] > 0:
        if (asset == 'Weapons' or asset == 'TeammateHealth'):
            assetBoundaries[asset] = mulitpleBounds
        else:
            assetBoundaries[asset] = r

if removeImg == True:
    s3client.delete_object(Bucket=config['S3_BUCKET']['bucket'], Key=fileKey)
    print(f'deleted file {filename}')
elif not bail:
    assetBoundaries['CroppedWidth'] = frameWidth
    positives[os.path.splitext(filename)[0]] = assetBoundaries
    p = json.dumps(positives)
    s3client.put_object(
        Bucket=config['S3_BUCKET']['bucket'], Key='positives.json', Body=p)

shutil.rmtree(temppath)


import mysql.connector
from dotenv import load_dotenv
import config
from geopy import distance
load_dotenv()

def cursor_func(sql_komento):
    connection = mysql.connector.connect(
        host='127.0.0.1',
        port=3306,
        database='flight_game',
        user='root',
        password="",
        autocommit=True
    )
    cursor = connection.cursor()
    cursor.execute(sql_komento)
    result = cursor.fetchall()
    return result

class Airport:
    # lisätty data, jottei tartte jokaista lentokenttää hakea erikseen
    def __init__(self, ident, active=False, data=None):
        self.ident = ident
        self.name = data['name']
        self.latitude = float(data['latitude'])
        self.longitude = float(data['longitude'])
        sql = "SELECT  latitude_deg, longitude_deg FROM Airport WHERE ident='" + ident + "'"
        print(sql)
        cur = config.conn.cursor()
        cur.execute(sql)
        res = cur.fetchall()

    def find_nearby_airports(self):
        lista = []
        # haetaan kaikki tiedot kerralla
        sql = "SELECT ident, name, latitude_deg, longitude_deg FROM Airport WHERE latitude_deg BETWEEN "
        sql += str(self.latitude - config.max_lat_dist) + " AND " + str(self.latitude + config.max_lat_dist)
        sql += " AND longitude_deg BETWEEN "
        sql += str(self.longitude - config.max_lon_dist) + " AND " + str(self.longitude + config.max_lon_dist)
        print(sql)
        cur = config.conn.cursor()
        cur.execute(sql)
        res = cur.fetchall()
        for r in res:
            if r[0] != self.ident:
                # lisätty data, jottei jokaista kenttää tartte hakea
                # uudestaan konstruktorissa
                data = {'name': r[1], 'latitude': r[2], 'longitude': r[3]}
                print(data)
                nearby_apt = Airport(r[0], False, data)
                nearby_apt.distance = self.distanceTo(nearby_apt)
                if nearby_apt.distance <= config.max_distance:
                    lista.append(nearby_apt)
                    nearby_apt.co2_consumption = self.co2_consumption(nearby_apt.distance)
        return lista

    def distanceTo(self, target):
        coords_1 = (self.latitude, self.longitude)
        coords_2 = (target.latitude, target.longitude)
        dist = distance.distance(coords_1, coords_2).km
        consumption = self.co2_consumption(dist)
        return int(consumption)

    def co2_consumption(self, km):
        consumption = km / (1.69 * 3)
        return consumption


import json

def main():
    with open('demographics.json') as demographics_data:
        counties = json.load(demographics_data)
    print(alphabetically_first_county(counties))
    print(county_most_under_18(counties))
    print(percent_most_under_18(counties))
    print(most_under_18(counties))
    print(state_with_most_counties(counties))

def alphabetically_first_county(counties):
    """Return the county with the name that comes first alphabetically."""
    first = counties[0]["County"]
    for c in counties:
        if c["County"] < first:
            first = c["County"]
    return first

def county_most_under_18(counties):
    """Return the name and state of a county ("<county name>, <state>") with the highest percent of under 18 year olds."""
    highest=0
    county = ""
    for c in counties:
        if c["Age"]["Percent Under 18 Years"] > highest:
            highest = c["Age"]["Percent Under 18 Years"]
            county = c["County"] + ", " + c["State"]
    return county

def percent_most_under_18(counties):
    """Return the highest percent of under 18 year olds."""
    highest=0
    for c in counties:
        if c["Age"]["Percent Under 18 Years"] > highest:
            highest = c["Age"]["Percent Under 18 Years"]
    return highest

def most_under_18(counties):
    """Return a list with the name and state of a county ("<county name>, <state>") and the percent of under 18 year olds for a county with the highest percent of under 18 year olds."""
    result = ["", 0]
    for c in counties:
        if c["Age"]["Percent Under 18 Years"] > result[1]:
            result[1] = c["Age"]["Percent Under 18 Years"]
            result[0] = c["County"] + ", " + c["State"]
    return result

def state_with_most_counties(counties):
    """Return a state that has the most counties."""
    #Make a dictionary that has a key for each state and the values keep track of the number of counties in each state
    states={}
    for c in counties:
        if c["State"] in states:
            states[c["State"]] += 1
        else:
            states[c["State"]] = 1
    #Find the state in the dictionary with the most counties
    highest = 0
    state = ""
    for s in states:
        if states[s] > highest:
            highest = states[s]
            state = s
    #Return the state with the most counties
    return state

def your_interesting_demographic_function(counties):
    """Compute and return an interesting fact using the demographic data about the counties in the US."""

if __name__ == '__main__':
    main()


import socket
import cv2
import numpy
from multiprocessing import Process
from threading import Thread

class Server:
    def __init__(self):
        # 接收数据量大小
        self.BUFFER_SIZE = 1024
        # 静态socket，用于监听后续发送视频数据的端口
        self.static_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 0.0.0.0代表监听局域网下所有IPV4地址的连接
        self.host = '0.0.0.0'
        # 静态端口，用于接收后续端口
        self.static_port = 6400
        # 绑定静态socket
        self.static_socket.bind((self.host, self.static_port))
        # 设置监听数
        self.static_socket.listen(1)
        self.port = None
        self.port_list = []

    def StaticHandle(self):
        while True:
            # 等待连接
            client_socket, client_address = self.static_socket.accept()
            # 连接成功后接收后续用于传输数据的端口
            self.ReceivePort(client_socket)

    def handle(self):
        # 建立新的套接字
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 与后续传输视频的端口绑定
        server_socket.bind((self.host, int(self.port)))
        server_socket.listen(1)
        client_socket, client_address = server_socket.accept()
        self.ReceiveVideo(client_socket, self.port)
        server_socket.close()

    def ReceivePort(self, client_socket):
        # 接收后续传输数据的端口耨
        receive_port = client_socket.recv(self.BUFFER_SIZE)
        self.port = receive_port.decode("utf-8")
        self.port_list.append(self.port)

        # 将接收到的信息发送回客户端进行确认
        return_data = "confirm"
        client_socket.send(return_data.encode('utf-8'))
        handle_thread = Thread(target=self.handle)
        handle_thread.start()
        # self.handle()

    def ReceiveVideo(self, client_socket, name):
        def Receive(sock, count):
            buf = b''
            while count:
                new_buf = sock.recv(count)
                if not new_buf:
                    return None
                buf += new_buf
                count -= len(new_buf)
            return buf

        while True:
            # 首先接收客户端发送的数据长度，16代表接收长度
            try:
                length = Receive(client_socket, 16)
            except socket.error:
                break
            # 若客户端没有向服务端发送数据长度，停止接收
            if length is None:
                self.port_list.remove(name)
                break
            # 接收字符串格式数据
            stringData = Receive(client_socket, int(length))
            # 将字符串格式数据转换为numpy矩阵格式数据
            data = numpy.frombuffer(stringData, numpy.uint8)
            # 对numpy矩阵格式数据进行解码得到图片
            decode_img = cv2.imdecode(data, cv2.IMREAD_COLOR)
            # 使用opencv显示图像，在此处进行修改
            cv2.imshow(f'{name}', decode_img)
            k = cv2.waitKey(30) & 0xff
            if k == 27:
                break
        cv2.destroyAllWindows()

if __name__ == '__main__':
    server = Server()
    t = Thread(target=server.StaticHandle)
    t.start()


## Logistic Regression Model - HOMEMADE
import theano.tensor as T
from pylearn2.costs.cost import Cost, DefaultDataSpecsMixin
from pylearn2.models.model import Model
from pylearn2.utils import sharedX
from pylearn2.space import VectorSpace
import numpy as np

## The order of DefaultDataSpecsMixin and Cost matters!
class LogisticRegressionCost(DefaultDataSpecsMixin, Cost):
    supervised = True ## specify supervised learning costs

    ## need model to map input to output, need data to test with target
    def expr(self, model, data, **kwargs):
        space, source = self.get_data_specs(model) ## model's data specification
        space.validate(data) ## use model's vector space to validate data

        ## All X, y, yhat are theano variables
        X, y = data ## since it is supervised cost, we got both
        yhat = model.logistic_regression(X) ## call model to map X to yhat
        loss = -(y * T.log(yhat)).sum(axis = 1) ## rowwise selection
        return loss.mean() ## take the mean

class LogisticRegression(Model):
    def __init__(self, nvis, nclasses):
        super(LogisticRegression, self).__init__() ## call superclass Model constructure

        self.nvis = nvis ## standard name for ninputs
        self.nclasses = nclasses ## standard name for noutputs

        ## all model parameters are shared variable in Theano
        ## they usually come with an initialization and a name
        W_value = np.random.uniform(size = (self.nvis, self.nclasses))
        self.W = sharedX(W_value, "W")
        b_value = np.zeros(self.nclasses)
        self.b = sharedX(b_value, "b")
        ## all model parameters should be recorded in self._params
        ## for gradient calculation and house-keeping
        self._params = [self.W, self.b]

        ## construct the data specification
        self.input_space = VectorSpace(dim = self.nvis)
        self.output_space = VectorSpace(dim = self.nclasses)

    def logistic_regression(self, X):
        return T.nnet.softmax(T.dot(X, self.W) + self.b)


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Perform performance testing of aba-web
"""
from os import listdir, getpid
from os.path import isfile, join, splitext
import logging
from aba.aba_parser import ABA_Parser
from aba.aba_perf_logger import ABA_Perf_Logger

## Safety measure so that the process won't overshoot my RAM limit
import sys
if sys.platform == "win32":
    import perf_memory_limiter
    five_gb = 5 * 1024 * 1024 * 1024
    perf_memory_limiter.set_limit(getpid(), five_gb)

logging.basicConfig(filename=join('logs', 'PerfTests.log'),level=logging.INFO,format='[%(asctime)s] %(levelname)s:%(name)s: %(message)s',datefmt='%Y-%m-%d %H:%M:%S') # Note: making debug level DEBUG will slow down the process A LOT due to disk I/O

logging.info("Start performance test")
global_perf_logger = ABA_Perf_Logger("Overall performance test")
global_perf_logger.start()

runonly = []
with open("perf_test_runonly.txt", "r") as f:
    runonly = f.readlines()
runonly = [x.strip() for x in runonly]

path = "perf_test_data"
test_files = [f for f in listdir(path) if splitext(f)[0] in runonly and isfile(join(path, f)) and splitext(f)[1] == ".txt"]

for file in test_files:
    with open(join(path, file), 'r') as f:
        source_code = f.read()
        logging.info("Start running %s", file)
        perf_logger = ABA_Perf_Logger("%s" % file)
        perf_logger.start()

        parser = ABA_Parser(source_code)
        parse_errors = parser.parse()

        if len(parse_errors) > 0:
            logging.info("Parse error: %s", ', '.join(parse_errors))
        else:
            try:
                parser.construct_aba()
            except MemoryError:
                logging.error("Out of memory!")
            except Exception as exp: # "trick" to continue to next test even when exception occurs during runtime
                logging.error("Runtime error: %s", str(exp))
            except BaseException as exp: # catch those that can't be caught
                logging.error("Unexpected error: %s", str(exp))

        perf_logger.end()

global_perf_logger.end()


import numpy as np
from mss import mss

def capture_screenshot_as_numpy():
    with mss() as sct:
        # Define the region for capturing screenshot. Adjust the left and top accordingly.
        monitor = {"top": 0, "left": 0, "width": 500, "height": 500}

        # Capture screenshot
        screenshot = sct.grab(monitor)

        # Convert the screenshot's raw bytes to a numpy array
        np_screenshot = np.array(screenshot)

        return np_screenshot

# Capture the screenshot and save as numpy array
np_image = capture_screenshot_as_numpy()

print(np_image)  # This


# -*- coding: utf-8 -*-
import scrapy

class KotaindustriSpider(scrapy.Spider):
    name = 'kotaindustri'
    allowed_domains = ['www.kotaindustri.co.id']
    start_urls = ['https://www.kotaindustri.co.id/all-categories/']

    def parse(self, response):
        for node in response.css('#directorist a'):
            node_url = node.css('a::attr(href)').get().strip()
            yield response.follow(node_url, callback=self.parse_category)

    def parse_category(self, response):
        for node in response.css('.atbdp_column .atbd_listing_title > a'):
            node_url = node.css('a::attr(href)').get().strip()
            yield response.follow(node_url, callback=self.parse_detail)

    def parse_detail(self, response):
        contact = response.css('.atbd_contact_information_module')
        if contact is None:
            return
        category = response.css('.directory_tag span a::text').get() or ''
        name = response.css('h1::text').get() or ''
        address = ''
        city = ''
        phone = ''
        email = ''
        website = ''
        description = []
        url = response.url or ''

        # description
        for txt in response.css('.about_detail p::text'):
            description.append(txt.get().strip())
        description = '. '.join(description)
        description = description.replace('..', '.')
        description = description.replace('. . ', '. ')

        # table information
        for tr in response.css('.atbd_contact_info > ul > li'):
            k = tr.css('.atbd_info_title::text').get()
            v = tr.css('.atbd_info::text').get()
            if k is None or len(k) == 0:
                continue
            elif 'Alamat' in k:
                address = v
            elif 'Telepon' in k:
                phone = tr.css('.atbd_info a::text').get()
            elif 'Email' in k:
                email = tr.css('.atbd_info a::text').get()
            elif 'Website' in k:
                website = v

        if len(email) == 0:
            self.logger.info('{} : EMPTY EMAIL'.format(url))
        if len(phone) == 0:
            self.logger.info('{} : EMPTY PHONE'.format(url))

        if len(email) > 0 and len(phone) > 0:
            yield {
                'category': category.strip(),
                'name': name.strip(),
                'address': address.strip(),
                'city': city.strip(),
                'phone': phone.strip(),
                'email': email.strip(),
                'website': website.strip(),
                'description': description.strip(),
                'url': url.strip(),
            }


from django.contrib import admin

# Register your models here.

from .models import Apps, Purchases

class PurchasesInline(admin.TabularInline):
    model = Purchases
    extra = 1

class AppsAdmin(admin.ModelAdmin):
    fields = ['app_name', 'app_description', 'app_price']
    list_display = ('app_name', 'app_description', 'app_price')

    inlines = [PurchasesInline]

    class Meta:
        verbose_name_plural = "Apps"

admin.site.register(Apps, AppsAdmin)


import pymysql
import schedule
import time

estacion=1

class DataBase:
    def __init__(self):
        self.connection = pymysql.connect(
            host='localhost',
            user='root',
            password='',
            db='proyecto_grado'
        )

        self.cursor = self.connection.cursor()

        print("Conexión establecida exitosamente")

    def select_user(self, id):
        sql = 'SELECT * FROM usuarios WHERE id={}'.format(id)

        try:
            self.cursor.execute(sql)
            user = self.cursor.fetchone()
            print("Id: ", user[0])
            print("Nombre: ", user[1])
            print("Apellidos: ", user[2])

        except Exception as e:
            raise

    def insert_humedadrelativa(self):
        datos = 'datos.txt'
        with open(datos) as f_obj:
            lines = f_obj.readlines()

        sql = "INSERT INTO humedad_relativa (estacion, valor) VALUES ('{}', '{}')".format(estacion, lines[0])
        sql2 = "INSERT INTO temperatura (estacion, valor) VALUES ('{}', '{}')".format(estacion, lines[1])
        sql3 = "INSERT INTO presion_atmosferica (estacion, valor) VALUES ('{}', '{}')".format(estacion, lines[2])
        sql4 = "INSERT INTO pmtwo (estacion, valor) VALUES ('{}', '{}')".format(estacion, lines[3])
        sql5 = "INSERT INTO pmten (estacion, valor) VALUES ('{}', '{}')".format(estacion, lines[4])

        try:
            self.cursor.execute(sql)
            self.cursor.execute(sql2)
            self.cursor.execute(sql3)
            self.cursor.execute(sql4)
            self.cursor.execute(sql5)
            self.connection.commit()

            print("Insercción de datos exitosa! ")
        except Exception as e:
            raise

def calldb():
    database = DataBase()
    database.insert_humedadrelativa()

schedule.every(10).seconds.do(calldb)

while 1:
    schedule.run_pending()
    time.sleep


from file_class import File
import datetime

class TextFile(File):

    def __init__(self, name: str, file_type: str, size: str, description: str, content: str):
        super().__init__(name, file_type, size, description, content)
        self.num_of_characters = len(self.content)

    def write(self, new_content):
        self.content = new_content
        self.num_of_characters = len(new_content)
        self.date = datetime.datetime.now().date()
        self.time = datetime.datetime.now().time()


#encoding=utf-8

import argparse
import pkuseg
import pprint

import sys
import os
# 确保在命令行下执行，不出现ModuleNotFoundError: No module named ERROR
sys.path.append(os.getcwd())    # 在命令行中，把当前路径加入到sys.path中
print(sys.path)
from openpyxl import load_workbook

def get_label_maps(path):
    wb = load_workbook(path)
    sheet_names = wb.get_sheet_names()
    ws = wb.get_sheet_by_name(sheet_names[0])

    id2name = {}        # 标签Id 到 标签名字  字典表
    id_tree = {}        # 标签树结构

    # 把数据存到字典中
    last_id = 0
    for rx in range(1, ws.max_row + 1):
        w1 = ws.cell(row=rx, column=1).value
        w2 = ws.cell(row=rx, column=2).value
        w3 = ws.cell(row=rx, column=3).value
        w4 = ws.cell(row=rx, column=4).value
        if w1 == "标签ID":
            continue
        if w1 is not None:
            id2name[w1] = w2
            id_tree[w1] = []
            last_id = w1
        if w3 is not None:
            id2name[w3] = w4

        id_tree[last_id].append(w3)

    print("label2name dict:")
    print(id2name)
    print(id_tree)
    return id2name, id_tree

dict_file = 'data/my_dict.txt'

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.register("type", "bool", lambda v: v.lower() == "true")
    parser.add_argument(
        "--is_debug",
        type=lambda x: (str(x).lower() == 'true'),
        default=True,
        help="use debug mode")

    FLAGS, unparsed = parser.parse_known_args()
    pp = pprint.PrettyPrinter().pprint
    pp("FLAGS: " + str(FLAGS))
    pp("unparsed: " + str(unparsed))
    print(FLAGS.is_debug)

    finnal_context = []

    num = 0
    # raw_tribe_data.txt文件在160上，太大
    input_file = "data/test.txt" if FLAGS.is_debug else "data/raw_tribe_data.txt"
    with open(input_file, "r", encoding='utf-8') as f:
        for line in f:
            sp = line.split("\t")
            label = sp[0].replace("__label__", "")
            if label is not None and label != "" and label.isdigit() and int(label) > 800 and int(label) <= 1000:
                context = []
                for i in sp:
                    if i.startswith("__label__"):
                        continue
                    if i.startswith("__infoid__") or i.startswith("__tribeid__") or i.startswith("__topic__"):
                        break
                    without_answer = " ".join(i.split("\t")[0:2])
                    context.append(without_answer)

                num += 1
                if num % 100 == 0:
                    print("processing {} lines".format(num))

                context_str = " ".join(context)
                finnal_context.append((label, context_str))

    print("valid file lines total num: {}".format(len(finnal_context)))

    id2name, id_tree = get_label_maps("data/new_labels.xlsx")

    import pandas as pd
    df = pd.DataFrame(finnal_context, columns=["label", "context"])
    print("-" * 20)
    print(df.sample(5))

    df["label"] = df["label"].apply(lambda x: id2name[int(x)])

    print("-" * 10 + "label -> num" + "-" * 10)
    for label_df in df.groupby("label"):
        print("label: {} nums: {}".format(label_df[0], len(label_df[1])))
    print("-" * 20)

    input_file = 'input.txt'
    output_file = 'output.txt'
    final_file = 'old_finnal_data.txt'

    df.to_csv(input_file, sep=" ", index=False, header=False, quotechar=" ")

    print("seg txt start:")
    pkuseg.test(input_file, output_file, user_dict=dict_file, nthread=20)
    print("seg txt stop")
    print("-" * 20)

    with open(final_file, 'w') as out_f:
        with open(output_file, 'r') as input_f:
            for line in input_f:
                sp = line.split(" ", 1)
                if len(sp) >= 2:
                    out_f.write("__label__" + sp[0] + "\t" + sp[1] + "\n")

    print("final file:{}".format(final_file))


from django import template
from google.appengine.api import images

register = template.Library()

@register.simple_tag
def get_resized_image(image, size):
	blob_key = str(image.blobstore_info.key())
	thumbnail_picture_url = images.get_serving_url(blob_key, size)
	return thumbnail_picture_url


import cv2
import numpy as np
import joblib

# 最开始计算轮廓会出现异常现象，会出现count =1 的错误
def count_conts(frame, contours, area ):
    count = 0
    for contour in contours:
        if cv2.contourArea(contour) < area:
            continue
        count += 1
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
    return count

""" 获取轮廓面积大于预定值的轮廓，用于追踪目标"""
def get_contours(contours,area):
    conts = []
    for contour in contours:
        if cv2.contourArea(contour) < area:
            continue
        conts.append(contour)
    return conts

# def get_area_center(points):
#
#     return (x,y)

"""
    计算区域中心，左中右进行排序
"""
def get_center(pts):
    x = 0
    y = 0

    for i in range(len(pts)):
        x += pts[i][0]
        y += pts[i][1]
    x /= len(pts)
    y /= len(pts)
    x_left = (pts[0][0]+pts[1][0])/2
    y_left = (pts[0][1]+pts[1][1])/2
    x_right = (pts[2][0] + pts[3][0]) / 2
    y_right = (pts[2][1] + pts[3][1]) / 2

    return (int(x),int(y)),(int(x_left),int(y_left)),(int(x_right),int(y_right))

"""
    异常分类：
        单目标异常：
            异常一：穿过区域,代码表示，3s内穿过中心点
            异常二：在异常区停留3s，代码表示3s内未穿过中心点
        todo：多目标异常
"""
if __name__ == '__main__':
    cap = cv2.VideoCapture(1)

    """
        获取手工标记的roi区域
    """
    fgbg = cv2.createBackgroundSubtractorMOG2()
    Roi = joblib.load("config1.pkl")
    pts = Roi.get('ROI1')
    points = np.array(pts, np.int32)
    points = points.reshape((-1, 1, 2))

    """
        获取手工标记的异常区域
    """
    Roi_error = joblib.load("config2.pkl")
    pts_error = Roi_error.get('ROI2')
    points_error = np.array(pts_error, np.int32)
    points_error = points_error.reshape((-1, 1, 2))

    """
        获取异常区域中
    """
    center_point,left_point,right_point = get_center(pts_error)

    print(center_point, left_point, right_point)

    """
        time_count: 解决第一次获取轮廓会获取最外层轮廓的异常现象
    """
    time_count = 0

    """
        用于判断异常类型
    """
    frequnence = cv2.getTickFrequency()
    start_time = 0
    flag = 0  # 用于计时，需要保证前后两人进入监控区的时间误差为1s
    error_time_first = 0  # 用于第一次异常判断，判断属于一个物体异常还是两个物体异常
    flag_error_first = 0
    flag_error_second = 0 #用于第二次异常判断
    error_type = 0 # 用于判断异常类型

    while (cap.isOpened):
        success, frame = cap.read()
        if success:
            """ 标记roi区域，为避免影响roi区域以外的区域不进行训练"""
            mask = np.zeros(frame.shape, np.uint8)
            # mask = cv2.polylines(mask, [points], True, (255, 255, 255), 2)
            mask2 = cv2.fillPoly(mask.copy(), [points], (255, 255, 255))  # 用于求 ROI
            mask3 = cv2.fillPoly(mask.copy(), [points], (0, 255, 0))  # 用于 显示在桌面的图像
            # show_image = cv2.addWeighted(src1=frame, alpha=0.8, src2=mask3, beta=0.2, gamma=0)
            ROI = cv2.bitwise_and(mask2, frame)  #  获取roi区域掩模
            # cv2.imshow("roi",ROI)
            fgmask_roi = fgbg.apply(ROI)  #  背景减除算法应用
            ret, fgmask_roi = cv2.threshold(fgmask_roi, 254, 255, cv2.THRESH_BINARY) #  获取无阴影的图片
            # kernel = np.ones((3,1),np.uint8)
            # fgmask_roi = cv2.erode(fgmask_roi,kernel) #  腐蚀算法
            frame = cv2.polylines(frame, [points], True, (255, 0, 0), 2)  # 标定监控区域
            frame = cv2.polylines(frame, [points_error], True, (0, 255, 0), 2)
            frame = cv2.circle(frame, center_point, 3, (0, 0, 255), -1)
            frame = cv2.circle(frame, left_point, 3, (0, 0, 255), -1)
            frame = cv2.circle(frame, right_point, 3, (0, 0, 255), -1)

            contours, _ = cv2.findContours(fgmask_roi, cv2.RETR_EXTERNAL,
                                                   cv2.CHAIN_APPROX_SIMPLE)
            """
                直接跳过第一帧的画面从第二帧开始算起
            """
            if time_count == 0:
                time_count += 1
                continue
            count = count_conts(frame,contours,7000)

            """ 当检测区域中出现第一个异常开始计时判断异常"""
            if count == 1 and flag == 0 :
                start_time = cv2.getTickCount()
                error_time_first = start_time
                flag = 1
                # print(start_time)

            """ 保证err_time_first在start_time计时之后开始计时"""
            if flag == 1:
                error_time_first = cv2.getTickCount()
                if (error_time_first-start_time)/frequnence > 0.7 and flag_error_first == 0:
                    if count == 1:
                        print("属于第一大类异常")
                        flag_error_first = 1
                    else:
                        print("属于第二大类异常")
                        flag_error_first = 2
                    flag =2

            """若异常为第一大异常"""
            if flag_error_first == 1:
                # print("判断第一大类异常")
                conts = get_contours(contours,7000)
                # print(conts[0])
                if conts:   # 如果轮廓不为空

                    dist = cv2.pointPolygonTest(conts[0],center_point,False)
                    # print(dist)
                    if dist == 1.0 and flag_error_second == 0:
                        start_time = cv2.getTickCount()
                        # print("error1 starttime= ", start_time)
                        error_time_first = start_time
                        flag_error_second = 1
                    if flag_error_second == 1:

                        dist1 = cv2.pointPolygonTest(conts[0], left_point, False)
                        error_time_first = cv2.getTickCount()
                        if dist1 == 1.0 and dist == -1:
                            print("发生异常1")
                            error_type = 1
                            flag_error_first = 3

                        elif (error_time_first-start_time)/frequnence > 1:

                            dist2 = cv2.pointPolygonTest(conts[0],right_point,False)
                            # if dist == -1:
                            #     print("发生异常1")
                            #     error_type =1
                            #
                            # else:
                            #     error_type = 2
                            #     print("发生异常2")

                            if dist2 == 1:
                                print("发生异常3")
                                error_type = 3
                                flag_error_first = 3
                            elif (error_time_first-start_time)/frequnence > 3:
                                print("发生异常2")
                                error_type = 2
                                flag_error_first = 3

            elif flag_error_first==2:
                """若异常为第二大类异常"""
                # print("判断第一大类异常")
                conts = get_contours(contours, 7000)
                # print(conts[0])
                if conts:
                    dist = cv2.pointPolygonTest(conts[0], center_point, False)

                    if dist == 1 and flag_error_second==0:
                        start_time = cv2.getTickCount()
                        error_time_first = start_time
                        flag_error_second = 1
                    if flag_error_second == 1:
                        error_time_first = cv2.getTickCount()
                        if (error_time_first-start_time)/frequnence > 2:
                            if len(conts)>1:
                                print("发生异常4")
                                error_type =4

                            else:
                                error_type = 5
                                print("发生异常5")
                            flag_error_first = 3
                    # print("判断第二大类异常")

            if error_type == 1:
                frame = cv2.putText(frame, 'Error Happening, Error Type: 1', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2,
                                    (0, 0, 255), 2)
            elif error_type ==2:
                frame = cv2.putText(frame, 'Error Happening, Error Type: 2', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2,
                                    (0, 0, 255), 2)
            elif error_type == 3:
                frame = cv2.putText(frame, 'Error Happening, Error Type: 3', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2,
                                    (0, 0, 255), 2)
            elif error_type == 4:
                frame = cv2.putText(frame, 'Error Happening, Error Type: 4', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2,
                                    (0, 0, 255), 2)
            elif error_type == 5:
                frame = cv2.putText(frame, 'Error Happening, Error Type: 5', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2,
                                    (0, 0, 255), 2)

            cv2.namedWindow("src",cv2.WINDOW_NORMAL)
            cv2.resizeWindow("src",800,600)
            cv2.imshow("src", frame)
            cv2.namedWindow("mask", cv2.WINDOW_KEEPRATIO)
            cv2.resizeWindow("mask", 800, 600)
            cv2.imshow("mask", fgmask_roi)
            key = cv2.waitKey(1) & 0xFF
            '''重置'''
            if key == ord('r'):
                print("重置实验")
                start_time = 0
                flag = 0  # 用于计时，需要保证前后两人进入监控区的时间误差为1s
                error_time_first = 0  # 用于第一次异常判断，判断属于一个物体异常还是两个物体异常
                flag_error_first = 0
                flag_error_second = 0  # 用于第二次异常判断
                error_type = 0  # 用于判断异常类型

            if key == ord('q'):
                break
        else:
            break
cap.release()
cv2.destroyAllWindows()


import logging
import time
import RPi.GPIO as GPIO
from servo import *
from Motor import *
from PCA9685 import PCA9685
from redis import Redis
import cv2
import json

logging.basicConfig(level=logging.DEBUG, filename= './logs/raspberry_car.log', filemode = 'a',format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

cli = Redis('localhost')
CONTROL_CYCLE = 0.02 # Control cycle is every 20ms.
SERVO_ORIZON = 95
SERVO_VERTIC = 95
DEFAULT_PATH = '/home/pi/'

# Controller
# Request the sensor data from Redis every 20ms and control the motors, servos, camera to react:
#          - Realtime Sensor data
#          - AWS Cloud events

class Controller:
    def __init__(self):
        # Callibrate the Servo
        self.pwm_S=Servo()
        self.pwm_S.setServoPwm('0',SERVO_ORIZON)
        self.pwm_S.setServoPwm('1',SERVO_VERTIC)

        self.PWM = Motor()

    def navigate(self, infrared_LMR):
        logger.debug("Func_navigate: infrared_LMR =%d"%infrared_LMR)
        if infrared_LMR==2:
            logger.debug("Func_navigate: LMR=2")
            self.PWM.setMotorModel(800,800,800,800) #Forward
        if infrared_LMR==0:
            logger.debug("Func_navigate: LMR=0")
            self.PWM.setMotorModel(500,500,500,500) #Slow Forward
        elif infrared_LMR==4:
            logger.debug("Func_navigate: LMR=4")
            self.PWM.setMotorModel(-1500,-1500,2500,2500) #Left
        elif infrared_LMR==6:
            logger.debug("Func_navigate: LMR=6")
            self.PWM.setMotorModel(-2000,-2000,4000,4000) #Left ++
        elif infrared_LMR==1:
            logger.debug("Func_navigate: LMR=1")
            self.PWM.setMotorModel(2500,2500,-1500,-1500) #Right
        elif infrared_LMR==3:
            logger.debug("Func_navigate: LMR=3")
            self.PWM.setMotorModel(4000,4000,-2000,-2000) #Right ++
        elif infrared_LMR==7:
            logger.debug("Func_navigate: LMR=7")
            pass

    def save_image(self,img_pos):
        video_capture = cv2.VideoCapture(0)
        # Check success
        if not video_capture.isOpened():
            logger.debug("Func_Save_img: Could not open video device")
            raise Exception("Could not open video device")
            # Read picture. ret === True on success
        ret, frame = video_capture.read()
        video_capture.release()
        if ret and frame is not None:
            detection_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            img_local_path = DEFAULT_PATH+"camera_images/img_%s_%s.jpg"%(img_pos, detection_time)
            logger.debug("Func_Save_img: img_local_path: %s"%img_local_path)
            cv2.imwrite(img_local_path, frame)

            rfid_pos = "xe01" # to replace
            img_meta = {'img_local_path':img_local_path,'detection_time': detection_time, 'position':img_pos, 'rfid_pos':rfid_pos}
            img_meta = json.dumps(img_meta)
            logger.debug("Func_Save_img: --> image meta")
            logger.debug(img_meta)
            cli.rpush("car_images", img_meta)

    def obstacle_recognition(self):
        # Functions:
        # - Stop motor
        # - Measure the Left distance and Right distance to know the Object position.
        # - Take a picture of the obstacle and save it at local. -> save_image()

        obstacle_pos = "middle"

        self.PWM.setMotorModel(0,0,0,0)

        self.pwm_S.setServoPwm('0',SERVO_ORIZON-15)
        time.sleep(0.3)
        dist_L = int(cli.get('ultrasonic_M'))

        self.pwm_S.setServoPwm('0',SERVO_ORIZON)
        time.sleep(0.3)

        self.pwm_S.setServoPwm('0',SERVO_ORIZON+15)
        time.sleep(0.3)
        dist_R = int(cli.get('ultrasonic_M'))

        if dist_R < dist_L:
            logger.info("Func_Obstacle: Object on right")
            self.pwm_S.setServoPwm('0',SERVO_ORIZON+15)
            obstacle_pos = "right"
        else:
            logger.info("Func_Obstacle: Object on left")
            self.pwm_S.setServoPwm('0',SERVO_ORIZON-15)
            obstacle_pos = "left"

        self.save_image(obstacle_pos)

    def run(self):
        last_obstacle = 0

        while True:
            time.sleep(CONTROL_CYCLE)
            ultrasonic_M = int(cli.get('ultrasonic_M'))
            infrared_LMR = int(cli.get('infrared_LMR'))
            logger.debug("Func_Run: ultrasonic_M = %d; infrared_LMR = %d"%(ultrasonic_M,infrared_LMR))

            # Basic control modules: Obstacle recognition and Line Tracking.
            if ultrasonic_M<30 and ((time.time()-last_obstacle)>5):
                logger.info("Func_Run: detect new obstacle")
                last_obstacle = time.time()
                self.obstacle_recognition()

            # elif cloud events

            else:
                logger.info("Func_Run: navigate...")
                self.navigate(infrared_LMR)

# Main program logic follows:
controller = Controller()
if __name__ == '__main__':
    print ('Controller is starting ... ')
    try:
        controller.run()
    except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
        controller.pwm_S.setServoPwm('0',SERVO_ORIZON)
        controller.PWM.setMotorModel(0,0,0,0)


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
import re
import os

#run web driver headlessly
os.environ['MOZ_HEADLESS'] = '1'
binary = FirefoxBinary('/usr/bin/firefox')
driver = webdriver.Firefox(firefox_binary=binary)
advanced_csv = 'Rk,Player,Pos,Age,Tm,G,MP,PER,TS%,3PAr,FTr,ORB%,DRB%,TRB%,AST%,STL%,BLK%,TOV%,USG%,,OWS,DWS,WS,WS/48,,OBPM,DBPM,BPM,VORP,Year\n'
per_game_csv = 'Rk,Player,Pos,Age▼,Tm,G,GS,MP,FG,FGA,FG%,3P,3PA,3P%,2P,2PA,2P%,eFG%,FT,FTA,FT%,ORB,DRB,TRB,AST,STL,BLK,TOV,PF,PS/G,Year\n'

#iterate all advanced stats
for year in range(1950,2018):
    driver.get('https://www.basketball-reference.com/leagues/NBA_'+str(year)+'_advanced.html')
    driver.execute_script('document.querySelector("#advanced_stats_toggle_partial_table").click()')
    driver.execute_script('document.querySelector("#all_advanced_stats > div:nth-child(1) > div:nth-child(3) > ul:nth-child(1) > li:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(4) > button:nth-child(1)").click()')
    csv = driver.find_element_by_css_selector("#csv_advanced_stats").text.split('\n',1)[-1]

    #add year to each row, clean up formatting
    csv = csv.replace('\n', ',' + str(year) + '\n')
    csv +=  ',' + str(year) + '\n'
    advanced_csv += csv

#iterate all per_game stats
for year in range(1950,2018):
    driver.get('https://www.basketball-reference.com/leagues/NBA_'+str(year)+'_per_game.html')
    driver.execute_script('document.querySelector("#per_game_stats_toggle_partial_table").click()')
    driver.execute_script('document.querySelector("#all_per_game_stats > div:nth-child(1) > div:nth-child(3) > ul:nth-child(1) > li:nth-child(1) > div:nth-child(2) > ul:nth-child(1) > li:nth-child(4) > button:nth-child(1)").click()')
    csv = driver.find_element_by_css_selector("#csv_per_game_stats").text.split('\n',1)[-1]

    #add year to each row, clean up formatting
    csv = csv.replace('\n', ',' + str(year) + '\n')
    csv +=  ',' + str(year) + '\n'
    per_game_csv += csv

#write to csv
stats = open("advanced_stats.csv", "w")
stats.write(advanced_csv)
stats.close()
stats = open("per_game_stats.csv", "w")
stats.write(per_game_csv)
stats.close()


#!/usr/bin/env python3.10
import argparse
import re
import cairo

def get_args():
    parser = argparse.ArgumentParser(description = "Program to visualize motifs and exons within fasta sequence.")
    parser.add_argument("-f","--fasta", help ="Fasta file to search.", type = str, required = True)
    parser.add_argument("-m","--motif",help = "File containing target motifs.",type = str, required = True)
    return parser.parse_args()
args = get_args()

fasta_file = args.fasta
motif_file = args.motif

class FastaParse:
    def __init__(self, filename):
        self.filename = filename
        self.records = []

    def parse_fasta(self):
        'Parses a fasta file to separate sequence and header lines. Storing them in a list of tuples. Concatenates seq lines into one'
        with open(self.filename) as file:
            record = {'header': '', 'sequence': '', 'exons': []}
            for line in file:
                line = line.strip()
                if line.startswith('>'):
                    if record['header']:
                        self.records.append(record)
                        record = {'header': '', 'sequence': '', 'exons': []}
                    record['header'] = line[1:]
                else:
                    record['sequence'] += line
                    if 'exon' in record['header'].lower():
                        # Extract start and end positions of exon from the header
                        exon_start, exon_end = re.findall(r'\d+', record['header'])
                        # Add exon positions to the list of exons for this record
                        record['exons'].append((int(exon_start), int(exon_end)))
            if record['header']:
                self.records.append(record)
        return self.records

    def header_info(self):
        'Used to extract individual components of fasta headers. Name, start, stop. Can be modified as needed.'
        for record in self.records:
            header = record['header']
            header_info = re.match(r'^(\S+)\s+(\S+):(\d+)-(\d+)', header)
            if header_info:
                name = header_info.group(1)
                start = int(header_info.group(3))
                stop = int(header_info.group(4))

    def find_exons(self):
        'Adds exons to records information , exon is defined by strings of uppercase letters in fasta sequence'
        for record in self.records:
            sequence = record['sequence']
            exons = []
            i = 0
            while i < len(sequence):
                if sequence[i].isupper():
                    start = i
                    while i < len(sequence) and sequence[i].isupper():
                        i += 1
                    end = i
                    exons.append((start, end))
                else:
                    i += 1
            record['exons'] = exons
        return self.records

class Motif:
    def __init__(self, filename):
        self.filename = filename
        self.motifs = []
        self.patterns = []

    def get_motifs(self):
        'Fetches motifs from the motif file, storing in a list, implies that the format is one motif per line in file. '
        with open(self.filename) as f:
            for line in f:
                motif = self.motifs.append(line.strip())
            print(self.motifs)

    def convert_to_regex(self):
        'Converts a list of motifs to their corresponding regex based on nucleic acid notation'
        for motif in self.motifs:
            pattern = ''
            for char in motif:
                #Rules for nucleic acid notation.
                if char in ['a', 'A']:
                    pattern += '[Aa]'
                elif char in ['t', 'T']:
                    pattern += '[Tt]'
                elif char in ['c', 'C']:
                    pattern += '[Cc]'
                elif char in ['g', 'G']:
                    pattern += '[Gg]'
                elif char in ['y', 'Y']:
                    pattern += '[CcTt]'
                elif char in ['r', 'R']:
                    pattern += '[AaGg]'
                elif char in ['w', 'W']:
                    pattern += '[AaTt]'
                elif char in ['s', 'S']:
                    pattern += '[CcGg]'
                elif char in ['k', 'K']:
                    pattern += '[GgTt]'
                elif char in ['m', 'M']:
                    pattern += '[AaCc]'
                elif char in ['d', 'D']:
                    pattern += '[AaGgTt]'
                elif char in ['v', 'V']:
                    pattern += '[AaCcGg]'
                elif char in ['h', 'H']:
                    pattern += '[AaCcTt]'
                elif char in ['n', 'N']:
                    pattern += '[AaCcGgTt]'
                else:
                    pattern += char
            self.patterns.append(pattern)
        print(self.patterns)

    def search_motifs(self, records):
        'Returns a list of tuples for each motif match per record'
        results = []
        for record in records:
            for i, pattern in enumerate(self.patterns):
                matches = re.finditer(pattern, record['sequence'], re.IGNORECASE)
                for match in matches:
                    start = match.start() + 1  # base 1 conversion
                    stop = match.end()
                    #This is the format of the list. Record = header , index is order, start and stop are positions.
                    result = {'record': record, 'pattern_index': i, 'start': start, 'stop': stop}
                    results.append(result)
        return results

class Draw:
    #Define size and spacing for elements, color_map is the colors per motif
    def __init__(self, records, color_map=None):
        self.records = records
        self.width = 800
        self.height = 600
        self.font_size = 16
        self.line_spacing = 20
        self.rect_height = 5
        self.color_map = color_map or []

    def draw_motif_matches(self, results, filename):
        'Takes on positional data for motif and exon matches per record, and draws them to a .png with reference to record lines'
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height)
        ctx = cairo.Context(surface)

        # Sets background to white
        ctx.set_source_rgb(1, 1, 1)
        ctx.paint()

        # Draws record lines
        ctx.set_line_width(2)
        ctx.set_source_rgb(0, 0, 0)
        for i, record in enumerate(self.records):
            y = ((i + 1) * self.height) / (len(self.records) + 2)
            ctx.move_to(0, y)
            ctx.line_to(self.width, y)
            ctx.stroke()

            # Adds header label per record line
            ctx.select_font_face('Arial', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
            ctx.set_font_size(self.font_size)
            text = record['header']
            x_bearing, y_bearing, width, height = ctx.text_extents(text)[:4]
            ctx.move_to((self.width - width) / 2, y - self.font_size - 2)
            ctx.show_text(text)

            # Draw motifs based on color_map
            ctx.save()
            for result in results:
                if result['record'] == record:
                    pattern_index = result['pattern_index']
                    #Currently defaults extra motifs to black
                    color = self.color_map[pattern_index] if pattern_index < len(self.color_map) else (0, 0, 0)
                    ctx.set_source_rgb(*color)
                    x = (result['start'] - 1) * self.width / len(record['sequence'])
                    y = ((i + 1) * self.height) / (len(self.records) + 2) + self.rect_height
                    width = (result['stop'] - result['start'] + 1) * self.width / len(record['sequence'])
                    ctx.rectangle(x, y, width, self.rect_height)
                    ctx.fill()
            ctx.restore()

            # Draw Exons as Orange
            ctx.save()
            ctx.set_source_rgb(1, 0.5, 0)  # Set the color to orange
            for exon_start, exon_stop in record['exons']:
                exon_width = (exon_stop - exon_start) * self.width / len(record['sequence'])
                exon_x = exon_start * self.width / len(record['sequence'])
                exon_y = y - self.line_spacing - self.font_size - self.rect_height + 33
                ctx.rectangle(exon_x, exon_y, exon_width, self.rect_height)
                ctx.fill()

            ctx.restore()

        # Add legend for color map
        legend_x = self.width * 0.8
        legend_y = self.height * 0.8
        legend_width = self.width * 0.15
        legend_height = self.line_spacing * (len(self.color_map) + 1)
        ctx.rectangle(legend_x, legend_y, legend_width, legend_height)
        ctx.set_source_rgb(0, 0, 0)
        ctx.stroke()

        ctx.select_font_face('Arial', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
        ctx.set_font_size(self.font_size)
        for i, color in enumerate(self.color_map):
            y = legend_y + (i + 0.5) * self.line_spacing
            ctx.set_source_rgb(*color)
            ctx.rectangle(legend_x + 5, y - self.rect_height / 2, self.rect_height, self.rect_height)
            ctx.fill()
            ctx.move_to(legend_x + self.rect_height + 10, y)
            #Motif 1...2...3.. etc. refers to their order in the initial motif list.
            ctx.show_text(f"Motif {i+1}")

        # Add exon to the legend
        y = legend_y + (len(self.color_map) + 0.5) * self.line_spacing
        ctx.set_source_rgb(1, 0.5, 0)
        ctx.rectangle(legend_x + 5, y - self.rect_height / 2, self.rect_height, self.rect_height)
        ctx.fill()
        ctx.move_to(legend_x + self.rect_height + 10, y)
        ctx.show_text("Exon")

        surface.write_to_png(filename)

parser = FastaParse(fasta_file)
records = parser.parse_fasta()
parser.header_info()
parser.find_exons()
motif = Motif(motif_file)
motif.get_motifs()
motif.convert_to_regex()

matches = motif.search_motifs(records)

#To add more colors, simply add more pixel values to color_map below
color_map = [(1, 0, 0), (0, 1, 0), (0, 0, 1),(1,0.5,1)]
draw = Draw(records,color_map)

#Outputs drawing based on initial fasta file name
draw.draw_motif_matches(matches, f'{fasta_file}.png')


import logging
import time

from selenium.common.exceptions import ElementNotVisibleException
from selenium.webdriver.common.by import By

from page_objects.base import BaseElement
from page_objects.base import BaseLoadingElement
from page_objects.base import BasePage
from page_objects.base import TextInput

class Page(BasePage):

    def __init__(self, driver):
        super().__init__(driver=driver, desc='Pokedex Page', url='https://www.pokemon.com/us/pokedex/')
        self._locators = dict()
        self._locators['main_nav'] = (By.CSS_SELECTOR, 'nav.main')

        self._locators['execute_search_button'] = (By.CSS_SELECTOR, 'input.button-search')
        self._locators['loading_indicator'] = (By.CSS_SELECTOR, 'div.loader')
        self._locators['no_results'] = (By.CSS_SELECTOR, 'div.no-results')
        self._locators['search_field'] = (By.CSS_SELECTOR, '#searchInput')
        self._locators['search_result'] = (By.CSS_SELECTOR, 'li.animating')
        self._locators['sort_dropdown'] = (By.CSS_SELECTOR, 'section.overflow-visible > div > div > div.custom-select-menu')

        self._locators['load_more_button'] = (By.CSS_SELECTOR, '#loadMore > span')

        self._locators['footer'] = (By.CSS_SELECTOR, 'div.footer-divider')
        return

    # Basic Filters

    def click_execute_search_button(self):
        element = self.driver.find_element(*self._locators['execute_search_button'])
        logging.info("Clicking execute search button.")
        element.click()
        return

    def find_search_field_text_input_object(self):
        element = self.driver.find_element(*self._locators['search_field'])
        return TextInput(element)

    def find_sort_dropdown_object(self):
        element = self.driver.find_element(*self._locators['sort_dropdown'])
        return SortDropdown(element=element)

    # Search Results

    def all_search_results_names_displayed(self):
        results = self.find_search_result_objects()
        return [i.name for i in results]

    def all_search_results_numbers_displayed(self):
        results = self.find_search_result_objects()
        return [i.number for i in results]

    def no_results_found(self):
        return self.driver.find_element(*self._locators['no_results']).is_displayed()

    @property
    def number_of_results(self):
        return len(self.find_search_result_objects())

    def find_search_result_objects(self):
        elements = self.driver.find_elements(*self._locators['search_result'])
        return [SearchResult(i) for i in elements]

    # Load More Button

    def click_load_more_button(self):
        self._verify_load_more_button_is_displayed()
        self.scroll_to_load_more_button()
        element = self.driver.find_element(*self._locators['load_more_button'])
        logging.info("Clicking 'Load More' button.")
        element.click()
        return

    def load_more_button_is_displayed(self):
        elements = self.driver.find_elements(*self._locators['load_more_button'])
        if len(elements) == 0:
            return False
        else:
            return elements[0].is_displayed()

    def scroll_to_load_more_button(self):
        self._verify_load_more_button_is_displayed()
        load_more_button_element = self.driver.find_element(*self._locators['load_more_button'])

        # This method scrolls and returns coordinates.
        load_more_button_location = load_more_button_element.location_once_scrolled_into_view

        # But this method alone isn't good enough. The nav could still cover the button, resulting in an
        #   ElementClickInterceptedException.

        nav_element = self.driver.find_element(*self._locators['main_nav'])
        load_more_button_y = load_more_button_location['y']
        if load_more_button_y < nav_element.size['height']:
            scroll_distance = -(nav_element.size['height'] - load_more_button_y)
            self.driver.execute_script("window.scrollBy(0,{})".format(scroll_distance))
        return

    def _verify_load_more_button_is_displayed(self):
        if not self.load_more_button_is_displayed():
            log_str = "'Load More' button is not displayed."
            logging.error(log_str)
            raise ElementNotVisibleException(log_str)
        return

    # Misc

    def accept_cookies(self):
        cookie_modal = CookieModal(driver=self.driver)

        if not cookie_modal.is_loaded():
            logging.debug(f"{cookie_modal.desc} is not displayed. No action needed.")
            return

        cookie_modal.click_ok_button()
        cookie_modal.wait_until_closed()
        return

    def loading_indicator_is_displayed(self):
        elements = self.driver.find_elements(*self._locators['loading_indicator'])
        if len(elements) == 0:
            return False
        else:
            return elements[0].is_displayed()

    def is_loaded(self):
        return not self.loading_indicator_is_displayed()

    def scroll_to_footer(self):
        element = self.driver.find_element(*self._locators['footer'])
        element.location_once_scrolled_into_view
        return

class SortDropdown(BaseElement):

    def __init__(self, element):
        super().__init__(element=element, desc='Sort Dropdown')
        self._locators = dict()
        self._locators['current_option'] = (By.CSS_SELECTOR, 'label')
        self._locators['option'] = (By.CSS_SELECTOR, 'li')
        return

    # Displaying Options

    def click_dropdown(self):
        logging.info(f"Clicking {self.desc}.")
        self.element.click()
        time.sleep(0.1)
        return

    def display_options(self):
        if self.options_are_displayed():
            logging.debug('Options are already displayed. No action needed.')
            return
        self.click_dropdown()
        return

    def options_are_displayed(self):
        label_element = self.element.find_element(*self._locators['current_option'])
        return 'opened' in label_element.get_attribute('class')

    def _verify_options_are_displayed(self):
        if not self.options_are_displayed():
            log_str = "Options are not displayed."
            logging.error(log_str)
            raise ElementNotVisibleException(log_str)
        return

    # Setting/Getting Options

    def click_option(self, option):
        self._verify_options_are_displayed()
        self._verify_option_exists(option)

        element = self._find_option_element(option=option)
        logging.info(f"Clicking sort option '{option}'.")
        element.click()
        return

    def _find_option_element(self, option):
        self._verify_options_are_displayed()

        elements = self.element.find_elements(*self._locators['option'])
        for i in elements:
            if option.lower() == i.text.lower():
                return i

        log_str = f"Invalid option '{option}' specified."
        logging.error(log_str)
        raise ValueError(log_str)

    @property
    def selected_option(self):
        return self.element.find_element(*self._locators['current_option']).text

    @selected_option.setter
    def selected_option(self, option):
        self.display_options()
        self._verify_option_exists(option=option)
        self.click_option(option=option)
        return

    def _verify_option_exists(self, option):
        self._find_option_element(option=option)
        return

class SearchResult(BaseElement):

    def __init__(self, element):
        super().__init__(element=element, desc='Search Result')

        self._locators = dict()
        self._locators['name'] = (By.CSS_SELECTOR, 'h5')
        self._locators['number'] = (By.CSS_SELECTOR, 'p.id')

        self.desc = f"Search Result - {self.number} {self.name}"
        return

    @property
    def name(self):
        return self.element.find_element(*self._locators['name']).text

    @property
    def number(self):
        return self.element.find_element(*self._locators['number']).text

    def __str__(self):
        return self.desc

class CookieModal(BaseLoadingElement):

    def __init__(self, driver):
        super().__init__(driver=driver, desc="Cookie Modal")
        self._locators = dict()
        self._locators['cookie_modal'] = (By.CSS_SELECTOR, 'div.ot-sdk-container')
        self._locators['ok_button'] = (By.CSS_SELECTOR, '#onetrust-accept-btn-handler')
        return

    def click_ok_button(self):
        button = self.driver.find_element(*self._locators['ok_button'])
        logging.info(f"Clicking 'OK' on {self.desc}")
        button.click()
        return

    def is_loaded(self):
        elements = self.driver.find_elements(*self._locators['cookie_modal'])
        if len(elements) == 0:
            return False
        else:
            return elements[0].is_displayed()


from sklearn.datasets import load_iris
from sklearn.utils import shuffle
import numpy as np
import tqdm
import matplotlib.pyplot as plt
### multi classification with decision tree

class Binary_inquiry_train:
    def __init__(self,X,Y): # input unnomarlized X and divided label into 0 and 1
        self.X = self.normalize(X)
        self.Y = Y
        self.W = np.random.rand(self.X.shape[1], 1)
        self.bias = np.random.rand()
        self.learning_rate = 0.01
        self.hypothesis = self.hypothesis_(self.X, self.W, self.bias)

        for i in tqdm.tqdm(range(8000)):
            self.W, self.bias, self.acc = self.GD_optimizer(self.X, self.Y, self.W, self.hypothesis, self.bias, self.learning_rate)
            self.hypothesis = self.sigmoid(np.dot(self.X, self.W) + self.bias).reshape((self.X.shape[0],))
            self.H = self.Binary_cross_entropy(self.hypothesis, self.Y)

        print("H = {}, train_acc = {}".format(self.H, self.acc))
        self.output = (self.W, self.bias)

    def normalize(self,X):
        mean = np.mean(X, axis=0, dtype=np.float32)
        std = np.std(X, axis=0, dtype=np.float32)
        X = (X - mean) / std
        return X

    def sigmoid(self,X):
        return 1/(1 + np.exp(-X))

    def Round_H_Round_W(self,X, hypothesis, Y):
        return ( np.dot(X.T,( hypothesis - Y )) / X.shape[0] ).reshape(4,1)

    def Round_H_Round_bias(self,X, hypothesis, Y):
        return np.sum( hypothesis - Y ) / X.shape[0]

    def Binary_cross_entropy(self,hypothesis, Y):
        H = - np.sum(( ( hypothesis - Y ) * np.log(hypothesis) + ( 1 - Y ) * np.log(1 - hypothesis)  ))
        return H

    def hypothesis_(self,X,W,bias):
        return self.sigmoid(np.dot(X, W) + bias).reshape((X.shape[0],))

    def SGD_optimizer(self,X,Y,W,hypothesis,bias,alpha,batch_size):
        #making...
        sampled_X,sampled_Y = shuffle(X,Y)
        sampled_X = sampled_X[0:batch_size]
        sampled_Y = sampled_Y[0:batch_size]
        W = W - alpha * self.Round_H_Round_W(sampled_X, hypothesis, sampled_Y)
        bias = bias - alpha * self.Round_H_Round_bias(sampled_X, hypothesis, sampled_Y)
        acc = self.accuracy(hypothesis, sampled_Y)
        return W, bias, acc

    def GD_optimizer(self,X,Y,W,hypothesis,bias, alpha):
        W = W - alpha * self.Round_H_Round_W(X, hypothesis, Y)
        bias = bias - alpha * self.Round_H_Round_bias(X, hypothesis, Y)
        acc = self.accuracy(hypothesis, Y)
        return W, bias, acc

    def accuracy(self,hypothesis,Y):
        predict = np.round(hypothesis)
        correct = [1 if predict[i] == Y[i] else 0 for i in range(len(Y))]
        acc = np.sum(correct) / len(correct)
        return acc

def divide_data_into_0_1(combined_data):
    temp = []
    for i in combined_data:
        if int(i[-1]) != 2:
            temp += [i]
    a =  np.array(temp)
    b = np.split(a, [-1], axis=1)
    X = b[0]
    Y = b[1].astype(np.int32)
    Y = np.squeeze(Y)  # array shape (number,1) >> (number,)

    return X,Y

def normalize(X):
    mean = np.mean(X, axis=0, dtype=np.float32)
    std = np.std(X, axis=0, dtype=np.float32)
    X = (X - mean) / std
    return X

def sigmoid(X):
    return 1/(1 + np.exp(-X))

if __name__ == '__main__':

    # data preparing
    a = load_iris()
    target = a['target']
    target_names = a['target_names']  ## setosa == 0 , versicolor == 1 , virginica == 2
    features = a['data']  ## 4 feature
    #np.random.seed(0)
    features, target = shuffle(features, target)  # fixed by np.random.seed

    feature_for_train = features[:130]
    target_for_train = target[:130].reshape(130,1)
    feature_for_test = features[130:]
    target_for_test = target[130:].reshape(150-130,1)

    #######################################
    #decision tree for specific case {0,1,2}
    #######################################

    #train for first decision {0,1} || {2}
    X = feature_for_train
    Y = np.array([0 if i == 0 or i == 1 else 1 for i in target_for_train])
    W1,bias1 = Binary_inquiry_train(X,Y).output
    print(X.shape,Y.shape)

    #train for second decision {0} || {1}
    combined_data = np.concatenate((feature_for_train, target_for_train), axis=1)
    X, Y = divide_data_into_0_1(combined_data)
    print(X.shape, Y.shape)
    W2,bias2 = Binary_inquiry_train(X,Y).output

    #test
    test_X = normalize(feature_for_test)
    test_Y = target_for_test

    acc = 0
    for i,X in enumerate(test_X):

        hypothesis = sigmoid(np.dot(X,W1) + bias1)
        predict = np.squeeze(np.round(hypothesis).astype(np.int32))

        if predict == 1:
            print("ans = {} , prediction = {}".format(test_Y[i][0], 2))
            acc += test_Y[i] == 2
        else:
            hypothesis = sigmoid(np.dot(X, W2) + bias2)
            predict = np.squeeze(np.round(hypothesis).astype(np.int32))

            if predict ==1:
                print("ans = {} , prediction = {}".format(test_Y[i][0], 1))
                acc += test_Y[i] == 1

            else:
                print("ans = {} , prediction = {}".format(test_Y[i][0], 0))
                acc += test_Y[i] == 0

    acc = acc / len(test_Y)
    print("acc = {} %".format(acc[0]*100))