import glob
import json
import os
import argparse
import time
import re
import pickle

# Libs
from tqdm import tqdm
from xmltodict import unparse
import xml.etree.ElementTree as ET
import sys
import numpy as np
import pandas as pd
from multiprocessing import Pool

import matplotlib

# If you get _tkinter.TclError: no display name and no $DISPLAY environment variable use
# matplotlib.use('Agg') instead
matplotlib.use('TkAgg')

from six import BytesIO

import matplotlib.pyplot as plt
from PIL import Image, ImageDraw, ImageFont

import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as viz_utils

# Own modules
import bbox_utils as bbox
import image_utils as im
from datetime import datetime

__author__ = 'Alexander Wendt'
__copyright__ = 'Copyright 2021, Christian Doppler Laboratory for ' \
                'Embedded Machine Learning'
__credits__ = ['']
__license__ = 'ISC'
__version__ = '0.1.0'
__maintainer__ = 'Alexander Wendt'
__email__ = 'alexander.wendt@tuwien.ac.at'
__status__ = 'Experimental'

parser = argparse.ArgumentParser(description='Google Tensorflow Detection API 2.0 Inferrer')
# parser.add_argument("-p", '--model_path', default='pre-trained-models/efficientdet_d5_coco17_tpu-32/saved_model/',
#                    help='Saved model path', required=False)
parser.add_argument("-i", '--image_dir', default='images/inference',
                    help='Image directory', required=False)
parser.add_argument("-l", '--labelmap', default='annotations/mscoco_label_map.pbtxt.txt',
                    help='Labelmap path', required=False)
parser.add_argument("-d", '--detections_file', default='detections.csv',
                    help='TF2 Object Detection API saved inference file as csv.', required=False)
parser.add_argument("-s", '--min_score', default=0.5, type=float,
                    help='Max score of detection box to save the image.', required=False)

# parser.add_argument("-r", '--run_detection', default=False,
#                    help='Run detection or load saved detection model', required=False, type=bool)
# parser.add_argument("-x", '--xml_dir', default=None,
#                    help='Source of XML files. '
#                         'If run_detection is True, xml files are saved here. '
#                         'If run detection is False, XML files are loaded from here. '
#                         'If run_detection is True and value is None, no XMLs are saved.', required=False, type=str)
# parser.add_argument("-vis", '--run_visualization', default=False,
#                    help='Run image visualization', required=False, type=bool)
parser.add_argument("-o", '--output_dir', default="detection_images", help='Result directory for images. ',
                    required=False)
# parser.add_argument("-lat", '--latency_out', default="latency.csv", help='Output path for latencies file, which is '
#                                                                         'appended or created new. ',
#                    required=False)

# parser.add_argument("-m", '--model_name', default="Model", type=str,
#                    help='Model name for collecting model data.', required=False)
# parser.add_argument("-hw", '--hardware_name', default="Hardware", type=str,
#                    help='Hardware name collecting statistical data.', required=False)

args = parser.parse_args()

def load_model(model_path):
    '''
    Load tensorflow model

    :param model_path:
    :return:
    '''

    print("Start model loading from path ", model_path)
    tf.keras.backend.clear_session()
    start_time = time.time()
    detect_fn = tf.saved_model.load(model_path)
    end_time = time.time()
    elapsed_time = end_time - start_time
    print('Finished. Elapsed time: {:.0f}s'.format(elapsed_time))

    return detect_fn

def create_single_imagedict(source, image_name):
    '''

    :type

    '''
    image_dict = {}
    image_path = os.path.join(source, image_name)
    image_np = bbox.load_image_into_numpy_array(image_path)
    input_tensor = np.expand_dims(image_np, 0)
    image_dict[image_name] = (image_np, input_tensor)
    return image_dict

def detect_image(detect_fn, image_path, min_score):
    '''

    :param detect_fn:
    :param image_dict:

    :return:
    '''
    elapsed = []
    detection_dict = dict()

    # print("Start detection")
    # for image_name in image_list:
    # Load image
    # image_path = os.path.join(image_dir, image_name)
    # Convert image to array
    print("Process ", image_path)
    image_np = im.load_image_into_numpy_array(image_path)

    # Make image tensor of it
    input_tensor = np.expand_dims(image_np, 0)

    # Infer
    start_time = time.time()
    detections = detect_fn(input_tensor)
    end_time = time.time()
    latency = end_time - start_time
    # elapsed.append(latency)

    image_filename = os.path.basename(image_path)

    print("Inference time {} : {}s".format(image_filename, latency))

    # Process detections
    boxes = detections['detection_boxes'][0].numpy()
    classes = detections['detection_classes'][0].numpy().astype(np.int32)
    scores = detections['detection_scores'][0].numpy()

    return image_filename, image_np, boxes, classes, scores, latency

def convert_reduced_detections_to_df(image_filename, image_np, boxes, classes, scores, min_score=0.8):
    image_width = image_np.shape[1]
    image_height = image_np.shape[0]

    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax', 'score']
    xml_df = pd.DataFrame(columns=column_name)

    for i in range(scores.shape[0]):
        if min_score <= scores[i]:
            ymin, xmin, ymax, xmax = tuple(boxes[i].tolist())
            content = [image_filename, image_width, image_height,
                       classes[i], xmin, ymin, xmax, ymax, scores[i]]
            xml_df = xml_df.append(pd.DataFrame([content], columns=column_name))

    return xml_df

def plot_image(image, title=None):
    ax = plt.subplot(111)
    ax.tick_params(labelbottom=False, labelleft=False)
    if title:
        plt.title(title, fontsize=40)
    plt.imshow(image)

    plt.axis('off')
    plt.tight_layout()

    return plt.gcf()

def infer_images(detections_file, image_dir, labelmap, min_score, output_dir):
    '''

    '''
    if not os.path.isdir(output_dir):
        os.makedirs(output_dir)
        print("Created ", output_dir)

    # Load inference images
    print("Loading images from ", image_dir)
    image_list = im.get_images_name(image_dir)

    # Load label path
    print("Loading labelmap from ", labelmap)
    category_index = label_map_util.create_category_index_from_labelmap(os.path.abspath(labelmap))

    # Load stored XML Files
    print("Loading saved Detections files from ealier inferences from ", detections_file)
    data = pd.read_csv(detections_file, sep=';').set_index('filename')

    # Define scores and latencies
    # detection_scores = pd.DataFrame(columns=['filename', 'width', 'height', 'class', 'xmin',
    #
    # 'ymin', 'xmax', 'ymax', 'score'])
    # Process each image
    for image_name in image_list:

        print("Load xml data for ", image_name)
        if isinstance(data.loc[image_name], pd.Series):
            subdata = pd.DataFrame([data.loc[image_name]])
        else:
            subdata = data.loc[image_name]
        #classes = np.array(data.loc[image_name].shape[0])
        boxes = np.zeros([subdata.shape[0], 4])
        classes = np.zeros([subdata.shape[0]]).astype('int')

        if 'score' in subdata.columns and subdata['score'][0] is not None:
            scores = np.zeros([subdata.shape[0]])
        else:
            scores = None

        for i in range(subdata.shape[0]):
            boxes[i][0] = subdata['ymin'][i]
            boxes[i][1] = subdata['xmin'][i]
            boxes[i][2] = subdata['ymax'][i]
            boxes[i][3] = subdata['xmax'][i]

            if 'score' in data.columns and subdata['score'][i] is not None:
                scores[i] = subdata['score'][i]

            #class_index = [category_index[j + 1].get('id') for j in range(len(category_index)) if
            #               category_index[j + 1].get('name') == subdata['class'][i]][0]

            classes[i] = subdata['class'][i]

        #if classes.size == 1:  # If only one detection
        #    classes = classes.reshape(-1)
        #    np.vstack(classes, 1)
        #scores = np.array(data.loc[image_name]['score'])
        #if scores.size == 1:  # If only one detection
        #    scores = scores.reshape(-1)
        #    np.vstack(scores, 0)
        #boxes = np.array(data.loc[image_name][['ymin', 'xmin', 'ymax', 'xmax']])
        #if boxes.size==4:
        #    boxes = boxes.reshape(1, -1)
        #    np.vstack(boxes, [0, 0, 0, 0])
        image_filename = image_name
        image_np = im.load_image_into_numpy_array(os.path.join(image_dir, image_name))

        # If output directory is provided, visualize and save image
        image = bbox.visualize_image(image_name, image_np, scores, boxes, classes, category_index, min_score=min_score)

        plt.gcf()
        new_image_path = os.path.join(output_dir, os.path.splitext(image_filename)[0] + "_det" + ".png")
        print("Save image {} to {}".format(image_filename, new_image_path))

        fig = plot_image(image)
        plt.savefig(new_image_path)

if __name__ == "__main__":
    infer_images(args.detections_file, args.image_dir, args.labelmap, args.min_score, args.output_dir)

    print("=== Program end ===")


from onyx.core import Structure, DateOffset
from onyx.core import GraphNodeDescriptor, GetVal
from onyx.core import FloatField, StringField, ReferenceField

from .ufo_commod_forward import CommodForward
from ..system.tradable_api import AgingTradableObj, AddByInference
from ..system.tradable_api import HashStoredAttrs
from ..system.ufo_forward_cash import ForwardCash

__all__ = ["CommodFutures"]

###############################################################################
class CommodFutures(AgingTradableObj):
    """
    Tradable class that represents a commodity futures contract with physical
    delivery.
    """
    Asset = ReferenceField(obj_type="CommodCnt")
    FixedPrice = FloatField(positive=True)

    # --- the settlement currency can differ from the denomination of the asset
    SettlementCcy = ReferenceField(obj_type="Currency")

    # --- fx rate uesd to convert the fixed price (which is expressed in the
    #     currency of the asset) to the settlement currency
    SettlementFx = FloatField()

    # --- the date rule for the cash payment, defaults to 2 biz days after
    #     settlement
    PaymentDateRule = StringField("+2b")

    # -------------------------------------------------------------------------
    def __post_init__(self):
        asset_ccy = GetVal(self.Asset, "Denominated")

        self.SettlementCcy = self.SettlementCcy or asset_ccy

        if self.SettlementFx is None:
            # --- default to spot
            if asset_ccy == self.SettlementCcy:
                fx = 1.0
            else:
                asset_cross = "{0:3s}/USD".format(asset_ccy)
                sett_cross = "{0:3s}/USD".format(self.SettlementCcy)
                fx = GetVal(asset_cross, "Spot") / GetVal(sett_cross, "Spot")

            self.SettlementFx = fx

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def Leaves(self, graph):
        asset = graph(self, "Asset")
        mul = graph(asset, "Multiplier")
        lot = graph(asset, "ContractSize")
        cal = graph(asset, "HolidayCalendar")

        sett_fx = graph(self, "SettlementFx")
        sett_date = graph(asset, "FutSettDate")
        pay_rule = graph(self, "PaymentDateRule")

        fwd_info = {
            "Asset": graph(asset, "CommodAsset"),
            "AvgStartDate": sett_date,
            "AvgEndDate": sett_date,
            "AvgType": "LAST",
            "Margined": True,
        }
        cash_info = {
            "Currency": graph(self, "SettlementCcy"),
            "PaymentDate": DateOffset(sett_date, pay_rule, cal),
        }

        fwd_sec = AddByInference(CommodForward(**fwd_info), True)
        cash_sec = AddByInference(ForwardCash(**cash_info), True)

        # --- use list-based constructor to enforce key ordering
        return Structure([
            (fwd_sec.Name,  lot),
            (cash_sec.Name, -lot*mul*sett_fx*graph(self, "FixedPrice"))
        ])

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def MktValUSD(self, graph):
        mtm = 0.0
        for sec, qty in graph(self, "Leaves").items():
            mtm += qty*graph(sec, "MktValUSD")
        return mtm

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def MktVal(self, graph):
        sett_ccy = graph(self, "SettlementCcy")
        spot_fx = graph("{0:3s}/USD".format(sett_ccy), "Spot")
        return graph(self, "MktValUSD") / spot_fx

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def ExpirationDate(self, graph):
        asset = graph(self, "Asset")
        cnt = graph(asset, "GetContract", graph(self, "DeliveryMonth"))
        return graph(cnt, "FutSettDate")

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def NextTransactionDate(self, graph):
        return graph(self, "ExpirationDate")

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def TradeTypes(self, graph):
        mapping = super().TradeTypes
        mapping.update({
            "Delivery": "DeliverySecurities",
        })
        return mapping

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def ExpectedTransaction(self, graph):
        return "Delivery"

    # -------------------------------------------------------------------------
    @GraphNodeDescriptor()
    def DeliverySecurities(self, graph):
        """
        Delivery of physical commodity: here we only include the cash leg
        """
        asset = graph(self, "Asset")
        sett_ccy = graph(self, "SettlementCcy")
        sett_date = graph(asset, "FutSettDate")
        pay_rule = graph(self, "PaymentDateRule")
        cal = graph(asset, "HolidayCalendar")

        mul = graph(asset, "Multiplier")
        lot = graph(asset, "ContractSize")

        cash = ForwardCash(Currency=sett_ccy,
                           PaymentDate=DateOffset(sett_date, pay_rule, cal))

        return [
            {"Security": AddByInference(cash, in_memory=True),
             "Quantity": -mul*lot*graph(self, "FixedPrice")},
        ]

    # -------------------------------------------------------------------------
    #  this property is used by edit screens
    @GraphNodeDescriptor()
    def AssetSpot(self, graph):
        return graph(graph(self, "Asset"), "Spot")

    # -------------------------------------------------------------------------
    @property
    def ImpliedName(self):
        mkt = GetVal(self.Asset, "Market")
        sym = GetVal(self.Asset, "Symbol")
        cnt = GetVal(self.Asset, "DeliveryMonth")
        mush = HashStoredAttrs(self, 3)
        return ("CmdFUT {0:s} {1:s} {2:3s}"
                " {3:3s} {{0:2d}}").format(mkt, sym, cnt, mush)

