"""Contains PyTorch Lightning LightningModule class for multimodal contrastive learning."""

import torch
from torch import nn, Tensor
from pytorch_lightning import LightningModule
from simclr.modules import NT_Xent, LARS

class MultimodalLearning(LightningModule):
    def __init__(
        self,
        args,
        encoder: nn.Module,
        video_crop_length_sec: int,
        video_n_features: int,
        video_lstm_n_layers: int = 2,
    ):
        super().__init__()
        self.save_hyperparameters(args)

        # dimensionality of representation:
        self.n_features = self.encoder.output_size

        # audio encoder:
        self.encoder = encoder
        # keep first 4 convolutional blocks frozen:
        c0, c1 = 0, 0
        for child in self.encoder.children():
            for block in child.children():
                for param in block.parameters():
                    param.requires_grad = False
                c1 += 1
                if c1 > 3:
                    break
            c0 += 1
            if c0 > 0:
                break

        # audio projector:
        self.audio_projector = nn.Sequential(
            nn.Linear(self.n_features, self.n_features, bias=False),
            nn.ReLU(),
            nn.Linear(self.n_features, self.hparams.projection_dim, bias=False),
        )
        # full audio model (encoder + projector):
        self.audio_model = nn.Sequential(self.encoder, self.audio_projector)

        # video temporal model:
        self.video_temporal = nn.LSTM(
            input_size=video_n_features,
            hidden_size=video_n_features,
            num_layers=video_lstm_n_layers,
            batch_first=True,
            dropout=0.1,
        )
        # video encoder:
        self.video_encoder = nn.Sequential(
            nn.Flatten(),
            nn.Linear(video_crop_length_sec * video_n_features, self.n_features),
            nn.ReLU(),
        )

        # video projector:
        self.video_projector = nn.Sequential(
            nn.Linear(self.n_features, self.n_features, bias=False),
            nn.ReLU(),
            nn.Linear(self.n_features, self.hparams.projection_dim, bias=False),
        )
        # video model (encoder + projector):
        self.video_model = nn.Sequential(self.video_encoder, self.video_projector)

        # criterion function:
        self.criterion = self.configure_criterion()

    def forward(self, x_i: Tensor, x_j: Tensor) -> Tensor:
        z_i = self.audio_model(x_i)
        x_j, _ = self.video_temporal(x_j)
        z_j = self.video_model(x_j)
        return self.criterion(z_i, z_j)

    def training_step(self, batch, _) -> Tensor:
        x_i, x_j, _ = batch
        loss = self.forward(x_i, x_j)
        self.log("Train/loss", loss)
        return loss

    def validation_step(self, batch, _) -> Tensor:
        x_i, x_j, _ = batch
        loss = self.forward(x_i, x_j)
        self.log("Valid/loss", loss)
        return loss

    def configure_criterion(self) -> nn.Module:
        # PT lightning aggregates differently in DP mode
        if self.hparams.accelerator == "dp" and self.hparams.gpus:
            batch_size = int(self.hparams.batch_size / self.hparams.gpus)
        else:
            batch_size = self.hparams.batch_size

        criterion = NT_Xent(batch_size, self.hparams.temperature, world_size=1)
        return criterion

    def configure_optimizers(self) -> dict:
        scheduler = None
        if self.hparams.optimizer == "Adam":
            optimizer = torch.optim.AdamW(
                self.parameters(), lr=5e-4
            )  # self.hparams.learning_rate)
        elif self.hparams.optimizer == "LARS":
            # optimized using LARS with linear learning rate scaling
            # (i.e. LearningRate = 0.3 × BatchSize/256) and weight decay of 1e−6.
            learning_rate = 0.3 * self.hparams.batch_size / 256
            optimizer = LARS(
                self.parameters(),
                lr=learning_rate,
                weight_decay=self.hparams.weight_decay,
                exclude_from_weight_decay=["batch_normalization", "bias"],
            )

            # "decay the learning rate with the cosine decay schedule without restarts"
            scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
                optimizer, self.hparams.max_epochs, eta_min=0, last_epoch=-1
            )
        else:
            raise NotImplementedError

        if scheduler:
            return {"optimizer": optimizer, "lr_scheduler": scheduler}
        else:
            return {"optimizer": optimizer}


from typing import List
class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:

        board = [['.'] * n for _ in range(n)]
        self.n = n
        self.result = []
        self.col = [False] * n
        self.diag, self.codiag = set(), set()
        self.backtrack(board, 0)
        return self.result
    def backtrack(self, board, row):
        if row == self.n:
            strTmp = [''.join(row) for row in board]
            self.result.append(strTmp)
        for c in range(self.n):
            if self.valid(row, c):
                board[row][c] = 'Q'
                self.col[c] = True
                self.diag.add(row+c)
                self.codiag.add(row-c)
                self.backtrack(board, row + 1)
                board[row][c] = '.'
                self.col[c] = False
                self.diag.remove(row+c)
                self.codiag.remove(row-c)
    def valid(self, row, col):
        return not (self.col[col] or row+col in self.diag or row-col in self.codiag)
if __name__ == "__main__":
    s = Solution()
    s.solveNQueens(3)
    pass


#!/usr/bin/env python
# coding: utf-8

import os
import time
import argparse
import numpy as np
import logging

import torch
from torchvision import models
from torchvision import transforms
from PIL import Image

import tensorrt as trt
import engine as eng
from onnx import ModelProto

import pycuda.driver as cuda
import pycuda.autoinit

# #### Directly convert keras model to TensorRT
def convert_tf_to_onnx():
    # tf2onnx module needs to be installed in order to use this function
    import onnx
    import tf2onnx
    img0, x = process_images('./data/img0.jpg')
    model_proto, external_tensor_storage = tf2onnx.convert.from_keras(model, input_signature=[tf.TensorSpec(shape=x.shape, dtype=tf.float32)])
    onnx.save(model_proto,'./resnet50_model_tf/resnet50_tf_onnx.onnx"')
    # ! python3 -m tf2onnx.convert --saved-model "./resnet50_model_tf" --output "./resnet50_model_tf/resnet50_tf_onnx.onnx"
    return

def convert_torch_to_onnx(model_name):
    # https://pytorch.org/docs/stable/onnx.html
    size= 224
    # Pre-process the image and convert into a tensor
    transform = transforms.Compose([
        transforms.Resize(size),
        transforms.CenterCrop(size),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                        std=[0.229, 0.224, 0.225]),
    ])
    if model_name == "mobilenet_v2":
        trained_model = models.mobilenet_v2(pretrained=True)
    else:
        trained_model = models.resnet50(pretrained=True)

    img_path = './data/img0.jpg'
    img = Image.open(img_path).convert('RGB')
    dummy_input = transform(img).unsqueeze(0)
    onnx_output = 'model/' + model_name + '_torch_onnx.onnx'
    torch.onnx.export(trained_model, dummy_input, onnx_output)
    # torch.onnx.export(trained_model, dummy_input, onnx_output, dynamic_axes={"actual_input_1":{0:"batch_size"}, "output2":{0:"batch_size"}})

    # visualise onnx model
    # ! python3 -m pip install netron
    # http://localhost:8080/
    return

def process_images(img_path):
    # read input image
    input_img = Image.open(img_path).convert('RGB')

    # transform image for the input data
    preprocess = transforms.Compose([
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize(
            mean=[0.485, 0.456, 0.406],
            std=[0.229, 0.224, 0.225]
        )])
    input_data = preprocess(input_img)
    batch_data = torch.unsqueeze(input_data, 0)
    return input_img, batch_data#.cuda()

def decode_predictions(out):
    # Load the file containing the 1,000 labels for the ImageNet dataset classes
    # imagenet label: https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a

    with open('./data/imagenet_classes.txt') as f:
        labels = [line.strip() for line in f.readlines()]

    # find the index (tensor) corresponding to the maximum score in the out tensor.
    out_list = out.tolist()
    max_value = max(out_list)
    max_index = out_list.index(max_value)

    return labels[max_index]

def predict_images(num_images, engine, h_input_1, d_input_1, h_output, d_output, stream):

    height, width = 224, 224
    time_list = []
    for i in range(num_images):
        img_path = 'data/img%d.jpg'%i
        input_img, batch_data = process_images(img_path)
        pics_1 = batch_data
        batch_size = 1
        # start timing # ========
        # start_time = time.time()
        out, inference_time = do_inference(engine, pics_1, h_input_1, d_input_1, h_output, d_output, stream, batch_size, height, width)
        # end_time = time.time()
        # end timing # ========

        # calculate inference time
        # inference_time = ( end_time - start_time ) * 1000
        time_list.append(inference_time)

        # decode the result
        decoded_result = decode_predictions(out)
        print('Image {}: {:4.1f}ms => {}'.format(i, inference_time, decoded_result))
    print ("median time: {} ms".format(np.median(time_list)))
    return

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

# build engine using onnx model
def build_engine_from_onnx(onnx_path, engine_name, batch_size, TRT_LOGGER):
    model = ModelProto()
    with open(onnx_path, "rb") as f:
        model.ParseFromString(f.read())

    d0 = model.graph.input[0].type.tensor_type.shape.dim[1].dim_value
    d1 = model.graph.input[0].type.tensor_type.shape.dim[2].dim_value
    d2 = model.graph.input[0].type.tensor_type.shape.dim[3].dim_value
    shape = [batch_size , d0, d1 ,d2]
    engine = eng.build_engine(TRT_LOGGER, onnx_path, shape= shape)
    eng.save_engine(engine, engine_name)
    return engine

# Running inference from the TensorRT engine:
def allocate_buffers(engine, batch_size, data_type):

    """
    This is the function to allocate buffers for input and output in the device
    Args:
        engine : The path to the TensorRT engine.
        batch_size : The batch size for execution time.
        data_type: The type of the data for input and output, for example trt.float32.

    Output:
        h_input_1: Input in the host.
        d_input_1: Input in the device.
        h_output_1: Output in the host.
        d_output_1: Output in the device.
        stream: CUDA stream.

    """

    # Determine dimensions and create page-locked memory buffers (which won't be swapped to disk) to hold host inputs/outputs.
    h_input_1 = cuda.pagelocked_empty(batch_size * trt.volume(engine.get_binding_shape(0)), dtype=trt.nptype(data_type))
    h_output = cuda.pagelocked_empty(batch_size * trt.volume(engine.get_binding_shape(1)), dtype=trt.nptype(data_type))

    # Allocate device memory for inputs and outputs.
    d_input_1 = cuda.mem_alloc(h_input_1.nbytes)
    d_output = cuda.mem_alloc(h_output.nbytes)

    # Create a stream in which to copy inputs/outputs and run inference.
    stream = cuda.Stream()
    return h_input_1, d_input_1, h_output, d_output, stream

def load_images_to_buffer(pics, pagelocked_buffer):
    preprocessed = np.asarray(pics).ravel()
    np.copyto(pagelocked_buffer, preprocessed)

