#!/usr/bin/env python3

import dolfinx
import dolfiny
import numpy as np
import ufl
import basix
from mpi4py import MPI
from petsc4py import PETSc

import mesh_planartruss_gmshapi as mg

# Basic settings
name = "continuation_planartruss"
comm = MPI.COMM_WORLD

# Geometry and mesh parameters
L = 1.0  # member length
θ = np.pi / 3  # angle
p = 1  # physics: polynomial order
q = 1  # geometry: polynomial order

# Create the regular mesh of a curve with given dimensions
gmsh_model, tdim = mg.mesh_planartruss_gmshapi(name, L=L, nL=2, θ=θ, order=q)

# Get mesh and meshtags
mesh, mts = dolfiny.mesh.gmsh_to_dolfin(gmsh_model, tdim, prune_z=True)
gdim = mesh.geometry.dim

# Get merged MeshTags for each codimension
subdomains, subdomains_keys = dolfiny.mesh.merge_meshtags(mesh, mts, tdim - 0)
interfaces, interfaces_keys = dolfiny.mesh.merge_meshtags(mesh, mts, tdim - 1)

# Define shorthands for labelled tags
support = interfaces_keys["support"]
connect = interfaces_keys["connect"]
verytop = interfaces_keys["verytop"]
upper = subdomains_keys["upper"]
lower = subdomains_keys["lower"]

# Define integration measures
dx = ufl.Measure("dx", domain=mesh, subdomain_data=subdomains)
ds = ufl.Measure("ds", domain=mesh, subdomain_data=interfaces)
dS = ufl.Measure("dS", domain=mesh, subdomain_data=interfaces)

# Define elements
Ue = basix.ufl.element("P", mesh.basix_cell(), degree=p, gdim=gdim, shape=(gdim,))

# Define function spaces
Uf = dolfinx.fem.FunctionSpace(mesh, Ue)

# Define functions
u = dolfinx.fem.Function(Uf, name='u')
u_ = dolfinx.fem.Function(Uf, name='u_')  # boundary conditions
δu = ufl.TestFunction(Uf)

# Define state as (ordered) list of functions
m, δm = [u], [δu]

# System properties
K = dolfinx.fem.Constant(mesh, 1.0)  # axial stiffness, lower
β = dolfinx.fem.Constant(mesh, 1.2)  # stiffness factor for upper
p = dolfinx.fem.Constant(mesh, [0.0, -1.0])  # load vector, 2D

# Identify dofs of function spaces associated with tagged interfaces/boundaries
support_dofs_Uf = dolfiny.mesh.locate_dofs_topological(Uf, interfaces, support)
verytop_dofh_Uf = dolfiny.mesh.locate_dofs_topological((Uf.sub(0), Uf.sub(0).collapse()[0]), interfaces, verytop)

# Define boundary conditions
bcs = [dolfinx.fem.dirichletbc(u_, support_dofs_Uf),  # fix full displacement at support
       dolfinx.fem.dirichletbc(u_, verytop_dofh_Uf, Uf)]  # fix horizontal displacement at verytop

# Tangent basis (un-deformed configuration)
t0 = ufl.geometry.Jacobian(mesh)[:, 0]
# Unit tangent basis
t0 /= ufl.sqrt(ufl.dot(t0, t0))
# Projector to tangent space
P = ufl.outer(t0, t0)

# Define EPS
EPS = dolfinx.fem.Constant(mesh, 1.0e-10) / ufl.JacobianDeterminant(mesh)

# Various expressions
I = ufl.Identity(mesh.geometry.dim)  # noqa: E741
F = I + ufl.grad(u)

# Strain state (axial): from axial stretch λ
λ = ufl.sqrt(ufl.dot(F * t0, F * t0) + EPS)  # deformed tangent t = F * t0
# Em = P * (λ**2 - 1) / 2 * P  # Green-Lagrange strain
Em = P * (λ - 1) * P  # Biot strain

# Virtual membrane strain
dEm = dolfiny.expression.derivative(Em, m, δm)

# Membrane stress
Sm = K * Em

# load factor
λ = dolfinx.fem.Constant(mesh, 0.1)

# Weak form
F = - ufl.inner(dEm, Sm) * dx(lower) - β * ufl.inner(dEm, Sm) * dx(upper)
F += λ * ufl.inner(δu, p) * ds(verytop)

# Overall form (as list of forms)
F = dolfiny.function.extract_blocks(F, δm)

# Create output xdmf file -- open in Paraview with Xdmf3ReaderT
ofile = dolfiny.io.XDMFFile(comm, f"{name}.xdmf", "w")
# Write mesh, meshtags
ofile.write_mesh_meshtags(mesh, mts) if q <= 2 else None

# Options for PETSc backend
opts = PETSc.Options("continuation")

opts["snes_type"] = "newtonls"
opts["snes_linesearch_type"] = "basic"
opts["snes_atol"] = 1.0e-09
opts["snes_rtol"] = 1.0e-09
opts["snes_stol"] = 1.0e-09
opts["snes_max_it"] = 12
opts["ksp_type"] = "preonly"
opts["pc_type"] = "cholesky"
opts["pc_factor_mat_solver_type"] = "mumps"

u_step, λ_step = [], []

def monitor(context=None):

    if comm.size > 1:
        return

    u1_component = (Uf.sub(1), Uf.sub(1).collapse()[0])

    track_ids = [
        dolfiny.mesh.locate_dofs_topological(u1_component, interfaces, verytop),
        dolfiny.mesh.locate_dofs_topological(u1_component, interfaces, connect),
    ]

    track_val = [u.vector[idx[0]].squeeze() for idx in track_ids]

    u_step.append(track_val)
    λ_step.append(context.λ.value.item())

def block_inner(a1, a2):
    b1, b2 = [], []
    for mi in m:
        b1.append(dolfinx.fem.Function(mi.function_space, name=mi.name))
        b2.append(dolfinx.fem.Function(mi.function_space, name=mi.name))
    dolfiny.function.vec_to_functions(a1, b1)
    dolfiny.function.vec_to_functions(a2, b2)
    inner = 0.0
    for b1i, b2i in zip(b1, b2):
        inner += dolfiny.expression.assemble(ufl.inner(b1i, b2i), ufl.dx(mesh))
    return inner

# Create nonlinear problem context
problem = dolfiny.snesblockproblem.SNESBlockProblem(F, m, bcs, prefix="continuation")

# Create continuation problem context
continuation = dolfiny.continuation.Crisfield(problem, λ, inner=block_inner)

# Initialise continuation problem
continuation.initialise(ds=0.05, λ=0.0)

# Monitor (initial state)
monitor(continuation)

# Continuation procedure
for k in range(60):

    dolfiny.utils.pprint(f"\n*** Continuation step {k:d}")

    # Solve one step of the non-linear continuation problem
    continuation.solve_step(ds=0.05)

    # Monitor
    monitor(continuation)

    # Write output
    ofile.write_function(u, k) if q <= 2 else None

ofile.close()

# Post-processing
if comm.size == 1:

    # plot
    import matplotlib.pyplot
    from cycler import cycler
    flip = (cycler(color=['tab:orange', 'tab:blue']))
    flip += (cycler(markeredgecolor=['tab:orange', 'tab:blue']))
    fig, ax1 = matplotlib.pyplot.subplots(figsize=(8, 6), dpi=400)
    ax1.set_title(f"3-member planar truss, $θ$ = {θ / np.pi:1.3f}$π$", fontsize=12)
    ax1.set_xlabel('displacement $u / L$ $[-]$', fontsize=12)
    ax1.set_ylabel('load factor $λ$ $[-]$', fontsize=12)
    ax1.grid(linewidth=0.25)
    fig.tight_layout()

    # monitored results (load-response curves)
    ax1.plot(np.array(u_step) / L, λ_step, lw=1.5, ms=6.0, mfc='w', marker='.', label=["$u^{top}_1$", "$u^{mid}_1$"])

    ax1.legend()
    ax1.set_xlim([-2.0, +0.0])
    ax1.set_ylim([-0.6, +0.6])
    fig.savefig(f"{name}.png")


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

# Načtení černobílé fotky (výška, šířka)
image = cv2.imread('photos/IMG_0385.JPG', cv2.IMREAD_GRAYSCALE)[450:500, 2900:2950]
height, width = image.shape

# Výpočet gradientů v x a y směru pro původní fotografii
grad_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
grad_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)
grad_x2 = cv2.Sobel(image, cv2.CV_64F, 2, 0, ksize=3)
grad_y2 = cv2.Sobel(image, cv2.CV_64F, 0, 2, ksize=3)

# Nyní načteme novou fotografii
sx, sy, ex, ey = 450, 500, 2900, 2950
new_image = cv2.imread('photos/IMG_0385.JPG', cv2.IMREAD_GRAYSCALE)[sx:sy, ex:ey]
# Výpočet gradientů v x a y směru pro novou fotografii na bodě (10, 32)
target_x, target_y = np.int32(35), np.int32(40)

# Velikost oblasti pro porovnání
region_size = 3

grad_x_target = cv2.Sobel(new_image[target_y - 1:target_y + 2, target_x - 1:target_x + 2], cv2.CV_64F, 1, 0, ksize=3)
grad_y_target = cv2.Sobel(new_image[target_y - 1:target_y + 2, target_x - 1:target_x + 2], cv2.CV_64F, 0, 1, ksize=3)
grad_x2_target = cv2.Sobel(new_image[target_y - 1:target_y + 2, target_x - 1:target_x + 2], cv2.CV_64F, 2, 0, ksize=3)
grad_y2_target = cv2.Sobel(new_image[target_y - 1:target_y + 2, target_x - 1:target_x + 2], cv2.CV_64F, 0, 2, ksize=3)

"""# Výpočet magnitudy gradientu a směru pro bod (10, 32) na nové fotografii
gradient_magnitude_target = np.sqrt(grad_x_target[target_x, target_y]**2 + grad_y_target[target_x, target_y]**2)
gradient_direction_target = np.arctan2(grad_y_target[target_x, target_y], grad_x_target[target_x, target_y]) * 180 / np.pi
if gradient_direction_target < 0:
    gradient_direction_target += 180"""

# Vyhledání bodů na původní fotografii, které mají podobné gradienty jako bod (target_x, target_y) na nové fotografii
matching_points = []
for x in range(1, image.shape[0] - 1):
    for y in range(1, image.shape[1] - 1):
        # Výpočet gradientů v dané oblasti na původní fotografii
        """grad_x_region = grad_x[x - 1:x + 2, y - 1:y + 2]
        grad_y_region = grad_y[x - 1:x + 2, y - 1:y + 2]"""
        img = image[y - 1:y + 2, x - 1:x + 2]

        grad_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
        grad_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
        grad_x2 = cv2.Sobel(img, cv2.CV_64F, 2, 0, ksize=3)
        grad_y2 = cv2.Sobel(img, cv2.CV_64F, 0, 2, ksize=3)

        # Porovnání gradientů
        if np.allclose(grad_x_target, grad_x) and np.allclose(grad_y_target, grad_y) and \
                np.allclose(grad_x2_target, grad_x2) and np.allclose(grad_y2_target, grad_y2):
            matching_points.append((x, y))

# Vypsání bodů
for x, y in matching_points:
    print(f"Souřadnice: ({x}, {y})")

print(f"Správně je: ({ex - 2900 + target_x}, {sx - 450 + target_y})")

# Vykreslení výsledků
plt.figure(figsize=(12, 6))

plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.scatter(x, y, color='red', marker='x', label='Target Point (Original)')
plt.title('Original Image')

plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB))
plt.scatter(target_x, target_y, color='red', marker='x', label='Target Point (New)')
plt.title('New Image')

"""plt.subplot(1, 3, 3)
plt.imshow(new_image, cmap='gray')
plt.quiver(target_y, target_x, grad_x_target[target_x, target_y], grad_y_target[target_x, target_y],
           angles='xy', scale_units='xy', scale=1, color='red')
plt.scatter(target_y, target_x, color='red', marker='x', label='Target Point (New)')
plt.title('Gradient at (10, 32)')"""

# plt.legend()
plt.tight_layout()
plt.show()