# -----------------------------------------------------------------------------
def prepare_for_test():
    from . import ufo_commod_contract
    from ..system import ufo_forward_cash

    cnt, prc = ufo_commod_contract.prepare_for_test()[0]
    ufo_forward_cash.prepare_for_test()

    info = {
        "Asset": cnt,
        "FixedPrice": prc - 0.1,
    }

    securities = [AddByInference(CommodFutures(**info))]

    return [sec.Name for sec in securities]


# non local imports ^_^
# if your reading this use auto-py-to-exe to convert this to an .exe file
from colorama import Fore, Back, Style
import asyncio
import time
import sys
import socket
import requests

x = 0
responses = []

async def get_isp_from_api(ip):
    url = f"http://ip-api.com/json/{ip}"
    response = requests.get(url)

    if response.status_code == 200:
        data = response.json()
        return data["isp"]
    else:
        print(f"Failed to fetch ISP information. Status code: {response.status_code}")
        return None
    pass

async def ping(host, port, x):
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    timeout = 1
    try:
        client_socket.settimeout(timeout)

        await asyncio.sleep(1)

        start_time = time.time()
        client_socket.connect((host, port))
        end_time = time.time()

        response_time = (end_time - start_time) * 1000
        responses.insert(x,
                         f"time= {Fore.GREEN}{response_time:.2f}ms{Fore.RESET} - port={Fore.GREEN}{port}{Fore.RESET} ")
        return response_time

    except socket.timeout:
        responses.insert(x,
                         f"{Fore.RED}TIMED OUT{Fore.RESET} - port={Fore.RED}{port}{Fore.RESET} ")
        return None
    except socket.error as e:
        print(f"Error: {e}")
        return None
    finally:
        client_socket.close()

async def startup():

    global x
    host = sys.argv[1]
    ports = [int(c) for c in sys.argv[2].split(',')]
    ip = socket.gethostbyname(host)
    isp = await get_isp_from_api(ip)
    while True:
        for port in ports:
            x = x + 1
            asyncio.create_task(ping(host, port, x))
        all_tasks = asyncio.all_tasks()
        current_task = asyncio.current_task()
        all_tasks.remove(current_task)
        await asyncio.wait(all_tasks)
        print(f"Connected to {Fore.GREEN}{host}{Fore.RESET} ({Fore.MAGENTA}{isp}{Fore.RESET}) {''.join(responses)} ")
        responses.clear()
        x = 0

asyncio.run(startup())


from config import dino_pretrain_path
from .resnet import ResNet
from .vision_transformer import *
import torch

def get_backbone(args, **kwargs):
    if "resnet" in args.arch:
        return _get_resnet_backbone(args)
    elif "vit" in args.arch:
        return _get_vit_backbone(args, **kwargs)
    else:
        raise NotImplementedError("The arch has not implemented.")

def _get_resnet_backbone(args):
    backbone = ResNet(args.arch, args.low_res)
    return backbone

def _get_vit_backbone(args, drop_path_rate=0):
    vit_backbone = vit_base(drop_path_rate=drop_path_rate)
    # vit_backbone = vit_small(drop_path_rate=drop_path_rate)
    try:
        state_dict = torch.load(dino_pretrain_path, map_location='cpu')
        vit_backbone.load_state_dict(state_dict)
    except RuntimeError:
        print("Noting you are failed to load the pretrained model, we will load the dino pretrained model.")
    for m in vit_backbone.parameters():
        m.requires_grad = False

    # Only finetune layers from block 'args.grad_from_block' onwards
    for name, m in vit_backbone.named_parameters():
        if 'block' in name:
            block_num = int(name.split('.')[1])
            if block_num >= args.grad_from_block:
                m.requires_grad = True

    return vit_backbone


from construct import Struct, Int32ul, Int16ul, Int8ul, Nibble, Const, IfThenElse, this, Bytes, BitStruct

from formats.common import FlagsEnumCumulative

'''
typedef enum FLG_CONTIGUOUS_MIP {
    FLG_7ZIP = 0x40000000,
    FLG_ADDRU_MASK = 0xf,
    FLG_ADDRV_MASK = 0xf0,
    FLG_ARRTEX = 0x200000,
    FLG_COMPR_MASK = 0xe0000000,
    FLG_CONTIGUOUS_MIP = 0x100,
    FLG_CUBTEX = 0x800,
    FLG_GAMMA_EQ_1 = 0x8000,
    FLG_GENMIP_BOX = 0x2000,
    FLG_GENMIP_KAIZER = 0x4000,
    FLG_GLES3_TC_FMT = 0x100000,
    FLG_HASBORDER = 0x400,
    FLG_HOLD_SYSMEM_COPY = 0x10000,
    FLG_HQ_PART = 0x80000,
    FLG_NEED_PAIRED_BASETEX = 0x20000,
    FLG_NONPACKED = 0x200,
    FLG_OODLE = 0x60000000,
    FLG_REV_MIP_ORDER = 0x40000,
    FLG_VOLTEX = 0x1000,
    FLG_ZLIB = 0x80000000,
    FLG_ZSTD = 0x20000000
} FLG_CONTIGUOUS_MIP;
'''
ddsx_flags_enum = FlagsEnumCumulative(
    Int32ul,
    FLG_7ZIP=0x40_000_000,
    FLG_ADDRU_MASK=0xf,
    FLG_ADDRV_MASK=0xf0,
    FLG_ARRTEX=0x200_000,
    FLG_COMPR_MASK=0xe0_000_000,
    FLG_CONTIGUOUS_MIP=0x100,
    FLG_CUBTEX=0x800,
    FLG_GAMMA_EQ_1=0x8_000,
    FLG_GENMIP_BOX=0x2_000,
    FLG_GENMIP_KAIZER=0x4_000,
    FLG_GLES3_TC_FMT=0x100_000,
    FLG_HASBORDER=0x400,
    FLG_HOLD_SYSMEM_COPY=0x10_000,
    FLG_HQ_PART=0x80_000,
    FLG_NEED_PAIRED_BASETEX=0x20_000,
    FLG_NONPACKED=0x200,
    FLG_OODLE=0x60_000_000,
    FLG_REV_MIP_ORDER=0x40_000,
    FLG_VOLTEX=0x1_000,
    FLG_ZLIB=0x80_000_000,
    FLG_ZSTD=0x20_000_000
)

'''
struct Header {
    uint label;
    uint d3dFormat;
    uint flags;
    ushort w;
    ushort h;
    uchar levels;
    uchar hqPartLevels;
    ushort depth;
    ushort bitsPerPixel;
    uchar lQmip:4;
    uchar mQmip:4;
    uchar dxtShift:4;
    uchar uQmip:4;
    uint memSz;
    uint packedSz;
};
'''
ddsx_header = Struct(
    "label" / Const(b"DDSx"),
    "d3dFormat" / Bytes(4),
    # there error in parsing flags, fixed somewhere on future of construct, but not on 2.9.24
    "flags" / ddsx_flags_enum,
    "w" / Int16ul,
    "h" / Int16ul,
    "levels" / Int8ul,
    "hqPartLevels" / Int8ul,
    "depth" / Int16ul,
    "bitsPerPixel" / Int16ul,
    # this field added, from Embedded(BitStruct constrict package updating
    "bits_" / BitStruct(
        "lQmip" / Nibble,
        "mQmip" / Nibble,
        "dxtShift" / Nibble,
        "uQmip" / Nibble,
    ),
    "memSz" / Int32ul,
    "packedSz" / Int32ul,
)

ddsx = Struct(
    "header" / ddsx_header,
    "body" / IfThenElse(
        this.header.packedSz != 0,
        Bytes(this.header.packedSz),
        Bytes(this.header.memSz)
    )
)


import copy
import math
import sys
import time

import numpy as np
import readdata

_bid_, _req_, _delta_, _re_, eBW, cBW, _sigma_ = readdata.get_data()

ECS_SIZE = len(_re_)
USER_SIZE = len(_bid_)

if ECS_SIZE > 0:
    RES_SIZE = len(_re_[0])
else:
    RES_SIZE = 0

ecs_cap = np.array(_re_)
user_deploy = np.array(_delta_)
user_req = np.array(_req_)
user_sigma = np.array(_sigma_, dtype=np.float64)
user_bid = np.array(_bid_, dtype=np.float64)

class USER:
    def __init__(self, id, req: list, deploy: list, bid: float, sigma: float):
        self.id = id
        self.deploy = deploy
        self.req = req
        self.bid = bid
        self.sigma = sigma
        self.allocated = False

class ECS:  # 服务器类
    def __init__(self, id, r_: list):
        self.id = id
        self.cap = r_

def is_feasible(User: USER, cpr):
    flag = True
    for r in range(RES_SIZE):
        if User.req[r] > cpr[r]:
            flag = False
            break
    return flag

def g_pmrm_win(users, Ecss):
    max_payment = 0
    obj_X = [[0] * USER_SIZE] * ECS_SIZE
    bw_cloud = cBW
    bw_cloud2 = cBW
    for ecs in Ecss:
        Users = []

        for i in users:
            if _delta_[i.id][ecs.id] == 1 and i.allocated is False:
                Users.append(i)
        """First phase"""
        cap = ecs.cap.copy()
        obj_x1 = [0] * USER_SIZE
        canallocatuser = []
        half_cap = np.array(cap)
        for user in Users:
            if is_feasible(user, cap):
                canallocatuser.append(user)
        max_pay = 0
        max_j = -1
        for user in canallocatuser:
            if user.bid > max_pay and all(map(lambda x: x >= 0, half_cap - user.req)) and bw_cloud - (
                    user.req[3] * user.sigma) > 0:
                max_pay = user.bid
                max_j = user.id
                bw_cloud -= user.req[3] * user.sigma
        if max_j != -1:
            obj_x1[max_j] = 1
        """Second phase"""
        canallocatuser2 = []
        obj_x2 = [0] * USER_SIZE
        for user in Users:
            if is_feasible(user, half_cap):
                canallocatuser2.append(user)
        if len(canallocatuser2) == 0:
            continue
        norm_di = []
        for user in canallocatuser2:
            sum_rec = 0
            for r in range(RES_SIZE):
                sum_rec += user.req[r] / cap[r]
            sum_rec = sum_rec ** 0.5
            norm_di.append([user.id, user.bid / sum_rec])
        norm_di.sort(key=lambda x: x[1], reverse=True)
        allocate_user = []
        cap_copy = [0] * RES_SIZE
        flag = True
        while (len(canallocatuser2) != 0) and flag:
            index_i = norm_di[0][0]
            for r in range(RES_SIZE):
                if half_cap[r] - users[index_i].req[r] < 0 or bw_cloud2 - (
                        users[index_i].req[3] * users[index_i].sigma) < 0:
                    flag = False
            if flag:
                copyi = 0
                for i in range(len(canallocatuser2)):
                    if canallocatuser2[i].id == index_i:
                        copyi = i
                        allocate_user.append(canallocatuser2[copyi])
                        del canallocatuser2[i]
                        del norm_di[0]
                        break
                obj_x2[index_i] = 1
                for r in range(RES_SIZE):
                    # cap_copy[r] += Users[copyi].req[r]
                    half_cap[r] -= Users[copyi].req[r]
                    bw_cloud2 -= Users[copyi].req[3]*Users[copyi].sigma
        max_pay2 = 0
        cap_alloc = [0] * RES_SIZE
        if len(allocate_user) != 0:
            for i in range(len(allocate_user) - 1):
                max_pay2 += allocate_user[i].bid
                for r in range(RES_SIZE):
                    cap_alloc[r] += allocate_user[i].req[r]
            last_user = allocate_user[len(allocate_user) - 1]
            for r in range(RES_SIZE):
                last_user.req[r] = cap[r] / 2 - cap_alloc[r]
            flag = True
            for r in range(RES_SIZE):
                if allocate_user[len(allocate_user) - 1].req[r] > last_user.req[r]:
                    flag = False
            if flag:
                for r in range(RES_SIZE):
                    last_user.req[r] = allocate_user[len(allocate_user) - 1].req[r]
            for d in range(len(norm_di)):
                if last_user.id == norm_di[d][0]:
                    sums = 0
                    for r in range(RES_SIZE):
                        sums += last_user.req[r] / cap[r]
                    sums = sums ** 0.5
                    last_user.bid = norm_di[d][1] * sums
            max_pay2 += last_user.bid
        """Third phase"""
        if max_pay >= max_pay2:
            payment_p = max_pay
            win_p = obj_x1
            for rr in range(RES_SIZE):
                half_cap[rr] -= users[max_j].req[rr]
            bw_cloud2 = bw_cloud
        else:
            payment_p = max_pay2
            win_p = obj_x2
            bw_cloud = bw_cloud2
        for winer in range(len(win_p)):
            if win_p[winer] == 1:
                users[winer].allocated = True
        max_payment += payment_p
        obj_X[ecs.id] = win_p
    return max_payment, obj_X