def do_inference(engine, pics_1, h_input_1, d_input_1, h_output, d_output, stream, batch_size, height, width):
    """
    This is the function to run the inference
    Args:
        engine : Path to the TensorRT engine
        pics_1 : Input images to the model.
        h_input_1: Input in the host
        d_input_1: Input in the device
        h_output_1: Output in the host
        d_output_1: Output in the device
        stream: CUDA stream
        batch_size : Batch size for execution time
        height: Height of the output image
        width: Width of the output image

    Output:
        The list of output images

    """

    load_images_to_buffer(pics_1, h_input_1)

    with engine.create_execution_context() as context:
        # Transfer input data to the GPU.
        cuda.memcpy_htod_async(d_input_1, h_input_1, stream)

        # Run inference.
        # start timing # ========
        start_time = time.time()
        # context.profiler = trt.Profiler()
        context.execute(batch_size=1, bindings=[int(d_input_1), int(d_output)])
        end_time = time.time()
        # end timing # ========
        # calculate inference time
        inference_time = ( end_time - start_time ) * 1000
        # print ("inference time: {}".format(inference_time))

        # Transfer predictions back from the GPU.
        cuda.memcpy_dtoh_async(h_output, d_output, stream)
        # Synchronize the stream
        stream.synchronize()
        # Return the host output.
        # out = h_output.reshape((batch_size, -1, height, width))
        out = h_output
        return out, inference_time

def main():
    # set up arguments
    run_case = args.case
    num_images = int(args.num_img)
    model_name = args.model_name

    # set up logging to file - see previous section for more details
    log_filename = "logs/output_tensorrt_{}_{}.log".format(model_name, run_case)
    os.makedirs(os.path.dirname(log_filename), exist_ok=True)
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                        datefmt='%m-%d %H:%M',
                        filename=log_filename,
                        filemode='w')
    logging.getLogger('tensorrt')
    logging.info("#### start model prediction ####")

    # logger to capture errors, warnings, and other information during the build and inference phases
    TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
    trt_runtime = trt.Runtime(TRT_LOGGER)

    # check model directory
    os.makedirs(os.path.dirname("model/"), exist_ok=True)

    # check data availability
    logging.info("check if data is available")
    logging.info("check data")
    if not os.path.exists("data"):
        return logging.error('check if data is available or run download_images.py for generating sample dataset')

    batch_size = 1
    # running inference from tensorrt
    logging.info("check engine")
    engine_name = "model/" + model_name + "_" + run_case + ".plan"
    if os.path.exists(engine_name):
        engine = eng.load_engine(trt_runtime, engine_name)
    else:
        onnx_path = "model/" + model_name + "_" + run_case + ".onnx"
        if not os.path.exists(onnx_path):
            logging.info("convert_torch_to_onnx")
            convert_torch_to_onnx(model_name)
        logging.info("build_engine_from_onnx")
        engine = build_engine_from_onnx(onnx_path, engine_name, batch_size, TRT_LOGGER)

    logging.info("start interference")
    data_type = trt.float32
    logging.info("allocate_buffers")
    h_input_1, d_input_1, h_output, d_output, stream = allocate_buffers(engine, batch_size, data_type)

    # predict images
    logging.info("do_inference")
    predict_images(num_images, engine, h_input_1, d_input_1, h_output, d_output, stream)

    return

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'TensorRT')
    parser.add_argument('-model_name', help='select model: resnet50(default), mobilenet_v2', default="resnet50", type=str, required=True)
    parser.add_argument('-case', help='select case: ', type=str, required=True)
    parser.add_argument('-num_img', help='set number of images to be run', type=int, required=True)
    args = parser.parse_args()
    main()

# python3 compare_tensorrt_native.py -model_name "resnet50" -case "torch_onnx" -num_img 10
# python3 compare_tensorrt_native.py -model_name "resnet50" -case "tf_onnx" -num_img 10


import requests

def handle_no_ban():
    print('No bans detected')

def handle_ban(body_json):
    ban_count = len(body_json['bans'])
    can_appeal = body_json['canAppeal']
    ban_info = body_json['bans']
    print('Ban count: ' + str(ban_count))
    print('Can appeal: ' + str(can_appeal))
    print('Ban info: ' + str(ban_info))

if __name__ == '__main__':
    SSO_TOKEN = '' # SET SSO TOKEN HERE

    response = requests.get('https://prod-psapi.infra-ext.activision.com/api/bans/appeal', cookies={'ACT_SSO_COOKIE': SSO_TOKEN})

    if response.status_code != 200:
        raise Exception('Non-200 status returned: ' + str(response.status_code))

    body = response.json()
    ban_count = len(body['bans'])
    if (ban_count == 0):
        handle_ban(body)
    else:
        handle_no_ban()


import numpy as np
import os
import cv2
import time
import mediapipe as mp

savePath = './face_recognition/FaceDetected'

def collate_fn(x):
    return x[0]

cap = cv2.VideoCapture(0)

# Ensure video file is opened
if not cap.isOpened():
    print("Error opening video file")
    exit()

mp_face_mesh = mp.solutions.face_mesh
face_mesh = mp_face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5)

mp_drawing = mp.solutions.drawing_utils

drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)

angleFaces = []
Forward = 'Forward'
Below = 'Below'
Above = 'Above'
Left = 'Left'
Right = 'Right'
LeftAbove = 'LeftAbove'
LeftBelow = 'LeftBelow'
RightAbove = 'RightAbove'
RightBelow = 'RightBelow'

number = 0

def saveImage(image, faceAngle, currentAngle):
    if image is not None:
        image_file = f'{str(savePath)}/{str(faceAngle)}.png'
        cv2.imwrite(image_file, image)
        print(f"Captured frame at {number}")
        angleFaces.append(currentAngle)