vypocty_pokusy/Detekce cv2/CV2 - corelation.py


"""Logs reminders to firehose"""
import json
import logging.config
import os

import boto3
from boto3.dynamodb.types import TypeDeserializer

DESERIALIZER = TypeDeserializer()
FIREHOSE_CLIENT = boto3.client('firehose')
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
REMINDERS_FIREHOSE = os.environ['REMINDERS_FIREHOSE_STREAM_NAME']

def handler(event, context):
    """handler function works as controller function"""
    firehose_records = list()
    for record in event['Records']:
        firehose_records.append(build_firehose_record(record))

    put_records_on_firehose(firehose_records)
    LOGGER.debug('Time left to execute %s ms', context.get_remaining_time_in_millis())
    return {'Complete': True}

def build_firehose_record(record):
    """builds firehose record based on event type"""
    if record['eventName'] == 'REMOVE':
        image = {k: DESERIALIZER.deserialize(
            v) for k, v in record['dynamodb']['OldImage'].items()}
    else:
        image = {k: DESERIALIZER.deserialize(
            v) for k, v in record['dynamodb']['NewImage'].items()}

    image.update({'event': record['eventName']})
    return json.dumps(image, separators=(',', ':'), sort_keys=True) + '\n'

def put_records_on_firehose(firehose_records):
    """Break list of firehose records into lists of 500 and put on firehose"""
    firehose_record_chunks = [firehose_records[i:i + 500] for i in range(0, len(firehose_records), 500)]

    for chunk in firehose_record_chunks:
        FIREHOSE_CLIENT.put_record_batch(
            DeliveryStreamName=REMINDERS_FIREHOSE,
            Records=chunk
        )


from operator import add
from functools import reduce
from time import sleep
from pyttsx3 import speak

from radiodtmf.audio import DTMFDecocder
from radiodtmf.datasources import *
from radiodtmf.datasources.config import config
from radiodtmf.datasources.SourceTypes import SourceType

class ProgramController():

    def __init__(self):

        cfg = config("services")

        def get_nine_key_code(alpha_string):

            def letter_to_nine_key(letter):
                if letter in ['.', ',', '?', '!', ':']:
                    return '1'
                elif letter in ['A', 'B', 'C']:
                    return '2'
                elif letter in ['D', 'E', 'F']:
                    return '3'
                elif letter in ['G', 'H', 'I']:
                    return '4'
                elif letter in ['J', 'K', 'L']:
                    return '5'
                elif letter in ['M', 'N', 'O']:
                    return '6'
                elif letter in ['P', 'Q', 'R', 'S']:
                    return '7'
                elif letter in ['T', 'U', 'V']:
                    return '8'
                elif letter in ['W', 'X', 'Y', 'Z']:
                    return '9'

            return reduce(add, map(letter_to_nine_key,  alpha_string))

        self.modules = {}

        for module, code in {module:code for module, code in cfg.items() if module in [x.name for x in SourceType]}.items():
            nine_key_code = get_nine_key_code(code)
            self.modules[nine_key_code] = next( cls(nine_key_code) for cls in DataSource.__subclasses__() if cls.source_type() == SourceType[module] )

        self.dtmf_decoder = DTMFDecocder()

    def __build_help_menu(self):
        return "Available Commands. " + ", ".join([str(cls) for cls in self.modules.values()])

    def __get_info_from_dtmf_code(self, code):
        if code in self.modules.keys():
            return self.modules[code].get_data()
        else:
            return None

    def start(self):

        # reduce( lambda x,y : x + y, self.dtmf_decoder.dtmf_code(), '')
        def speak_with_delay(phrase):
            sleep(2)
            speak(phrase)

        seq = ""

        for x in self.dtmf_decoder.dtmf_code():

            if x == "#":
                speak_with_delay(self.__build_help_menu())
                seq = ""
            else:
                seq = seq + x

            if seq in self.modules.keys():
                speak_with_delay(self.__get_info_from_dtmf_code(seq))
                seq = ""
                continue

            if len(seq) > max([len(x) for x in self.modules.keys()]):
                seq = x


#job8

def multiplication():

    #declar/typ/init
    entree=""
    num1=int()
    num2=int()
    rslt=int()

    #entrees

        # importance de parser l'input!!
    num1=int(input ("Donnez la première valeur svp, sinon la valeur par défaut sera '3'"))
    print("Typage de num1 avant condition: ",type(num1))
    if entree==str(num1) :
        (num1)=(3)

    print ("la première valeur est donc: ",num1)

        # importance de parser l'input en int()!!
    num2=int(input ("Donnez la deuxième valeur svp, sinon la valeur par défaut sera '14'"))
    if entree==str(num2) :
        num2=(14)
    print ("la deuxième valeur est donc: ",num2)

    # Calcul du produit
    rslt=num1*num2

    #imp
    print ("Le résultat du produit de", num1, " * ", num2," est donc: ", rslt )

multiplication()


import re
import csv
import os

def load_words():
    valid_words = [""]
    with open('words_alpha.txt') as word_file:
        valid_words += list(word_file.read().split())

    return valid_words

words = load_words()#{i:words[i] for i in range(1, len(words))}

diction = {i:words[i] for i in range(1, len(words))}

#for i in range(len(diction)):
 # words.append(diction[i])

with open('movie_lines.txt') as f:
    lines = f.readlines()

temp = []

def getLineNum(line):
    line = line[1:]
    num = ""
    for char in line:
        if char == " ":
            break
        else:
            num += char
    return int(num)

convo = []
prevLineNum = 0

for line in lines:
    #line = line[36:]
    i = 0
    u = 0
    lNum = getLineNum(line)
    if (lNum + 1) != prevLineNum:
        temp.insert(0, convo)
        convo = []
    prevLineNum = lNum
    for char in line:
        i += 1
        if char == "+":
            u = i
    line = line[u:]
    line = re.sub(r"[']", '', line)
    line = re.sub(r"[^a-zA-Z]+", ' ', line)
    line = line.lower()
    line = line.split()
    l = [words.index(word) for word in line if word in words]
    convo.append(l)
lines = temp

print(lines[0])
#words.index to get key
with open('inputData.csv', 'w', newline='') as f:

    # using csv.writer method from CSV package
    write = csv.writer(f)

   # write.writerow(fields)
    write.writerows(lines)


import os
import cv2
from datetime import datetime
import json
import sys
import traceback
# Model 폴더 찾기 위한 방법
basePath = os.path.abspath(os.path.join(os.path.join(os.path.dirname(__file__), os.path.pardir, "../")))
# Model Path 등록
sys.path.append(basePath)

from Output.PredictOutput import operator
from Common.Camera.BaseCamera import BaseCamera
from Network.TFRT.YOLOv3.yolov3 import TrtYOLOv3
from Common.Logger.Logger import logger
from Common.Utils.Utils import connectCamera
from Output.Output import sendMsg

log = logger("log")

try:
    import pycuda.driver as cuda
    cuda.init()
except ImportError as e:
    log.error(e)
    pass

try:
    from pypylon import pylon
except ImportError as e:
    log.error(e)
    pass

pid = os.getpid()

class Camera(BaseCamera):
    video_source = 0
    mdlPath = None
    serialNo = None
    frameRatio = None
    target = None
    svrIp = None
    svrPort = None
    hwPort = None
    hwType = None
    isCD = None
    isType = None

    def __init__(self, svrIp, svrPort, mdlPath, serialNo, frameRatio, target, hwType, isCD, isType, hwPort):
        Camera.mdlPath = mdlPath
        Camera.serialNo = serialNo
        Camera.frameRatio = int(frameRatio)
        Camera.svrIp = svrIp
        Camera.svrPort = svrPort
        Camera.hwType = hwType
        Camera.isCD = isCD
        Camera.isType = isType
        Camera.hwPort = hwPort

        if target != "":
            Camera.target = target

        else:
            Camera.target = None

        if os.environ.get('OPENCV_CAMERA_SOURCE'):
            Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))
        super(Camera, self).__init__()

    @staticmethod
    def set_video_source(source):
        Camera.video_source = source

    @staticmethod
    def frames():
        try:
            # cuda_ctx = cuda.Device(0).make_context()
            camera = None
            try:
                # basler camera bind
                camera, err = connectCamera(Camera.serialNo, width=1920, height=1680, exposureTime=8000)
                if err is None:
                    pass
                else:
                    log.error(err)
                converter = pylon.ImageFormatConverter()

                # converting to opencv bgr format
                converter.OutputPixelFormat = pylon.PixelType_BGR8packed
                converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

            except Exception as e:
                out = {"IS_CD": Camera.isCD, "CODE": "040", "MSG": str(e)}
                log.error(out)
                log.error(traceback.format_exc())
                try:
                    _ = sendMsg('http://{}:{}/api/QI/report/stateCheck'.format(Camera.svrIp, Camera.svrPort), out)
                    # # cuda_ctx.pop()
                    return
                except Exception as ee:
                    log.error(ee)
                    log.error(traceback.format_exc())

            cnt = 0
            targets = []

            target = json.loads(Camera.target)
            captureTime = None
            for tmp in target:
                classCD = tmp["CLASS_CD"]
                className = tmp["CLASS_NAME"]
                dpLabel = tmp["DP_LABEL"]
                location = tmp["LOCATION"]
                color = tmp["COLOR"]
                accScope = tmp["ACC_SCOPE"].split(',')

                con1 = accScope[0]
                accu1 = accScope[1]
                logical = accScope[2]
                con2 = accScope[3]
                accu2 = accScope[4]

                targets.append([classCD, className, con1, accu1, logical, con2, accu2, dpLabel, location, color])

            if Camera.hwType == 'B':
                try:
                    while camera.IsGrabbing():
                        # read current frame
                        try:
                            grabResult = camera.RetrieveResult(20000, pylon.TimeoutHandling_ThrowException)

                        except Exception as e:
                            out = {"IS_CD": Camera.isCD, "CODE": "042", "MSG": str(e)}
                            _ = sendMsg('http://{}:{}/api/QI/report/stateCheck'.format(Camera.svrIp, Camera.svrPort), out)
                            # cuda_ctx.pop()
                            log.error(out)
                            log.error(traceback.format_exc())
                            return

                        # grab success check
                        if grabResult.GrabSucceeded():
                            # gray -> color change
                            image = converter.Convert(grabResult)
                            img = image.GetArray()
                            today = datetime.today()
                            captureTime = "{}-{}-{} {}:{}:{}.{}".format(today.year, today.month, today.day, today.hour,
                                                                        today.minute, today.second, today.microsecond)

                            out = {"HW_TYPE": Camera.hwType, "BOXES": None, "ACC": None, "CLASS": None,
                                   "isRect": False, "IS_CD": Camera.isCD, "IS_TYPE": Camera.isType, "RAW_TIME": captureTime}

                            # res = requests.post(server, headers=headers, data=json.dumps(out))
                            yield cv2.imencode('.jpg', img)[1].tobytes(), json.dumps(out)

                except Exception as e:
                    out = {"IS_CD": Camera.isCD, "CODE": "041", "MSG": str(e)}
                    _ = sendMsg('http://{}:{}/api/QI/report/stateCheck'.format(Camera.svrIp, Camera.svrPort), out)
                    log.error(out)
                    log.error(traceback.format_exc())
                    # cuda_ctx.pop()
                    return

            # elif Camera.hwType == 'F' or Camera.hwType == 'R':
            #     mdlList = os.listdir(Camera.mdlPath)
            #     # get model file and class file
            #     for tmp in mdlList:
            #         if ".tf" in tmp:
            #             tmp = tmp.split(".tf")
            #             modelName = tmp[0] + '.tf'
            #             break

            #     clssDirList = os.listdir(os.path.join(Camera.mdlPath, os.path.pardir))
            #     for tmp in clssDirList:
            #         if "_." in tmp:
            #             continue
            #         elif ".txt" in tmp or ".csv" in tmp:
            #             classPath = os.path.join(os.path.join(Camera.mdlPath, os.path.pardir), tmp)

            #     # get classes and numClasses in class file
            #     with open(classPath, 'r') as f:
            #         numClasses = (len(f.readlines()))

            #     classesTmp = [c.strip() for c in open(classPath).readlines()]
            #     classes = []

            #     for tmp in classesTmp:
            #         tmp = tmp.split(",")
            #         classes.append(tmp[1])

            #     modelPath = (os.path.join(Camera.mdlPath, modelName))
            #     try:
            #         trtYolov3 = TrtYOLOv3(modelPath, (416, 416), numClasses)
            #         # trtYolov3 = predictLoadModel("D", (416, 416, 3), Camera.isCD, modelPath)

            #     except Exception as e:
            #         out = {"IS_CD": Camera.isCD, "CODE": "031", "MSG": str(e)}
            #         _ = sendMsg('http://{}:{}/api/QI/report/stateCheck'.format(Camera.svrIp, Camera.svrPort), out)
            #         # cuda_ctx.pop()
            #         log.error(out)
            #         log.error(traceback.format_exc())
            #         return

            #     try:
            #         out = {"IS_CD": Camera.isCD, "CODE": "000", "MSG": None, "HW_PID": os.getpid()}
            #         _ = sendMsg('http://{}:{}/api/QI/report/stateCheck'.format(Camera.svrIp, Camera.svrPort), out)
            #         log.debug(out)

            #         while camera.IsGrabbing():
            #             # read current frame
            #             grabResult = camera.RetrieveResult(20000, pylon.TimeoutHandling_ThrowException)
            #             # grab success check
            #             if grabResult.GrabSucceeded():
            #                 # gray -> color change
            #                 image = converter.Convert(grabResult)
            #                 img = image.GetArray()
            #                 today = datetime.today()
            #                 capturedTime = "{}-{}-{} {}:{}:{}.{}".format(today.year, today.month, today.day, today.hour,
            #                                                              today.minute, today.second, today.microsecond)
            #                 if cnt % Camera.frameRatio == 0:
            #                     boxes, acc, clss = trtYolov3.detect(img, 0.3)
            #                     boxes = boxes.tolist()
            #                     if len(boxes) > 0:
            #                         acc = acc.tolist()
            #                         clss = clss.tolist()
            #                         for idx in clss:
            #                             if Camera.target is not None:
            #                                 for j, targetData in enumerate(targets):
            #                                     (classCD,
            #                                         className,
            #                                         con1,
            #                                         accu1,
            #                                         logical,
            #                                         con2,
            #                                         accu2,
            #                                         tag,
            #                                         location,
            #                                         color) = targetData

            #                                     if classes[idx] == className:
            #                                         for accuracy in acc:
            #                                             # out = roughExpress(boxes, accuracy, idx, targetData, capturedTime,
            #                                                               #  Camera.hwType, classes, Camera.isCD, Camera.isType)
            #                                               out = operator()
            #                                     else:
            #                                         for accuracy in acc:
            #                                             # out = roughExpress(boxes, accuracy, idx, targetData, capturedTime,
            #                                                               #  Camera.hwType, classes, Camera.isCD, Camera.isType)

            #                     else:
            #                         out = {"HW_TYPE": Camera.hwType, "BOXES": None, "ACC": None, "CLASS": None, "isRect": False,
            #                                "IS_CD": Camera.isCD, "IS_TYPE": Camera.isType, "RAW_TIME": capturedTime}

            #             else:
            #                 out = {"HW_TYPE": Camera.hwType, "BOXES": None, "ACC": None, "CLASS": None, "isRect": False,
            #                        "IS_CD": Camera.isCD, "IS_TYPE": Camera.isType, "RAW_TIME": capturedTime}

            #             # encode as a jpeg image and return it
            #             yield cv2.imencode('.jpg', img)[1].tobytes(), json.dumps(out)
            #             cnt += 1
                    # cuda_ctx.pop()

                except Exception as e:
                    out = {"IS_CD": Camera.isCD, "CODE": "040", "MSG": str(e)}
                    _ = sendMsg('http://{}:{}/api/QI/report/stateCheck'.format(Camera.svrIp, Camera.svrPort), out)
                    log.error(out)
                    log.error(traceback.format_exc())
                    # cuda_ctx.pop()

        except Exception as e:
            out = {"IS_CD": Camera.isCD, "CODE": "030", "MSG": str(e)}
            _ = sendMsg('http://{}:{}/api/QI/report/stateCheck'.format(Camera.svrIp, Camera.svrPort), out)
            log.error(out)
            log.error(traceback.format_exc())
            # cuda_ctx.pop()
            return