ECSs = [ECS(_, ecs_cap[_].copy()) for _ in range(ECS_SIZE)]
USERs = [USER(_, user_req[_].copy(), user_deploy[_].copy(), user_bid[_].copy(), user_sigma[_].copy()) for _ in
         range(USER_SIZE)]

if __name__ == '__main__':
    start = time.perf_counter()
    user_copy = copy.deepcopy(USERs)
    social_welfare, winners = g_pmrm_win(user_copy, ECSs)

    caps = [0] * RES_SIZE
    num_winner = 0
    cbw=0
    for j in ECSs:
        for i in USERs:
            if winners[j.id][i.id] == 1:
                for r in range(RES_SIZE - 1):
                    caps[r] += i.req[r]
                caps[RES_SIZE - 1] += i.req[RES_SIZE - 1] + i.req[RES_SIZE - 1] * i.sigma
                cbw += i.req[RES_SIZE - 1] * i.sigma
                num_winner += 1

    payment = [0] * USER_SIZE
    user_copy = copy.deepcopy(USERs)
    for user in user_copy:
        for j in winners:
            if j[user.id] == 1:
                lb = 0
                hb = user.bid
                while (hb - lb) >= 1:
                    temp_pay = (hb + lb) / 2
                    user_copy[user.id].bid = temp_pay
                    getwiner = g_pmrm_win(user_copy, ECSs)[1]
                    fail = True
                    for es in getwiner:
                        if es[user.id] == 1:
                            hb = temp_pay
                            fail = False
                    if fail:
                        lb = temp_pay
                    user_copy = copy.deepcopy(USERs)
                payment[user.id] = int(hb)
                print("用户%d支付确定" % user.id)
                break
    print("总支付：", sum(payment))
    print("社会福利：", social_welfare)

    print("胜出人数：", num_winner)
    sum_caps = np.sum(ecs_cap, axis=0)
    sum_caps[3] += cBW
    print("资源利用率：", [caps[r] / sum_caps[r] for r in range(RES_SIZE)])
    end = time.perf_counter()
    print("执行时间：", end - start)


from utils import read_file

values = read_file(8, str, False)

grid = []

for current_tree_height in values:
    grid.append(list(current_tree_height))

visible = 0

def get_column(matrix, i):
    return [_row[i] for _row in matrix]

for row in range(len(grid)):
    for column in range(len(grid[row])):
        # Ignore Edges
        if row == 0 or row == len(grid) - 1 or column == 0 or column == len(grid[row]) - 1:
            visible += 1
            continue
        # Current tree height to compare to
        current_tree_height = grid[row][column]
        current_column = get_column(grid, column)
        current_row = grid[row]
        up = current_column[0:row]
        down = current_column[row + 1:]
        left = current_row[0:column]
        right = current_row[column + 1:]
        from_left = len([tree for tree in left if tree >= current_tree_height]) == 0
        from_right = len([tree for tree in right if tree >= current_tree_height]) == 0
        from_up = len([tree for tree in up if tree >= current_tree_height]) == 0
        from_down = len([tree for tree in down if tree >= current_tree_height]) == 0
        if from_up or from_down or from_left or from_right:
            visible += 1

print("Part 1: " + str(visible))
# Part 1: 1809

scenic_scores = []

for row in range(len(grid)):
    for column in range(len(grid[row])):
        # Ignore Edges
        if row == 0 or row == len(grid) - 1 or column == 0 or column == len(grid[row]) - 1:
            continue
        current_tree_height = grid[row][column]
        current_column = get_column(grid, column)
        current_row = grid[row]
        up = current_column[0:row]
        down = current_column[row + 1:]
        left = current_row[0:column]
        right = current_row[column + 1:]

        up_score, down_score, left_score, right_score = 0, 0, 0, 0
        for i in reversed(range(len(up))):
            up_score += 1
            if current_tree_height <= up[i]:
                break

        for i in range(len(down)):
            down_score += 1
            if current_tree_height <= down[i]:
                break

        for i in reversed(range(len(left))):
            left_score += 1
            if current_tree_height <= left[i]:
                break

        for i in range(len(right)):
            right_score += 1
            if current_tree_height <= right[i]:
                break

        scenic_score = up_score * left_score * right_score * down_score
        scenic_scores.append(scenic_score)

print("Part 2: " + str(max(scenic_scores)))
# Part 2: 479400


# script1_merge_files.py
# merge the data

# modules
from HW3_functions import merge_data

def main():
    # merge various data
    df = merge_data(save=True)  # save the merged data to a .csv file

    # print the head and tail to confirm result
    print('\nHead of the merged data:')
    print(df.head())
    print('\n\nTail of the merged data:')
    print(df.tail())

    return

if __name__ == '__main__':
    main()


"""
http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.Python.03.html
"""

from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb',region_name='us-east-1')

table = dynamodb.Table('users')

### put item
id = "The Big New Movie"
email = "given.family@sungardas.com"
family_name = "Family"
given_name = "Given"
name = "Given Family"

response = table.put_item(
   Item={
        'id': id,
        'email': email,
        'family_name': family_name,
        'given_name': given_name,
        'name': name
    }
)

print("PutItem succeeded:")
print(json.dumps(response, indent=4, cls=DecimalEncoder))

### get Item

from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError

try:
    response = table.get_item(
        Key={
            'id': id
        }
    )
except ClientError as e:
    print(e.response['Error']['Message'])
else:
    item = response['Item']
    print("GetItem succeeded:")
    print(json.dumps(item, indent=4, cls=DecimalEncoder))

### update item

try:
    response = table.update_item(
        Key={
                'id': id
        },
        UpdateExpression="set family_name = :fn, given_name=:gn, #name=:n",
        ExpressionAttributeNames={
            '#name': 'name'
        },
        ExpressionAttributeValues={
            ':fn': "Family2",
            ':gn': "Given2",
            ':n': "Given2 Family2"
        },
        #ConditionExpression="size(info.actors) > :num",
        #ExpressionAttributeValues={
        #    ':num': 3
        #},
        ReturnValues="UPDATED_NEW"
    )
except ClientError as e:
    print(e.response['Error']['Message'])
else:
    print("UpdateItem succeeded:")
    print(json.dumps(response, indent=4, cls=DecimalEncoder))

### delete item

try:
    response = table.delete_item(
        Key={
                'id': id
        },
        #ConditionExpression="family_name <> :val",
        #ExpressionAttributeValues= {
        #    ":val": "Family"
        #}
    )
except ClientError as e:
    if e.response['Error']['Code'] == "ConditionalCheckFailedException":
        print(e.response['Error']['Message'])
    else:
        raise
else:
    print("DeleteItem succeeded:")
    print(json.dumps(response, indent=4, cls=DecimalEncoder))


from typing import List, Optional
from db.database import SessionLocal
from db import models
import logging

class NoTeamException(Exception):
    pass

class TeamRepository:

    def __init__(self):
        self.db = SessionLocal()

    def create_team(self, name: str, country: str, cur_pos_league: str) -> models.Team:
        new_team = models.Team(name=name, country=country,
                               cur_pos_league=cur_pos_league)
        self.db.add(new_team)
        self.db.commit()
        self.db.refresh(new_team)
        return new_team

    def delete_team(self, id: int) -> int:
        team = self.db.query(models.Team).filter(
            models.Team.id == id).delete(synchronize_session=False)
        self.db.commit()
        logging.debug('TEAMS FOUND: ',  team)
        if not team:
            raise NoTeamException()
        return team

    def get_teams(self, skip: int, limit: Optional[int] = None) -> List[models.Team]:
        teams = self.db.query(models.Team).offset(skip).limit(limit)
        return teams

    def get_team(self, id: int) -> models.Team:
        team = self.db.query(models.Team).filter(models.Team.id == id).first()
        if not team:
            raise NoTeamException()
        return team

    def update_team(self, id: int, name: str, country: str, cur_pos_league: str) -> models.Team:
        team = self.db.query(models.Team)\
            .filter(models.Team.id == id)\
            .update({models.Team.name: name if name else models.Team.name,
                    models.Team.country: country if country else models.Team.country,
                    models.Team.cur_pos_league: cur_pos_league if cur_pos_league else models.Team.cur_pos_league},
                    synchronize_session=False)
        self.db.commit()
        logging.debug('TEAMS FOUND: ',  team)
        if not team:
            raise NoTeamException()
        return self.db.query(models.Team).filter(models.Team.id == id).first()


from datetime import datetime
from functools import lru_cache

import requests
from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import RedirectResponse
from pydantic import BaseModel, BaseSettings

app = FastAPI(docs_url=None, redoc_url=None)

class Labels(BaseModel):
    alertname: str
    prometheus: str | None = None
    severity: str | None = None

class Annotations(BaseModel):
    description: str
    runbook_url: str
    summary: str

class SingleAlert(BaseModel):
    status: str
    labels: Labels
    annotations: Annotations
    startsAt: datetime | None = None
    endsAt: datetime | None = None
    generatorURL: str
    fingerprint: str | None = None

class Alerts(BaseModel):
    receiver: str
    status: str
    alerts: list[SingleAlert]
    groupLabels: Labels
    commonLabels: Labels
    commonAnnotations: Annotations
    externalURL: str
    version: int
    groupKey: str
    truncatedAlerts: int | None = None

class Settings(BaseSettings):
    env_name: str = "Local"
    kuma_url: str = "http://127.0.0.1:3001"
    kuma_tokens: list[str] = ["AAaaAaAaaa"]

    class Config:
        env_file = ".env"

@lru_cache()
def get_settings():
    return Settings()

# Incoming alerts debugging (POST request body printing)
# NOTE: Need Request in fastapi import
# @app.post("/{token}")
# async def inspect(token: str, r: Request, s: Settings = Depends(get_settings)):
#     body = await r.json()
#     print(body)
#     return body

@app.get("/", response_class=RedirectResponse, status_code=302)
def redirect():
    return "https://github.com/hadret/forwardly"

@app.post("/{token}")
def forward(am: Alerts, token: str, settings: Settings = Depends(get_settings)):
    if token in settings.kuma_tokens:
        kuma = requests.get(f"{settings.kuma_url}/{token}")
        return am, kuma.json()
    else:
        raise HTTPException(status_code=401, detail="Unauthorized")


import datetime, time, os, pyautogui, playsound

from PIL import ImageGrab
from functools import partial
ImageGrab.grab = partial(ImageGrab.grab, all_screens=True)

def min(x, y):
    x *= 60
    return (x + y)

updating_Animation = [
    '[.  ]     ',
    '[.. ]     ',
    '[...]     '
]

started = False
updating_Frame = 0
executed = 0
weekday = datetime.date.today().weekday()
currentTime = min(datetime.datetime.now().hour, datetime.datetime.now().minute)
os.system ("cls")