capture_countdown = 0
capture_duration = 1  # 3 seconds countdown
currentFaceAngle = ""
while cap.isOpened():
    ret, frame = cap.read()

    if not ret:
        break
    image = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
    start = time.time()
        # To improve performance
    frame.flags.writeable = False

    # Get the result
    results = face_mesh.process(image)

    # To improve performance
    image.flags.writeable = True

    # Convert the color space from RGB to BGR
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    image2 = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    img_h, img_w, img_c = image.shape
    face_3d = []
    face_2d = []

    if results.multi_face_landmarks:
        for face_landmarks in results.multi_face_landmarks:
            for idx, lm in enumerate(face_landmarks.landmark):
                if idx == 33 or idx == 263 or idx == 1 or idx == 61 or idx == 291 or idx == 199:
                    if idx == 1:
                        nose_2d = (lm.x * img_w, lm.y * img_h)
                        nose_3d = (lm.x * img_w, lm.y * img_h, lm.z * 3000)

                    x, y = int(lm.x * img_w), int(lm.y * img_h)

                    # Get the 2D Coordinates
                    face_2d.append([x, y])

                    # Get the 3D Coordinates
                    face_3d.append([x, y, lm.z])
            # Convert it to the NumPy array
            print(face_2d)
            face_2d = np.array(face_2d, dtype=np.float64)
            print(face_2d)

            # Convert it to the NumPy array
            print(face_3d)
            face_3d = np.array(face_3d, dtype=np.float64)
            print(face_3d)

            # The camera matrix
            focal_length = 1 * img_w

            cam_matrix = np.array([ [focal_length, 0, img_h / 2],
                                    [0, focal_length, img_w / 2],
                                    [0, 0, 1]])

            # The distortion parameters
            dist_matrix = np.zeros((4, 1), dtype=np.float64)

            # Solve PnP
            success, rot_vec, trans_vec = cv2.solvePnP(face_3d, face_2d, cam_matrix, dist_matrix)

            # Get rotational matrix
            rmat, jac = cv2.Rodrigues(rot_vec)

            # Get angles
            angles, mtxR, mtxQ, Qx, Qy, Qz = cv2.RQDecomp3x3(rmat)

            # Get the y rotation degree
            x = angles[0] * 360
            y = angles[1] * 360
            z = angles[2] * 360

            if y < -10:
                text = "Right"
                if x < -5:
                    text += "Above"
                    currentAngle = RightBelow
                    if RightBelow not in angleFaces:
                        if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration
                elif x > 10:
                    text += "Bellow"
                    currentAngle = RightAbove
                    if RightAbove not in angleFaces:
                        if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration
                else:
                    currentAngle = Right
                    if Right not in angleFaces:
                        if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration

            elif y > 10:
                text = "Left"
                if x < -5:
                    text += "Above"
                    currentAngle = LeftBelow
                    if LeftBelow not in angleFaces:
                        if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration
                elif x > 10:
                    text += "Bellow"
                    currentAngle = LeftAbove
                    if LeftAbove not in angleFaces:
                        if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration
                else:
                    currentAngle = Left
                    if Left not in angleFaces:
                        if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration

            elif x < -10:
                text = "Above"
                currentAngle = Above
                if Above not in angleFaces:
                        if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration
            elif x > 20:
                text = "Bellow"
                currentAngle = Below
                if Below not in angleFaces:
                    if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration
            else:
                text = "Forward"
                currentAngle = Forward
                if Forward not in angleFaces:
                    if capture_countdown == 0:
                            capture_countdown = time.time() + capture_duration
            # Display the nose direction
            nose_3d_projection, jacobian = cv2.projectPoints(nose_3d, rot_vec, trans_vec, cam_matrix, dist_matrix)

            p1 = (int(nose_2d[0]), int(nose_2d[1]))
            p2 = (int(nose_2d[0] + y * 10) , int(nose_2d[1] - x * 10))

            cv2.line(image, p1, p2, (255, 0, 0), 3)

            # Add the text on the image
            cv2.putText(image, text, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 255, 0), 2)

            if Forward not in angleFaces:
                cv2.circle(image, (img_w // 2, img_h // 2), 100, (0, 0, 255), -1)
            if Below not in angleFaces:
                cv2.circle(image, (img_w // 2, 20), 100, (0, 0, 255), -1)
            if Above not in angleFaces:
                cv2.circle(image, (img_w // 2, img_h - 20), 100, (0, 0, 255), -1)
            if Right not in angleFaces:
                cv2.circle(image, (20, img_h // 2), 100, (0, 0, 255), -1)
            if Left not in angleFaces:
                cv2.circle(image, (img_w - 20, img_h // 2), 100, (0, 0, 255), -1)
            if RightAbove not in angleFaces:
                cv2.circle(image, (20, 20), 100, (0, 0, 255), -1)
            if RightBelow not in angleFaces:
                cv2.circle(image, (20, img_h - 20), 100, (0, 0, 255), -1)
            if LeftAbove not in angleFaces:
                cv2.circle(image, (img_w - 20, 20), 100, (0, 0, 255), -1)
            if LeftBelow not in angleFaces:
                cv2.circle(image, (img_w - 20, img_h - 20), 100, (0, 0, 255), -1)

        # Countdown for capturing image
        if currentAngle is not currentFaceAngle:
            capture_countdown = 0
            currentFaceAngle = currentAngle

        if capture_countdown > 0:
            remaining_time = capture_countdown - time.time()
            if remaining_time > 0:
                # Draw countdown text on the image
                cv2.putText(image, f"Capturing in {int(remaining_time)} seconds", (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
            else:
                # Capture the image after countdown is finished
                number+=1
                saveImage(frame, text, currentAngle)
                capture_countdown = 0

        end = time.time()
        totalTime = end - start

        mp_drawing.draw_landmarks(
            image=image,
            landmark_list=face_landmarks,
            landmark_drawing_spec=drawing_spec)

    # Display the frame (optional)
    cv2.imshow('Head Pose Estimation', image)

    # Press 'q' to exit the loop
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    if len(angleFaces) == 9:
        print(angleFaces)
        break

# Release video capture and close all windows
cap.release()
cv2.destroyAllWindows()


import docx

file = docx.Document()

# 添加段落
file.add_paragraph('Hello World', 'Title')  # add_paragraph 方法可以用于写入一段文段，第一个参数接受写入的内容，第二段参数接受样式。返回的是 Paragraph 对象

para_obj1 = file.add_paragraph('This is a second paragraph.')
para_obj2 = file.add_paragraph('This is a yet another paragraph.')
para_obj1.add_run("This text is being added to the second paragraph")  # para_obj1 是一个新的自然段，可以在该自然段后通过 add_run 方法，在此自然段后添加句子。 add_run 返回的是 Run 对象

# 添加标题
# add_heading 方法可以添加标题，标题层次为0-4，add_heading 接受两个参数，第一个参数是标题内容，第二个参数是标题层次。返回的是 Paragraph 对象
file.add_heading('Header 0', 0)
file.add_heading('Header 1', 1)
file.add_heading('Header 2', 2)
file.add_heading('Header 3', 3)
file.add_heading('Header 4', 4)

# 添加换页符/换行符
# file.add_break()  # 添加换行符
file.paragraphs[-1].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)  # 插入分页符
file.add_paragraph("This is a new page")

# 插入图片
file.paragraphs[-1].runs[0].add_break(docx.enum.text.WD_BREAK.PAGE)
file.add_picture("gaoda.jpg")

file.save('write_doc.docx')


import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
import os
from stockfish import Stockfish

stockfish = Stockfish(r'C:/Users/15193/OneDrive/PYTHON/ChessDetect/SF/stockfish-11-win/stockfish-11-win/Windows/stockfish_20011801_x64.exe')

# FLANN PARAMS

# FLANN_INDEX_KDTREE = 0
# index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
# search_params = dict(checks=200)

# flann = cv.FlannBasedMatcher(index_params, search_params)

# GET IMAGES

imc = cv.imread('ChessDetect/test/test12.jpg')
im = cv.imread('ChessDetect/test/test12.jpg', cv.IMREAD_GRAYSCALE)

# GET TURN

turn = input("turn (w/b): ")

# blank = cv.imread('ChessDetect/templates/boardcorner/blank.jpg', cv.IMREAD_GRAYSCALE)

# START SIFT

# sift = cv.SIFT_create()

# blank_pts, blank_desc = sift.detectAndCompute(blank, None)
# board_pts, board_desc = sift.detectAndCompute(im, None)

# FEATURE MATCHING

# matches = flann.knnMatch(blank_desc, board_desc, k=2)

# masked_blank_pts = []
# masked_board_pts = []

# lowe_coeff = 0.8

# for i, (m,n) in enumerate(matches):
#     if m.distance < lowe_coeff * n.distance:
#         masked_board_pts.append(board_pts[m.trainIdx].pt)
#         masked_blank_pts.append(blank_pts[m.queryIdx].pt)

# masked_blank_pts = np.int32(masked_blank_pts)
# masked_board_pts = np.int32(masked_board_pts)

# F, mask = cv.findFundamentalMat(masked_blank_pts, masked_board_pts, cv.FM_LMEDS)

# masked_blank_pts = masked_blank_pts[mask.ravel()==1]
# masked_board_pts = masked_board_pts[mask.ravel()==1]

# CREATE BOARD OUTLINE

# leftmost = min(masked_board_pts[:, 0])
# rightmost = max(masked_board_pts[:, 0])

# uppermost = min(masked_board_pts[:, 1])
# lowermost = max(masked_board_pts[:, 1])

# bound_safety = 10

# GET BOARD PARAMS

# board_crop = im[uppermost - bound_safety:lowermost + bound_safety, leftmost - bound_safety:rightmost + bound_safety]
square_sl = int(im.shape[0] / 8)

# GET PIECE LOCATIONS

dataset = 'ChessDetect/templates/128h/'

board_data = np.zeros((8, 8), dtype=np.int32)
key_arr = ['b', 'k', 'n', 'p', 'q', 'r', 'B', 'K', 'N', 'P', 'Q', 'R']

icount = 0

for item in os.listdir(dataset):

    piece = cv.imread(dataset + item, cv.IMREAD_GRAYSCALE)
    piece_res = cv.resize(piece, (int(square_sl), int(square_sl)))

    tm_result = cv.matchTemplate(im, piece_res, cv.TM_CCOEFF_NORMED)

    threshold = 0

    if icount < 6:
        threshold = 0.85
    else:
        threshold = 0.7

    locations = np.where(tm_result >= threshold)
    locations = list(zip(*locations[::-1]))

    sqs = []
    for piece_loc in locations:
        file = piece_loc[0] * 8 / (im.shape[0])
        file = round(file)
        #file = chr(ord('a') + file - 1)

        rank = (piece_loc[1] * 8 / (im.shape[0]))
        rank = round(rank)

        pos = [file, rank]

        sqs.append(pos)

    sqs_clear = []

    for sq in sqs:
        if sq not in sqs_clear:
            sqs_clear.append(sq)

    # print(item + ": ")
    # print(sqs_clear)

    for sq in sqs_clear:
        r = sq[1]
        f = sq[0]
        board_data[r][f] = ord(key_arr[icount])

    icount = icount + 1

# GET FEN CODE
fen = ""

for r in range (8):
    zcount = 0
    for f in range (8):
        if board_data[r][f] == 0:
            zcount = zcount + 1
            if f == 7:
                fen = fen + str(zcount)
        else:
            if zcount > 0:
                fen = fen + str(zcount)
                zcount = 0
            fen = fen + chr(board_data[r][f])
    if r != 7: fen = fen + "/"

fen = fen + " " + turn + " - - 0 1"

print(fen)

# GET BEST MOVE

# print(stockfish.is_fen_valid(fen))

if stockfish.is_fen_valid(fen):
    stockfish.set_fen_position(fen)
    best_move = stockfish.get_best_move()

start_f, start_r, end_f, end_r = best_move[0], best_move[1], best_move[2], best_move[3]

start_pt = [round((ord(start_f) - ord('a')) * im.shape[0] / 8) + int(square_sl)/2, round((8 - int(start_r)) * im.shape[0] / 8) + int(square_sl)/2]
end_pt = [round((ord(end_f) - ord('a')) * im.shape[0] / 8) + int(square_sl)/2, round((8 - int(end_r)) * im.shape[0] / 8) + int(square_sl)/2]

start_pt = np.int32(start_pt)
end_pt = np.int32(end_pt)

# DISPLAY

imc = cv.line(imc, start_pt, end_pt, (0, 255, 0), 2)
imc = cv.circle(imc, end_pt, radius=5, color=(0, 255, 0), thickness=3)

# out = im

# for pt in masked_board_pts:
#     out = cv.circle(out, (int(pt[0]), int(pt[1])), radius=5, color=(0, 255, 0), thickness=3)

plt.imshow(cv.cvtColor(imc, cv.COLOR_BGR2RGB))
plt.show()

# MUST SPECIFY WHICH COLOUR IS BEING PLAYED AS AND WHO'S TURN IT IS

##### TO DO #####
# implement play for black
# create templates based on initial set up
# live play


import requests
from async_helper import Async

async def get_homepages():
    quora_future = Async.run_in_executor(None, requests.get, 'http://www.quora.com')
    reddit_future = Async.run_in_executor(None, requests.get, 'http://www.reddit.com')
    quora_response = await quora_future
    reddit_response = await reddit_future
    return quora_response.content, reddit_response.content

def main():
    quora_homepage, reddit_homepage = Async.run_until_complete(get_homepages())
    print("Quora: {}, Reddit {}".format(len(quora_homepage), len(reddit_homepage)))

if __name__ == '__main__':
    main()


import argparse
import os
import sys

import kernelci
from kernelci import print_color, shell_cmd

def add_date_commit(path, msg, fname):
    with open(os.path.join(path, fname), 'w') as f:
        f.write(msg)
    shell_cmd("""
cd {path}
git add {fname}
git commit --author='"kernelci.org bot" <bot@kernelci.org>' -am {msg}
""".format(path=path, fname=fname, msg=msg))

def main(args):
    path = os.path.join('checkout', args.project)
    print("path: {}".format(path))
    repo_name = '/'.join([args.namespace, args.project])
    print("repo: {}".format(repo_name))
    repo = kernelci.GITHUB.get_repo(repo_name)
    print("checking out {} {}".format(args.from_url, args.from_branch))
    kernelci.checkout_repository(path, repo, args.from_url, args.from_branch)
    patches_path = os.path.join('patches', args.project, args.branch)
    print("patches: {}".format(patches_path))
    if not kernelci.apply_patches(path, patches_path):
        print_color('red', "Aborting, all patches must apply.")
        return False
    tag = args.tag or kernelci.date_tag(path, args.tag_prefix)
    print("tag: {}".format(tag))
    add_date_commit(path, tag, args.branch)
    kernelci.create_tag(path, tag)
    if args.push:
        print("\nPushing tag ({}) and branch ({})".format(tag, args.branch))
        ssh_key = kernelci.default_ssh_key(args.ssh_key, args.branch)
        if not ssh_key:
            print_color('red', "No SSH key provided.")
            return False
        kernelci.push_tag_and_branch(path, ssh_key, args.branch, tag)
        if args.tag_limit:
            kernelci.delete_old_tags(args, path, ssh_key)
    return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser("\
Create a kernel branch to test KernelCI")
    parser.add_argument("--tag",
                        help="Tag to create, default is to use current date")
    parser.add_argument("--tag-prefix", default="staging-",
                        help="Prefix to create date with current date")
    parser.add_argument("--tag-limit", default="20", type=int,
                        help="Number of previous tags to keep, 0 for all")
    parser.add_argument("--branch", default="staging.kernelci.org",
                        help="Name of the branch to force-push to")
    parser.add_argument("--from-url", default=kernelci.TORVALDS_GIT_URL,
                        help="URL to pull from")
    parser.add_argument("--from-branch", default="master",
                        help="Branch to pull from")
    parser.add_argument("--namespace", default='kernelci',
                        help="Github project namespace")
    parser.add_argument("--project", default='linux',
                        help="Name of the Github project")
    parser.add_argument("--ssh-key",
                        help="Path to SSH key to push branches and tags")
    parser.add_argument("--push", action="store_true",
                        help="Push the resulting branch and tag")
    args = parser.parse_args(sys.argv[1:])
    ret = main(args)
    sys.exit(0 if ret is True else 1)


#!/usr/bin/python
#coding=utf8

import sys
import configparser, hashlib, urllib, json

def getBTCTicker():
    response = urllib.request.urlopen('https://www.okcoin.com/api/ticker.do')
    #print(response.status)
    data = response.read().decode('utf-8')
    jsondata = json.loads(data)
    return jsondata

def getLTCTicker():
    response = urllib.request.urlopen('https://www.okcoin.com/api/ticker.do?symbol=ltc_cny')
    #print(response.status)
    data = response.read().decode('utf-8')
    jsondata = json.loads(data)
    return jsondata

def getBTCDepth():
    response = urllib.request.urlopen('https://www.okcoin.com/api/depth.do')
    data = response.read().decode('utf-8')
    jsondata = json.loads(data)
    return jsondata

def getLTCDepth():
    response = urllib.request.urlopen('https://www.okcoin.com/api/depth.do?symbol=ltc_cny')
    data = response.read().decode('utf-8')
    jsondata = json.loads(data)
    print(jsondata)
    return jsondata

def getBTCTrades(since=0):
    url = 'https://www.okcoin.com/api/trades.do'
    if since > 0:
        url += '?since=' + str(since)
    # print(url)
    response = urllib.request.urlopen(url)
    data = response.read().decode('utf-8')
    jsondata = json.loads(data)
    return jsondata

def getLTCTrades(since=0):
    url = 'https://www.okcoin.com/api/trades.do?symbol=ltc_cny'
    if since > 0:
        url += '&since=' + str(since)
    #print(url)
    response = urllib.request.urlopen(url)
    data = response.read().decode('utf-8')
    jsondata = json.loads(data)
    #print(jsondata)
    return jsondata

class OKC:
    def __init__(self):
        self.partner = ''
        self.key = ''
        self.sign = ''
        self.free_ltc = 0.0
        self.free_btc = 0.0
        self.free_cny = 0.0
        self.freezed_ltc = 0.0
        self.freezed_btc = 0.0
        self.freezed_cny = 0.0
        self.total_assets = 0.0
        self.partner, self.sign = self.readUserInfo()
        self.accountinfo = self.getUserAccount()
        self.canSell = True
        self.canBuy = True
        self.buyprice = 0.0
        self.sellprice = 0.0
        pass

    def _signature(self, params):
        s = ''
        for k in sorted(params.keys()):
            if len(s) > 0:
                s += '&'
            s += k + '=' + str(params[k])
        s += self.key
        return hashlib.md5(bytes(s, encoding='utf-8')).hexdigest().upper()

    def readUserInfo(self):
        # read partner and secretKey from file
        cfg = configparser.RawConfigParser()
        cfg.read('userinfo.ini')
        partner = cfg.get('userinfo', 'partner')
        pri_key = cfg.get('userinfo', 'secretkey')
        sign = hashlib.md5(
            b'partner=' + bytes(partner, encoding='utf-8') + bytes(pri_key, encoding='utf-8')).hexdigest().upper()
        # print(bytes(partner, encoding = 'utf-8'))
        # print(pri_key)
        # print(sign)
        self.partner = partner
        self.key = pri_key
        self.sign = sign
        return (partner, sign)

    def getUserAccount(self):
        data = urllib.parse.urlencode({'partner': self.partner, 'sign': self.sign})
        data = data.encode('utf-8')
        request = urllib.request.Request('https://www.okcoin.com/api/userinfo.do')
        request.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        f = urllib.request.urlopen(request, data)
        print(f.status)
        jsondata = json.loads(f.read().decode('utf-8'))
        result = jsondata['result']
        if (result != True):
            print("ErrCode=%d" % jsondata['errorCode'])
            return None

        self.free_ltc = float(jsondata['info']['funds']['free']['ltc'])
        self.free_btc = float(jsondata['info']['funds']['free']['btc'])
        self.free_cny = float(jsondata['info']['funds']['free']['cny'])
        self.freezed_btc = float(jsondata['info']['funds']['freezed']['btc'])
        self.freezed_cny = float(jsondata['info']['funds']['freezed']['cny'])
        self.freezed_ltc = float(jsondata['info']['funds']['freezed']['ltc'])
        print(jsondata)
        return jsondata

    def trade(self, symbol, type, rate=None, amount=None):
        # type : 'buy' / 'sell' / 'buy_market' / 'sell_market'
        # rate : 0 < rate < 1000000 ;  if 'buy_market', set buy cny amount
        # amount : btc > 0.01, ltc > 0.1; if 'sell_market', set sell btc/ltc number
        param = {
            'partner': self.partner,
            'symbol': symbol,
            'type': type
        }
        if rate is not None:
            param['rate'] = rate
        if amount is not None:
            param['amount'] = amount
        param['sign'] = self._signature(param)
        data = urllib.parse.urlencode(param).encode('utf-8')
        req = urllib.request.Request('https://www.okcoin.com/api/trade.do')
        req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        f = urllib.request.urlopen(req, data)
        print(f.status)
        jsondata = json.loads(f.read().decode('utf-8'))
        print(jsondata)
        result = jsondata['result']
        if result == False:
            print("ErrCode=%d" % jsondata['errorCode'])
        else:
            print("order %s ltc success, order_id=%d" % (type, jsondata['order_id']))
        return result

    # trade ltc interface
    def buy_ltc(self, rate, amount):
        return self.trade('ltc_cny', 'buy', rate, amount)

    def sell_ltc(self, rate, amount):
        return self.trade('ltc_cny', 'sell', rate, amount)

    def buyMarket_ltc(self, rate):
        return self.trade('ltc_cny', 'buy_market', rate)

    def sellMarket_ltc(self, amount):
        return self.trade('ltc_cny', 'sell_market', amount=amount)

    # trade btc interface
    def buy_btc(self, rate, amount):
        return self.trade('btc_cny', 'buy', rate, amount)

    def sell_btc(self, rate, amount):
        return self.trade('btc_cny', 'sell', rate, amount)

    def buyMarket_btc(self, rate):
        return self.trade('btc_cny', 'buy_market', rate)

    def sellMarket_btc(self, amount):
        return self.trade('btc_cny', 'sell_market', amount=amount)

    def getOrder_ltc(self, orderid = -1):
        # get ltc orders
        param = {
            'partner' : self.partner,
            'order_id' : orderid,
            'symbol' : 'ltc_cny'
        }
        param['sign'] = self._signature(param)
        data = urllib.parse.urlencode(param).encode('utf-8')
        req = urllib.request.Request('https://www.okcoin.com/api/getorder.do')
        req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        f = urllib.request.urlopen(req, data)
        print(f.status)
        jsondata = json.loads(f.read().decode('utf-8'))
        print(jsondata)
        result = jsondata['result']
        if result == False:
            print("ErrCode=%d" % jsondata['errorCode'])
            return None

        orders = jsondata['orders']
        return orders

    def cancelOrder_ltc(self, orderid):
        param = {
            'partner' : self.partner,
            'order_id' : orderid,
            'symbol' : 'ltc_cny'
        }
        param['sign'] = self._signature(param)
        data = urllib.parse.urlencode(param).encode('utf-8')
        req = urllib.request.Request('https://www.okcoin.com/api/cancelorder.do')
        req.add_header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
        f = urllib.request.urlopen(req, data)
        print(f.status)
        jsondata = json.loads(f.read().decode('utf-8'))
        print(jsondata)
        result = jsondata['result']
        if result == False:
            print(sys._getframe().f_code.co_name + ':' + sys._getframe().f_lineno)
            print("ErrCode=%d" % jsondata['errorCode'])

        return result


import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import adfuller
from arch.unitroot import PhillipsPerron
from statsmodels.regression.linear_model import OLS
import statsmodels.api as sm

acoes = ["PETR4.SA", "TIMS3.SA"]

start = "2023-01-01"
end = "2023-08-31"

df = yf.download(acoes, start=start, end=end)['Adj Close']

df.isna().sum()

# Trate os dados brutos para preencher os valores ausentes com a média
df.fillna(df.mean(), inplace=True)

# Extrai do data frame uma coluna com iloc
acao1 = df.iloc[:,0]
acao1.head()
acao2 = df.iloc[:,1]
acao2.head()

#Test Philip-Perron hipótese nula (H0): A série temporal possui uma raiz unitária e é não estacionária.
pp = PhillipsPerron(acao1)
print(pp.summary().as_text())

# Teste PP para ação 02
pp = PhillipsPerron(acao2)
print(pp.summary().as_text())

# Regressão Linear Simples
acao2 = sm.add_constant(acao2)
model = sm.OLS(acao1, acao2).fit()

# Print a summary of the regression results
print(model.summary())

# Extrair os resíduos do modelo
residuos = model.resid
residuos.plot()
plt.show()

# Teste de raiz unitária dos resíduos (PP)
pp = PhillipsPerron(residuos)
print(pp.summary().as_text())

# A série é cointegrada se apresentar P-valor abaixo de 0.10

# Apresentar séries no data frame em gráfico
df.plot()
plt.show()

# BBDC4 = -04,1373 + 0,7270 * ITUB4 (relação de equilíbrio)
bbdc4 = 14.30
itub4 = 27.21
diferenca = bbdc4 - (-4.1373 + 0.7270 * itub4)
diferenca

np.std(residuos) # desvio médio dos resíduos
max(residuos) # diferença máxima da média dos resíduos em módulo
min(residuos) # diferença mínima da média dos resíduos em módulo

'''
Processo Ornstein–Uhlenbeck
Teste de contagem para saber quantas vezes os pares cruzaram 0.00
Prepapar o loop para os outros ativos do IBOV
'''

# Calcular diferentes pares de ativos para uma série do IBOV
n_assets = 85
x = np.math.factorial(n_assets) / (np.math.factorial(n_assets - 2) * 2)
xyp-jani-qpk


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import json
import copy
# replace path below with a path to aaa_dgalPy
sys.path.append('/Users/Mumtaz/Downloads/Carbon-Footprint-DGS')
sys.path.append(r'/lib')
import lib.dgalPy as dgal
import utilization_points

dgal.startDebug()

def optimizeUtility(input):

    optAnswer = dgal.min({
        "model": utilization_points.carbonFootPrints,
        "input": input,
        "obj": lambda o: o["totalCo2EmissionPerPerson"],
        "constraints": lambda o: o["constraints"],
        "options": {"problemType": "mip", "solver":"glpk","debug": True}
    })
    optOutput = utilization_points.carbonFootPrints(optAnswer["solution"])
    dgal.debug("optOutput",optOutput)
    dgal.debug("constraints", optOutput["constraints"])

    output = {
        "optAnswer": optAnswer,
        "optOutput": optOutput
    }

    return output


from rest_framework import generics, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated

from booking_manager_api.serializers import BookingScheduleSerializer
from intel_api.serializers.accounts_serializers import IntelUserProfileRequestSerializer
from intel_api.models import UserEntity,ExternalEntity
from booking_manager_api.models.util import get_object_or_none
from booking_manager_api.models import EntityService
from intel_api.views.authentication import GetRequestAuthenticationBase

from booking_manager_api.models import EntityWorkingDays,EntityBookingSchedule,DaysOfTheWeek,TimeSlot
from rest_framework.views import APIView

class BookingScheduleView(GetRequestAuthenticationBase,APIView):
    """
        Request: Post
            {
                "schedule":
                    [
                        {
                            "day_of_the_week":1,
                            "time_slots":
                                [
                                    {
                                        "slot_id":1,
                                        "max_bookee":100
                                    },
                                    {
                                        "slot_id":2,
                                        "max_bookee":120
                                    },
                                    {
                                        "slot_id":3,
                                        "max_bookee":105
                                    },...
                                ]
                        },
                        {
                            "day_of_the_week":2,
                            "time_slots":
                                [
                                    {
                                        "slot_id":4,
                                        "max_bookee":100
                                    },
                                    {
                                        "slot_id":5,
                                        "max_bookee":120
                                    },...
                                ]
                        },...
                    ]
            }

        Headers:
            Authorization: Token 1947031a3608dd4a1de89eadffd4497f4e6b9288
            session-key = your session key

        Response:
            {
              "status": "success",
              "message": "Booking schedule successfully created."
            }
    """

    serializer_class = BookingScheduleSerializer

    def post(self, request, *args, **kwargs):
        try:
            user = self.authenticate(request)
        except Exception as e:
            return Response({"status":"error","message":"%s"%str(e)},status=status.HTTP_401_UNAUTHORIZED)

        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            try:
                external_entity = user.get_external_entity()
                if external_entity:
                    schedules = serializer.validated_data['schedule']
                    for schedule in schedules:
                        day = get_object_or_none(DaysOfTheWeek,id=schedule['day_of_the_week'])
                        if day:
                            time_slots = schedule['time_slots']
                            entity_working_day,_ = EntityWorkingDays.objects.get_or_create(bookable_entity=external_entity,day=day,created_by=user.user_entity)
                            for slot in time_slots:
                                t_slot = get_object_or_none(TimeSlot,id=slot['slot_id'])
                                if t_slot:
                                    if entity_working_day:
                                        is_created = EntityBookingSchedule.objects.filter(
                                            entity_working_days__bookable_entity=external_entity,
                                            entity_working_days=entity_working_day,
                                            timeslot=t_slot
                                        )
                                        if not is_created.exists():
                                                EntityBookingSchedule.create(
                                                    entity_working_days=entity_working_day,timeslot=t_slot,
                                                    created_by=user.user_entity,maximum_bookee=slot['max_bookee'])
                                        else:
                                            return Response({
                                                "status":"error",
                                                "message":"Schedule already exists."},status=status.HTTP_400_BAD_REQUEST)
                                    else:
                                        return Response({
                                            "status":"error",
                                            "message":"Error creating entity working days."},status=status.HTTP_400_BAD_REQUEST)
                                else:
                                    return Response({"status":"error","message":"Error getting the apropriate time slot."},status=status.HTTP_404_NOT_FOUND)
                        else:
                            return Response({"status":"error","message":"Error getting the apropriate day of the week."},status=status.HTTP_404_NOT_FOUND)

                    return Response({"status": "success", "message": "Booking schedule successfully created."},status=status.HTTP_200_OK)
                else:
                    return Response({"status":"error","message":"User does not belong to a lab entity."},status=status.HTTP_400_BAD_REQUEST)
            except Exception as e:
                return Response({"status":"error","message":"Error occured(%s)."%str(e)},status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({"status":"error","message":serializer.errors},status=status.HTTP_400_BAD_REQUEST)

class EntityBookingSchedules(GetRequestAuthenticationBase,APIView):
    """
        Request Format:
            import requests

            url = "http://localhost:8000/api/v1/booking/manager/entity/booking/schedules/"

            headers = {
                "session-key": "BDUhANPuZs",
                "Content-Type": "application/json",
                "Authorization": "Token ac9c93b147a701dea08ee41f9a224a27b0c06ffe"
            }

            response = requests.request("GET", url, headers=headers)

            print(response.text)

        Response:
            {
              "status": "success",
              "data": {
                "schedule": [
                  {
                    "day_of_the_week": 1,
                    "time_slots": [
                      {
                        "slot_id": 1,
                        "max_bookee": 100
                      },
                      {
                        "slot_id": 2,
                        "max_bookee": 120
                      },
                      {
                        "slot_id": 3,
                        "max_bookee": 105
                      }
                    ]
                  },
                  {
                    "day_of_the_week": 2,
                    "time_slots": [
                      {
                        "slot_id": 4,
                        "max_bookee": 120
                      },
                      {
                        "slot_id": 5,
                        "max_bookee": 105
                      }
                    ]
                  }
                ]
              }
            }
    """

    def serialize_data(self,bookings):
        try:
            schedule = list()
            for booking in bookings:
                s = dict()
                s['day_of_the_week'] = booking.day.day
                b_schedules = EntityBookingSchedule.objects.filter(entity_working_days=booking)
                slots = list()
                for item in b_schedules:
                    slots.append({"slot":{
                        "start_time":item.timeslot.start_time,"end_time":item.timeslot.end_time,
                        "interval":item.timeslot.interval_in_minute},"max_bookee":item.maximum_bookee})
                s['time_slots'] = slots
                schedule.append(s)
            return {'schedule':schedule}
        except Exception as e:
            raise Exception("Error serializing data.")

    def get(self,request):
        try:
            user = self.authenticate(request)
        except Exception as e:
            return Response({"status":"error","message":"%s"%str(e)},status=status.HTTP_401_UNAUTHORIZED)

        try:
            user_external_entity = user.get_external_entity()
            if user_external_entity:
                entity_bookings = EntityWorkingDays.get_entity_bookings(user_external_entity)
                if entity_bookings.exists():
                    return Response({"status": "success", "data":self.serialize_data(entity_bookings)},status=status.HTTP_200_OK)
                else:
                    return Response({"status":"error","message":"No bookings available."},status=status.HTTP_404_NOT_FOUND)
            else:
                return Response({"status":"error","message":"External entity not found."},status=status.HTTP_404_NOT_FOUND)

        except  Exception as e:
            return Response({"status":"error","message":"Error occured(%s)."%str(e)},status=status.HTTP_400_BAD_REQUEST)


import os
import sys
import random
import math
import re
import time
import numpy as np
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from tqdm import tqdm

# Root directory of the project
ROOT_DIR = os.path.abspath("../../")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
from mrcnn import visualize
from mrcnn.visualize import display_images
import mrcnn.model as modellib
from mrcnn.model import log

from samples.graves import graves_aug as graves

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
#GRAVES_MODEL_PATH = "/work1/thogujo/logs/graves20191205T1211/mask_rcnn_graves_0032.h5"

GRAVES_MODEL_PATH = "/work3/thgujo/logs/mask_rcnn_graves_0032.h5"

#%%
class InferenceConfig(graves.CustomConfig):
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1
    IMAGE_MIN_DIM = 800
    IMAGE_MAX_DIM = 1024
    DETECTION_MIN_CONFIDENCE = 0.9

inference_config = InferenceConfig()

model = modellib.MaskRCNN(mode='inference',
                          config=inference_config,
                          model_dir=MODEL_DIR)

model_path = GRAVES_MODEL_PATH

assert model_path != ""
print("Loading weights from ", model_path)
model.load_weights(model_path,by_name=True)

#%%
dataset = graves.CustomDataset()
dataset.load_custom("/zhome/2e/9/124284/environments/gravestones_env/Code/Mask_RCNN/samples/graves/dataset_g/","val")
#dataset.load_custom("/media/thorsteinngj/c1f0e49d-1218-4d11-ab9f-aadb4a021648/home/thorsteinngj/Documents/Thesis/pics/")

# Must call before using the dataset
dataset.prepare()

#%%
import pandas as pd
from time import time

#%%
import skimage
import re

test_dir = '/work3/thgujo/Pictures/1944'
image_paths = []
for filename in  os.listdir(test_dir):
    if os.path.splitext(filename)[1].lower() in ['.jpg','.png','.jpeg']:
        image_paths.append(os.path.join(test_dir,filename))

image_paths = image_paths
datapoints = []
res = []
t0 = time()
for i in tqdm(range(len(image_paths))):
    try:
        img = skimage.io.imread(image_paths[i])
        if len(np.shape(img)) > 2 and (np.shape(img)[2] == 3):
            img_arr = np.array(img)
            results = model.detect([img_arr],verbose=1)
            r = results[0]
            #print(r['class_ids'])

            zeros = 0
            ones = 0
            twos = 0
            threes = 0
            fours = 0
            fives = 0
            sixes = 0
            sevens = 0
            if r['class_ids'].size == 0:
                zeros += 1
            else:
                for j in range(len(r['class_ids'])):
                    if r['class_ids'][j] == 1:
                        ones +=1
                    elif r['class_ids'][j] == 2:
                        twos +=1
                    elif r['class_ids'][j] == 3:
                        threes +=1
                    elif r['class_ids'][j] == 4:
                        fours +=1
                    elif r['class_ids'][j] == 5:
                        fives +=1
                    elif r['class_ids'][j] == 6:
                        sixes +=1
                    else:
                        sevens += 1

            #Þarf að læra að save-a myndir eftir þvi hvort þær seu png, jpeg, jpg, gif ...
            datapoint = re.findall('\d+',image_paths[i])[-1]
            print(i)
            print(datapoint)

            #Getting the values
            t1 = time()
            tot_time = t1-t0

            data = {'grave_id': int(datapoint),'no_sign':zeros,'angels':ones,"bibles":twos,"crosses":threes,"david_star":fours,"doves":fives,"persons":sixes,"praying_hands":sevens,"time_elapsed":tot_time}

            datapoints.append(data)
    except:
        print("Couldn't process image")

my_dataset_df = pd.DataFrame.from_dict(datapoints)
my_dataset_df.to_csv('/work3/thgujo/dataframes/1944.csv')


import logging
import os
import re
import sys
import xml
import csv
import subprocess

import nltk

sys.path.append("lib")
import pymongo
from BeautifulSoup import BeautifulSoup

logging.basicConfig(level=logging.DEBUG, format="%(levelname)-8s %(message)s")

mongo_conn = pymongo.Connection('localhost', 27017)
db = mongo_conn['wikileaks']

class Cable():

  raw = ""
  attrs = {}

  def __init__(self,raw):
    logging.info('Cable()')
    self.raw = raw

  def __getitem__(self,name):
    if name == 'raw':
      return self.raw
    if name in self.attrs:
      return self.attrs[name]
    else:
      return None

  def __setitem__(self,name,value):
    self.attrs[name] = value

  def get(self):
    return self.attrs

class CableGateMirror():

  mirror_directory = 'data/cablegate/'

  def __init__(self):
    logging.info('CableGateMirror()')
    self.update()

  def update(self):
    logging.info('CableGateMirror.update')
    #subprocess.call(["httrack",'--update'],cwd=self.mirror_directory)
    Processor()

class Processor():

  data_directory = 'data/cablegate/cablegate.wikileaks.org/cable'

  country_dictionary_path = 'data/countries.csv'
  countries = []
  country_frequency = nltk.probability.FreqDist()

  file_regex = re.compile("\.html$")

  counts = {
    'files_to_process':0,
    'files_processed':0,
    'files_not_processed':0
  }

  def __init__(self):
    logging.info('Processor()')
    self.load_countries()
    self.process()

  def process(self):
    logging.info('Processor.process')
    self.read_files()

  def load_countries(self):
    logging.info('Processor.load_countries')
    try:
      file = open(self.country_dictionary_path,'r')
    except OSError:
      logging.warning('Processor.CANNOT OPEN FILE '+path)
      return
    countries = csv.reader(file, delimiter=',')
    for row in countries:
      self.countries.append(row[1].lower())

  def read_files(self):
    logging.info('Processor.read_files')
    try:
      for root, dirs, files in os.walk(self.data_directory):
        for name in files:
          if self.file_regex.search(name) is not None:
            path = root+"/"+name
            self.counts['files_to_process'] = self.counts['files_to_process'] + 1
            self.read_file(path)
    except OSError:
      logging.info(str(OSError))

  def read_file(self,path):
    logging.info('Processor.read_file')
    try:
      file = open(path)
    except OSError:
      logging.warning('Processor.CANNOT OPEN FILE '+path)
      self.counts['files_not_processed'] = self.counts['files_not_processed'] + 1
      return
    self.extract_content(file.read())

  def extract_content(self,raw):
    logging.info('Processor.extract_content')

    soup = BeautifulSoup(raw)
    cable_table = soup.find("table", { "class" : "cable" })
    cable_id = cable_table.findAll('tr')[1].findAll('td')[0]\
      .contents[1].contents[0]
    if db.cables.find_one({'_id':cable_id}):
      self.counts['files_not_processed'] = self.counts['files_not_processed'] + 1
      logging.info('Processor.extract_content["CABLE ALREADY EXISTS"]')
      self.print_counts()
      return

    cable = Cable(raw)
    cable['_id'] = cable_id
    cable['reference_id'] = cable_id
    cable['date_time'] = cable_table.findAll('tr')[1].findAll('td')[1]\
      .contents[1].contents[0]
    cable['classification'] = cable_table.findAll('tr')[1].findAll('td')[2]\
      .contents[1].contents[0]
    cable['origin'] = cable_table.findAll('tr')[1].findAll('td')[3]\
      .contents[1].contents[0]
    cable['header'] = nltk.clean_html(str(soup.findAll(['pre'])[0]))
    cable['body'] = nltk.clean_html(str(soup.findAll(['pre'])[1]))

    db.cables.insert(cable.get())

    self.counts['files_processed'] = self.counts['files_processed'] + 1

    self.print_counts()

    if (self.counts['files_processed'] + self.counts['files_not_processed'])\
      == self.counts['files_to_process']:
      self.dump_json()

  def print_counts(self):
    logging.info('Processor.print_counts')
    logging.info(str(self.counts['files_to_process'])+" | "+\
      str(self.counts['files_processed'])+" | "+\
      str(self.counts['files_not_processed']))

  def dump_json(self):
    logging.info('Processor.dump_json')

CableGateMirror()


from PyQt6 import QtCore, QtGui, QtWidgets

progress_bar_style = """
QSlider::groove:horizontal {
background: rgba(0, 0, 0, 0);
height: 10px;
border-radius: 5px;
}

QSlider::sub-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(40, 113, 250, 150), stop:1 rgba(103, 23, 205, 150));
height: 10px;
border-radius: 5px;
}

QSlider::add-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(56, 56, 56, 150), stop:1 rgba(40, 40, 40, 150));
height: 10px;
}

QSlider::sub-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::add-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::handle:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border: 1px solid #aaa;
border-radius: 5px;
}
"""
controlled_progress_bar_style = """
QSlider::groove:horizontal {
background: rgba(0, 0, 0, 0);
height: 10px;
border-radius: 5px;
}

QSlider::sub-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(210, 90, 70, 0), stop:1 rgba(5, 240, 25, 0));
height: 10px;
border-radius: 5px;
}

QSlider::add-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(56, 56, 56, 0), stop:1 rgba(40, 40, 40, 0));
height: 10px;
}

QSlider::sub-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::add-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::handle:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border: 1px solid #aaa;
border-radius: 5px;
}
"""
volume_slider_style = """
QSlider::groove:horizontal {
background: rgba(0, 0, 0, 0);
height: 10px;
border-radius: 5px;
}

QSlider::sub-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(40, 113, 250, 150), stop:1 rgba(103, 23, 205, 150));
height: 10px;
border-radius: 5px;
}

QSlider::add-page:horizontal {
background: qlineargradient(spread:pad, x1:0.463054, y1:0.0965909, x2:0.487685, y2:0.813, stop:0 rgba(56, 56, 56, 150), stop:1 rgba(40, 40, 40, 150));
height: 10px;
}

QSlider::handle:horizontal {
background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
    stop:0 #eee, stop:1 #ccc);
border: 1px solid #777;
width: 13px;
margin-top: -2px;
margin-bottom: -2px;
border-radius: 6px;
}
QSlider::handle:horizontal:hover {
background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
    stop:0 #fff, stop:1 #ddd);
border: 1px solid #444;
border-radius: 6px;
}
QSlider::sub-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::add-page:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border-color: #999;
border-radius: 5px;
}

QSlider::handle:horizontal:disabled {
background: rgba(0, 0, 0, 0);
border: 1px solid #aaa;
border-radius: 5px;
}"""
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.background = QtWidgets.QLabel(self.centralwidget)
        self.background.setGeometry(QtCore.QRect(0, 0, 801, 601))
        self.background.setText("")
        self.background.setPixmap(QtGui.QPixmap("music-player/src/BackGround-v5.png"))
        self.background.setScaledContents(True)
        self.cur_time = QtWidgets.QLabel(self.centralwidget)
        self.cur_time.setGeometry(QtCore.QRect(400, 180, 60, 20))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.cur_time.setFont(font)
        self.cur_time.setObjectName("cur_time")
        self.song_name = QtWidgets.QLabel(self.centralwidget)
        self.song_name.setGeometry(QtCore.QRect(400, 110, 380, 32))
        font = QtGui.QFont()
        font.setPointSize(24)
        self.song_name.setFont(font)
        self.song_name.setObjectName("song_name")
        self.total_time = QtWidgets.QLabel(self.centralwidget)
        self.total_time.setGeometry(QtCore.QRect(710, 180, 60, 20))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.total_time.setFont(font)
        self.total_time.setObjectName("total_time")
        self.volume_slider = QtWidgets.QSlider(self.centralwidget)
        self.volume_slider.setGeometry(QtCore.QRect(320, 550, 160, 25))
        self.volume_slider.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.volume_slider.setValue(88)
        self.volume_slider.setStyleSheet(volume_slider_style)
        self.volume_slider.setObjectName("volume_slider")
        self.progress_slider = QtWidgets.QSlider(self.centralwidget)
        self.progress_slider.setGeometry(QtCore.QRect(453, 185, 250, 10))
        self.progress_slider.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.progress_slider.setStyleSheet(progress_bar_style)
        self.progress_slider.setRange(0, 99)
        self.progress_slider.setValue(0)
        self.progress_slider.setTracking(False)
        self.progress_slider_controlled = QtWidgets.QSlider(self.centralwidget)
        self.progress_slider_controlled.setGeometry(QtCore.QRect(453, 185, 250, 10))
        self.progress_slider_controlled.setOrientation(QtCore.Qt.Orientation.Horizontal)
        self.progress_slider_controlled.setStyleSheet(controlled_progress_bar_style)
        self.progress_slider.setRange(0, 99)
        self.progress_slider_controlled.setValue(0)
        self.volume_button = QtWidgets.QPushButton(self.centralwidget)
        self.volume_button.setGeometry(QtCore.QRect(270, 540, 42, 42))
        self.volume_button.setAutoFillBackground(False)
        self.volume_button.setText("")
        iconV = QtGui.QIcon()
        iconV.addPixmap(QtGui.QPixmap("music-player/src/sound.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.volume_button.setIcon(iconV)
        self.volume_button.setIconSize(QtCore.QSize(42, 42))
        self.volume_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.loop_button = QtWidgets.QPushButton(self.centralwidget)
        self.loop_button.setGeometry(QtCore.QRect(200, 540, 42, 42))
        self.loop_button.setAutoFillBackground(False)
        self.loop_button.setText("")
        iconR = QtGui.QIcon()
        iconR.addPixmap(QtGui.QPixmap("music-player/src/loop.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.loop_button.setIcon(iconR)
        self.loop_button.setIconSize(QtCore.QSize(42, 42))
        self.loop_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.pause_button = QtWidgets.QPushButton(self.centralwidget)
        self.pause_button.setGeometry(QtCore.QRect(20, 540, 42, 42))
        self.pause_button.setAutoFillBackground(False)
        self.pause_button.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("music-player/src/pause.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.pause_button.setIcon(icon)
        self.pause_button.setIconSize(QtCore.QSize(32, 32))
        self.pause_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.pause_button.setObjectName("pause")
        self.hidenButton = QtWidgets.QPushButton(self.centralwidget)
        self.hidenButton.setGeometry(QtCore.QRect(20, 540, 42, 42))
        self.hidenButton.setAutoFillBackground(False)
        self.hidenButton.setText("")
        iconk = QtGui.QIcon()
        iconk.addPixmap(QtGui.QPixmap("music-player/src/pause.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.hidenButton.setIcon(iconk)
        self.hidenButton.setIconSize(QtCore.QSize(32, 32))
        self.hidenButton.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.hidenButton.hide()
        self.prev_button = QtWidgets.QPushButton(self.centralwidget)
        self.prev_button.setGeometry(QtCore.QRect(80, 540, 42, 42))
        self.prev_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.prev_button.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("music-player/src/prev.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.prev_button.setIcon(icon1)
        self.prev_button.setIconSize(QtCore.QSize(32, 32))
        self.prev_button.setCheckable(False)
        self.prev_button.setObjectName("prev")
        self.next_button = QtWidgets.QPushButton(self.centralwidget)
        self.next_button.setGeometry(QtCore.QRect(130, 540, 42, 42))
        self.next_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.next_button.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("music-player/src/next.png"), QtGui.QIcon.Mode.Active, QtGui.QIcon.State.Off)
        self.next_button.setIcon(icon2)
        self.next_button.setIconSize(QtCore.QSize(32, 32))
        self.next_button.setObjectName("next")
        self.settings_button = QtWidgets.QPushButton(self.centralwidget)
        self.settings_button.setGeometry(QtCore.QRect(718, 535, 45, 45))
        self.settings_button.setAutoFillBackground(False)
        self.settings_button.setText("")
        self.icon3 = QtGui.QIcon()
        self.icon3.addPixmap(QtGui.QPixmap("music-player/src/settings.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.settings_button.setIcon(self.icon3)
        self.settings_button.setIconSize(QtCore.QSize(42, 42))
        self.settings_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.add_song_button = QtWidgets.QPushButton(self.centralwidget)
        self.add_song_button.setGeometry(QtCore.QRect(720, 535, 42, 42))
        self.add_song_button.setAutoFillBackground(False)
        self.add_song_button.setText("")
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("music-player/src/folder.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
        self.add_song_button.setIcon(icon4)
        self.add_song_button.setIconSize(QtCore.QSize(32, 32))
        self.add_song_button.setStyleSheet("background-color: rgba(255, 255, 255, 0);\n"
"border: none;")
        self.add_song_button.hide()
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", ""))
        self.cur_time.setText(_translate("MainWindow", "00:00"))
        self.song_name.setText(_translate("MainWindow", "Add music to folder"))
        self.total_time.setText(_translate("MainWindow", "03:00"))

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.setFixedSize(320, 240)
        self.warning_background = QtWidgets.QLabel(Dialog)
        self.warning_background.setGeometry(QtCore.QRect(0, 0, 321, 241))
        self.warning_background.setText("")
        self.warning_background.setScaledContents(True)
        self.warning_background.setObjectName("warning_background")
        self.warning_background.setPixmap(QtGui.QPixmap("music-player/src/WarningBackGround.png"))
        self.warning_background.setScaledContents(True)
        self.info_label = QtWidgets.QLabel(Dialog)
        self.info_label.setGeometry(QtCore.QRect(70, 50, 180, 90))
        font = QtGui.QFont()
        font.setPointSize(22)
        font.setBold(False)
        font.setWeight(50)
        self.info_label.setFont(font)
        self.info_label.setScaledContents(False)
        self.info_label.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
        self.info_label.setWordWrap(True)
        self.info_label.setObjectName("label")
        self.okey_button = QtWidgets.QPushButton(Dialog)
        self.okey_button.setGeometry(QtCore.QRect(105, 160, 110, 32))
        self.okey_button.setObjectName("pushButton")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", ""))
        self.info_label.setText(_translate("Dialog", "Добавьте музыку в папку"))
        self.okey_button.setText(_translate("Dialog", "Окей"))


from flask import Flask, render_template, request, send_file
import openpyxl

app = Flask(__name__, static_folder='static', static_url_path='')

#main loading code
@app.route('/')
def entering():
    kosha_listdata = open('x.txt', 'r', encoding='utf-8')
    koshalist = kosha_listdata.readlines()
    guideList = []
    for view_list in koshalist:
        guideList.append(view_list.replace('\n',''))

    return render_template('home.html', guidelists=guideList)

# Search code
@app.route('/find', methods=['POST'])
def finding(keyword=None):
    if request.method == 'POST':
        finding_word = request.form['keyword']
    else:
        finding_word = None

    x = open('keyword recoder.txt', 'a', encoding='utf-8')
    x.write(finding_word)
    x.close()

    data_base = openpyxl.load_workbook('./Guide_DB.xlsx')
    data_base = data_base.get_sheet_by_name('Sheet1')

    guide_name = []
    guide_page = []
    guide_contents = []

    #empty list add guide contents
    for contents in data_base.rows:
        guide_name.append(str(contents[0].value))
        guide_page.append(str(contents[1].value))
        guide_contents.append(str(contents[2].value))

    finding_name = []
    finding_page = []
    finding_contents = []

    #finding contents added to temp database for detail seraching
    count = 0
    for searchWord in guide_contents:
        count = count + 1
        if finding_word in searchWord:
            finding_contents.append(searchWord)
            finding_name.append(guide_name[count-1])
            finding_page.append(guide_page[count-1])

    temp_db = openpyxl.load_workbook('./Temp_DB.xlsx')
    temp_db_ws1 = temp_db.worksheets[0]
    temp_db.remove(temp_db_ws1)
    temp_db_ws = temp_db.create_sheet('find')

    numberOfcount = len(finding_contents)

    rewrite_count1 = 0
    rewrite_count2 = 0
    rewrite_count3 = 0

    for result_name in finding_name:
        rewrite_count1 = rewrite_count1 + 1
        temp_db_ws.cell(row=rewrite_count1, column=1).value = result_name

    for result_page in finding_page:
        rewrite_count2 = rewrite_count2 + 1
        temp_db_ws.cell(row=rewrite_count2, column=2).value = result_page

    for result_contents in finding_contents:
        rewrite_count3 = rewrite_count3 + 1
        temp_db_ws.cell(row=rewrite_count3, column=3).value = result_contents

    temp_db.save('./Temp_DB.xlsx')

    link_db = openpyxl.load_workbook('./link.xlsx')
    link_db = link_db.get_sheet_by_name('Sheet1')

    link_name = []
    link_path = []

    for link_write in link_db.rows:
        link_name.append(str(link_write[0].value))
        link_path.append(str(link_write[1].value))

    link_data = {

    }

    link_cont = 0

    for link_dic in link_name:
        link_data[link_name[link_cont]] = link_path[link_cont]
        link_cont = link_cont + 1

    link_link = []

    for linkserach in finding_name:
        link_link.append(link_data.get(linkserach))

    return render_template(
        'home_find.html',
        test=finding_name,
        test2=finding_page,
        test3=finding_contents,
        findcount=numberOfcount,
        adress=link_link)

@app.route('/detailfind', methods=['POST'])
def detailsearching(detail_keyword=None):
    if request.method == 'POST':
        detail_keyword = request.form['detail_keyword']
    else:
        detail_keyword = None

    searching_list = openpyxl.load_workbook('./Temp_DB.xlsx')
    searching_sheet = searching_list.worksheets[0]

    detail_name =[]
    detail_page =[]
    detail_contents = []

    for detail in searching_sheet.rows:
        detail_name.append(str(detail[0].value))
        detail_page.append(str(detail[1].value))
        detail_contents.append(str(detail[2].value))

    searching_list.remove_sheet(searching_sheet)

    detail_find_name = []
    detail_find_page = []
    detail_find_contents = []

    countdetail = 0
    for detailsearching in detail_contents:
        countdetail = countdetail + 1
        if detail_keyword in detailsearching:
            detail_find_contents.append(detailsearching)
            detail_find_name.append(detail_name[countdetail-1])
            detail_find_page.append(detail_page[countdetail-1])

    searching_newSheet = searching_list.create_sheet('find')

    name_count = 0
    page_count = 0
    contents_count = 0

    for detail_name1 in detail_find_name:
        name_count = name_count + 1
        searching_newSheet.cell(row=name_count, column=1).value = detail_name1

    for detail_page1 in detail_find_page:
        page_count = page_count + 1
        searching_newSheet.cell(row=page_count, column=2).value = detail_page1

    for detail_contents1 in detail_find_contents:
        contents_count = contents_count + 1
        searching_newSheet.cell(row=contents_count, column=3).value = detail_contents1

    searching_list.save('./Temp_DB.xlsx')

    link_db = openpyxl.load_workbook('./link.xlsx')
    link_db = link_db.get_sheet_by_name('Sheet1')

    link_name = []
    link_path = []

    for link_write in link_db.rows:
        link_name.append(str(link_write[0].value))
        link_path.append(str(link_write[1].value))

    link_data = {

    }

    link_cont = 0

    for link_dic in link_name:
        link_data[link_name[link_cont]] = link_path[link_cont]
        link_cont = link_cont + 1

    link_link = []

    for linkserach in detail_find_name:
        link_link.append(link_data.get(linkserach))

    return render_template(
        'home_find.html',
         test=detail_find_name,
         test2=detail_find_page,
         test3=detail_find_contents,
         adress=link_link)

#kosha guide downlaod code
@app.route('/download/<path:file>')
def download(file):
    guide_n = file
    guide_a = 'templates/Guide/'+guide_n
    return send_file(guide_a)

#favicon loaidng code
@app.route('/favicon.ico')
def favicon():
    return send_file('favicon.ico')

#robots loading code
@app.route('/robots.txt')
def robots():
    return send_file('robots.txt')

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


# Author: Mainak Jas <mainak.jas@telecom-paristech.fr>
#         Mikolaj Magnuski <mmagnuski@swps.edu.pl>
#         Stefan Appelhoff <stefan.appelhoff@mailbox.org>
#
# License: BSD (3-clause)

from copy import deepcopy
from distutils.version import LooseVersion
import os.path as op
import shutil
from unittest import SkipTest

import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
                           assert_equal, assert_allclose)
import pytest
from scipy import io

from mne import write_events, read_epochs_eeglab
from mne.io import read_raw_eeglab
from mne.io.tests.test_raw import _test_raw_reader
from mne.datasets import testing
from mne.utils import requires_h5py, run_tests_if_main
from mne.annotations import events_from_annotations, read_annotations
from mne.io.eeglab.tests._utils import _read_eeglab_montage

base_dir = op.join(testing.data_path(download=False), 'EEGLAB')

raw_fname_mat = op.join(base_dir, 'test_raw.set')
raw_fname_onefile_mat = op.join(base_dir, 'test_raw_onefile.set')
raw_fname_event_duration = op.join(base_dir, 'test_raw_event_duration.set')
epochs_fname_mat = op.join(base_dir, 'test_epochs.set')
epochs_fname_onefile_mat = op.join(base_dir, 'test_epochs_onefile.set')
raw_mat_fnames = [raw_fname_mat, raw_fname_onefile_mat]
epochs_mat_fnames = [epochs_fname_mat, epochs_fname_onefile_mat]

raw_fname_h5 = op.join(base_dir, 'test_raw_h5.set')
raw_fname_onefile_h5 = op.join(base_dir, 'test_raw_onefile_h5.set')
epochs_fname_h5 = op.join(base_dir, 'test_epochs_h5.set')
epochs_fname_onefile_h5 = op.join(base_dir, 'test_epochs_onefile_h5.set')
raw_h5_fnames = [raw_fname_h5, raw_fname_onefile_h5]
epochs_h5_fnames = [epochs_fname_h5, epochs_fname_onefile_h5]

raw_fnames = [raw_fname_mat, raw_fname_onefile_mat,
              raw_fname_h5, raw_fname_onefile_h5]
montage_path = op.join(base_dir, 'test_chans.locs')

def _check_h5(fname):
    if fname.endswith('_h5.set'):
        try:
            import h5py  # noqa, analysis:ignore
        except Exception:
            raise SkipTest('h5py module required')

@requires_h5py
@testing.requires_testing_data
@pytest.mark.parametrize(
    'fname', [raw_fname_mat, raw_fname_h5], ids=op.basename
)
def test_io_set_raw(fname):
    """Test importing EEGLAB .set files."""
    montage = _read_eeglab_montage(montage_path)
    montage.ch_names = [
        'EEG {0:03d}'.format(ii) for ii in range(len(montage.ch_names))
    ]

    _test_raw_reader(read_raw_eeglab, input_fname=fname)
    # test that preloading works
    raw0 = read_raw_eeglab(input_fname=fname, preload=True)
    raw0.set_montage(montage)
    raw0.filter(1, None, l_trans_bandwidth='auto', filter_length='auto',
                phase='zero')

    # test that using uint16_codec does not break stuff
    raw0 = read_raw_eeglab(input_fname=fname,
                           preload=False, uint16_codec='ascii')
    raw0.set_montage(montage)

@testing.requires_testing_data
def test_io_set_raw_more(tmpdir):
    """Test importing EEGLAB .set files."""
    tmpdir = str(tmpdir)
    eeg = io.loadmat(raw_fname_mat, struct_as_record=False,
                     squeeze_me=True)['EEG']

    # test reading file with one event (read old version)
    negative_latency_fname = op.join(tmpdir, 'test_negative_latency.set')
    evnts = deepcopy(eeg.event[0])
    evnts.latency = 0
    io.savemat(negative_latency_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate,
                        'nbchan': eeg.nbchan,
                        'data': 'test_negative_latency.fdt',
                        'epoch': eeg.epoch, 'event': evnts,
                        'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}},
               appendmat=False, oned_as='row')
    shutil.copyfile(op.join(base_dir, 'test_raw.fdt'),
                    negative_latency_fname.replace('.set', '.fdt'))
    with pytest.warns(RuntimeWarning, match="has a sample index of -1."):
        read_raw_eeglab(input_fname=negative_latency_fname, preload=True)

    # test negative event latencies
    evnts.latency = -1
    io.savemat(negative_latency_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate,
                        'nbchan': eeg.nbchan,
                        'data': 'test_negative_latency.fdt',
                        'epoch': eeg.epoch, 'event': evnts,
                        'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}},
               appendmat=False, oned_as='row')
    with pytest.raises(ValueError, match='event sample index is negative'):
        with pytest.warns(RuntimeWarning, match="has a sample index of -1."):
            read_raw_eeglab(input_fname=negative_latency_fname, preload=True)

    # test overlapping events
    overlap_fname = op.join(tmpdir, 'test_overlap_event.set')
    io.savemat(overlap_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate,
                        'nbchan': eeg.nbchan, 'data': 'test_overlap_event.fdt',
                        'epoch': eeg.epoch,
                        'event': [eeg.event[0], eeg.event[0]],
                        'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}},
               appendmat=False, oned_as='row')
    shutil.copyfile(op.join(base_dir, 'test_raw.fdt'),
                    overlap_fname.replace('.set', '.fdt'))
    read_raw_eeglab(input_fname=overlap_fname, preload=True)

    # test reading file when the EEG.data name is wrong
    io.savemat(overlap_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate,
                        'nbchan': eeg.nbchan, 'data': 'test_overla_event.fdt',
                        'epoch': eeg.epoch,
                        'event': [eeg.event[0], eeg.event[0]],
                        'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}},
               appendmat=False, oned_as='row')
    with pytest.warns(RuntimeWarning, match="must have changed on disk"):
        read_raw_eeglab(input_fname=overlap_fname, preload=True)

    # raise error when both EEG.data and fdt name from set are wrong
    overlap_fname = op.join(tmpdir, 'test_ovrlap_event.set')
    io.savemat(overlap_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate,
                        'nbchan': eeg.nbchan, 'data': 'test_overla_event.fdt',
                        'epoch': eeg.epoch,
                        'event': [eeg.event[0], eeg.event[0]],
                        'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}},
               appendmat=False, oned_as='row')
    with pytest.raises(FileNotFoundError, match="not find the .fdt data file"):
        read_raw_eeglab(input_fname=overlap_fname, preload=True)

    # test reading file with one channel
    one_chan_fname = op.join(tmpdir, 'test_one_channel.set')
    io.savemat(one_chan_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate,
                        'nbchan': 1, 'data': np.random.random((1, 3)),
                        'epoch': eeg.epoch, 'event': eeg.epoch,
                        'chanlocs': {'labels': 'E1', 'Y': -6.6069,
                                     'X': 6.3023, 'Z': -2.9423},
                        'times': eeg.times[:3], 'pnts': 3}},
               appendmat=False, oned_as='row')
    read_raw_eeglab(input_fname=one_chan_fname, preload=True)

    # test reading file with 3 channels - one without position information
    # first, create chanlocs structured array
    ch_names = ['F3', 'unknown', 'FPz']
    x, y, z = [1., 2., np.nan], [4., 5., np.nan], [7., 8., np.nan]
    dt = [('labels', 'S10'), ('X', 'f8'), ('Y', 'f8'), ('Z', 'f8')]
    nopos_dt = [('labels', 'S10'), ('Z', 'f8')]
    chanlocs = np.zeros((3,), dtype=dt)
    nopos_chanlocs = np.zeros((3,), dtype=nopos_dt)
    for ind, vals in enumerate(zip(ch_names, x, y, z)):
        for fld in range(4):
            chanlocs[ind][dt[fld][0]] = vals[fld]
            if fld in (0, 3):
                nopos_chanlocs[ind][dt[fld][0]] = vals[fld]
    # In theory this should work and be simpler, but there is an obscure
    # SciPy writing bug that pops up sometimes:
    # nopos_chanlocs = np.array(chanlocs[['labels', 'Z']])

    if LooseVersion(np.__version__) == '1.14.0':
        # There is a bug in 1.14.0 (or maybe with SciPy 1.0.0?) that causes
        # this write to fail!
        raise SkipTest('Need to fix bug in NumPy 1.14.0!')

    # test reading channel names but not positions when there is no X (only Z)
    # field in the EEG.chanlocs structure
    nopos_fname = op.join(tmpdir, 'test_no_chanpos.set')
    io.savemat(nopos_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate, 'nbchan': 3,
                        'data': np.random.random((3, 2)), 'epoch': eeg.epoch,
                        'event': eeg.epoch, 'chanlocs': nopos_chanlocs,
                        'times': eeg.times[:2], 'pnts': 2}},
               appendmat=False, oned_as='row')
    # load the file
    raw = read_raw_eeglab(input_fname=nopos_fname, preload=True)

    # test that channel names have been loaded but not channel positions
    for i in range(3):
        assert_equal(raw.info['chs'][i]['ch_name'], ch_names[i])
        assert_array_equal(raw.info['chs'][i]['loc'][:3],
                           np.array([np.nan, np.nan, np.nan]))

@pytest.mark.slowtest  # slow-ish on Travis OSX
@pytest.mark.timeout(60)  # ~60 sec on Travis OSX
@requires_h5py
@testing.requires_testing_data
@pytest.mark.parametrize('fnames', [epochs_mat_fnames, epochs_h5_fnames])
def test_io_set_epochs(fnames):
    """Test importing EEGLAB .set epochs files."""
    epochs_fname, epochs_fname_onefile = fnames
    with pytest.warns(RuntimeWarning, match='multiple events'):
        epochs = read_epochs_eeglab(epochs_fname)
    with pytest.warns(RuntimeWarning, match='multiple events'):
        epochs2 = read_epochs_eeglab(epochs_fname_onefile)
    # one warning for each read_epochs_eeglab because both files have epochs
    # associated with multiple events
    assert_array_equal(epochs.get_data(), epochs2.get_data())

@testing.requires_testing_data
def test_io_set_epochs_events(tmpdir):
    """Test different combinations of events and event_ids."""
    tmpdir = str(tmpdir)
    out_fname = op.join(tmpdir, 'test-eve.fif')
    events = np.array([[4, 0, 1], [12, 0, 2], [20, 0, 3], [26, 0, 3]])
    write_events(out_fname, events)
    event_id = {'S255/S8': 1, 'S8': 2, 'S255/S9': 3}
    out_fname = op.join(tmpdir, 'test-eve.fif')
    epochs = read_epochs_eeglab(epochs_fname_mat, events, event_id)
    assert_equal(len(epochs.events), 4)
    assert epochs.preload
    assert epochs._bad_dropped
    epochs = read_epochs_eeglab(epochs_fname_mat, out_fname, event_id)
    pytest.raises(ValueError, read_epochs_eeglab, epochs_fname_mat,
                  None, event_id)
    pytest.raises(ValueError, read_epochs_eeglab, epochs_fname_mat,
                  epochs.events, None)

@testing.requires_testing_data
def test_degenerate(tmpdir):
    """Test some degenerate conditions."""
    # test if .dat file raises an error
    tmpdir = str(tmpdir)
    eeg = io.loadmat(epochs_fname_mat, struct_as_record=False,
                     squeeze_me=True)['EEG']
    eeg.data = 'epochs_fname.dat'
    bad_epochs_fname = op.join(tmpdir, 'test_epochs.set')
    io.savemat(bad_epochs_fname,
               {'EEG': {'trials': eeg.trials, 'srate': eeg.srate,
                        'nbchan': eeg.nbchan, 'data': eeg.data,
                        'epoch': eeg.epoch, 'event': eeg.event,
                        'chanlocs': eeg.chanlocs, 'pnts': eeg.pnts}},
               appendmat=False, oned_as='row')
    shutil.copyfile(op.join(base_dir, 'test_epochs.fdt'),
                    op.join(tmpdir, 'test_epochs.dat'))
    with pytest.warns(RuntimeWarning, match='multiple events'):
        pytest.raises(NotImplementedError, read_epochs_eeglab,
                      bad_epochs_fname)

@pytest.mark.parametrize("fname", raw_fnames)
@testing.requires_testing_data
def test_eeglab_annotations(fname):
    """Test reading annotations in EEGLAB files."""
    _check_h5(fname)
    annotations = read_annotations(fname)
    assert len(annotations) == 154
    assert set(annotations.description) == {'rt', 'square'}
    assert np.all(annotations.duration == 0.)

@testing.requires_testing_data
def test_eeglab_read_annotations():
    """Test annotations onsets are timestamps (+ validate some)."""
    annotations = read_annotations(raw_fname_mat)
    validation_samples = [0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
    expected_onset = np.array([1.00, 1.69, 2.08, 4.70, 7.71, 11.30, 17.18,
                               20.20, 26.12, 29.14, 35.25, 44.30, 47.15])
    assert annotations.orig_time is None
    assert_array_almost_equal(annotations.onset[validation_samples],
                              expected_onset, decimal=2)

    # test if event durations are imported correctly
    raw = read_raw_eeglab(raw_fname_event_duration, preload=True)
    # file contains 3 annotations with 0.5 s (64 samples) duration each
    assert_allclose(raw.annotations.duration, np.ones(3) * 0.5)

@testing.requires_testing_data
def test_eeglab_event_from_annot():
    """Test all forms of obtaining annotations."""
    base_dir = op.join(testing.data_path(download=False), 'EEGLAB')
    raw_fname_mat = op.join(base_dir, 'test_raw.set')
    raw_fname = raw_fname_mat
    event_id = {'rt': 1, 'square': 2}
    raw1 = read_raw_eeglab(input_fname=raw_fname, preload=False)

    annotations = read_annotations(raw_fname)
    assert len(raw1.annotations) == 154
    raw1.set_annotations(annotations)
    events_b, _ = events_from_annotations(raw1, event_id=event_id)
    assert len(events_b) == 154

def _assert_array_allclose_nan(left, right):
    assert_array_equal(np.isnan(left), np.isnan(right))
    assert_allclose(left[~np.isnan(left)], right[~np.isnan(left)], atol=1e-8)

@pytest.fixture(scope='session')
def one_chanpos_fname(tmpdir_factory):
    """Test file with 3 channels to exercise EEGLAB reader.

    File characteristics
       - ch_names: 'F3', 'unknown', 'FPz'
       - 'FPz' has no position information.
       - the rest is aleatory

    Notes from when this code was factorized:
    # test reading file with one event (read old version)
    """
    fname = str(tmpdir_factory.mktemp('data').join('test_chanpos.set'))
    file_conent = dict(EEG={
        'trials': 1, 'nbchan': 3, 'pnts': 3, 'epoch': [], 'event': [],
        'srate': 128, 'times': np.array([0., 0.1, 0.2]),
        'data': np.empty([3, 3]),
        'chanlocs': np.array(
            [(b'F3', 1., 4., 7.),
             (b'unknown', 2., 5., 8.),
             (b'FPz', np.nan, np.nan, np.nan)],
            dtype=[('labels', 'S10'), ('X', 'f8'), ('Y', 'f8'), ('Z', 'f8')]
        )
    })

    io.savemat(file_name=fname, mdict=file_conent, appendmat=False,
               oned_as='row')

    return fname

@testing.requires_testing_data
def test_position_information(one_chanpos_fname):
    """Test reading file with 3 channels - one without position information."""
    nan = np.nan
    EXPECTED_LOCATIONS_FROM_FILE = np.array([
        [-4.,  1.,  7.,  0.,  0.,  0., nan, nan, nan, nan, nan, nan],  # noqa: E241,E501
        [-5.,  2.,  8.,  0.,  0.,  0., nan, nan, nan, nan, nan, nan],  # noqa: E241,E501
        [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan],
    ])

    EXPECTED_LOCATIONS_FROM_MONTAGE = np.array([
        [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan],
        [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan],
        [nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan],
    ])

    raw = read_raw_eeglab(input_fname=one_chanpos_fname, preload=True)
    assert_array_equal(np.array([ch['loc'] for ch in raw.info['chs']]),
                       EXPECTED_LOCATIONS_FROM_FILE)

    # To accommodate the new behavior so that:
    # read_raw_eeglab(.. montage=montage) and raw.set_montage(montage)
    # behaves the same we need to flush the montage. otherwise we get
    # a mix of what is in montage and in the file
    raw = read_raw_eeglab(
        input_fname=one_chanpos_fname,
        preload=True,
    ).set_montage(None)  # Flush the montage builtin within input_fname

    _assert_array_allclose_nan(np.array([ch['loc'] for ch in raw.info['chs']]),
                               EXPECTED_LOCATIONS_FROM_MONTAGE)

    _assert_array_allclose_nan(np.array([ch['loc'] for ch in raw.info['chs']]),
                               EXPECTED_LOCATIONS_FROM_MONTAGE)

run_tests_if_main()