import math
import pytest

def isolamento_input_usuario():
    num1 = float(input("\nEntre com o valor de X: "))
    calculo_se_for_maior_4(num1)

def calculo_se_for_maior_4(num1_str):
    num1 = float(num1_str)
    if num1 > 4 or num1 < (-4):
        raiz = math.sqrt(num1**2 - 16)
        resultado = (5 * num1) / raiz
        mensagem = f"O resultado é {resultado:.2f}"
        print(mensagem)
        return mensagem
    mensagem = "Essa operação não pode ser feita para este valor de X"
    print(mensagem)
    return mensagem

@pytest.mark.parametrize(
    "num1, mensagem_esperada",
    [
        (5, "O resultado é 8.33"),
        (6, "O resultado é 6.71"),
        (2, "Essa operação não pode ser feita para este valor de X"),
    ],
)
def test_calculo_se_for_maior_4(num1, mensagem_esperada):
    resposta = calculo_se_for_maior_4(num1)
    assert resposta == mensagem_esperada

if __name__ == "__main__":
    isolamento_input_usuario()


#
# This file is subject to the terms and conditions defined in the
# file 'LICENSE', which is part of this source code package.
#
import copy
from dateutil import parser
from dateutil.parser import ParserError
import hashlib
import json
import logging
import os
import re
import time

from sqlalchemy import and_
from sqlalchemy.exc import IntegrityError

from rdr_service.dao.resource_dao import ResourceDataDao
from rdr_service.model.code import Code
from rdr_service.model.participant import Participant
from rdr_service.model.resource_data import ResourceData
from rdr_service.model.resource_schema import ResourceSchema
from rdr_service.model.resource_type import ResourceType
from rdr_service.model.site import Site
from rdr_service.resource import fields

# See BaseGenerator._lookup_code_value and BaseGenerator._lookup_code_id
_CODEBOOK_CODE_VALUES = None
_CODEBOOK_CODE_IDS = None

class ResourceRecordSet(object):
    """

    """
    _schema = None
    _data = None
    _resource = None
    _meta = None

    def __init__(self, schema, data=None):
        """
        :param schema: Schema model object for for this object
        :param data: Data record dict
        """
        if not hasattr(schema, 'Meta'):
            raise AttributeError('SchemaMeta object not found in schema.Meta.')
        self._schema = schema()
        self._meta = self._schema.Meta

        # Make sure 'participant_id' is a string(10) type.
        if 'participant_id' in self._schema.fields and (
                    not isinstance(self._schema.fields['participant_id'], fields.String) or
                    self._schema.fields['participant_id'].validate.max != 10):
            raise TypeError('Participant ID must be defined as String(10) in schema.')

        if data:
            # Make a copy of the data before calling _load_data().
            self._data = copy.deepcopy(data)
            data = self._load_data(self._schema, data)
            data.update(self._schema.dump(data))
            self._resource = data

    def _load_data(self, schema, data):
        """
        Recursive function to load data into this object.  Convert datetime and date string values.
        :param data: dict
        """
        # Force the 'participant_id' field value to a string with a 'P' prefix.
        if 'participant_id' in data and data['participant_id'] and str(data['participant_id'])[0] != 'P':
            data['participant_id'] = f'P{data["participant_id"]}'
        # Convert date or datetime fields if necessary.
        for name, meta in schema._declared_fields.items():
            if isinstance(meta, fields.Nested):
                if name in data:
                    if isinstance(data[name], list):
                        data[name] = [self._load_data(meta.schema, i) for i in data[name]]
                    elif isinstance(data[name], dict):
                        data[name] = self._load_data(meta.schema, data[name])
                continue
            if name in data and type(meta) in (fields.DateTime, fields.Date) and isinstance(data[name], str):
                try:
                    val = parser.parse(data[name])
                    data[name] = val if type(meta) == fields.DateTime else val.date()
                except (ParserError, TypeError):
                    pass
            # Only provide enum name string, not full class + name.
            if name in data and type(meta) == fields.EnumString:
                try:
                    data[name] = data[name].name
                except AttributeError:
                    pass

        # Remove any extra fields that are not declared in the schema.
        schema_fields = schema._declared_fields.keys()
        data_fields = data.keys()
        remove = list()
        for field in data_fields:
            if field not in schema_fields:
                remove.append(field)
        for field in remove:
            data.pop(field)

        return data

    def _get_or_create_type_record(self, dao, schema_meta):
        """
        Get or create the ResourceType record.
        :param dao: DAO object
        :param schema_meta: Schema model SchemaMeta object
        :return: ResourceType object
        """
        type_uid = schema_meta.uid()
        retry_count = 5
        notified = False

        while retry_count:
            with dao.session() as session:
                rec = session.query(ResourceType).filter(ResourceType.typeUID == type_uid).first()
                if rec:
                    return rec

                retry_count -= 1

                rec = ResourceType()
                rec.resourceURI = schema_meta.resource_uri()
                rec.resourcePKField = schema_meta.resource_pk_field()
                rec.typeName = schema_meta.name()
                rec.typeUID = type_uid

                session.add(rec)
                try:
                    session.commit()
                    return rec
                except IntegrityError:
                    # Record already exists, parallel tasks can cause this when the record does not already exist.
                    # We should not see these often. Only log this once.
                    if not notified:
                        logging.warning(f'Resource type record already exists for {rec.typeName}.')
                        notified = True
                    time.sleep(0.25)

        raise LookupError('Failed to retrieve resource Type record.')

    def _get_or_create_schema_record(self, dao, type_rec, schema):
        """
        Get or create the ResourceSchema record.
        :param dao: DAO object
        :param type_rec: ResourceType object
        :param schema: Schema model object.
        :return: ResourceSchema object
        """
        schema_dict = schema.to_dict()
        # Hash the schema. sort_keys=True is required so the hash remains the same for the same schema.
        hash_value = hashlib.sha256(json.dumps(schema_dict, sort_keys=True).encode('utf-8')).hexdigest()

        with dao.session() as session:
            rec = session.query(ResourceSchema).filter(and_(
                ResourceSchema.resourceTypeID == type_rec.id, ResourceSchema.schemaHash == hash_value)
            ).first()
            if rec:
                return rec

            rec = ResourceSchema()
            rec.schema = schema_dict
            rec.schemaHash = hash_value
            rec.resourceTypeID = type_rec.id

            session.add(rec)
            session.commit()

        return rec

    def _save(self, resources, schema, schema_meta, parent_resource=None, w_dao=None):
        """
        Recursive save resource function
        :param resources: List of Resource data dicts.
        :param schema: Resource schema object
        :param schema_meta: Resource SchemaMeta object
        :param parent_resource: Parent resource data dict
        :param w_dao: Writable DAO object.
        """
        if parent_resource:
            for k, v in schema.declared_fields.items():  # pylint: disable=unused-variable
                if k not in resources[0] and k in parent_resource:
                    for row in resources:
                        row[k] = parent_resource[k]

        if not w_dao:
            w_dao = ResourceDataDao()
        # Retrieve the schema type record, create if needed.
        type_rec = self._get_or_create_type_record(w_dao, schema_meta)
        # Retrieve the schema record, create if needed.
        schema_rec = self._get_or_create_schema_record(w_dao, type_rec, schema)

        pk_fld = type_rec.resourcePKField

        with w_dao.session() as session:
            for resource in resources:
                pid = None
                hpo_id = None

                if 'participant_id' in resource and resource['participant_id']:
                    pid = int(re.sub('[^0-9]', '', str(resource['participant_id'])))
                    # Force the 'participant_id' field to a string with a 'P' prefix.
                    resource['participant_id'] = f'P{pid}'
                # Attempt to find hpo_id for this resource record.
                if 'hpo_id' in resource:
                    hpo_id = resource['hpo_id']
                elif pid:
                    hpo_id = session.query(Participant.hpoId).filter(Participant.participantId == pid).first()

                # TODO: Populate parent resource values in URI in recursive calls.
                res_uri = type_rec.resourceURI + '/' + str(resource[type_rec.resourcePKField])

                # Look for existing resource record.
                rec = session.query(ResourceData).filter(ResourceData.uri == res_uri).first()
                if not rec:
                    rec = ResourceData()

                rec.resourceTypeID = type_rec.id
                rec.resourceSchemaID = schema_rec.id
                rec.uri = res_uri
                rec.hpoId = hpo_id
                if pk_fld in ['participant_id']:
                    rec.resourcePKID = pid
                else:
                    rec.resourcePKID = resource[pk_fld] if isinstance(resource[pk_fld], int) else None
                rec.resourcePKAltID = str(resource[pk_fld]) if isinstance(resource[pk_fld], str) else None
                rec.resource = resource
                # TODO: Populate rec.parent_id and rec.parent_type_id in recursive calls.

                session.add(rec)
                session.commit()

                # TODO: Fix recursive calls in the future.
                # # Recursively save nested resources.
                # if schema_meta.nested_schemas:
                #     for nested_id, nested_schema in schema_meta.nested_schemas:
                #         nested_schema = nested_schema()
                #         if nested_id in resource:
                #             self._save(resource[nested_id], nested_schema, nested_schema.Meta.schema_meta,
                #                        parent_resource if parent_resource else resource)

        return rec

    def save(self, w_dao=None):
        """
        Save resource to database.
        """
        return self._save(resources=[self._resource], schema=self._schema, schema_meta=self._meta, w_dao=w_dao)

    def get_schema(self):
        """ Return data schema """
        return self._schema

    def get_resource(self):
        """ Return resource """
        return self._resource

    def get_data(self):
        """ Return data dict """
        return self._data