def Start():
    if (weekday >= 5 or Holiday() == True):
        time.sleep(30)
        Discord()
        os.system ('start ""')
        time.sleep(1)
        pyautogui.write('"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"  https://www.youtube.com/ https://www.netflix.com/browse/ https://geizhals.de/' '&& exit')
        pyautogui.press('enter')
        time.sleep(10)
        pyautogui.hotkey('ctrl', 'tab')
        time.sleep(1)
        pyautogui.click(1600, 700)
        time.sleep(5)
        exit()

def CheckHoliday(x, y, _y, z, _z): #year, month, monthEnd, day, dayEnd
    days = (datetime.date(x, y, z) - datetime.date.today()).days
    _days = (datetime.date(x, _y, _z) - datetime.date.today()).days
    if (days <= 0 and _days >= 0):
        return True
    return False

def Holiday():
    if (CheckHoliday(2021, 3, 4, 31, 11)):
        return True
    elif (CheckHoliday(2021, 5, 6, 23, 6)):
        return True
    elif (CheckHoliday(2021, 7, 9, 29, 11)):
        return True
    elif (CheckHoliday(2021, 5, 5, 13, 16)):
        return True
    return False

def Execution(path, x, *screen):
    try:
        execution = pyautogui.locateCenterOnScreen('Images/' + path, region = (screen))
        pyautogui.click(execution.x - 1920, execution.y)
        time.sleep(x)
    except: playsound.playsound('Sounds/Error.mp3')

def Discord():
    Execution('Discord.png', 1, 0, 265, 1400, 840)
    Execution('Channel.png', 0, 0, 265, 1400, 840)

def Join():
    time.sleep(1)
    pyautogui.click(395, 180)
    time.sleep(2)
    pyautogui.click(1150, 780)
    pyautogui.hotkey('ctrl', 'shift', 'tab')
    pyautogui.hotkey('ctrl', 'w')
    playsound.playsound("Sounds/Message.mp3")

def Complete(j):
    Execution( j , 3, 3720, 700, 2500, 840)
    pyautogui.click(1076, 598)
    pyautogui.click(1220, 700)
    pyautogui.hotkey('ctrl', 'w')

def Open_Link(id):
    os.system ('start ""')
    time.sleep(1)
    pyautogui.write('"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" https://04104644.moodle.belwue.de/moodle/' + id +' && exit')
    pyautogui.press('enter')

def BBB_Join():
    time.sleep(2)
    repeat = 0
    if (pyautogui.locateCenterOnScreen('Images/notakepart.png', region = (2390, 700, 860, 900))):
        while pyautogui.locateCenterOnScreen('Images/takepart.png', region = (2390, 700, 860, 900)) == False and repeat <= 50:
            repeat += 1
            time.sleep(5)
        if (repeat > 50):
            playsound.playsound("Sounds/Error.mp3")
            return
        elif (pyautogui.locateCenterOnScreen('Images/takepart.png', region = (2390, 700, 860, 900))):
            Execution('takepart.png', 1, 2390, 700, 860, 900)
            for _ in range(5):
                time.sleep(2)
                if (pyautogui.locateCenterOnScreen('Images/micro.png', region = (2920, 635, 1300, 920))):
                    Execution('micro.png', 2920, 635, 1300, 920)
                    break
            time.sleep(1)
            Join()
        else:
            pyautogui.hotkey('ctrl', 'w')
            return
    else:
        Execution('takepart.png', 10, 2390, 700, 860, 900)
        Execution('micro.png', 3, 2920, 635, 1300, 920)
        Join()

def Attendence_complete():
    time.sleep(3)
    pyautogui.moveTo(100, 100)
    for i in range(5):
        if(pyautogui.locateCenterOnScreen('Images/Capture.png', region = (3820, 640, 2450, 1100))):
            Complete('Capture.png')
            break
        else:
            if(pyautogui.locateCenterOnScreen('Images/Capture2.png', region = (3820, 640, 2450, 1100))):
                Complete('Capture2.png')
                break
            else:
                pyautogui.scroll(-425)
                if (i == 4):
                    playsound.playsound("Sounds/Error.mp3")
                    pyautogui.hotkey('ctrl', 'w')

def BBB_search():
    time.sleep(3)
    for i in range(10):
        if (pyautogui.locateCenterOnScreen('Images/BBB.png', region = (2465, 475, 1360, 1180))):
            Execution('BBB.png', 1, 2465, 475, 1360, 1180)
            break
        else:
            pyautogui.scroll(-425)
            if (i == 9):
                playsound.playsound("Sounds/Error.mp3")
                pyautogui.hotkey('ctrl', 'w')

def Schedule():
    global started
    global weekday
    if (started == False):
            started = True
            time.sleep(30)
            Discord()
            os.system('start ""')
            time.sleep(1)
            pyautogui.write('"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" https://www.youtube.com/ https://04104644.moodle.belwue.de/moodle/my/ https://www.netflix.com/browse/ https://geizhals.de/ && exit')
            pyautogui.press('enter')
            time.sleep(5)
            pyautogui.hotkey('ctrl', 'tab')
            time.sleep(1)
            pyautogui.click(1040, 630)
            time.sleep(3)
            pyautogui.hotkey('ctrl', 'tab')
            time.sleep(1)
            pyautogui.click(1600, 700)
            pyautogui.hotkey('ctrl', '1')
    elif (weekday == 0):
        Monday()
    elif (weekday == 1):
        Thuesday()
    elif (weekday == 2):
        Wednesday()
    elif (weekday == 3):
        Thursday()
    elif (weekday == 4):
        Friday()

def Monday():
    global executed
    global currentTime
    if (currentTime == min(7,45) and executed != 1):
        executed = 1
        Open_Link('course/view.php?id=208') #Link Reli-Moodleraum
        BBB_search()
        BBB_Join()
        #Open_Link('course/view.php?id=208 && exit') #Link zum Reli-Raum
        #Attendence_complete()
    elif (currentTime == min(9,35) and executed != 2):
        executed = 2
        Open_Link('course/view.php?id=764') #Link zum IMP-Pysikraum
        BBB_search()
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=6599') #Anwesenheitslink IMP Physik
        Attendence_complete()
    elif (currentTime == min(10,20) and executed != 3):
        executed = 3
        Open_Link('course/view.php?id=419') #Link zum IMP-Informatik
        BBB_search()
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=15108') #Anwesenheitslink ImP-Info
        Attendence_complete()
    elif (currentTime == min(11,25) and executed != 4):
        executed = 4
        Open_Link('mod/bigbluebuttonbn/view.php?id=32375') #BBB Englisch
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=12126') #Anwesenheit Englisch
        Attendence_complete()
    elif (currentTime == min(12,10) and executed != 5):
        executed = 5
        Open_Link('mod/bigbluebuttonbn/view.php?id=32576') #BBB Mathe
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=6741') #Anwesenheit Mathe
        Attendence_complete()
    elif (currentTime == min(15,40) and executed != 6):
        executed = 6
        Open_Link('mod/bigbluebuttonbn/view.php?id=35947') #BBB WBS
        BBB_Join()
        exit()

def Thuesday():
    global executed
    global currentTime
    if (currentTime == min(7,45) and executed != 1):
        executed = 1
        Open_Link('mod/bigbluebuttonbn/view.php?id=32907') #BBB Deutsch
        BBB_Join()
    elif (currentTime == min(8,30) and executed != 2):
        executed = 2
        Open_Link('mod/bigbluebuttonbn/view.php?id=23953') #BBB Latein
        BBB_Join()
    elif (currentTime == min(11,25) and executed != 3):
        executed = 3
        Open_Link('course/view.php?id=578') #Link zum Pysikraum
        BBB_search()
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=23299') #Anwesenheit Physik
        Attendence_complete()
    elif (currentTime == min(14,00) and executed != 4):
        executed = 4
        Open_Link('mod/bigbluebuttonbn/view.php?id=31114') #BBB Gk
        BBB_Join()
    elif (currentTime == min(15,40) and executed != 5):
        executed = 5
        Open_Link('mod/bigbluebuttonbn/view.php?id=1221') #BBB Chemie
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=2871') #Anwesenheit Chemie
        Attendence_complete()
        exit()

def Wednesday():
    global executed
    global currentTime
    if (currentTime == min(7,45) and executed != 1):
        executed = 1
        Open_Link('mod/bigbluebuttonbn/view.php?id=1480') #BBB Geschichte
        BBB_Join()
    elif (currentTime == min(9,35) and executed != 2):
        executed = 2
        Open_Link('mod/bigbluebuttonbn/view.php?id=32907') #BBB Deutsch
        BBB_Join()
    elif (currentTime == min(11,25) and executed != 3):
        executed = 3
        Open_Link('mod/bigbluebuttonbn/view.php?id=23953') #BBB Latein
        BBB_Join()
        exit()

def Thursday():
    global executed
    global currentTime
    if (currentTime == min(7,45) and executed != 1):
        executed = 1
        Open_Link('course/view.php?id=901 && exit') #Link zum Bioraum
        BBB_search()
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=16996') #Anwesenheit Bio
        Attendence_complete()
    elif (currentTime == min(9,35) and executed != 2):
        executed = 2
        Open_Link('mod/bigbluebuttonbn/view.php?id=32907') #BBB Deutsch
        BBB_Join()
    elif (currentTime == min(10,20) and executed != 3):
        executed = 3
        Open_Link('mod/bigbluebuttonbn/view.php?id=32576') #BBB Mathe
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=6741') #Anwesenheit Mathe
        Attendence_complete()
    elif (currentTime == min(11,25) and executed != 4):
        executed = 4
        Open_Link('course/view.php?id=312') #Link zum IMP-Matheraum
        BBB_search
        BBB_Join
        #Open_Link('course/view.php?id=312 && exit') #Link zum IMP-Matheraum
        #Attendence_complete()
        exit()

def Friday():
    global executed
    global currentTime
    if (currentTime == min(7,45) and executed != 1):
        executed = 1
        Open_Link('mod/bigbluebuttonbn/view.php?id=32576') #BBB Mathe
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=6741') #Anwesenheit Mathe
        Attendence_complete()
    elif (currentTime == min(9,35) and executed != 2):
        Open_Link('course/view.php?id=888') #Link zum BK-Raum
        executed = 2
        BBB_search()
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=18799') #Anwesenheit BK
        Attendence_complete()
    elif (currentTime == min(11,25) and executed != 3):
        executed = 3
        Open_Link('mod/bigbluebuttonbn/view.php?id=32375') #BBB Englisch
        BBB_Join()
        Open_Link('mod/attendance/view.php?id=12126') #Anwesenheit Englisch
        Attendence_complete()
        exit()

Start()

while True:
    currentTime = min(datetime.datetime.now().hour, datetime.datetime.now().minute)
    Schedule()
    print(updating_Animation[updating_Frame % len(updating_Animation)], end = '\r')
    time.sleep(1)
    updating_Frame += 1


# -*- coding: utf8 -*-
"""Base model."""

import os
import datetime
from flask import url_for, current_app
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy import Integer, Text, Unicode, Boolean
from sqlalchemy.schema import Column
from sqlalchemy.inspection import inspect as sa_inspect

from explicates.model.utils import make_timestamp, make_uuid

class BaseDomainObject(object):
    """Base domain object class."""

    #: The object's primary key.
    key = Column(Integer, primary_key=True)

    #: The object's ID.
    id = Column(Unicode, unique=True, default=make_uuid)

    #: The time at which the object was created.
    created = Column(Text, default=make_timestamp)

    #: The time at which the object was modified, after creation.
    modified = Column(Text, onupdate=make_timestamp)

    #: True if the object was deleted, False otherwise.
    deleted = Column(Boolean, default=False)

    #: The modifiable JSON data.
    _data = Column(JSONB)

    @hybrid_property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        self._data = data

    def dictize(self):
        """Return the domain object as a dictionary."""
        private = [
            'key',
            'id',
            '_data',
            'deleted',
            'collection_key',
            'data',
            'iri',
            'language'
        ]
        out = {}

        # Add column values
        for col in self.__table__.c:
            obj = getattr(self, col.name)
            if not obj or col.name in private:
                continue
            elif isinstance(obj, datetime.datetime):
                obj = obj.isoformat()
            out[col.name] = obj

        # Add default generator to Annotations
        generator = current_app.config.get('GENERATOR')
        if generator and self.__class__.__name__ == 'Annotation':
            out['generator'] = generator

        # Add data
        if self._data:
            out.update(self._data)

        # Add hybrid properties
        for item in sa_inspect(self.__class__).all_orm_descriptors:
            if type(item) == hybrid_property and item.__name__ not in private:
                obj = getattr(self, item.__name__)
                out[item.__name__] = obj

        # Add generated
        out['generated'] = make_timestamp()

        # Add ID
        if self.iri:
            out['id'] = self.iri

        return out

    def update(self):
        """Set the modified time to now."""
        self.modified = make_timestamp()


# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2008-2021 NV Access Limited, James Teh, Michael Curran, Leonard de Ruijter, Reef Turner,
# Julien Cochuyt
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html

import typing

import appModuleHandler
import api
import controlTypes
import versionInfo
from NVDAObjects.IAccessible import IAccessible
from baseObject import ScriptableObject
import gui
from scriptHandler import script
import speech
import textInfos
import braille
import config
from logHandler import log

if typing.TYPE_CHECKING:
	import inputCore

nvdaMenuIaIdentity = None

class NvdaDialog(IAccessible):
	"""Fix to ensure NVDA message dialogs get reported when they pop up.
	"""

	def _get_presentationType(self):
		presType = super(NvdaDialog, self).presentationType
		# Sometimes, NVDA message dialogs briefly report the invisible state
		# after they're focused.
		# This causes them to be treated as unavailable and they are thus not reported.
		# If this dialog is in the foreground, treat it as content.
		if presType == self.presType_unavailable and self == api.getForegroundObject():
			return self.presType_content
		return presType

class NvdaDialogEmptyDescription(IAccessible):
	"""Fix to ensure the NVDA settings dialog does not run getDialogText including panel descriptions
		when alt+tabbing back to a focused control on a panel with a description. This would result in the
		description being spoken twice.
	"""

	def _get_description(self):
		"""Override the description property (because we can't override the classmethod getDialogText)
			However this will do to ensure that the dialog is described as we wish.
		"""
		return ""

# Translators: The name of a category of NVDA commands.
SCRCAT_PYTHON_CONSOLE = _("Python Console")

class NvdaPythonConsoleUIOutputClear(ScriptableObject):

	# Allow the bound gestures to be edited through the Input Gestures dialog (see L{gui.prePopup})
	isPrevFocusOnNvdaPopup = True

	@script(
		gesture="kb:control+l",
		# Translators: Description of a command to clear the Python Console output pane
		description=_("Clear the output pane"),
		category=SCRCAT_PYTHON_CONSOLE,
	)
	def script_clearOutput(self, gesture: "inputCore.InputGesture"):
		from pythonConsole import consoleUI
		consoleUI.clear()

class NvdaPythonConsoleUIOutputCtrl(ScriptableObject):

	# Allow the bound gestures to be edited through the Input Gestures dialog (see L{gui.prePopup})
	isPrevFocusOnNvdaPopup = True

	@script(
		gesture="kb:alt+downArrow",
		# Translators: Description of a command to move to the next result in the Python Console output pane
		description=_("Move to the next result"),
		category=SCRCAT_PYTHON_CONSOLE
	)
	def script_moveToNextResult(self, gesture: "inputCore.InputGesture"):
		self._resultNavHelper(direction="next", select=False)

	@script(
		gesture="kb:alt+upArrow",
		# Translators: Description of a command to move to the previous result
		# in the Python Console output pane
		description=_("Move to the previous result"),
		category=SCRCAT_PYTHON_CONSOLE
	)
	def script_moveToPrevResult(self, gesture: "inputCore.InputGesture"):
		self._resultNavHelper(direction="previous", select=False)

	@script(
		gesture="kb:alt+downArrow+shift",
		# Translators: Description of a command to select from the current caret position to the end
		# of the current result in the Python Console output pane
		description=_("Select until the end of the current result"),
		category=SCRCAT_PYTHON_CONSOLE
	)
	def script_selectToResultEnd(self, gesture: "inputCore.InputGesture"):
		self._resultNavHelper(direction="next", select=True)

	@script(
		gesture="kb:alt+shift+upArrow",
		# Translators: Description of a command to select from the current caret position to the start
		# of the current result in the Python Console output pane
		description=_("Select until the start of the current result"),
		category=SCRCAT_PYTHON_CONSOLE
	)
	def script_selectToResultStart(self, gesture: "inputCore.InputGesture"):
		self._resultNavHelper(direction="previous", select=True)

	def _resultNavHelper(self, direction: str = "next", select: bool = False):
		from pythonConsole import consoleUI
		startPos, endPos = consoleUI.outputCtrl.GetSelection()
		if self.isTextSelectionAnchoredAtStart:
			curPos = endPos
		else:
			curPos = startPos
		if direction == "previous":
			for pos in reversed(consoleUI.outputPositions):
				if pos < curPos:
					break
			else:
				# Translators: Reported when attempting to move to the previous result in the Python Console
				# output pane while there is no previous result.
				speech.speakMessage(_("Top"))
				return
		elif direction == "next":
			for pos in consoleUI.outputPositions:
				if pos > curPos:
					break
			else:
				# Translators: Reported when attempting to move to the next result in the Python Console
				# output pane while there is no next result.
				speech.speakMessage(_("Bottom"))
				return
		else:
			raise ValueError(u"Unexpected direction: {!r}".format(direction))
		if select:
			consoleUI.outputCtrl.Freeze()
			anchorPos = startPos if self.isTextSelectionAnchoredAtStart else endPos
			consoleUI.outputCtrl.SetSelection(anchorPos, pos)
			consoleUI.outputCtrl.Thaw()
			self.detectPossibleSelectionChange()
			self.isTextSelectionAnchoredAtStart = anchorPos < pos
		else:
			consoleUI.outputCtrl.SetSelection(pos, pos)
		info = self.makeTextInfo(textInfos.POSITION_CARET)
		copy = info.copy()
		info.expand(textInfos.UNIT_LINE)
		if (
			copy.move(textInfos.UNIT_CHARACTER, 4, endPoint="end") == 4
			and copy.text == ">>> "
		):
			info.move(textInfos.UNIT_CHARACTER, 4, endPoint="start")
		speech.speakTextInfo(info, reason=controlTypes.OutputReason.CARET)

class AppModule(appModuleHandler.AppModule):
	# The configuration profile that has been previously edited.
	# This ought to be a class property.
	oldProfile = None

	@classmethod
	def handlePossibleProfileSwitch(cls):
		from gui.settingsDialogs import NvdaSettingsDialogActiveConfigProfile as newProfile
		if (cls.oldProfile and newProfile and newProfile != cls.oldProfile):
			# Translators: A message announcing what configuration profile is currently being edited.
			speech.speakMessage(_("Editing profile {profile}").format(profile=newProfile))
		cls.oldProfile = newProfile

	def event_appModule_loseFocus(self):
		self.oldProfile = None

	def isNvdaMenu(self, obj):
		global nvdaMenuIaIdentity
		if not isinstance(obj, IAccessible):
			return False
		if nvdaMenuIaIdentity and obj.IAccessibleIdentity == nvdaMenuIaIdentity:
			return True
		if nvdaMenuIaIdentity is not True:
			return False
		# nvdaMenuIaIdentity is True, so the next menu we encounter is the NVDA menu.
		if obj.role == controlTypes.Role.POPUPMENU:
			nvdaMenuIaIdentity = obj.IAccessibleIdentity
			return True
		return False

	def event_NVDAObject_init(self, obj):
		# It seems that context menus always get the name "context" and this cannot be overridden.
		# Fudge the name of the NVDA system tray menu to make it more friendly.
		if self.isNvdaMenu(obj):
			obj.name=versionInfo.name

	def event_gainFocus(self, obj, nextHandler):
		if obj.role == controlTypes.Role.UNKNOWN and controlTypes.State.INVISIBLE in obj.states:
			return
		nextHandler()

	# Silence invisible unknowns for stateChange as well.
	event_stateChange = event_gainFocus

	def event_foreground(self, obj, nextHandler):
		if not gui.shouldConfigProfileTriggersBeSuspended():
			config.conf.resumeProfileTriggers()
		else:
			self.handlePossibleProfileSwitch()
		nextHandler()

	def event_nameChange(self, obj, nextHandler):
		self.handlePossibleProfileSwitch()
		nextHandler()

	def isNvdaSettingsDialog(self, obj):
		if not isinstance(obj, IAccessible):
			return False
		windowHandle = obj.windowHandle
		from gui.settingsDialogs import NvdaSettingsDialogWindowHandle
		if windowHandle == NvdaSettingsDialogWindowHandle:
			return True
		return False

	def isNvdaPythonConsoleUIInputCtrl(self, obj):
		from pythonConsole import consoleUI
		if not consoleUI:
			return
		return obj.windowHandle == consoleUI.inputCtrl.GetHandle()

	def isNvdaPythonConsoleUIOutputCtrl(self, obj):
		from pythonConsole import consoleUI
		if not consoleUI:
			return
		return obj.windowHandle == consoleUI.outputCtrl.GetHandle()

	def chooseNVDAObjectOverlayClasses(self, obj, clsList):
		if obj.windowClassName == "#32770" and obj.role == controlTypes.Role.DIALOG:
			clsList.insert(0, NvdaDialog)
			if self.isNvdaSettingsDialog(obj):
				clsList.insert(0, NvdaDialogEmptyDescription)
				return
		if self.isNvdaPythonConsoleUIInputCtrl(obj):
			clsList.insert(0, NvdaPythonConsoleUIOutputClear)
		elif self.isNvdaPythonConsoleUIOutputCtrl(obj):
			clsList.insert(0, NvdaPythonConsoleUIOutputClear)
			clsList.insert(0, NvdaPythonConsoleUIOutputCtrl)


from matplotlib.collections import PolyCollection
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import nanopores.geometries.pughpore as pughpore
import nanopores
from  scipy.interpolate import LinearNDInterpolator
import numpy as np
from nanopores.tools import fields
import folders
from mirror import xf, Felx, Fely, Felz, Fdragx, Fdragy, Fdragz, Fx, Fy, Fz, Jf, Ja
xf=np.array(xf)
f=LinearNDInterpolator(xf,Ja)

fig = plt.figure()
ax = fig.gca(projection='3d')

up = nanopores.user_params(pughpore.params, k=3)

R = up.R
H = up.H
l0 = up.l0
l1 = up.l1
l2 = up.l2
l3 = up.l3
l4 = up.l4
hpore = up.hpore
hmem = up.hmem
h2 = up.h2
h1 = up.h1
h4 = up.h4
rMolecule = up.rMolecule
eps = 0.1
r = rMolecule + eps

verts=[]
xs = [l3*.5,R*.5,R*.5,l4*.5,l4*.5,l0*.5,l0*.5,l1*.5,l1*.5,l2*.5,l2*.5,l3*.5]
xsm = [-xs[i] for i in range(len(xs))]
ys = [-hpore*.5,-hpore*.5,-hpore*.5+hmem,-hpore*.5+hmem,-hpore*.5+h4,-hpore*.5+h4,hpore*.5,hpore*.5,hpore*.5-h1,hpore*.5-h1,hpore*.5-h2,hpore*.5-h2]
verts.append(list(zip(xs,ys)))
verts.append(list(zip(xsm,ys)))

poly = PolyCollection(verts)
poly.set_alpha(.3)

ax.set_xlim3d(-15, 15)
ax.set_ylim3d(-15, 15)
ax.set_zlim3d(1.1e-9,1.3e-9)
lx=80
ly=160
X_=np.linspace(-R*.5,R*.5,lx)
Y_=np.linspace(-hpore*.5,hpore*.5,ly)
#X_=np.linspace(-(l3*.5-r),l3*.5-r)
X, Y = np.meshgrid(X_,Y_)
#np.save('X',X)
#np.save('Y',Y)
#ZJ=np.array([[f.__call__(np.array([X_[i],0.,Y_[j]]))[0] for i in range(X_.shape[0])] for j in range(Y_.shape[0])])
#np.save('J_int_shrink',ZJ)
ZJ=np.load('J_int.npy')
surf=ax.plot_surface(X,Y,ZJ, rstride=1, cstride=1, cmap=cm.viridis, linewidth=0., alpha=1.)
fig.colorbar(surf, shrink=0.5, aspect=5)

ax.add_collection3d(poly, zs=[0.,0.], zdir='z')

ax.view_init(23.,-32.)
#ax.view_init(90.,-90.)
plt.tight_layout()
plt.show()


from mrjob.job import MRJob
from mrjob.step import MRStep
import re
WORD_RE = re.compile(r"[\w]+")

# clean reference frame input, save it to a list
f = open('myframe.txt', 'r')
x = f.readlines()
f.close()
total = []
for i in range(len(x)):
	temp = x[i].split(',')
	for t in temp:
		t = t.strip()
		t = t.strip('\n')
		total.append(t)

REFERENCE = total