class BaseGenerator(object):
    """
    Base class for generating Resource data JSON.
    """

    def _merge_schema_dicts(self, dict1, dict2):
        """
        Safely merge dict2 schema into dict1 schema
        :param dict1: dict object
        :param dict2: dict object
        :return: dict
        """
        lists = {key: val for key, val in dict1.items()}
        dict1.update(dict2)
        for key, val in lists.items():  # pylint: disable=unused-variable
            if key in dict2:
                # This assumes all sub-tables are set to repeated (multi-row) type.
                dict1[key] = lists[key] + dict2[key]

        return dict1

    def _lookup_code_value(self, code_id, session):
        """
        Return the code id string value from the code table.
        :param code_id: codeId from code table
        :param session: DAO session object
        :return: string
        """
        global _CODEBOOK_CODE_VALUES
        if code_id is None:
            return None

        # Code id to value mappings change from one unittest to another, we can't create a global
        # cache of data while running unittests.
        if not os.environ.get('UNITTEST_FLAG', 0) == 1 and _CODEBOOK_CODE_VALUES is None:
            results = session.query(Code.codeId, Code.value).\
                        filter(Code.system=='http://terminology.pmi-ops.org/CodeSystem/ppi').all()
            if not results:
                return None
            _CODEBOOK_CODE_VALUES = dict()
            for row in results:
                _CODEBOOK_CODE_VALUES[row.codeId] = row.value

            if code_id in _CODEBOOK_CODE_VALUES:
                return _CODEBOOK_CODE_VALUES[code_id]

        # The code might not be in our data because it is new, try fetching the record.
        # Also we might be running unittests, if that is the case we do a lookup
        # everytime and don't cache the lookup result.
        result = session.query(Code.value).filter(Code.codeId == int(code_id)).first()
        if result:
            if isinstance(_CODEBOOK_CODE_VALUES, dict):
                _CODEBOOK_CODE_VALUES[code_id] = result.value
            return result.value

        return None

    def _lookup_code_id(self, code, session):
        """
        Return the code id for the given code value string.
        :param code: code value string
        :param session: ReadOnly DAO session object
        :return: int
        """
        global _CODEBOOK_CODE_IDS
        if code is None:
            return None

        # Code id to value mappings change from one unittest to another, we can't create a global
        # cache of data while running unittests.
        if not os.environ.get('UNITTEST_FLAG', 0) == 1 and _CODEBOOK_CODE_IDS is None:
            results = session.query(Code.codeId, Code.value).\
                        filter(Code.system=='http://terminology.pmi-ops.org/CodeSystem/ppi').all()
            if not results:
                return None
            _CODEBOOK_CODE_IDS = dict()
            for row in results:
                _CODEBOOK_CODE_IDS[row.value] = row.codeId

            if code in _CODEBOOK_CODE_IDS:
                return _CODEBOOK_CODE_IDS[code]

        # The code might not be in our data because it is new, try fetching the record.
        # Also we might be running unittests, if that is the case we do a lookup
        # everytime and don't cache the lookup result.
        result = session.query(Code.codeId).filter(Code.value == code).first()
        if result:
            if isinstance(_CODEBOOK_CODE_IDS, dict):
                _CODEBOOK_CODE_IDS[code] = result.codeId
            return result.codeId

        return None

    def _lookup_site_name(self, site_id, ro_session):
        """
        Look up the site name
        :param site_id: site id integer
        :param ro_session: Readonly DAO session object
        :return: string
        """
        site = ro_session.query(Site.googleGroup).filter(Site.siteId == site_id).first()
        if not site:
            return None
        return site.googleGroup


# Copied from: https://github.com/danielgreenfeld3/XIC/blob/master/hsic.py

import torch

def pairwise_distances(x):
    # x should be two dimensional
    instances_norm = torch.sum(x ** 2, -1).reshape((-1, 1))
    return -2 * torch.mm(x, x.t()) + instances_norm + instances_norm.t()

def GaussianKernelMatrix(x, sigma=1):
    pairwise_distances_ = pairwise_distances(x)
    return torch.exp(-pairwise_distances_ / sigma)

def HSIC(x, y, s_x=1, s_y=1):
    m, _ = x.shape  # batch size
    K = GaussianKernelMatrix(x, s_x)
    L = GaussianKernelMatrix(y, s_y)
    H = torch.eye(m) - 1.0 / m * torch.ones((m, m))
    # H = H.double().cuda()
    H = H.to(x.device)
    HSIC = torch.trace(torch.mm(L, torch.mm(H, torch.mm(K, H)))) / ((m - 1) ** 2)
    return HSIC

def hsic_residuals(
    residuals: torch.tensor, targets: torch.tensor, featurewise: bool = True
) -> torch.Tensor:
    batch, num_classes, num_feats = residuals.shape
    residuals = _index_residuals(residuals, targets)

    targets = torch.nn.functional.one_hot(targets, num_classes=num_classes).float()
    targets = targets.to(residuals.device)

    if featurewise:
        loss = 0
        for i in range(num_feats):
            loss += HSIC(residuals[:, [i]], targets)
    else:
        loss = HSIC(residuals, targets)
    return loss

def _index_residuals(residuals: torch.tensor, targets: torch.tensor) -> torch.Tensor:
    batch, num_classes, num_feats = residuals.shape

    # Select only class residuals for independence
    index = torch.reshape(targets, (batch, 1, 1))
    index = torch.broadcast_to(index, size=(batch, 1, num_feats))
    residuals = torch.gather(residuals, dim=1, index=index)[:, 0, :]
    return residuals


from django import template

from django.contrib.sites.shortcuts import get_current_site

from django_plotly_dash.models import DashApp
from django_plotly_dash.util import pipe_ws_endpoint_name, store_initial_arguments

register = template.Library()

ws_default_url = "/%s" % pipe_ws_endpoint_name()

SANDBOX_SETTINGS = ["allow-downloads",
                    "allow-scripts",
                    "allow-same-origin",
                    "allow-modals",
                    "allow-popups",
                    "allow-popups-to-escape-sandbox",
                    ]

SANDBOX_STRING = " ".join(SANDBOX_SETTINGS)

def _locate_daapp(name, slug, da, cache_id=None):

    app = None

    if name is not None:
        da, app = DashApp.locate_item(name, stateless=True, cache_id=cache_id)

    if slug is not None:
        da, app = DashApp.locate_item(slug, stateless=False, cache_id=cache_id)

    if not app:
        app = da.as_dash_instance()

    return da, app

@register.inclusion_tag("django_plotly_dash/plotly_app.html", takes_context=True)
def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None):
    'Insert a dash application using a html iframe'

    fbs = '1' if use_frameborder else '0'

    dstyle = """
    position: relative;
    padding-bottom: %s%%;
    height: 0;
    overflow:hidden;
    """ % (ratio*100)

    istyle = """
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    """

    cache_id = store_initial_arguments(context['request'], initial_arguments)

    da, app = _locate_daapp(name, slug, da, cache_id=cache_id)

    sandbox_settings = SANDBOX_STRING

    return locals()

@register.inclusion_tag("django_plotly_dash/plotly_app_bootstrap.html", takes_context=True)
def plotly_app_bootstrap(context, name=None, slug=None, da=None, aspect="4by3", initial_arguments=None):
    'Insert a dash application using a html iframe'

    valid_ratios = ['21by9',
                    '16by9',
                    '4by3',
                    '1by1',
                    ]

    if aspect not in valid_ratios:
        raise ValueError("plotly_app_bootstrap requires a valid aspect ratio from %s, but was supplied %s" % (str(valid_ratios),
                                                                                aspect))

    cache_id = store_initial_arguments(context['request'], initial_arguments)

    da, app = _locate_daapp(name, slug, da, cache_id=cache_id)

    sandbox_settings = SANDBOX_STRING

    return locals()

@register.simple_tag(takes_context=True)
def plotly_header(context):
    'Insert placeholder for django-plotly-dash header content'
    return context.request.dpd_content_handler.header_placeholder

@register.simple_tag(takes_context=True)
def plotly_footer(context):
    'Insert placeholder for django-plotly-dash footer content'
    return context.request.dpd_content_handler.footer_placeholder

@register.inclusion_tag("django_plotly_dash/plotly_direct.html", takes_context=True)
def plotly_direct(context, name=None, slug=None, da=None):
    'Direct insertion of a Dash app'

    da, app = _locate_daapp(name, slug, da)

    view_func = app.locate_endpoint_function()

    # Load embedded holder inserted by middleware
    eh = context.request.dpd_content_handler.embedded_holder

    # Need to add in renderer launcher
    renderer_launcher = '<script id="_dash-renderer" type="application/javascript">var renderer = new DashRenderer();</script>'

    app.set_embedded(eh)
    try:
        resp = view_func()
    finally:
        eh.add_scripts(renderer_launcher)
        app.exit_embedded()

    return locals()

@register.inclusion_tag("django_plotly_dash/plotly_messaging.html", takes_context=True)
def plotly_message_pipe(context, url=None):
    'Insert script for providing background websocket connection'
    url = url if url else ws_default_url
    return locals()

@register.simple_tag()
def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
    'Return a slug-friendly identifier'

    da, app = _locate_daapp(name, slug, da)

    slugified_id = app.slugified_id()

    if postfix:
        return "%s-%s" %(slugified_id, postfix)
    return slugified_id

@register.simple_tag()
def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
    'Return a string of space-separated class names'

    da, app = _locate_daapp(name, slug, da)

    return app.extra_html_properties(prefix=prefix,
                                     postfix=postfix,
                                     template_type=template_type)

@register.simple_tag(takes_context=True)
def site_root_url(context):
    'Provide the root url of the demo site'
    current_site_url = get_current_site(context.request)
    return current_site_url.domain


import arcade

# Handles all the entities in the game and drawing them
# Everything in this class is static
from collider import Collider