class MRCount(MRJob):
	def mapper(self, _, line):
		'''
		This function goes through each line in the text files, counts words
		and loop over the reference frame and records the co-occurence time
		of the word in reference frame and the keyword in the text file. It
		yields a list, which has one more elements than the reference frame
		(the word counts).
		'''
		newline = WORD_RE.findall(line)
		for word in newline:
			rvlist = [0] * (len(REFERENCE)+1)
			rvlist[0] = 1
			for ind in range(len(REFERENCE)):
				if (REFERENCE[ind] in newline) and (REFERENCE[ind]!=word):
					rvlist[ind+1] = 1

			yield word, rvlist

	def combiner(self, word, countstep1):
		'''
		Sum up the list with same key word.
		:param word: word in text file.
		:param countstep1: the list generated in the mapper.
		:return: a list.
		'''
		sumstep1 = list(countstep1)
		yield word,[sum(i) for i in zip(*sumstep1)]

	def reducer_pre(self, word, countstep2):
		'''
		Sum up the list with same key word.
		:param word: word in text file.
		:param countstep2: the list combined in the combiner.
		:return: a list.
		'''
		sumstep2 = list(countstep2)
		yield word,[sum(i) for i in zip(*sumstep2)]

	def reducer_final(self, word, allnum):
		'''
		Divide the second-to-last elements in the list by the first
		element. Yield a vector with the same length of reference frame for
		each unique word in the text file.
		:param word: unique word in the text file.
		:param allnum: the list generated in the first step.
		:return: a list.
		'''
		final = []
		mycount = list(allnum)[0]
		for i in range(len(mycount)):
			if i > 0:
				final.append(mycount[i]/mycount[0])
		yield word, final

	def steps(self):
		return[
		MRStep(
			mapper = self.mapper,
			combiner = self.combiner,
			reducer = self.reducer_pre),
		MRStep(reducer = self.reducer_final)]

if __name__ == '__main__':
  MRCount.run()


from django.urls import path
from .views import home, send_invitation, accept_invitation, reject_invitation
from django.contrib.auth.views import LoginView, LogoutView

urlpatterns = [
    path('', home, name = 'player_home'),
    path('login/', LoginView.as_view(template_name='player/login_form.html'), name='player_login'),
    path('logout/', LogoutView.as_view(), name='player_logout'),
    path('send_invite/', send_invitation, name='send_invitation'),
    path('accept/<str:username>', accept_invitation, name='accept_invitation'),
    path('reject/<str:username>', reject_invitation, name='reject_invitation'),
]


import time

def lcs(X, Y, m, n):
	if(m == 0 or n == 0):
		return 0

	if(X[m-1] == Y[n-1]):
		return lcs(X, Y, m-1, n-1)+1
	else :
		return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n))

def readFile(file):
    lines = []
    with open(file) as f:
        lines= f.readlines()
    return lines

fileName = "LCS1.txt"
strings = readFile(fileName)
t = []
for i in range(0, len(strings), 1):
    inputStrings = strings[i].split(",")
    if(len(inputStrings) > 0):
        start_time = time.time()

        length = lcs(inputStrings[0], inputStrings[1], len(inputStrings[0]), len(inputStrings[1]))
        end_time = time.time()
        print()
        print("##########################################################")
        print("Length of the Longest common Subsequence of Strings {} & {} is {} ".format(inputStrings[0], inputStrings[1], length))
        print("Time taken to find length of longest common subsequence is : {} seconds".format(end_time-start_time))
        t.append(end_time-start_time)
        print("##########################################################")
        print()

for i in range (0, len(t), 1):
    print(t[i])


import shutil
import os
import subprocess
import torch
from util.workspace import Workspace
from util.dataset import Dataset
from parameters import Parameters
from util.train_emb import train_test, unload_dll

p = Parameters()
params = p.get_parameters()

workspace = Workspace(params.w, params.em, params.exp_id)

if os.path.exists(workspace.base):
	shutil.rmtree(workspace.base)

os.makedirs(workspace.base)
os.makedirs(workspace.result_dir)

# fresh start generate train data from raw for mining and embedding
dataset = Dataset(workspace, train_ratio=params.tr_ratio, shuffle=True, load_existing_test_files=params.load_existing_test_files, load_existing_test_files_sparsity=params.load_existing_test_files_sparsity)

global_iters = params.g_iters

print(str(params))
params_dump_file = open(workspace.base + "/params.txt", "w")
n = params_dump_file.write(str(params))
params_dump_file.close()

for iter_id in range(global_iters):
	print("Global Iter: ", iter_id)

	# run embedding model
	if iter_id == 0:

		tester, train_dataloader, test_dataloader = train_test(workspace, params, iter_id, params.gpu_id, is_pretrain=False)

		if not os.path.isfile(workspace._base +'/rules.txt.sorted'):
			subprocess.run(["java", "-XX:-UseGCOverheadLimit", "-Xmx100G", "-jar", "mining/build.jar", "-rt", workspace.model_dir,"-w", workspace.base, "-em",params.em, "-ew", "0.3" ])
			shutil.copy(workspace.base + '/rules.txt.sorted', workspace._base +'/rules.txt.sorted', follow_symlinks=True)
	else:
		tester, train_dataloader, test_dataloader = train_test(workspace, params, iter_id, params.gpu_id, is_pretrain=True)

	# embedding saved to result folder
	# run mining system

	# subprocess.run(["java", "-XX:-UseGCOverheadLimit", "-Xmx100G", "-jar", "mining/build.jar", "-rt", workspace.model_dir,"-w", workspace.base, "-em",params.em, "-ew", "0.3", "-pca", "true" ])

	# infer new facts
	mining_log_fpath = workspace.mining_log_dir + "/iter-" + str(iter_id)
	os.makedirs(mining_log_fpath, exist_ok=True)

	subprocess.run(["bash", "infer.sh", workspace.base, workspace._base +'/rules.txt.sorted', str(params.m_top_rules), workspace.mining_new_facts_fpath, mining_log_fpath])

	# read data from mining log

	# new facts in /new_facts.txt
	# read and add to train2id.txt
	#con = init_OpenKE(workspace, params, 0, params.gpu_id, is_pretrain=True, is_sans_mining=True)

	#dataset.augment_inferred_data_random(tester)
	dataset.augment_inferred_data()

	dataset.gen_type_constraints()

	# unload dll

	# unload dll
	unload_dll(train_dataloader)
	unload_dll(test_dataloader)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 21:41:21 2018

@author: Guannan Shen
"""
#%%
## assign value, math operation and shorcuts in spyder
pi = 3.14159
radius = 2.2
# add comment, following is the circle equation
area = pi*(radius**2)
print(area)
# control enter to run whole cell
# "#%%" to add a cell

#%%
#####################
#### comment lines
#####################
##comment many line at a time
##like this
##hlighting all then
##using ctrl 1
#or uncomment using ctrl 1 again

##########################
####  autocomplete names
#########################

# Spyder can autocomplete names for you
# start typing a variable name defined in your program and hit tab
# before you finish typing -- try it below

a_superrrrrr_long_and_tedious_variable_names = 1

print(a_superrrrrr_long_and_tedious_variable_names * 1001)

#%%
###########
## Strings and other objects type to be continued
############


# 기존 구간 곱 구하기 문제랑 같습니다만, 그 문제와는 다르게 나눌 특정수가 없기에 숫자가 매우 커질 수 있습니다. 이 문제는 결국 '+' / '-' / 0 즉 부호만 판별하면 되기 때문에 트리에 각 배열 index의
# 부호에 따른 1 / -1 / 0를 넣어 해결합니다.

import sys, math
input = sys.stdin.readline

def init(node, st, end):
    if st == end:
        if a[st] < 0:tree[node] = -1
        elif a[st] > 0:tree[node] = 1
        else: tree[node] = 0
    else:
        t = (st+end)//2
        init(node*2, st, t)
        init(node*2+1, t+1, end)
        tree[node] = tree[node*2] * tree[node*2 + 1]

def query(node, st, end, l, r):
    if l <= st and r >= end:
        return tree[node]
    if st > r or end < l:
        return 1
    t = (st+end)//2
    l_c = query(node * 2, st, t, l, r)
    r_c = query(node * 2 + 1, t + 1, end, l, r)
    return l_c * r_c

def change(node, st, end, ind, val):
    if ind < st or ind > end:
        return
    if st == end:
        a[ind] = val
        if val < 0:tree[node] = -1
        elif val > 0:tree[node] = 1
        else:tree[node] = 0
        return
    t = (st + end) // 2
    change(node * 2, st, t, ind, val)
    change(node * 2 + 1, t + 1, end, ind, val)
    tree[node] = tree[node*2] * tree[node*2 + 1]

while True:
    try:
        n, m = map(int, input().split())
        a = list(map(int, input().split()))
        tree = [0] * (1 << (math.ceil(math.log2(n))+1))
        init(1, 0, n-1)
        ans = ""
        for i in range(m):
            q = input().split()
            if q[0] == 'C':
                change(1, 0, n - 1, int(q[1]) - 1, int(q[2]))
            else:
                k = query(1, 0, n - 1, int(q[1]) - 1, int(q[2]) - 1)
                if k > 0:
                    ans += '+'
                elif k < 0:
                    ans += '-'
                else:
                    ans += '0'
        print(ans)
    except:
        break


import jax.numpy as jnp
import jax
from jax import device_put
from jax import numpy as np
from bench.core.executer import Executer

def box_area(boxes):
    return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])

def box_iou(boxes1, boxes2):

    area1 = box_area(boxes1)
    area2 = box_area(boxes2)

    lt = np.maximum(boxes1[:, None, :2], boxes2[:, :2])  # [N,M,2]
    rb = np.minimum(boxes1[:, None, 2:], boxes2[:, 2:])  # [N,M,2]

    wh = jax.numpy.clip(rb - lt, 1.0)  # [N,M,2]
    inter = wh[:, :, 0] * wh[:, :, 1]  # [N,M]

    union = area1[:, None] + area2 - inter

    iou = inter / union
    return iou, union

def generalized_box_iou(boxes1, boxes2):
    """
    Generalized IoU from https://giou.stanford.edu/

    The boxes should be in [x0, y0, x1, y1] format

    Returns a [N, M] pairwise matrix, where N = len(boxes1)
    and M = len(boxes2)
    """
    # degenerate boxes gives inf / nan results
    # so do an early check
    assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
    iou, union = box_iou(boxes1, boxes2)

    lt = np.minimum(boxes1[:, None, :2], boxes2[:, :2])
    rb = np.maximum(boxes1[:, None, 2:], boxes2[:, 2:])

    wh = jax.numpy.clip(rb - lt, 1.0)  # [N,M,2]  # [N,M,2]
    area = wh[:, :, 0] * wh[:, :, 1]

    return iou - (area - union) / area

def args_adaptor(np_args):
    boxes1 = device_put(np_args[0])
    boxes2 = device_put(np_args[1])
    return [boxes1, boxes2]

def executer_creator():
    return Executer(generalized_box_iou, args_adaptor)


#https://atcoder.jp/contests/abc176/tasks/abc176_c

n =  int(input())
a = [int(x) for x in input().split()]
c = 0
for i in range(n-1):
    if a[i] > a[i+1]:
        c += a[i] - a[i+1]
        a[i+1] = a[i]
print(c)


import numpy as np
import matplotlib.pyplot as plt
import pickle
# import required libraries
from scipy.stats import norm
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb

#   https://www.askpython.com/python/normal-distribution
# creating the dataset
# data = {'C':20, 'C++':15, 'Java':30,
#         'Python':35}
# courses = list(data.keys())
# values = list(data.values())
with open("stc.pkl", "rb") as f:
    score = pickle.load(f)
# courses = []
# values = []
mean, std = 0,0
max1,min1 = 0,0
for k,v in score.items():
    # print(v)
    x = np.array(v)
    v = x.astype(np.float)
    # for js in v:
    #     courses

    # courses = v
    # values =
    #Calculate mean and Standard deviation.
    # print(v)
    mean = np.mean(v)
    std = np.std(v)
    max1 = np.amax(v)
    min1 = np.amin(v)
    # break

    # Creating the distribution
    # data = np.arange(1,10,0.01)
    print(min1,max1,mean,std)
    data = np.arange(min1,max1, 0.01)
    pdf = norm.pdf(data , loc = mean , scale = std )

    #Visualizing the distribution

    sb.set_style('whitegrid')
    sb.lineplot(data, pdf , color = 'black')
    plt.xlabel('Score')
    plt.ylabel('Probability Density')
    plt.title(k[3:])

    # fig = plt.figure(figsize = (10, 5))

    # # creating the bar plot
    # plt.bar(courses, values, color ='maroon',
    #         width = 0.4)

    # plt.xlabel("Courses offered")
    # plt.ylabel("No. of students enrolled")
    # plt.title("Students enrolled in different courses")
    # # plt.show()
    plt.savefig("fig/{}.png".format(k[3:]))
    plt.clf()


from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ChurroViewSet, submit_survey, submit_career, submit_contact, submit_order, home, submit_booking

router = DefaultRouter()
router.register(r'churros', ChurroViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('submit-survey/', submit_survey, name='submit_survey'),
    path('submit-career/', submit_career, name='submit_career'),
    path('submit-contact/', submit_contact, name='submit_contact'),
    path('submit-order/', submit_order, name='submit_order'),
    path('submit-booking/', submit_booking, name='submit_booking'),
    path('home/', home, name='home'),  # Assuming you want a separate endpoint for home
]


import os
import speech_recognition as sr

def transcribe_audio(audio_file):
    recognizer = sr.Recognizer()

    with sr.AudioFile(audio_file) as source:
        audio = recognizer.record(source)

    try:
        transcript = recognizer.recognize_google(audio, language="es-ES")
        return transcript
    except sr.UnknownValueError:
        return "No se pudo transcribir el audio"
    except sr.RequestError:
        return "Error en la solicitud al servicio de reconocimiento de voz"

# Ruta al archivo de audio
ruta_carpeta = "C:/Users/User/Documents/coding/xd/audios"
carpetaDeAudios = os.listdir("C:/Users/User/Documents/coding/xd/audios")
contador = 1
for file in carpetaDeAudios:
    audio_file = os.path.join(ruta_carpeta, file)
    transcript = transcribe_audio(audio_file)
    name_audio = "audio" + str(contador)
    output_file_path = f"C:/Users/User/Documents/coding/xd/transcipciones/{name_audio}.txt"
    with open(output_file_path, "w") as file:
        file.write(transcript)
    contador += 1
    print("Transcripción guardada correctamente.")


# Gabriella Miles, Farscope PhD Student, Bristol Robotics Laboratory
# Date created: 13th July 2020

import tensorflow.keras as keras
import tensorflow as tf
from keras.models import Model
from keras.layers import Dense, Input, Flatten, Dropout, LSTM
from datetime import datetime

class Classifier:
	def __init__(self, input_shape, num_classes, output_directory, variable, verbose=True, build=True):
		self.output_directory = output_directory
		self.verbose = verbose
		self.variable = variable

		if build:
			self.model = self.build_model(input_shape, num_classes)
			return

	def build_model(self, input_shape, num_classes):
		reverse_sequences = True

		input_layer = Input(input_shape)

		lstm_1 = LSTM(100, return_sequences=True, activation='relu', go_backwards=True)(input_layer)
		lstm_2 = LSTM(100, return_sequences=True, activation='relu')(lstm_1)
		lstm_3 = LSTM(100, activation='relu')(lstm_2)
		output_layer = Dense(num_classes, activation='softmax')(lstm_3)

		model = Model(inputs=input_layer, outputs = output_layer)
		model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

		return model

	def fit(self, trainX, trainy, testX, testy, variable):
		# hyperparameters
		mini_bs = 16
		num_epochs = 5
		suffix = datetime.now().strftime("%Y%,%d_%H%M%S")
		log = "./logs/scalars/"+suffix
		my_callbacks = [
			tf.keras.callbacks.TensorBoard(log_dir=log),
			tf.keras.callbacks.TerminateOnNaN(),
			tf.keras.callbacks.CSVLogger("./logs/test_"+suffix+".csv", separator=",", append=False)
		]

		hist = self.model.fit(trainX, trainy, validation_data=(testX, testy), callbacks=my_callbacks, batch_size=mini_bs, epochs=num_epochs, verbose=self.verbose)

		_, accuracy = self.model.evaluate(testX, testy, batch_size=mini_bs, verbose=self.verbose)

		return accuracy


import os

from nose.tools import assert_equal, with_setup

from mod import f

def f_setup():
    files = os.listdir('.')
    if 'no.txt' in files:
        os.remove('no.txt')
    if 'yes.txt' in files:
        os.remove('yes.txt')

def f_teardown():
    files = os.listdir('.')
    if 'yes.txt' in files:
        os.remove('yes.txt')

@with_setup(setup=f_setup, teardown=f_teardown)
def test_f():
    exp = 42
    f()
    with open('yes.txt', 'r') as fhandle:
        obs = int(fhandle.read())
    assert_equal(exp, obs)


from math import gcd
from math import sqrt
from collections import defaultdict, deque
from sys import stdin,stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy

int_input=lambda : int(stdin.readline())
string_input=lambda : stdin.readline()
multi_input =lambda : map(int, stdin.readline().split())
list_input=lambda : list(map(int,stdin.readline().split()))
string_list_input=lambda: list(string_input())
MOD = pow(10,9)+7
factor_dict = {}

# method to print the divisors
def findDivisors(n) :
    # List to store half of the divisors
    for i in range(1, int(sqrt(n) + 1)) :

        if (n % i == 0) :
            # Check if divisors are equal
            if (n // i == i) :
                if i not in factor_dict:
                    factor_dict[i] = 0
                else:
                    factor_dict[i]+=1
            else :
                # Otherwise print both
                if i not in factor_dict:
                    factor_dict[i] = 0
                else:
                    factor_dict[i]+=1
                if n//i not in factor_dict:
                    factor_dict[n//i] = 0
                else:
                    factor_dict[n//i]+=1

test = int_input()
for i in range(test):
    n = int_input()
    factor_dict = {}
    result = [0] * n
    sequence = list_input()
    max_val = 0

    for i in range(n):
        findDivisors(sequence[i])
        print(factor_dict)
        if sequence[i] in factor_dict:
            #factor_dict[sequence[i]]+=1
            result[i] = factor_dict[sequence[i]]

    print(result)
    print(max(result))


from django.urls import path

from .views import add_contact, contacts_list, edit_contact, delete_contact

urlpatterns = [
    path('add/', add_contact, name='add_contact'),
    path('edit/<int:id>/', edit_contact, name='edit_contact'),
    path('delete/<int:id>/', delete_contact, name='delete_contact'),
    path('', contacts_list, name='contacts_list')
]


import matplotlib.pyplot as plt
import numpy as np
from sklearn import svm

f=open('./CSR1.DAT')
trainscale=300
data=[]
flag=0
for line in f.readlines():
    str = line.strip().split("\t")
    tmp = []
    if str[0]=='1':
        flag=1
    if line=='\n':
        flag=0
    if flag==1:
        for i in range(1, len(str)):
            tmp.append(float(str[i]))
        data.append(tmp)

min=min(data)[0]
max=max(data)[0]
scale=max-min

for num in data:
    num[0]=(num[0]-min)/1#scale

ytrain=np.array(data[0:trainscale])
ytest=np.array(data[trainscale:len(data)])

ytrain=ytrain.ravel()
ytest=ytest.ravel()

y=np.array(data)
y=y.ravel()

norm=1
x = np.arange(1/norm, (len(data)+1)/norm, 1/norm)
xtrain=np.arange(1/norm, (trainscale+1)/norm, 1/norm)
xtrain.shape=(-1,1)
#xpredict = np.arange(trainscale+1, len(data)+1, 1)
xpredict = np.arange(1/norm, (len(data)+1)/norm, 1/norm)
xpredict.shape=(-1,1)

xtest = np.arange((trainscale+1)/norm,( len(data)+1)/norm, 1/norm)
xtest.shape=(-1,1)

train=svm.SVR(kernel='rbf', C=1e3, gamma=20)
train.fit(xtrain,ytrain)
ypredict=train.predict(xpredict)

plt.figure(figsize=(21, 8))
plt.plot(xtest, ytest, label="test", color='g')
plt.plot(xpredict, ypredict, label="predict", color='r')
plt.plot(x, data, label="raw", color='b')
plt.legend()
plt.title("SVR")
plt.show()

"""
x = np.arange(1, len(data)+1, 1)
x.reshape(-1,1)
x.tolist()
print(x)

x=[]
for i in range(1,(len(data)+1)):
    x.append(i)

train=svm.SVR()
train.fit(x,data)
print(train.predict([[1]]))

plt.figure(figsize=(21, 8))
plt.plot(x, data, label="CDF", color='g')
plt.title("CDF")
plt.show()