class GameManager:
    __entities = []
    # Setup sprite lists for drawing stuff to the screen
    __dynamic_entities_spritelist = arcade.SpriteList()
    __static_entities_spritelist = arcade.SpriteList()
    __background_entities_spritelist = arcade.SpriteList()
    __gui_entities_spritelist = arcade.SpriteList()

    SCREEN_WIDTH = 1920
    SCREEN_HEIGHT = 1080
    debug = False

    __paused = False

    @staticmethod
    def get_paused():
        return GameManager.__paused

    @staticmethod
    def set_paused(value):
        GameManager.__paused = value
        if value:
            print("Paused")
        else:
            print("Unpaused")

    main_camera = None  # Scrolling camera
    gui_camera = None  # Static camera

    # Delta time, here for convenience
    dt = 0.02

    # Runs once the game is started and the window is created
    @staticmethod
    def start():
        width, height = arcade.window_commands.get_display_size()
        GameManager.main_camera = arcade.Camera(width, height)
        GameManager.gui_camera = arcade.Camera(width, height)
        GameManager.set_paused(False)

    @staticmethod
    def get_dynamic_entities():
        return GameManager.__dynamic_entities_spritelist

    @staticmethod
    def get_static_entities():
        return GameManager.__static_entities_spritelist

    @staticmethod
    def get_background_entities():
        return GameManager.__background_entities_spritelist

    @staticmethod
    def get_gui_entities():
        return GameManager.__gui_entities_spritelist

    @staticmethod
    def remove_tagged_entities(tag):
        for entity in GameManager.__entities:
            if tag in entity.tags:
                for component in entity.components:
                    if hasattr(component, "on_remove"):
                        component.on_remove()
                if hasattr(entity, "on_remove"):
                    entity.on_remove()
                GameManager.__entities.remove(entity)
                entity.in_scene = False
                if entity.get_component_by_name("SpriteRenderer"):
                    sprite = entity.get_component_by_name("SpriteRenderer").sprite
                    if sprite in GameManager.__static_entities_spritelist:
                        GameManager.__static_entities_spritelist.remove(sprite)
                    if sprite in GameManager.__dynamic_entities_spritelist:
                        GameManager.__dynamic_entities_spritelist.remove(sprite)
                    if sprite in GameManager.__background_entities_spritelist:
                        GameManager.__background_entities_spritelist.remove(sprite)
                    if sprite in GameManager.__gui_entities_spritelist:
                        GameManager.__gui_entities_spritelist.remove(sprite)
                else:
                    print("Entity", entity.name, "has no SpriteRenderer")

    @staticmethod
    def remove_all_entities():
        for entity in GameManager.__entities:
            for component in entity.components:
                if hasattr(component, "on_remove"):
                    component.on_remove()
            if hasattr(entity, "on_remove"):
                entity.on_remove()
        GameManager.__entities = []
        GameManager.__dynamic_entities_spritelist = arcade.SpriteList()
        GameManager.__static_entities_spritelist = arcade.SpriteList()
        GameManager.__background_entities_spritelist = arcade.SpriteList()
        GameManager.__gui_entities_spritelist = arcade.SpriteList()

    @staticmethod
    def remove_background_entities():
        for entity in GameManager.__entities:
            if entity.get_component_by_name("SpriteRenderer"):
                sprite = entity.get_component_by_name("SpriteRenderer").sprite
                if sprite in GameManager.__background_entities_spritelist:
                    GameManager.__background_entities_spritelist.remove(sprite)
                    GameManager.remove_entity(entity)
        GameManager.__background_entities_spritelist = arcade.SpriteList()  # Clear the spritelist

    @staticmethod
    def remove_static_entities():
        for entity in GameManager.__entities:
            if entity.get_component_by_name("SpriteRenderer"):
                sprite = entity.get_component_by_name("SpriteRenderer").sprite
                if sprite in GameManager.__static_entities_spritelist:
                    GameManager.__static_entities_spritelist.remove(sprite)
                    GameManager.remove_entity(entity)
        GameManager.__static_entities_spritelist.clear()

    @staticmethod
    def remove_entity(entity):
        entity.in_scene = False
        if entity in GameManager.__entities:
            GameManager.__entities.remove(entity)
            for component in entity.components:
                if hasattr(component, "on_remove"):
                    component.on_remove()
            if hasattr(entity, "on_remove"):
                entity.on_remove()
        else:
            #print("Entity", entity.name, "not found in GameManager.__entities")
            pass

        if entity.get_component_by_name("SpriteRenderer"):
            sprite = entity.get_component_by_name("SpriteRenderer").sprite
            if sprite in GameManager.__static_entities_spritelist:
                GameManager.__static_entities_spritelist.remove(sprite)
            if sprite in GameManager.__dynamic_entities_spritelist:
                GameManager.__dynamic_entities_spritelist.remove(sprite)
            if sprite in GameManager.__background_entities_spritelist:
                GameManager.__background_entities_spritelist.remove(sprite)
            if sprite in GameManager.__gui_entities_spritelist:
                GameManager.__gui_entities_spritelist.remove(sprite)
        else:
            print("Entity", entity.name, "has no SpriteRenderer")

    # Adds a background entity (draws below everything else, has no collision)
    @staticmethod
    def add_background_entity(entity):
        entity.in_scene = True
        GameManager.__entities.append(entity)
        # Add sprite to list so it gets drawn
        sprite = entity.get_component_by_name("SpriteRenderer")
        if sprite is not None:
            GameManager.__background_entities_spritelist.append(sprite.sprite)
        # Call on_created for all components attached to this entity
        for component in entity.components:
            if hasattr(component, 'on_created'):
                component.on_created()
        # Call on_created on the entity if it has it (behaviour should be in components, but whatever)
        if hasattr(entity, "on_created"):
            entity.on_created()

    # Adds a new entity.
    # Handles adding it to sprite lists so it gets rendered
    @staticmethod
    def add_entity(entity):
        entity.in_scene = True
        GameManager.__entities.append(entity)
        sprite = entity.get_component_by_name("SpriteRenderer")
        # Only add to sprite lists if entity has a sprite component
        if sprite is not None:
            if entity.static:
                GameManager.__static_entities_spritelist.append(sprite.sprite)
            else:
                GameManager.__dynamic_entities_spritelist.append(sprite.sprite)
        # Call on_created for all components attached to this entity
        for component in entity.components:
            if hasattr(component, 'on_created'):
                component.on_created()
        # Call on_created on the entity if it has it (behaviour should be in components, but whatever)
        if hasattr(entity, "on_created"):
            entity.on_created()

    # Adds a new GUI entity.
    # Handles adding it to sprite lists so it gets rendered
    @staticmethod
    def add_gui_entity(entity):
        entity.in_scene = True
        GameManager.__entities.append(entity)
        sprite = entity.get_component_by_name("SpriteRenderer")
        # Only add to sprite lists if entity has a sprite component
        if sprite is not None:
            GameManager.__gui_entities_spritelist.append(sprite.sprite)
        # Call on_created for all components attached to this entity
        for component in entity.components:
            if hasattr(component, 'on_created'):
                component.on_created()
        # Call on_created on the entity if it has it (behaviour should be in components, but whatever)
        if hasattr(entity, "on_created"):
            entity.on_created()

    # Sets an entity to be static (True) or dynamic (False) and assigns it to the relevant SpriteList
    @staticmethod
    def set_static(entity, static):
        sprite = entity.get_component_by_name("SpriteRenderer")
        if sprite is not None:
            # Remove entity from existing sprite lists
            if entity.static:
                GameManager.__static_entities_spritelist.remove(sprite.sprite)
            else:
                GameManager.__dynamic_entities_spritelist.remove(sprite.sprite)
            # Add entity to new sprite list
            if static:
                GameManager.__static_entities_spritelist.append(sprite.sprite)
            else:
                GameManager.__dynamic_entities_spritelist.append(sprite.sprite)
        # Set the static flag if it isn't already set
        entity.static = static

    # Returns a list of entities with a given tag
    @staticmethod
    def get_entities_by_tag(tag):
        to_return = []
        for item in GameManager.__entities:
            if tag in item.tags:
                to_return.append(item)
        return to_return

    # Returns a list of entities matching the given name
    @staticmethod
    def get_entities_by_name(name):
        to_return = []
        for item in GameManager.__entities:
            if item.name == name:
                to_return.append(item)
        return to_return

    # Returns a list of active collider components in the scene
    @staticmethod
    def get_colliders():
        colliders = []
        for entity in GameManager.__entities:
            if entity.active:
                collider = entity.get_component_by_name("Collider")
                if collider is not None:
                    colliders.append(collider)
        return colliders

    # Returns a list of all entities
    @staticmethod
    def get_entities():
        return GameManager.__entities

    # Clears gui sprites for redraw
    @staticmethod
    def clear_gui_sprite():
        GameManager.__gui_entities_spritelist.clear()

    # Draw everything to screen
    @staticmethod
    def draw():
        GameManager.main_camera.use()
        GameManager.__background_entities_spritelist.draw()
        GameManager.__static_entities_spritelist.draw()
        GameManager.__dynamic_entities_spritelist.draw()
        # Debug
        if GameManager.debug:
            for collider in GameManager.get_colliders():
                if collider.auto_generate_polygon == "box":
                    arcade.draw_rectangle_outline(collider.transform.position[0], collider.transform.position[1], collider.width, collider.height, arcade.color.RED, 2)
                else:
                    arcade.draw_polygon_outline(collider.polygon, arcade.color.RED, 2)
                arcade.draw_circle_outline(collider.transform.position[0], collider.transform.position[1], 5.0, arcade.color.GREEN)

        # Draw GUI
        GameManager.gui_camera.use()
        GameManager.__gui_entities_spritelist.draw()

        # Debug
        if GameManager.debug:
            #player_cont = GameManager.get_entities_by_name("Player")[0].get_component_by_name("PlayerController")
            #string_to_print = "Pos: " + str(GameManager.get_entities_by_name("Player")[0].get_component_by_name("Transform").position)
            #string_to_print2 = "Vel: " + str(player_cont.velocity)

            #arcade.draw_text(string_to_print, 0, 500, arcade.color.BLACK, 20, anchor_x="left", anchor_y="bottom")
            #arcade.draw_text(string_to_print2, 0, 470, arcade.color.BLACK, 20, anchor_x="left", anchor_y="bottom")
            arcade.draw_text("Frame time: " + str(GameManager.dt), 0, 530, arcade.color.BLACK, 20, anchor_x="left", anchor_y="bottom")
            arcade.draw_text(str(len(GameManager.get_entities())) + " entities", 0, 550, arcade.color.BLACK, 20, anchor_x="left", anchor_y="bottom")


class Solution:
    def dietPlanPerformance(self, calories: List[int], k: int, lower: int, upper: int) -> int:
        score = 0
        n = len(calories)
        if n < k:
            return 0
        s = sum(calories[:k])
        if s < lower:
            score -= 1
        if s > upper:
            score += 1
        for i in range(1,n - k + 1):
            s -= calories[i - 1]
            s += calories[i + k - 1]
            if s < lower:
                score -= 1
            if s > upper:
                score += 1
        return score


import numpy as np

def open_pdb(file_location):
    """
    This function reads in a pdb file and returns the atom names and coordinates.

    Parameters
    ----------
    file_location : str
        The path to the pdb file.

    Returns
    -------
    symbols : list
        Symbols of all atoms in pdb.
    coords : np.ndarray
        Coordinates of each atom's positions.
    """

    with open(file_location) as f:
        data = f.readlines()
    coordinates = []
    symbols = []
    for line in data:
        if 'ATOM' in line[0:6] or 'HETATM' in line[0:6]:
            symbols.append(line[76:79].strip())
            atom_coords = [float(x) for x in line[30:55].split()]
            coordinates.append(atom_coords)
    coords = np.array(coordinates)
    return symbols, coords


def solution(numbers):
    answer = [-1]*len(numbers)
    stack = []

    for idx in range(len(numbers)):
        number = numbers[idx]
        while stack and numbers[stack[-1]]< number:
            answer[stack.pop()] = number
        stack.append(idx)
    return answer

프로그래머스/unrated/154539. 뒤에 있는 큰 수 찾기/뒤에 있는 큰 수 찾기.py

뒤에 있는 큰 수 찾기.py


import torch
from disprcnn.structures.point_cloud import PointCloud
import numpy as np

# from disprcnn.utils.eval_time import EvalTime

# get_time = EvalTime()
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1

class Box3DList(object):
    """
    This class represents a set of 3D bounding boxes.
    The bounding boxes are represented as a Nx7 Tensor in "ry_lhwxyz" mode or Nx24 in "corners" mode.
    In order ot uniquely determine the bounding boxes with respect
    to an image, we also store the corresponding image dimensions.
    They can contain extra information that is specific to each bounding box, such as
    labels.

    description of the "ry_lhwxyz":
        ry: the rotation around the Y-axis
        l, h, w: the length, height, width of the car
        x, y, z: the coordinate of the center of bottom face
    Draw 3d bounding box in image
    qs: (8,3) array of vertices for the 3d box in following order:
            2 -------- 6
           /|         /|
          1 -------- 5 .
          | |        | |
          . 3 -------- 7
          |/         |/
          0 -------- 4
    """

    def __init__(self, bbox_3d, mode="corners", frame="rect"):
        self.device = bbox_3d.device if isinstance(bbox_3d, torch.Tensor) else torch.device("cpu")
        bbox_3d = torch.as_tensor(bbox_3d, dtype=torch.float32, device=self.device)
        self.frame = frame

        if bbox_3d.ndimension() == 1:
            bbox_3d = bbox_3d.unsqueeze(0)
        if bbox_3d.ndimension() == 3:
            bbox_3d = bbox_3d.view(-1, 24)
        if bbox_3d.ndimension() != 2:
            raise ValueError(
                "bbox_3d should have 2 dimensions, got {} {}".format(bbox_3d.ndimension(), bbox_3d.size())
            )
        if (mode == "ry_lhwxyz" or mode == "alpha_lhwxyz" or mode == "xyzhwl_ry") and bbox_3d.size(-1) != 7:
            raise ValueError(
                "last dimenion of bbox_3d in the ry_lhwxyz mode should have a "
                "size of 7, got {}".format(bbox_3d.size(-1))
            )
        if mode == "corners" and bbox_3d.size(-1) != 24:
            raise ValueError(
                "last dimenion of bbox_3d in the corners mode should have a "
                "size of 24, got {}".format(bbox_3d.size(-1))
            )

        if mode not in ("ry_lhwxyz", "corners", "xyzhwl_ry", "alpha_lhwxyz"):
            raise ValueError("mode should be 'ry_lhwxyz', 'alpha_lhwxyz', 'xyzhwl_ry' or 'corners'")

        self.bbox_3d = bbox_3d
        self.mode = mode
        self.extra_fields = {}

    def add_field(self, field, field_data):
        self.extra_fields[field] = field_data

    def get_field(self, field):
        return self.extra_fields[field]

    def has_field(self, field):
        return field in self.extra_fields

    def fields(self):
        return list(self.extra_fields.keys())

    def _copy_extra_fields(self, bbox):
        for k, v in bbox.extra_fields.items():
            self.extra_fields[k] = v

    def __getitem__(self, item):
        bbox_3d = Box3DList(self.bbox_3d[item], self.mode, frame=self.frame)
        return bbox_3d

    def __len__(self):
        return self.bbox_3d.shape[0]

    def convert(self, mode):
        if mode not in ("ry_lhwxyz", "alpha_lhwxyz", "xyzhwl_ry", "corners"):
            raise ValueError("mode should be 'ry_lhwxyz', 'alpha_lhwxyz', 'xyzhwl_ry' or 'corners'")

        if mode == self.mode:
            return self

        corners = self._split_into_corners()
        if mode == "corners":
            bbox_3d = torch.cat(corners, dim=-1)
            box_3d_list = Box3DList(bbox_3d, mode=mode, frame=self.frame)
        elif mode == "ry_lhwxyz" or mode == "xyzhwl_ry":
            # TODO calculate the mean
            dif = (corners[3] - corners[0])
            if self.frame == "velodyne":
                ry = torch.atan2(dif[:, 1], dif[:, 0]).view(-1, 1)
            else:
                ry = -(torch.atan2(dif[:, 2], dif[:, 0])).view(-1, 1)
            xyz = ((corners[7] + corners[0]) / 2).view(-1, 3)
            l = torch.norm((corners[0] - corners[3]), dim=1).view(-1, 1)
            h = torch.norm((corners[0] - corners[1]), dim=1).view(-1, 1)
            w = torch.norm((corners[0] - corners[4]), dim=1).view(-1, 1)
            if mode == "xyzhwl_ry":
                bbox_3d = torch.cat((xyz, h, w, l, ry), dim=-1)
            else:
                bbox_3d = torch.cat((ry, l, h, w, xyz), dim=-1)

            box_3d_list = Box3DList(bbox_3d, mode=mode, frame=self.frame)

        else:
            dif = (corners[3] - corners[0])
            ry = -(torch.atan2(dif[:, 2], dif[:, 0])).view(-1, 1)
            xyz = ((corners[7] + corners[0]) / 2).view(-1, 3)
            alpha = ry + torch.atan2(xyz[:, 2].view(-1, 1), xyz[:, 0].view(-1, 1)) - np.pi / 2
            l = torch.norm((corners[0] - corners[3]), dim=1).view(-1, 1)
            h = torch.norm((corners[0] - corners[1]), dim=1).view(-1, 1)
            w = torch.norm((corners[0] - corners[4]), dim=1).view(-1, 1)
            bbox_3d = torch.cat((alpha, l, h, w, xyz), dim=-1)

            box_3d_list = Box3DList(bbox_3d, mode=mode, frame=self.frame)
        return box_3d_list

    def _split_into_corners(self):
        """
        :return: a list of 8 tensor, with shape of (N, 3), each row is a point of corners
        """
        if self.mode == "corners":
            corners = self.bbox_3d.split(3, dim=-1)
            return corners

        elif (self.mode == "ry_lhwxyz" or self.mode == "xyzhwl_ry") and self.frame == "velodyne":
            if self.mode == "xyzhwl_ry":
                x, y, z, h, w, l, ry = self.bbox_3d.split(1, dim=-1)
            else:
                ry, l, h, w, x, y, z = self.bbox_3d.split(1, dim=-1)
            # get_time('generate tensor')
            zero_col = torch.zeros(ry.shape).to(self.device)
            ones_col = torch.ones(ry.shape).to(self.device)
            # get_time('zero ones over')
            # get_time(str(w.shape))
            half_w = w / 2
            ne_half_w = - half_w
            half_l = l / 2
            ne_half_l = -half_l
            cos_ry = torch.cos(ry)
            sin_ry = torch.sin(ry)
            ne_sin_ry = -sin_ry
            # get_time('compute_over')
            y_corners = torch.cat((half_w, half_w, half_w, half_w, ne_half_w, ne_half_w, ne_half_w, ne_half_w), dim=1)
            # get_time('y_over')
            z_corners = torch.cat((zero_col, h, h, zero_col, zero_col, h, h, zero_col), dim=1)
            # get_time('l_over')
            x_corners = torch.cat((ne_half_l, ne_half_l, half_l, half_l, ne_half_l, ne_half_l, half_l, half_l), dim=1)
            # get_time('cat over')
            corners_obj = (torch.stack((x_corners, y_corners, z_corners), dim=1))
            # get_time('stack over')

            R = torch.cat([cos_ry, ne_sin_ry, zero_col, sin_ry, cos_ry, zero_col,
                           zero_col, zero_col, ones_col], dim=1)
            # get_time('cat again')

            R = R.view(-1, 3, 3)
            # get_time('box3d convert')
            corners_cam = torch.matmul(R, corners_obj) + torch.cat((x, y, z), dim=-1).view(-1, 3, 1)
            corners_cam = corners_cam.transpose(1, 2).reshape(-1, 24)
            return corners_cam.split(3, dim=-1)

        elif (self.mode == "ry_lhwxyz" or self.mode == "xyzhwl_ry") and self.frame == "rect":
            if self.mode == "xyzhwl_ry":
                x, y, z, h, w, l, ry = self.bbox_3d.split(1, dim=-1)
            else:
                ry, l, h, w, x, y, z = self.bbox_3d.split(1, dim=-1)

            zero_col = torch.zeros(ry.shape).to(self.device)
            ones_col = torch.ones(ry.shape).to(self.device)
            half_w = w / 2
            ne_half_w = - half_w
            half_l = l / 2
            ne_half_l = -half_l
            cos_ry = torch.cos(ry)
            sin_ry = torch.sin(ry)
            ne_sin_ry = -sin_ry
            x_corners = torch.cat((ne_half_l, ne_half_l, half_l, half_l, ne_half_l, ne_half_l, half_l, half_l), dim=1)
            y_corners = torch.cat((zero_col, -h, -h, zero_col, zero_col, -h, -h, zero_col), dim=1)
            z_corners = torch.cat((half_w, half_w, half_w, half_w, ne_half_w, ne_half_w, ne_half_w, ne_half_w), dim=1)
            corners_obj = (torch.stack((x_corners, y_corners, z_corners), dim=1))

            R = torch.cat([cos_ry, zero_col, sin_ry, zero_col, ones_col, zero_col,
                           ne_sin_ry, zero_col, cos_ry], dim=1)

            R = R.view(-1, 3, 3)
            corners_cam = torch.matmul(R, corners_obj) + torch.cat((x, y, z), dim=-1).view(-1, 3, 1)
            corners_cam = corners_cam.transpose(1, 2).reshape(-1, 24)
            return corners_cam.split(3, dim=-1)

        elif self.mode == "alpha_lhwxyz":
            alpha, l, h, w, x, y, z = self.bbox_3d.split(1, dim=-1)
            ry = alpha + (- torch.atan2(x, z))
            # TODO make code simple
            zero_col = torch.zeros(ry.shape).to(self.device)
            ones_col = torch.ones(ry.shape).to(self.device)
            x_corners = torch.cat((-l / 2, -l / 2, l / 2, l / 2, -l / 2, -l / 2, l / 2, l / 2), dim=1)
            y_corners = torch.cat((zero_col, -h, -h, zero_col, zero_col, -h, -h, zero_col), dim=1)
            z_corners = torch.cat((w / 2, w / 2, w / 2, w / 2, -w / 2, -w / 2, -w / 2, -w / 2), dim=1)
            corners_obj = (torch.stack((x_corners, y_corners, z_corners), dim=1))

            R = torch.cat([torch.cos(ry), zero_col, torch.sin(ry), zero_col, ones_col, zero_col,
                           -torch.sin(ry), zero_col, torch.cos(ry)], dim=1)
            R = R.view(-1, 3, 3)

            corners_cam = torch.matmul(R, corners_obj) + torch.cat((x, y, z), dim=-1).view(-1, 3, 1)
            corners_cam = corners_cam.transpose(1, 2).reshape(-1, 24)
            return corners_cam.split(3, dim=-1)

        else:
            raise RuntimeError("Should not be here")

    def _split_into_ry_lhwxyz(self):
        box_3d_list = self.convert("ry_lhwxyz")
        return box_3d_list.box_3d.split(1, dim=-1)

    def cart2hom(self, pts_3d):
        ''' Input: nx3 points in Cartesian
            Oupput: nx4 points in Homogeneous by pending 1
        '''
        pts_3d = pts_3d.view(-1, 3)
        ones = torch.ones(pts_3d.shape[0]).unsqueeze(1)
        pts_3d = torch.cat([pts_3d, ones], dim=1)
        return pts_3d

    def project_world_to_rect(self, boxes_world, pose):
        pts_3d_world = self.cart2hom(boxes_world)  # nx4
        box3d_rect = torch.inverse(pose) @ pts_3d_world.transpose(0, 1)
        return box3d_rect.transpose(0, 1)[:, :3]

    def project_rect_to_world(self, boxes_rect, pose):
        pts_3d_rect = self.cart2hom(boxes_rect)  # nx4
        box3d_world = pose @ pts_3d_rect.transpose(0, 1)
        return box3d_world.transpose(0, 1)[:, :3]

    def transpose(self, method):
        """
        Transpose bounding box (flip or rotate in 90 degree steps)
        :param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
          :py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
          :py:attr:`PIL.Image.ROTATE_180`, :py:attr:`PIL.Image.ROTATE_270`,
          :py:attr:`PIL.Image.TRANSPOSE` or :py:attr:`PIL.Image.TRANSVERSE`.
        """
        if method not in (FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM):
            raise NotImplementedError(
                "Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented"
            )
        corners = self._split_into_corners()
        if method == FLIP_LEFT_RIGHT:
            for corner in corners:
                # if self.frame == "velodyne":
                #     corner[:, :] = self.project_world_to_rect(corner, self.pose)
                #     corner[:, 0] = -corner[:, 0]
                #     corner[:, :] = self.project_rect_to_world(corner, self.pose)
                # else:
                corner[:, 0] = -corner[:, 0]

        if method == FLIP_TOP_BOTTOM:
            for corner in corners:
                corner[:, 1] = -corner[:, 1]

        bbox_3d = torch.stack(corners, dim=1)
        if method == FLIP_LEFT_RIGHT:
            bbox_3d = bbox_3d[:, [4, 5, 6, 7, 0, 1, 2, 3]]
        bbox_3d = bbox_3d.view(-1, 24)
        box_3d_list = Box3DList(bbox_3d, mode="corners", frame=self.frame)

        return box_3d_list

    # Tensor-like methods
    def to(self, device):
        bbox_3d = Box3DList(self.bbox_3d.to(device), self.mode, frame=self.frame)
        for k, v in self.extra_fields.items():
            if hasattr(v, "to"):
                v = v.to(device)
            bbox_3d.add_field(k, v)
        return bbox_3d

    def resize(self, size, *args, **kwargs):
        # TODO make sure image size is not changed before finished this part
        """
        Returns a resized copy of this bounding box

        :param size: The requested size in pixels, as a 2-tuple:
            (width, height).
        """
        return self

    def rotate(self, angle, gt_alpha):
        bbox_3d = self.convert('xyzhwl_ry').bbox_3d

        aug_gt_boxes3d = PointCloud.rotate_pc_along_y(bbox_3d, rot_angle=angle)

        # calculate the ry after rotation
        x, z = aug_gt_boxes3d[:, 0], aug_gt_boxes3d[:, 2]
        beta = torch.atan2(z, x)
        gt_alpha = torch.from_numpy(gt_alpha).to(self.device).float()
        new_ry = torch.sign(beta) * np.pi / 2 + gt_alpha - beta
        aug_gt_boxes3d[:, 6] = new_ry  # TODO: not in [-np.pi / 2, np.pi / 2]
        return Box3DList(aug_gt_boxes3d, 'xyzhwl_ry', frame=self.frame).convert('corners')

    def scale(self, scale):
        bbox_3d = self.convert('xyzhwl_ry').bbox_3d
        bbox_3d[:, :6] *= scale
        return Box3DList(bbox_3d, 'xyzhwl_ry', frame=self.frame).convert('corners')

    def crop(self, box):
        return self

    def clip_to_image(self, remove_empty=True):
        return self

    def area(self):
        bbox_3d = self.bbox_3d
        if self.mode == "corners":
            corners = self._split_into_corners()
            l = torch.norm((corners[0] - corners[4]), dim=1).reshape(-1, 1)
            h = torch.norm((corners[0] - corners[1]), dim=1).reshape(-1, 1)
            w = torch.norm((corners[0] - corners[3]), dim=1).reshape(-1, 1)
            area = l * h * w
        else:
            _, l, h, w, _, _, _ = self._split_into_ry_lhwxyz()
            area = l * h * w

        return area

    def project_to_2d(self, P):
        """
        project the 3d bbox to camera plane using the intrinsic
        :param P: the intrinsic and extrinsics of camera. shape: (3, 4)
        :return bbox_2d: the projected bbox in camera plane, shape: (N, 8, 2)
        """
        box_3d_list = self.convert("corners")
        bbox_3d = box_3d_list.bbox_3d
        bbox_3d = bbox_3d.view(-1, 8, 3)

        n = bbox_3d.shape[0]
        ones = torch.ones((n, 8, 1)).to(self.bbox_3d.device)
        bbox_3d = torch.cat([bbox_3d, ones], dim=-1)
        bbox_2d = torch.matmul(P, bbox_3d.permute(0, 2, 1)).permute(0, 2, 1)

        # (N, 8, 2)
        valid = bbox_2d[:, :, 2] > 0.5

        bbox_2d = torch.stack((bbox_2d[:, :, 0] / bbox_2d[:, :, 2], bbox_2d[:, :, 1] / bbox_2d[:, :, 2]), dim=2)
        return bbox_2d, valid

    def enlarge_box3d(self, extra_width):
        boxes3d = self.convert("xyzhwl_ry").bbox_3d
        large_boxes3d = boxes3d.clone()
        large_boxes3d[:, 3:6] += extra_width * 2
        large_boxes3d[:, 1] += extra_width
        box_3d_list = Box3DList(large_boxes3d, mode="xyzhwl_ry", frame=self.frame).convert(self.mode)
        return box_3d_list

    @staticmethod
    def get_faces():
        return [[2, 3, 7, 6],
                [2, 3, 0, 1],
                [6, 7, 4, 5],
                [0, 1, 5, 4],
                [0, 4, 5, 1],
                [5, 6, 2, 1]]

    def __repr__(self):
        s = self.__class__.__name__ + "("
        s += "num_boxes_3d={}, ".format(len(self))
        s += "mode={})".format(self.mode)
        return s

    def filter_out_point_cloud(self, pointcloud):
        """
        filter pointcloud
        @param pointcloud: nx3
        @return: bool tensor with shape (n, )
        """
        from disprcnn.utils.utils_3d import filter_bbox_3d
        assert pointcloud.shape[1] == 3
        if not isinstance(pointcloud, torch.Tensor):
            pointcloud = torch.tensor(pointcloud).float()
        all_corners = self.convert('corners').bbox_3d.reshape(-1, 8, 3)
        keeps = torch.zeros(pointcloud.shape[0]).bool()
        for corners in all_corners:
            _, _, keep = filter_bbox_3d(corners, pointcloud)
            keeps = keeps | keep
        keeps = ~keeps
        return keeps