print(data)
print(x)
"""


import math
import time

from matplotlib import cm, pyplot as plt
from numpy import array, convolve, linalg, matrix, trace, transpose
from PIL import Image

from gaussian_filters import gauss, gauss_1der, gauss_2der
from mark_show import mark_show_hess

def hessian(img,  # the input image name
            scale,  # standard Deviation value
            threshold  # threshold of eigen value to be considered as edge
            ):
    begin = time.time()
    size = 2  # kernel size = 2*(size) + 1
    I = array(Image.open(img).convert("L"))  # reads the input image into I

    # Gaussian along x
    Gx = []
    for i in range(- size, size + 1):
        Gx.append(gauss_1der(i, 0, scale, "x"))

    # Gaussian along y
    Gy = []
    for i in range(- size, size + 1):
        Gy.append([gauss_1der(0, i, scale, "y")])

    Gx2 = []
    for i in range(- size, size + 1):
        Gx2.append(gauss_2der(i, 0, scale, "x"))

    Gy2 = []
    for i in range(- size, size + 1):
        Gy2.append([gauss_2der(0, i, scale, "y")])

    # I*G along x
    Ix = []
    for i in range(len(I[:, 0])):
        Ix.extend([convolve(I[i, :], Gx)])
    Ix = array(matrix(Ix))

    # I*G along y
    Iy = []
    for i in range(len(I[0, :])):
        Iy.extend([convolve(I[:, i], Gx)])
    Iy = array(matrix(transpose(Iy)))

    # Ix*Gx along x
    Ixx = []
    for i in range(len(Ix[:, 0])):
        Ixx.extend([convolve(Ix[i, :], Gx2)])
    Ixx = array(matrix(Ixx))

    # Iy*Gy in y direction
    Iyy = []
    for i in range(len(Iy[0, :])):
        Iyy.extend([convolve(Ix[:, i], Gx2)])
    Iyy = array(matrix(transpose(Iyy)))

    Ixy = []
    for i in range(len(Iy[0, :])):
        Ixy.extend([convolve(Ix[:, i], Gx2)])
    Ixy = array(matrix(transpose(Ixy)))

    x = []  # x vertices of the corners
    y = []  # y vertices of the corners
    for i in range(len(I[:, 0])):
        for j in range(len(I[0, :])):
            H1 = linalg.eigvals(
                ([Ixx[i, j], Ixy[i, j]], [Ixy[i, j], Iyy[i, j]]))
            if((abs(H1[0]) > threshold) & (abs(H1[1]) > threshold)):  # check corner condition
                y.append(i - 2)
                x.append(j - 2)

    mark_show_hess(I, x, y)
    return time.time() - begin

img1 = hessian("../input_images/bicycle.bmp", scale=1, threshold=21)
img2 = hessian("../input_images/bird.bmp", scale=1, threshold=12)
img3 = hessian("../input_images/dog.bmp", scale=1, threshold=6)
img4 = hessian("../input_images/einstein.bmp", scale=1, threshold=15)
img5 = hessian("../input_images/plane.bmp", scale=1, threshold=10)
img6 = hessian("../input_images/toy_image.jpg", scale=1, threshold=38)

print("Execution time:\nImage 1: %.2fseconds\nImage 2: %.2fseconds\nImage 3: %.2fseconds\nImage 4: %.2fseconds\nImage 5: %.2fseconds\nImage 6: %.2fseconds)" %
      (img1, img2, img3, img4, img5, img6))


import matplotlib.pyplot as plt
import numpy as np
from numpy import pi, cos, sin

with open("water_data.txt") as f:
        lines = f.readlines()
        E = []
        A = []
        for line in lines:
            vals = line.split("\t")
            E.append(float(vals[0]))
            A.append(float(vals[1]))

Energy, mean_path = np.array(E), np.array(A)

#task 1
def plot_1():
    plt.title('Mean path as a function of Energy in water')
    plt.xlabel('log Energy (Mev)')
    plt.ylabel('Mean path μ/ρ(Cm^2/g)')
    plt.plot(np.log(Energy), mean_path)
    plt.show()

#task 2
def scatter(incomming_angle_deg, incomming_energy):
    hv = incomming_energy                             #energy in Mev
    mc2 = 0.511                                       #electron volt mass (Mev)
    phi = np.deg2rad(incomming_angle_deg)             #radians of incomming angle
    c = 3e8                                           #m/s

    new_hv = hv/(1+(hv/mc2)*(1-cos(phi)))
    return new_hv

Energy_range = np.linspace(1, 100, 1000)
new_energy_30deg = scatter(30, Energy_range)
new_energy_60deg = scatter(35, Energy_range)
new_energy_80deg = scatter(40, Energy_range)

def plot_2():
    plt.plot(Energy_range, new_energy_30deg)
    plt.plot(Energy_range, new_energy_60deg)
    plt.plot(Energy_range, new_energy_80deg)
    plt.legend(['30 degrees', '35 degrees', '40 degrees'])
    plt.xlabel('Incomming energy (Mev)')
    plt.ylabel('scattered energy (Mev)')
    plt.show()

#task 3
def cross_sec(hv, angle_deg, radius):
    phi = np.deg2rad(angle_deg)
    #cross_p = pi*radius**2 * (v_marked/v)**2 * (v_marked/v + v/v_marked - sin(phi)**2)*sin(phi) #with respect to phi
    hv_m = scatter(angle_deg, hv)
    f1 = (hv_m/hv)**2
    f2 = ((hv_m/hv) + (hv/hv_m) - (sin(phi))**2)
    crosso = (radius**2/2) * f1 * f2                    #with respect to omega
    return crosso

r0 = 2.82*1e-13                                         #electron radius in cm
cross_sec = cross_sec(Energy_range, 30, r0)
plt.plot(Energy_range, cross_sec)
plt.show()


# coding: utf8
import sofaros
import numpy

def send(data):
        return numpy.asarray(data.value[0], dtype=numpy.float32)

def recv(data, datafield):
        t = data.tolist()
        datafield.value = [t[0]+1.0, t[1], t[2]]

def createScene(rootNode):
        sofaros.init("SofaNode")
        rootNode.createObject("EulerImplicitSolver")
        rootNode.createObject("CGLinearSolver")

        s=rootNode.createChild("simulated")
        s.createObject("MechanicalObject", name="sender", position=[0.0,0.0,0.0])
        s.sender.showObject=True
        s.sender.showObjectScale=1.0

        a=rootNode.createChild("animated")
        a.createObject("MechanicalObject", name="receiver", position=[0.0,0.0,0.0])
        a.receiver.showObject=True
        a.receiver.showObjectScale=1.0

        sofaros.RosSender(rootNode, "/simulation/sender/position",
                          s.sender.findData("position"),  sofaros.numpy_msg(sofaros.Floats), send)

        ## Entre le sender et le receiver...il y un midpoint ros.

        sofaros.RosReceiver(rootNode, "/animation/receiver/position",
                            a.receiver.findData("position"), sofaros.numpy_msg(sofaros.Floats), recv)

        return rootNode


import sys
from collections import deque
sys.setrecursionlimit(100000)

def SNS(n_nodes, myInput, a, b):
    '''
    엘리스친구의 친구관계가 myInput으로 주어지고, 사용자 a, b가 주어질 때 둘 사이의 촌수를 반환합니다.
    '''
    if a == b : return 0

    graph = [[] for i in range(n_nodes)]
    m_edges = len(myInput)

    for line in myInput:
        graph[line[0]].append(line[1])
        graph[line[1]].append(line[0])

    queue = deque([a])
    visit = [0] * n_nodes

    visit[a] = 1

    while queue:
        cur = queue.popleft()
        for node in graph[cur]:
            if visit[node] == 0:
                visit[node] = visit[cur] + 1
                queue.append(node)
    return visit[b] -1 if visit[b] > 0 else -1

def main():
    '''
    아래 코드를 수정하지 마시오.
    '''

    n_nodes, m_edges = input().split()
    n_nodes = int(n_nodes)
    m_edges = int(m_edges)

    a, b = input().split()
    a = int(a)
    b = int(b)

    myInput = []

    for i in range(m_edges) :
        line = [int(x) for x in input().split()]
        myInput.append(line)

    print(SNS(n_nodes,myInput,a,b))

if __name__ == "__main__":
    main()


##########################################################
# Author : Hwx                                           #
# Date   : 2016-9-30                                     #
# Purpose: KaKs ratio calculation, statistic and figure  #
##########################################################

# import package
import os
import matplotlib
matplotlib.use('Agg')

import numpy             as np
import pandas            as pd
import matplotlib.pyplot as plt

# # def a class
class KaKs_ratio:
    # Initialize the parameters including path and raw data
    def __init__(self):

	# # Work path
        self.path_work = os.getcwd() + "/"

        # # Input path list
        self.path_rawdata_input    = self.path_work + "allSNV.txt"
        print(self.path_rawdata_input)
        print("Start input file")
        # # Read data file
        self.data_rawdata_input    = pd.read_table(self.path_rawdata_input)
        print("Finished raw data input")

        # # Output path list
        self.path_clean_output     = self.path_work + "allSNV_clean.csv"
        self.path_genelist_output  = self.path_work + "allSNV_genelist.csv"
        self.path_snprate_output   = self.path_work + "allSNV_snprate.csv"
        self.path_result_output    = self.path_work + "allSNV_KaKs.csv"
        self.path_figure_output    = self.path_work + "Kaks_genestat.pdf"

    # # Clean the raw data, strip the useless information
    def data_clean(self):

        # # Cleanning raw data
        self.data_clean_1 = self.data_rawdata_input.ix[:,["SNV NO.",
                                                          "Gene",
                                                          "Function",
                                                          "Case mutation",
                                                          "Case(wild|mutation)"
                                                          ]]
        self.data_clean_2 = self.data_clean_1.dropna()
        self.data_clean = self.data_clean_2.sort_index(by='Gene')
        self.data_clean.to_csv(self.path_clean_output)
        print("Finished data clean")

    # # Extract gene list and calculate SNP rate
    def data_preparation(self):

        # # Extract the useful data and acquire the gene list
        try:
            self.data_clean
        except:
            self.data_clean = pd.read_csv(self.path_clean_output)

        self.data_input = self.data_clean.ix[:,["Gene","Function","Case mutation","Case(wild|mutation)"]]
        self.gene_list = self.data_input["Gene"].drop_duplicates()

        # # Extract the mutation information and calculate snp rate of each SNP site
        self.snp_ratio = []
        for wt_snp in self.data_input["Case(wild|mutation)"]:
            wt, snp = wt_snp.split("|")
            self.snp_ratio.append(int(snp)/(int(snp) + int(wt)))
            self.snp_ratio_set = pd.DataFrame(self.snp_ratio,columns=["snp_ratio"])

        self.gene_list.to_csv(self.path_genelist_output)
        self.data_snpratio = pd.concat([self.data_input,self.snp_ratio_set],axis=1)
        self.data_snpratio.to_csv(self.path_snprate_output)
        print("Finished data preparation")

    # # This is core which calcualtes the Ka/Ks ratio
    def calculate_KaKs(self):

        # Prepare Nan data set
        self.ka_ratio = []
        self.ks_ratio = []
        self.ka_count = []
        self.ks_count = []
        self.kaks_ratio_set = []
        self.kaks_count_set = []

        # Extract the gene set and calculate the KaKs rate
        try:
            self.gene_list
        except:
            self.gene_list = pd.read_csv(self.path_genelist_output)

        try:
            self.data_snpratio
        except:
            self.data_snpratio = pd.read_csv(self.path_snprate_output)

        for gene in self.gene_list:
            # Acquire the gene set
            self.gene_set = self.data_snpratio[self.data_snpratio['Gene']==gene]

            # Acquire the total of synonymous and non-synonymous snp rate
            self.sum_snpratio_syn,self.sum_snpratio_nonsyn = self.gene_set[self.gene_set['Function']=='synonymous SNV']['snp_ratio'].sum(),self.gene_set[self.gene_set['Function'] == 'nonsynonymous SNV']['snp_ratio'].sum()
            self.sum_snpcount_syn,self.sum_snpcount_nonsyn = self.gene_set[self.gene_set['Function'] == 'synonymous SNV']['Function'].count(),self.gene_set[self.gene_set['Function'] == 'nonsynonymous SNV']['Function'].count()

            # # This is the very core part: -<| Calculate of KaKs_ratio |>-

            # Calculate Ka/Ks considering the snp distribution in each group
            ka = self.sum_snpratio_nonsyn
            ks = self.sum_snpratio_syn
            self.ka_ratio.append(ka)
            self.ks_ratio.append(ks)
            # print(ka,ks)
            if self.sum_snpratio_syn == 0:
                ks = 0.01
            kaks_ratio = ka / ks
            self.kaks_ratio_set.append(kaks_ratio)

            # Calculate Ka/Ks considering the snp distribution in each group
            ka         = self.sum_snpcount_nonsyn
            ks         = self.sum_snpcount_syn
            if self.sum_snpratio_syn == 0:
                ks = 0.01
            kaks_count = ka / ks
            self.kaks_count_set.append(kaks_count)
        print("Finished calculation")

    # # Summary and output the result
    def result_summary(self):

        # Collect results
        self.result_set = {
            "Gene"       : self.gene_list,
            "Ka"         : self.ka_ratio,
            "Ks"         : self.ks_ratio,
            # "kaks_count" : self.kaks_count_set,
            "kaks_ratio" : self.kaks_ratio_set
        }
        self.result_set = pd.DataFrame(self.result_set)

        # Output the result
        self.result_set = self.result_set.dropna()
        self.result_set.to_csv(self.path_result_output)
        print("Finished summary")

    # # Plot the statistic result of Ka/Ks ratio and genes
    def plot_hist(self):

        # If the result file of KaKs is exist, time can be saved by skipping steps all above and plotting directly
        try:
            self.result_set
        except:
            self.result_set = pd.read_csv(self.path_result_output)
        self.kaks_ratio_set = self.result_set["kaks_ratio"]

        # Acquire x value for x axis
        value_xAxis = []
        for i in self.kaks_ratio_set:
            if i >= 5:
                value_xAxis.append(5)
            else:
                value_xAxis.append(i)
        value_xAxis = pd.Series(value_xAxis).dropna()

        # Set the x axis
        x_max = round((max(self.kaks_ratio_set) * 10 + 1), 0)
        if  x_max >= 5:
            x_max = 52
        bins = []
        for i in range(0, int(x_max), 2):
            bins.append(i * 0.1)

        # Set the hist bins
        hist, bins = np.histogram(value_xAxis, bins=bins)
        width = np.diff(bins)
        center = (bins[:-1] + bins[1:]) / 2

        # Set figure attribute
        fig, ax = plt.subplots(figsize=(20, 10))
        ax.bar(center, hist, align='center', width=width, facecolor='green', edgecolor='white', alpha=0.5)

        # Set figure information
        font_title = {'family': 'serif',
                'color': 'black',
                'weight': 'normal',
                'size': 38,
                }
        font_label = {'family': 'serif',
                'color': 'darkred',
                'weight': 'normal',
                'size': 26,
                }
        ax.set_xticks(bins)
        ax.set_xlabel('Ka/Ks ratio', fontdict=font_label)
        ax.set_ylabel('Amount of specific Ka/Ks', fontdict=font_label)
        ax.set_title('Ka/Ks Pressure selection', fontdict=font_title)

        # Save the figure
        fig.savefig(self.path_figure_output)
        print("Finished plotting histogram")
        plt.show()

if __name__ == "__main__":

    kaks_ratio = KaKs_ratio()

    # kaks_ratio.data_clean()
    # kaks_ratio.data_preparation()
    # kaks_ratio.calculate_KaKs()
    # kaks_ratio.result_summary()
    kaks_ratio.plot_hist()

    print("Finished KaKs Process")


import pandas as pd
import os
import geohash

path = "./taxi_test" #文件夹目录

def to_split_txt_line(str_list):
    _vehicle_id = int(str_list[0])
    _report_time = str_list[1]
    _latitude = float(str_list[2])
    _longitude = float(str_list[3][:-1])
    return _vehicle_id, _report_time, _latitude, _longitude

def get_filelist(dir):
    Filelist = []
    for home, dirs, files in os.walk(dir):
        for filename in files:
            Filelist.append(os.path.join(home, filename))
            file_name = os.path.join(home, filename)
            f = open(file_name, 'r')
            lines = f.readlines()
            for line in lines:
                str_list = line.split(',')
                vehicle_id, report_time, latitude, longitude = to_split_txt_line(str_list)
                report_time_ = pd.to_datetime(report_time)
                geohash_str = geohash.encode(latitude, longitude)

            print(filename)
            pass

    return Filelist

if __name__ == "__main__":
    filelist = get_filelist(path)
    for i in filelist:
        print(i)