if __name__ == "__main__":
    # euler = (-0.06113487224401537, -0.010398221352184765, 0.35926017719345693)
    bbox_3d = torch.tensor([[-39.5482, 1.0015, 72.5878],
                            [-39.5280, -0.9614, 72.4898],
                            [-44.6086, -1.0026, 72.2687],
                            [-44.6288, 0.9603, 72.3666],
                            [-39.6350, 0.9002, 74.5999],
                            [-39.6148, -1.0627, 74.5020],
                            [-44.6954, -1.1039, 74.2808],
                            [-44.7155, 0.8590, 74.3788]], dtype=torch.float32)

    bbox_3d = bbox_3d.view(1, -1)

    box_3d_list = Box3DList(bbox_3d, (1280, 720))
    box_3d_list = box_3d_list.convert("ry_lhwxyz")
    # print("-----------convert to ry_lhwxyz-----------")
    # print("after convert: {}, annotation: {}".format(box_3d_list.bbox_3d[0, 0], euler[2]))
    # print("dif: {}".format(torch.norm(box_3d_list.bbox_3d[0, 0] - euler[2])))

    box_3d_list = box_3d_list.convert("corners")
    print("-----------convert to corners-----------")
    print("after convert: {}".format(box_3d_list.bbox_3d))
    print("annotation: {}".format(bbox_3d))
    print("dif: {}".format(torch.norm(box_3d_list.bbox_3d - bbox_3d)))


import tkinter as tk
import threading

import Crawl

# https://freemediatools.com

class Application(tk.Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.insert = tk.Entry(self)
        self.insert.pack(side="top", ipadx=200, padx=20, pady=20)
        self.insert.focus_set()

        self.btn_submit = tk.Button(self)
        self.btn_submit["text"] = "Click Here"
        self.btn_submit["command"] = self.execute_crawl_url
        self.btn_submit.pack(side="top")

        self.quit = tk.Button(
            self, text="QUIT", fg="red", command=root.destroy
        )

        self.quit.pack(side="bottom")

    def execute_crawl_url(self):
        url = self.insert.get()
        print(" ~ Executed url: " + url)
        process = threading.Thread(
            target=Crawl.Main, args=(self.insert.get(),)
        )
        process.start()

root = tk.Tk()
app = Application(master=root)
app.mainloop()


import os
import time
import asyncio
import xsensdot_pc_sdk
from PySide6.QtWidgets import QMainWindow, QFileDialog
from GUI.ui_windows import Ui_MainWindow
from PySide6.QtCore import QThread, Signal  # pyside6里面变成了signal
from xd_sdk_read import MeasureCtrl, CallbackHandler
from user_settings import measuremode_dic

class CtrlWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.tlis = []
        self.acc_xyzlis = [[],[],[]]
        self.gyr_xyzlis = [[],[],[]]
        self.MeasureCtrl = MeasureCtrl()
        self.allscan_devicelist = None
        self.fpdia = os.getcwd()  # 默认设置为当前路径

        # 工具栏和按钮绑定
        self.action_setpath.triggered.connect(self.mfileopen)
        self.action_stm.triggered.connect(self.measurethread_start)
        self.action_stop.triggered.connect(self.stopmeasure)
        self.pushButton_startscan.clicked.connect(self.scanthread_start)
        self.pushButton_stopscan.clicked.connect(self.stopscan)
        self.pushButton_refresh.clicked.connect(self.refresh)
        self.pushButton_connect.clicked.connect(self.scanthread_start)

        self.scanthread = ScanThread()
        self.scanthread.scanstextSignal.connect(self.logshow)
        self.scanthread.dotsSignal.connect(self.premeasureset)

        # measurement的设置控件绑定
        self.lineEdit_measuretime.inputRejected.connect(lambda :self.lineEdit_measuretime.setText("input measure time (s)"))
        self.lineEdit_measuretime.returnPressed.connect(self.getlineedit)
        self.comboBox_meauremode.currentIndexChanged.connect(self.getmeasuremode)

        # 一些测试的参数会通过这个地方传入给测试线程
        self.measurethread = MeasureThread()
        self.measurethread.measurelogSignal.connect(self.logshow)  # 数据传输至log端显示
        self.measurethread.measuredataSignal.connect(self.getrawdata) # 数据传输出来处理并绘图

    def refresh(self):
        self.MeasureCtrl.callback.clearDetectedDots()
        self.comboBox_dotlist.clear()
        self.graphicsView_acc.refreshclear()
        self.graphicsView_gyr.refreshclear()
        self.scanthread.connectedDOTCount = 0
        self.scanthread.scan_status = True
        if self.MeasureCtrl.manager is not None:
            self.MeasureCtrl.manager.close()

    def getlineedit(self):
        inputtext = self.lineEdit_measuretime.text()
        if inputtext.isdigit():
            self.measurethread.setmeasuretime = int(inputtext)*1000
            print(self.measurethread.setmeasuretime)
            self.textBrowser.append(f'measure time has been set!=={self.measurethread.setmeasuretime/1000}s')
        else:
            print('please input digital!')
            self.textBrowser.append('please input digital!')

    def getmeasuremode(self):
        comboboxmode = self.comboBox_meauremode.currentText()
        self.measurethread.measuremode = measuremode_dic[comboboxmode]
        self.textBrowser.append(f'measuremode change to =#{comboboxmode}#=!')

    def mfileopen(self):
        self.fpdia = QFileDialog.getExistingDirectory(None, "设置文件存储路径", os.path.join(os.getcwd(),'Data/'))  # 起始路径
        self.measurethread.logdirpath = self.fpdia
        # self.measurethread.logdirpath = os.path.join(self.fpdia,'data/')
        # if not os.path.exists(self.measurethread.logdirpath):
        #     os.mkdir(self.measurethread.logdirpath)
        self.textBrowser.append(f'data save path---【{self.measurethread.logdirpath}】 ')

    # 连接到两个信号，进行扫描和连接两种操作，这里需要对传过来的参数进行一个判断
    def scanthread_start(self):
        if self.sender() == self.pushButton_startscan:
            self.scanthread.scan_status = True
            self.scanthread.connect_status = False
        if self.sender() == self.pushButton_connect:
            self.scanthread.connect_status = True
            self.scanthread.scan_status = False
            self.scanthread.choose_dot_addr = [i for i in self.comboBox_dotlist.getCheckItem()]
        self.scanthread.start()

    def stopscan(self):
        self.scanthread.scan_status = False
        print("Stopped scanning for devices.")
        # 结束扫描之后，就将xsens dot的地址给传到logshow框中显示出来

    def logshow(self, message):
        self.textBrowser.append(message)

    def premeasureset(self, dotmessage):
        '''完成dot的初始化的配置，收集dot的一些基本信息，如电量等信息'''
        if isinstance(dotmessage,str):
            if dotmessage not in self.comboBox_dotlist.getCheckItem():
                self.comboBox_dotlist.addItem(dotmessage)
        if isinstance(dotmessage,dict): # {'choosedevicelist':self.choose_devicelist,'chooseDetectedDots':chooseDetectedDots}
            self.measurethread.choose_devicelist = dotmessage['choosedevicelist']
            # 这里需要将callback上面的 m_detectedDots 对象改成和选择的一致，这个是测试之前的准备工作
            self.MeasureCtrl.callback.chooseDetectedDots(dotmessage['chooseDetectedDots'])

    def measurethread_start(self):
        if len(self.scanthread.choose_devicelist) == 0:
            print('please choose dot to connect first!')
            self.textBrowser.append('please choose dot to connect first!')
            self.measurethread.measurestatus = False
        else:
            self.measurethread.measurestatus = True
            print(f"choosed dots: @{[i for i in self.scanthread.choose_dot_addr]}")
            self.textBrowser.append(f"choosed dots: @{[i for i in self.scanthread.choose_dot_addr]}")
            self.measurethread.start()

    def stopmeasure(self):
        self.measurethread.measurestatus = False
        # self.textBrowser.append(f"stop measurement!")

    def getrawdata(self,data_dic):
        # 后面需要考虑将送过来的原始数据进行什么样的处理，然后绘图等这些，目前仅仅绘制了两个plot
        device_addr = list(data_dic.keys())[0]
        # self.legend1.setText(device_addr)
        xs_t = data_dic[device_addr]['time']
        acc_xyz = data_dic[device_addr]['acc']
        gyr_xyz = data_dic[device_addr]['gyr']
        self.tlis.append(xs_t)
        self.acc_xyzlis.append(self.tlis)
        self.gyr_xyzlis.append(self.tlis)

        # 左边图绘制x方向上的加速度数据
        for i in range(3):
            self.acc_xyzlis[i].append(acc_xyz[i])
        self.graphicsView_acc.setTitle(f'RT Acc from {device_addr}')
        self.graphicsView_acc.setLabel("left", "Acc x (g/s2)",**{"color": "k", "font-size": "10px"})
        self.graphicsView_acc.update_ch(self.acc_xyzlis)

        # 右边图绘制x方向上的角速度数据
        for i in range(3):
            self.gyr_xyzlis[i].append(gyr_xyz[i])
        self.graphicsView_gyr.setTitle(f'RT Gyr from {device_addr}')
        self.graphicsView_gyr.setLabel("left", "Gyr x (rad/s)",**{"color": "k", "font-size": "10px"})
        self.graphicsView_gyr.update_ch(self.gyr_xyzlis)

# 添加一个搜索线程类，用于处理各种耗时的阻塞工作
class ScanThread(QThread):
    scanstextSignal = Signal(str)
    dotsSignal = Signal(object)  # 传递信号的种类

    def __init__(self):
        super().__init__()
        self.connectedDOTCount = 0 # 连接的xensdot数目
        self.scan_status = False
        self.connect_status = False
        self.MesureCtrl = MeasureCtrl()
        self.choose_dot_addr = None
        self.choose_devicelist = []

    def connectchoosedot(self):
        if len(self.choose_dot_addr) == 0:
            self.scanstextSignal.emit('please choose dots first!')
            print('please choose dots first!')
        else:
            st = time.perf_counter()
            self.scanstextSignal.emit('start connect...')
            chooseDetectedDots = []
            getDetectedDots = self.MesureCtrl.callback.getDetectedDots()
            for portInfo in getDetectedDots:
                address = portInfo.bluetoothAddress()
                if address in self.choose_dot_addr:
                    chooseDetectedDots.append(portInfo)
            # devicelist = self.MesureCtrl.getdevicelist(chooseDetectedDots) # 总共时间消耗： 15.603464700000002
            devicelist = asyncio.run(self.MesureCtrl.gdmain(chooseDetectedDots)) # 总共时间消耗： 总共时间消耗： 15.419088600000002
            self.choose_devicelist = devicelist
            # 把选择的原始chooseDetectedDots递上，以及处理过的devicelist递上；准备后续测试
            self.dotsSignal.emit({'choosedevicelist':self.choose_devicelist,'chooseDetectedDots':chooseDetectedDots})
            et = time.perf_counter()
            print('总共时间消耗：',et-st)
            self.scanstextSignal.emit(f"All choosed dots have been connected! you can start measurement!")

    # 开启一个线程用于搜索dots，默认搜索20s（20000）；并且进行处理dot的连接
    def run(self):
        if self.connect_status:
            self.connectchoosedot()
        if self.scan_status:
            print("Scanning for devices...")
            self.MesureCtrl.manager.enableDeviceDetection()
            # xsensdot_pc_sdk.XsTimeStamp_nowMs() - self.MesureCtrl.startTime <= 20000:
            scanstartTime = xsensdot_pc_sdk.XsTimeStamp_nowMs()
            while not self.MesureCtrl.callback.errorReceived() and self.scan_status:
                if not self.scan_status:
                    self.scan_status = False
                    self.MesureCtrl.manager.disableDeviceDetection()
                    break
                time.sleep(0.1)
                scan_time = (xsensdot_pc_sdk.XsTimeStamp_nowMs() - scanstartTime) / 1000
                print(f"\r scan time {scan_time} s...", end="")
                # self.scanstextSignal.emit(f"scan time {scan_time} s...")
                getDetectedDots = self.MesureCtrl.callback.getDetectedDots() # 注意这个一次while循环只能调用一次
                nextCount = len(getDetectedDots)
                if nextCount != self.connectedDOTCount:
                    deviceadress = getDetectedDots[nextCount - 1].bluetoothAddress()
                    print(f"Number of connected DOTs: {nextCount}---@{deviceadress}")
                    self.connectedDOTCount = nextCount
                    self.scanstextSignal.emit(
                        f"scan time {scan_time} s...Number of connected DOTs: {nextCount}---@{deviceadress}")  # 将扫描状态传过去
                    self.scanstextSignal.emit(f'DOT-{nextCount}--{deviceadress}')
            for d in self.MesureCtrl.callback.m_detectedDots:
                self.dotsSignal.emit(d.bluetoothAddress()) # 没有选择的dot递到bombobox里面
            self.scanstextSignal.emit(f'scan complete!')

        return True

# 添加一个数据采集和接受的线程
class MeasureThread(QThread):
    measurestatusSignal = Signal(str)
    measurelogSignal = Signal(str)
    measuredataSignal = Signal(dict)  # 传递信号的种类

    def __init__(self):
        super().__init__()
        self.choose_devicelist = []
        # self.logoption = kwargs['logoption']
        self.setmeasuretime = 7200000
        self.logdirpath = None
        self.measurestatus = False
        self.MesureCtrl = MeasureCtrl()
        self.measuremode = xsensdot_pc_sdk.XsPayloadMode_RateQuantities

    # 判断是否要打开log记录存储（默认存储），设置measure模式，进行测试
    def run(self):
        for device in self.choose_devicelist:
            self.MesureCtrl.startrelog(device, self.logdirpath)
        asyncio.run(self.MesureCtrl.msmain(self.choose_devicelist,measuremode=self.measuremode))  # 设置开始测试模式

        # 设置log头部
        s = ""
        for device in self.choose_devicelist:
            s += f"{device.portInfo().bluetoothAddress():42}"
        print("%s" % s, flush=True)
        self.measurelogSignal.emit(s)  # 将数据头传到log界面
        # 开始测试模块
        orientationResetDone = False
        measuretartTime = xsensdot_pc_sdk.XsTimeStamp_nowMs()
        while xsensdot_pc_sdk.XsTimeStamp_nowMs() - measuretartTime <= self.setmeasuretime:
            if not self.measurestatus:
                # 结束前需要进行一个方向重置
                for device in self.choose_devicelist:
                    print(f"\nResetting heading to default for device {device.portInfo().bluetoothAddress()}: ", end="",
                          flush=True)
                    self.measurelogSignal.emit(
                        f"\nResetting heading to default for device {device.portInfo().bluetoothAddress()}: ")
                    if device.resetOrientation(xsensdot_pc_sdk.XRM_DefaultAlignment):
                        print("OK", end="", flush=True)
                        self.measurelogSignal.emit("OK")
                    else:
                        print(f"NOK: {device.lastResultText()}", end="", flush=True)
                        self.measurelogSignal.emit(f"NOK: {device.lastResultText()}")
                print("\n", end="", flush=True)

                print("\nStopping measurement...")
                self.measurelogSignal.emit("\nStopping measurement...")
                for device in self.choose_devicelist:
                    if not device.stopMeasurement():
                        print("Failed to stop measurement.")
                        self.measurelogSignal.emit("Failed to stop measurement.")
                    if not device.disableLogging():
                        print("Failed to disable logging.")
                        self.measurelogSignal.emit("Failed to disable logging.")
                print("Closing ports...")
                self.measurelogSignal.emit("Closing ports...")
                self.MesureCtrl.manager.close()
                break

            if self.MesureCtrl.callback.packetsAvailable():
                datas = ""
                for device in self.choose_devicelist:
                    # Retrieve a packet
                    device_addr = device.portInfo().bluetoothAddress()
                    data_dic = {device_addr:{}}
                    packet = self.MesureCtrl.callback.getNextPacket(device_addr)
                    # containsRawAcceleration rawAcceleration
                    xs_time = xsensdot_pc_sdk.XsTimeStamp_nowMs() - measuretartTime
                    data_dic[device_addr]['time'] = xs_time
                    # 这里设置数据输入和输出的接口
                    if packet.containsCalibratedAcceleration():
                        acc = packet.calibratedAcceleration() # array
                        datas += f"Acc_x:{acc[0]:7.2f}, Acc_y:{acc[1]:7.2f}, Acc_z:{acc[2]:7.2f}| "
                        data_dic[device_addr]['acc'] = list(acc)
                    if packet.containsCalibratedGyroscopeData():
                        gyr = packet.calibratedGyroscopeData() # array
                        datas += f"Gyr_x:{gyr[0]:7.2f}, Gyr_y:{gyr[1]:7.2f}, Gyr_z:{gyr[2]:7.2f}| "
                        data_dic[device_addr]['gyr'] = list(gyr)
                    # if packet.containsOrientation(): # 目前只设定接受两种数据
                    #     euler = packet.orientationEuler() # array
                    #     datas += f"Roll:{euler[0]:7.2f}, Pitch:{euler[1]:7.2f}, Yaw:{euler[2]:7.2f}| "
                    #     data_dic[device_addr]['euler'] = list(euler)
                print("%s\r" % datas, end="", flush=True)
                self.measurelogSignal.emit(datas)
                self.measuredataSignal.emit(data_dic)

                # 在开始的前5秒进行一个方向重置
                if not orientationResetDone and xsensdot_pc_sdk.XsTimeStamp_nowMs() - measuretartTime >= 5000:
                    for device in self.choose_devicelist:
                        print(f"\nResetting heading for device {device.portInfo().bluetoothAddress()}: ", end="",
                              flush=True)
                        self.measurelogSignal.emit(
                            f"\nResetting heading for device {device.portInfo().bluetoothAddress()}: ")
                        if device.resetOrientation(xsensdot_pc_sdk.XRM_Heading):
                            print("OK", end="", flush=True)
                            self.measurelogSignal.emit("OK")
                        else:
                            print(f"NOK: {device.lastResultText()}", end="", flush=True)
                            self.measurelogSignal.emit(f"NOK: {device.lastResultText()}")
                    print("\n", end="", flush=True)
                    self.measurelogSignal.emit("\n")
                    orientationResetDone = True
        print("\n----------------------over!-------------------", end="", flush=True)
        self.measurelogSignal.emit("\n---------------------over!--------------------")
        return True