import math
import numpy as np
import os
import time

import torch
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable

from envs import *
from model import Encoder, Decoder, D_Module, R_Module
from common import *
from tensorboardX import SummaryWriter
from itertools import chain
from eval import test

def eval_reward(args, shared_model, writer_dir=None):
	"""
	For evaluation

	Arguments:
	- writer: the tensorboard summary writer directory (note: can't get it working directly with the SummaryWriter object)
	"""
	writer = SummaryWriter(log_dir=os.path.join(writer_dir,'eval')) if  writer_dir is not None else None

	# current episode stats
	episode_reward = episode_value_mse = episode_td_error = episode_pg_loss = episode_length = 0

	# global stats
	i_episode = 0
	total_episode = total_steps = 0
	num_goals_achieved = 0

	# intilialize the env and models
	torch.manual_seed(args.seed)
	env = create_env(args.env_name, framework=args.framework, args=args)
	set_seed(args.seed , env, args.framework)

	shared_enc, shared_dec, shared_d_module, shared_r_module = shared_model

	enc = Encoder(env.observation_space.shape[0], args.dim,
				  use_conv=args.use_conv)
	dec = Decoder(env.observation_space.shape[0], args.dim,
				  use_conv=args.use_conv)
	d_module = D_Module(env.action_space.shape[0], args.dim, args.discrete)
	r_module = R_Module(env.action_space.shape[0], args.dim,
					 discrete=args.discrete, baseline=False,
					 state_space=env.observation_space.shape[0])

	all_params = chain(enc.parameters(), dec.parameters(),
					   d_module.parameters(),
					   r_module.parameters())

	if args.from_checkpoint is not None:
		model_state, _ = torch.load(args.from_checkpoint)
		model.load_state_dict(model_state)

	# set the model to evaluation mode
	enc.eval()
	dec.eval()
	d_module.eval()
	r_module.eval()

	# reset the state
	state = env.reset()
	state = Variable(torch.from_numpy(state).float())

	start = time.time()

	while total_episode < args.num_episodes:

		# Sync with the shared model
		r_module.load_state_dict(shared_r_module.state_dict())
		d_module.load_state_dict(shared_d_module.state_dict())
		enc.load_state_dict(shared_enc.state_dict())
		dec.load_state_dict(shared_dec.state_dict())

		# reset stuff
		cd_p = Variable(torch.zeros(1, args.lstm_dim))
		hd_p = Variable(torch.zeros(1, args.lstm_dim))

		# for the reward
		cr_p = Variable(torch.zeros(1, args.lstm_dim))
		hr_p = Variable(torch.zeros(1, args.lstm_dim))

		i_episode += 1
		episode_length = 0
		episode_reward = 0
		args.local = True
		args.d = 0
		succ, _, episode_reward, episode_length = test(
			1, args, args, args, d_module, r_module, enc)
		log("Eval: succ {:.2f}, reward {:.2f}, length {:.2f}".format(
			succ, episode_reward, episode_length))
		# Episode has ended, write the summaries here
		if writer_dir is not None:
			# current episode stats
			writer.add_scalar('eval/episode_reward', episode_reward, i_episode)
			writer.add_scalar('eval/episode_length', episode_length, i_episode)
			writer.add_scalar('eval/success', succ, i_episode)

		time.sleep(args.eval_every)
		print("sleep")


from utils.import_lib import *
from utils.helper import *

import matplotlib
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.colors import NoNorm
import tkinter as Tk
import pickle

plt.rc('xtick', labelsize=7)
plt.rc('ytick', labelsize=7)
plt.rcParams.update({'font.size': 7})
colors = {'train': 'darkcyan', 'val':'crimson'}
colors4 = ['gold','greenyellow','steelblue','midnightblue']

my_dpi=96

""" COLLIN Anne-Sophie """

def hjson_parser(path):
    import hjson
    from collections import OrderedDict
    with open(path, 'r') as fp:
        result = hjson.load(fp)

    return hjson.dumps(result, indent=2, sort_keys=True)

""" -----------------------------------------------------------------------------------------
Find all elements of a list which match a query
INPUT :
    - list : initial list
    - query
OUTPUT :
    - list of matching elements
----------------------------------------------------------------------------------------- """
def update_list(list, query):
    new_list = []
    for this_elem in list:
        cdt = True
        for this_query in query:
            if len(this_query)>1:
                if this_query[0] == '~':
                    if this_query[1::].lower() in this_elem.lower():
                        cdt = False
                else:
                    if this_query.lower() not in this_elem.lower():
                        cdt = False
        if cdt:
            new_list += [this_elem]
    return new_list

""" -----------------------------------------------------------------------------------------
Return a figure with an image in it to be displayed on the GUI
INPUT :
    - img : a numpy array
    - row,col : size of the image
OUTPUT :
    - figure
----------------------------------------------------------------------------------------- """
def show_im(img, row, col):
    plt.figure(figsize=(col/my_dpi, row/my_dpi), dpi=my_dpi)
    plt.imshow(img, cmap = 'gray', interpolation = 'bicubic', norm=NoNorm())
    plt.axis('off')
    fig = plt.gcf()
    return fig

""" -----------------------------------------------------------------------------------------
Return a figure with an image in it to be displayed on the GUI
INPUT :
    - img : a numpy array
    - row,col : size of the image
OUTPUT :
    - figure
----------------------------------------------------------------------------------------- """
def show_im_with_uncertainty(img, uncertainty, row, col):
    mask = uncertainty
    mask = np.ma.masked_where(mask < 0.1, mask)
    plt.figure(figsize=(col/my_dpi, row/my_dpi), dpi=my_dpi)
    plt.imshow(img, cmap = 'gray', interpolation = 'bicubic', norm=NoNorm())
    plt.imshow(mask, cmap = 'jet', interpolation = 'bicubic', norm=NoNorm())
    plt.axis('off')
    fig = plt.gcf()
    return fig

""" -----------------------------------------------------------------------------------------
Return a figure with an image in it to be displayed on the GUI
INPUT :
    - input : the input image
    - pred: the prediction of the input image
    - row,col : size of the image
OUTPUT :
    - figure
----------------------------------------------------------------------------------------- """
def show_im_withdef(input, pred, row, col):
    plt.figure(figsize=(col/my_dpi, row/my_dpi), dpi=my_dpi)
    this_diff = diff(input, pred)
    this_diff = np.ma.masked_where(this_diff < 0.05, this_diff)
    plt.imshow(pred, cmap = 'gray', interpolation = 'bicubic', norm=NoNorm())
    plt.imshow(this_diff, cmap = 'jet', interpolation = 'bicubic')
    plt.axis('off')
    fig = plt.gcf()
    return fig

""" -----------------------------------------------------------------------------------------
Helper function used to plot an image on a Yk canvas
INPUT :
    - canvas
    -figure : as returned by show_im
OUTPUT :
    - photo
----------------------------------------------------------------------------------------- """
def draw_figure(canvas, figure, loc=(0, 0)):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
    return figure_canvas_agg

""" -----------------------------------------------------------------------------------------
Print ROC curve
INPUT :
    - json_path : path to json file containing informations
    - row, col: dimension of the figure
    - AUC: True to display AUC values
OUTPUT :
    - roc figure
----------------------------------------------------------------------------------------- """

def print_ROC(json_path, row, col, AUC=False):
    from sklearn.metrics import auc

    labels = ['L0 ', 'L1 ', 'L2 ', 'L$\infty$ ']

    dict = read_json(json_path)
    TP = dict['all_TP']
    FP = dict['all_FP']

    plt.figure(figsize=(col/my_dpi, row/my_dpi), dpi=my_dpi)
    idx, max_auc = 0, 0
    for this_TP, this_FP, this_color, this_label in zip(TP, FP, colors4, labels):
        if AUC :
            this_label += '('
            this_auc    = round(auc(this_FP, this_TP),2)
            if this_auc > max_auc:
                max_auc = this_auc
            this_label += str(this_auc)
            this_label += ')'
        idx += 1
        plt.plot(this_FP, this_TP, color=this_color, linewidth=1, label=this_label)
    plt.xlabel('FP rate')
    plt.ylabel('TP rate')
    plt.legend(bbox_to_anchor=(1.04,1), title= "Max AUC = " + str(max_auc) + "\n \n Norm (AUC) ", loc="upper left", fontsize=6)
    plt.tight_layout()
    fig = plt.gcf()
    return fig

""" -----------------------------------------------------------------------------------------
Print PSNR
INPUT :
    - h5_path : path to h5 file containing informations
    - row, col: dimension of the figure
OUTPUT :
    - PSNR plot
----------------------------------------------------------------------------------------- """
def print_learning_curves(h5_path, row, col):
    with open(h5_path, 'rb') as handle:
        history = pickle.loads(handle.read())

    plt.figure(figsize=(col/my_dpi, row/my_dpi), dpi=my_dpi)
    nb_epoch = len(history['loss'])+1
    # summarize history for PSNR
    plt.plot(range(1,nb_epoch), history['PSNRLoss'], color=colors['train'], linewidth=1, label='training set')
    plt.plot(range(1,nb_epoch), history['val_PSNRLoss'], color=colors['val'], linewidth=1, label='validation set')
    #plt.plot(range(1,nb_epoch), history['loss'], color=colors['train'], linewidth=2, label='training set')
    #plt.plot(range(1,nb_epoch), history['val_loss'], color=colors['val'], linewidth=2, label='validation set')
    plt.ylabel('PSNR')
    plt.xlabel('epoch')
    plt.legend(loc='lower right')
    plt.tight_layout()
    fig = plt.gcf()
    return fig


import urllib.request
import json

#Fast Bank python app
print('')
num = int(0)
CustID = int(0);
accountholder = {num: {'Name':'', 'Email':'','Date of Birth':'','Address':'','Personal Balance':'','Loan Balance':'','Saving Balance':''}}
accountholder[1]= {'Name':'john', 'Email':'1','Date of Birth':'23','Address':'s','Personal Balance':'1','Loan Balance':'2','Saving Balance':'3'}
accountholder[2]= {'Name':'sam', 'Email':'1','Date of Birth':'23','Address':'s','Personal Balance':'1','Loan Balance':'2','Saving Balance':'3'}

#the main meun
def menu():
    print('1. New Customer')
    print('2. Exisiting Customer')
    print('3. Banker')
    print('4. Exchange rate')

menu()

#Banker features
def bankermenu():
    print('1. Print All customer details')
    print('2. Transfer cheeque')
    print('3. Lookup')
    print('4. Menu')
    #print()
    inputbanker = int(input("Type in a number (1-4): "))
    if inputbanker == 1:
        for p_id, p_info in accountholder.items():
            print("\nPerson ID:", p_id)

            for key in p_info:
                print(key + ':', p_info[key])
        print()
        #transfer a to b amount
    if inputbanker == 2:
        custfrom =int(input("Enter customer ID which the cheque is from: "))
        custto =int(input("Enter customer ID which the cheque is going to: "))
        amount =float(input("Enter amount: "))
        temp1 = float(accountholder[custfrom]['Personal Balance'])
        temp2 = float(accountholder[custto]['Personal Balance'])
        tempa = float(temp1-amount)
        tempb = float(temp2+amount)
        accountholder[custfrom]['Personal Balance'] = temp1-amount
        accountholder[custto]['Personal Balance']= temp2+amount
        print(accountholder[custfrom])
        print(accountholder[custto])
        print()

    if inputbanker == 3:
        custnumbank = int(input("Enter customer ID : "))
        print(accountholder[custnum])
    else:
        menu()

#customer meun
def customermenu():

    """while True:
        try:
            CustID = int(input("Enter your customer ID: "))
        except ValueError:
            print('Please enter a valid integer')
            continue
        break"""
    custnum =int(input("Your customer number: "))
    print()

    print('1. See your details')
    print('2. Remove all details from bank')
    print('3. Edit details')
    print('4. Forcast Saving amount for 12 months time interest')
    print('5. Forcast Loan owing amount in months time with interest')
    print('6. Menu')
    #print()
    inputcust = int(input("Type in a number (1-6): "))
    if inputcust == 1:
        print(accountholder[custnum])
    if inputcust == 2:
        del accountholder[custnum]
        print("Removed " + "all details of customer number" + custnum)
    if inputcust == 3:
        print('Edit your details. Customer name, DOB and balances can be edited. ')
        print('1. edit email')
        print('2. edit address')
        print()
        edit = int(input("Edit number: "))
        if edit == 1:
            newemail = input("New Email: ")
            accountholder[custnum]['Email']= newemail
            print()
        if edit== 2:
            newadd = input("New address: ")
            accountholder[custnum]['email']= newadd
            print()
    if inputcust == 4:
        print("Forcast Saving at 2.1% per year")
        temp1=(float(accountholder[custnum]['Loan Balance'])*1.021)
        print("In one year, your total saving amount at 2.1% interest will be :")
        print(temp1)
        print()
    if inputcust == 5:
        temp2=(float(accountholder[custnum]['Saving Balance'])*1.0445)
        print("Forcast Loan for a amount payable in a years time")
        print("In one year, your loan amount $"+ (accountholder[custnum]['Saving Balance']) +" amount at 4.45% interest will become :")
        print(temp2)
        print()
    else:
        menu()

def customer():
    global num
    num= num + 1
    print("Enter Details")
    name = input("Name: ")
    email = input("Email: ")
    dob = input("Address: ")
    address = input("Date of brith: ")
    personal = input("Opening transfered balanced: ")
    loan = input("loan acqusion amount: ")
    saving = input("Saving balance ")
    print(num)
    accountholder[num] ={'Name':name, 'Email':email,'Date of Birth':dob,'Address':address,'Personal Balance':personal,'Loan Balance':loan,'Saving Balance':saving}
    print(accountholder[num])
    menu()

class CurrencyConverter:
    #data.fixer.io was used get the live data
    rates = {}

    def __init__(self, url):
        req = urllib.request.Request(url, headers={'User-Agent': 'howCode Currency Bot'})
        data = urllib.request.urlopen(req).read()
        data = json.loads(data.decode('utf-8'))
        self.rates = data["rates"]

    def convert(self, amount, from_currency, to_currency):
        initial_amount = amount
        if from_currency != "EUR":
            amount = amount / self.rates[from_currency]
        if to_currency == "EUR":
            return initial_amount, from_currency, '=', amount, to_currency
        else:
            return initial_amount, from_currency, '=', amount * self.rates[to_currency], to_currency

    def convertrate():
        convertamount = float(input("Enter amount which you wish to convert: "))
        print("Currency codes examples: NZD, USD, INR, SDG, AUD, EUR, GBR")
        CurrencyFrom = input("Input currency code which you wish to convert FROM: ").upper()
        CurrencyTo = input("Input currency code which you wish to convert TO: ").upper()
        #THIS is my personal key, so please to not use else where.
        converter = CurrencyConverter("http://data.fixer.io/api/latest?access_key=c145deb07bff162f7d930bebbf11ea2b&format=1")
        #converter.convert(convertamount, "NZD", "USD")
        print(converter.convert(convertamount, CurrencyFrom, CurrencyTo))

#main meun

select = 0
while select != 5:
    inputmenu = int(input("Type in a number (1-4) depening on the type of user: "))
    if inputmenu == 1:
        customer()
    elif inputmenu == 2:
        customermenu()
    elif inputmenu == 3:
        bankermenu()
    elif inputmenu == 4:
        CurrencyConverter.convertrate()
    else:
        menu()


import base64
import json
import urllib

class TextAnalytics(object):

    BASE_URL = 'https://api.datamarket.azure.com/data.ashx/amla/text-analytics/v1'

    def __init__(self, accountKey):
        encode_b64 = lambda s: base64.b64encode(s.encode('utf-8')).decode('utf-8')
        self.creds = encode_b64('AccountKey:' + accountKey)

    def request(self, url):
        headers = {'Content-Type': 'application/json', 'Authorization': ('Basic ' + self.creds)}
        req = urllib.request.Request(url, None, headers)
        response = urllib.request.urlopen(req)
        result = response.read().decode('utf-8')
        obj = json.loads(result)
        return obj

    def get_sentiment(self, text):
        params = {'Text': text.encode('utf-8')}
        url = self.BASE_URL + '/GetSentiment?' + urllib.parse.urlencode(params)
        sentiment = self.request(url)
        return sentiment['Score']

    def get_key_phrases(self, text):
        params = {'Text': text.encode('utf-8')}
        url = self.BASE_URL + '/GetKeyPhrases?' + urllib.parse.urlencode(params)
        keyPhrases = self.request(url)
        return keyPhrases['KeyPhrases']


"""
meetup_stats allows to download data about meetup.com events into csv files or a postgres database
"""

import csv_writer as csv
import database as db
import meetup_data_collector as meetup

def download_events_to_csv(meetup_group, output_folder):
    """
    Downloads events and attendance data using meetup_data_collector,
    and writes them into csv files using csv_writer.

    param meetup_group: identifier of the meetup group to get data for
    param output_folder: folder to write csv files to
    """
    print(
        f"downloading data for meetup group '{meetup_group}' into folder '{output_folder}'..."
    )

    events = meetup.collect_event_info(meetup_group)

    csv.write_events_overview(events, output_folder)

    for event in events:
        attendees_csv = meetup.collect_event_attendees(event)
        csv.write_attendee_csv(event, attendees_csv, output_folder)

def download_events_to_db(
    meetup_group, host="localhost", port="5432", user="postgres", password="pw"
):
    """
    Downloads events and attendance data using meetup_data_collector,
    and writes them into a postgres database using database

    param meetup_group: identifier of the meetup group to get data for
    param host: host to connect to
    param port: port to connect to
    param user: postgres user to connect as
    param pw: of the postgres user
    """

    print(
        f"downloading data for meetup group '{meetup_group}' to database '{host}:{port}'..."
    )

    conn = db.open_connection(meetup_group, host, port, user, password)

    db.create_tables_if_none_exist(conn)

    events = meetup.collect_event_info(meetup_group)

    for event in events:
        db.add_event_to_db(conn, event)

        attendees_csv = meetup.collect_event_attendees(event)
        db.add_users_to_db(conn, attendees_csv[1:])
        db.add_event_attendance(conn, event["id"], attendees_csv[1:])

    conn.close()

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "meetup",
        help=(
            "The meetup to query for."
            "This needs to be the identifier found in the meetup group's url path."
        ),
    )
    parser.add_argument(
        "command",
        help=(
            "The command to run."
            "Either 'csv' or 'db' downloading data either to csv files or a postgres database."
        ),
    )

    parser.add_argument(
        "--csv-outputfolder",
        help="folder to write csv files to. Default: output",
        default="output",
    )

    parser.add_argument(
        "--db-host",
        help="database host to connect to. Default: localhost",
        default="localhost",
    )
    parser.add_argument(
        "--db-port", help="database port to connect to. Default: 5432", default="5432"
    )
    parser.add_argument(
        "--db-user",
        help="database user to connect with. Default: postgres",
        default="postgres",
    )
    parser.add_argument("--db-pw", help="database password to connect with.")

    args = parser.parse_args()

    if args.command == "csv":
        download_events_to_csv(args.meetup, args.csv_outputfolder)
    elif args.command == "db":
        download_events_to_db(
            args.meetup, args.db_host, args.db_port, args.db_user, args.db_pw
        )
    else:
        print(f"unknown command '{args.command}' - needs to be 'csv' or 'db'")


from io import BufferedReader, BytesIO
from typing import Sequence
import requests
from pdf2image.pdf2image import convert_from_bytes
import json

from edenai_apis.features.image.anonymization.anonymization_dataclass import (
    AnonymizationDataClass,
)
from edenai_apis.features.image.explicit_content import (
    ExplicitContentDataClass,
    ExplicitItem,
)
from edenai_apis.features.image.face_detection import (
    FaceBoundingBox,
    FaceDetectionDataClass,
    FaceItem,
    FaceLandmarks,
)
from edenai_apis.features.image.logo_detection import (
    LogoBoundingPoly,
    LogoDetectionDataClass,
    LogoVertice,
    LogoItem,
)
from edenai_apis.features.image.object_detection import (
    ObjectDetectionDataClass,
    ObjectItem,
)
from edenai_apis.features.ocr.ocr.ocr_dataclass import Bounding_box, OcrDataClass
from edenai_apis.loaders.data_loader import ProviderDataEnum
from edenai_apis.loaders.loaders import load_provider
from edenai_apis.features import ProviderApi, Image, Ocr
from edenai_apis.utils.exception import ProviderException
from edenai_apis.utils.types import ResponseType
from .helpers import content_processing

class Api4aiApi(
    ProviderApi,
    Image,
    Ocr,
):

    provider_name = "api4ai"

    def __init__(self) -> None:
        self.api_settings = load_provider(ProviderDataEnum.KEY, self.provider_name)
        self.api_key = self.api_settings["key"]
        self.urls = {
            "object_detection": f"{self.api_settings['object_detection']['url']}"
                + f"?api_key={self.api_key}",
            "logo_detection": f"{self.api_settings['logo_detection']['url']}"
                + f"?api_key={self.api_key}",
            "face_detection": f"{self.api_settings['face_detection']['url']}"
                + f"?api_key={self.api_key}",
            "anonymization": "https://api4ai.cloud/img-anonymization/v1/results"
                + f"?api_key={self.api_key}",
            "nsfw": f"https://api4ai.cloud/nsfw/v1/results?api_key={self.api_key}",
            "ocr": f"https://api4ai.cloud/ocr/v1/results?api_key={self.api_key}",
        }

    def image__object_detection(
        self, file: BufferedReader
    ) -> ResponseType[ObjectDetectionDataClass]:
        """
        This function is used to detect objects in an image.
        """
        files = {"image": file}
        original_response = requests.post(
            self.urls["object_detection"], files=files
        ).json()
        items = []
        for item in original_response["results"][0]["entities"][0]["objects"]:
            label = next(iter(item.get("entities", [])[0].get("classes", {})))
            confidence = item["entities"][0]["classes"][label]
            if confidence > 0.3:
                boxes = item.get("box", [])
                items.append(
                    ObjectItem(
                        label=label,
                        confidence=confidence,
                        x_min=boxes[0],
                        x_max=boxes[2] + boxes[0],
                        y_min=boxes[1],
                        y_max=boxes[3] + boxes[1],
                    )
                )

        standarized_response = ObjectDetectionDataClass(items=items)
        result = ResponseType[ObjectDetectionDataClass](
            original_response=original_response,
            standarized_response=standarized_response,
        )
        return result

    def image__face_detection(
        self, file: BufferedReader
    ) -> ResponseType[FaceDetectionDataClass]:
        payload = {
            "image": file,
        }
        # Get response
        response = requests.post(self.urls["face_detection"], files=payload)

        # Handle errors
        if response.status_code != 200:
            raise ProviderException(response.json()["result"][0]["status"]["message"])

        # Get result
        original_response = response.json()

        # Face std
        faces_list = []
        faces = original_response["results"][0]["entities"][0]["objects"]
        for face in faces:
            bouding_box = FaceBoundingBox(
                x_min=face["box"][0],
                x_max=face["box"][0],
                y_min=face["box"][0],
                y_max=face["box"][0],
            )
            confidence = face["entities"][0]["classes"]["face"]

            # Landmarks
            landmarks_output = face["entities"][1]["namedpoints"]
            landmarks = FaceLandmarks(
                left_eye=landmarks_output["left-eye"],
                right_eye=landmarks_output["right-eye"],
                nose_tip=landmarks_output["nose-tip"],
                mouth_left=landmarks_output["mouth-left-corner"],
                mouth_right=landmarks_output["mouth-right-corner"],
            )
            faces_list.append(
                FaceItem(
                    confidence=confidence, bounding_box=bouding_box, landmarks=landmarks
                )
            )
        standarized_response = FaceDetectionDataClass(items=faces_list)
        result = ResponseType[FaceDetectionDataClass](
            original_response=original_response,
            standarized_response=standarized_response,
        )
        return result

    def image__anonymization(
        self, file: BufferedReader
    ) -> ResponseType[AnonymizationDataClass]:
        files = {"image": file}
        response = requests.post(self.urls["anonymization"], files=files)

        original_response = response.json()

        if response.status_code != 200:
            raise ProviderException(
                message=original_response["result"][0]["status"]["message"],
                code=response.status_code,
            )

        img_b64 = original_response["results"][0]["entities"][0]["image"]

        standarized_response = AnonymizationDataClass(image=img_b64)
        result = ResponseType[AnonymizationDataClass](
            original_response=original_response,
            standarized_response=standarized_response,
        )
        return result

    def image__logo_detection(
        self, file: BufferedReader
    ) -> ResponseType[LogoDetectionDataClass]:
        payload = {
            "image": file,
        }
        # Get response
        response = requests.post(self.urls["logo_detection"], files=payload)
        # Handle errors
        if response.status_code != 200:
            raise ProviderException(response.json()["result"][0]["status"]["message"])

        # Get result
        original_response = response.json()
        logos = original_response["results"][0]["entities"][0]["objects"]
        items: Sequence[LogoItem] = []
        for logo in logos:
            classes = logo.get("entities")[0].get("classes")
            for name in object:
                description = name
                score = classes[name]
            vertices = []
            vertices.append(LogoVertice(logo["box"][0], logo["box"][1]))
            vertices.append(LogoVertice(logo["box"][2], logo["box"][1]))
            vertices.append(LogoVertice(logo["box"][2], logo["box"][3]))
            vertices.append(LogoVertice(logo["box"][0], logo["box"][3]))
            items.append(
                LogoItem(
                    description=description,
                    score=score,
                    bounding_poly=LogoBoundingPoly(vertices=vertices),
                )
            )
        standarized = LogoDetectionDataClass(items=items)
        result = ResponseType[LogoDetectionDataClass](
            original_response=original_response, standarized_response=standarized
        )
        return result

    def image__explicit_content(
        self, file: BufferedReader
    ) -> ResponseType[ExplicitContentDataClass]:
        payload = {
            "image": file,
        }
        # Get response
        response = requests.post(self.urls["nsfw"], files=payload)

        # Handle errors
        if response.status_code != 200:
            raise ProviderException(response.json()["result"][0]["status"]["message"])

        # Get result
        original_response = response.json()
        nsfw_items = []
        nsfw_response = original_response["results"][0]["entities"][0]["classes"]
        for classe in nsfw_response:
            nsfw_items.append(
                ExplicitItem(
                    label=classe, likelihood=content_processing(nsfw_response[classe])
                )
            )
        standarized_response = ExplicitContentDataClass(items=nsfw_items)
        result = ResponseType[ExplicitContentDataClass](
            original_response=original_response,
            standarized_response=standarized_response
        )
        return result

    def ocr__ocr(self, file: BufferedReader, language: str) -> ResponseType[OcrDataClass]:
        payload = {
            "image": file,
        }

        file_content = file.read()
        is_pdf = file.name.lower().endswith(".pdf")
        responses = []

        if is_pdf:
            ocr_file_images = convert_from_bytes(
                file_content, fmt="jpeg", poppler_path=None
            )
            for ocr_image in ocr_file_images:
                ocr_image_buffer = BytesIO()
                ocr_image.save(ocr_image_buffer, format="JPEG")
                ocr_image_buffer.seek(0)

                response = requests.post(self.urls["ocr"], files= {"image" : BufferedReader(ocr_image_buffer)})
                if response.status_code == 200 and not "failure" in response.json()["results"][0]["status"]["code"]:
                    response = response.json()
                    responses.append(response)
            if len(responses) == 0:
                raise ProviderException(f"Can not convert the given file: {file.name}")

        else:
            file.seek(0)
            response = requests.post(self.urls["ocr"], files=payload)
            if response.status_code != 200 or "failure" in response.json()["results"][0]["status"]["code"]:
                raise ProviderException(response.json()["result"][0]["status"]["message"])
            response = response.json()
            responses.append(response)

        final_text = ""
        output_value = json.dumps(responses, ensure_ascii=False)
        messages_list = json.loads(output_value)
        boxes: Sequence[Bounding_box] = []

        for original_response in messages_list:
            # original_response = response.json()
            entities = original_response["results"][0]["entities"][0]["objects"]
            full_text = ""
            for text in entities:
                box = Bounding_box(
                    text=text["entities"][0]["text"],
                    top=text["box"][0],
                    left=text["box"][1],
                    width=text["box"][2],
                    height=text["box"][3],
                )
                full_text += text["entities"][0]["text"]
                boxes.append(box)

            final_text += " " + full_text

        standarized_response = OcrDataClass(text=full_text, bounding_boxes=boxes).dict()
        result = ResponseType[OcrDataClass](
            original_response=original_response,
            standarized_response=standarized_response,
        )
        return result


import dash
import dash_html_components as html
import dash_core_components as dcc
from dash import dependencies
import plotly.express as px
import plotly.graph_objects as go

import pandas as pd

from app import app
from cursor import cursor, voivodeships

interactive_statistics_html = []

df = pd.read_csv("data/ceidg_data_classif.csv")

barplot_div = html.Div([
    dcc.Graph(id="statistics-graph"),
])

layout = html.Div([
    html.Div(
        dcc.Markdown(
            """
            #### Check a category
            """
        )
    ),
    dcc.RadioItems(
        id="sex-option",
        options=[
            dict(label="Man", value="M"),
            dict(label="Woman", value="F")
        ],
        value="M"
    ),
    dcc.RadioItems(
        id="voivodeship-option",
        options=[
            dict(label=v, value=v) for v in voivodeships
        ],
        value=voivodeships[0]
    ),
    html.Div(id="number-of-observations"),
    barplot_div
])

@app.callback(
    [
        dependencies.Output("statistics-graph", "figure"), # figure is the output property of a statistics-graph
        dependencies.Output("number-of-observations", "children")
    ],
    [
        dependencies.Input("sex-option", "value"),
        dependencies.Input("voivodeship-option", "value")
    ]
)
def update_barplot(selected_sex, selected_voivodeship):
    failed, n = cursor.get_subset_summary(Sex=selected_sex, MainAddressVoivodeship=selected_voivodeship)
    fig = {
        "data": [
            {
                "x": ["failed", "not failed"],
                "y": [failed, 1 - failed],
                "type": "bar",

            }
        ],
        "layout": {
            "title": 'Percentage of failed companies per selected category',
            "yaxis": dict(type="bar", range=[0, 1])
        }
    }
    number_of_observations_text = "Number of observations with selected values: {}".format(n)
    return fig, number_of_observations_text

interactive_statistics_html.append(layout)

terminated_idx = df["Target"] == 1

categorical_variables = [
    "MonthOfStartingOfTheBusiness",
    "MainAddressVoivodeship",
    "CorrespondenceAddressVoivodeship",
    # "CorrespondenceAddressCounty",
    "PKDMainSection",
    "Sex",
    "MainAddressCounty",
    "CommunityProperty"
]

# fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group",
#              facet_row="time", facet_col="day",
#              category_orders={"day": ["Thur", "Fri", "Sat", "Sun"],
#                               "time": ["Lunch", "Dinner"]})
# fig.show()


import urllib.parse

import requests

from api import RequestUrls
from exceptions import ExecutionError
from task import Task, dict_to_task, dict_list_to_task_list
from server_mock import ServerMock, MockConstants

class ClientSession:
    def __init__(self, host: str, port: int, simulate_failure: bool) -> None:
        self._server_address = f"https-mock://{host}:{port}"
        self._session = self._create_mock_server_session(self._server_address)
        self._test_server_connection(simulate_failure)

    def get_address(self) -> str:
        return self._server_address

    def get_server_modification_time(self, simulate_failure: bool = False) -> int:
        headers = self._make_basic_request_header(simulate_failure)
        request_url = RequestUrls.get_modification_time(self._server_address).text()
        response = self._session.get(url=request_url, headers=headers)
        self._abort_if_response_is_bad(response)
        return int(response.text)

    def request_task_creation(self, robot_name: str, git_branch: str, run_count: int,
                              simulate_failure: bool = False) -> int:
        """:return: Task id for the created Task"""
        request_data = {"robot_name": robot_name, "branch": git_branch, "runs": run_count}
        request_url = RequestUrls.create_task(self._server_address).text()
        response = self._session.post(url=request_url,
                                      headers=self._make_basic_request_header(simulate_failure),
                                      json=request_data)

        self._abort_if_response_is_bad(response)
        return int(response.text)

    def get_robot_dict(self, simulate_failure: bool) -> dict:
        request_headers = self._make_basic_request_header(simulate_failure)
        response = self._session.get(url=RequestUrls.get_robots(self._server_address).text(),
                                     headers=request_headers)

        self._abort_if_response_is_bad(response)

        robot_list = response.text.split()
        robot_dict = {index: robot_name for index, robot_name in enumerate(robot_list)}
        return robot_dict

    def get_task(self, task_id: int, simulate_failure: bool) -> Task:
        request_headers = self._make_basic_request_header(simulate_failure)
        request_url = RequestUrls.get_single_task(self._server_address, task_id).text()
        response = self._session.get(url=request_url, headers=request_headers)

        self._abort_if_response_is_bad(response)

        return dict_to_task(response.json())

    def get_many_tasks(self, robot_name: str, status: str, simulate_failure: bool) -> list:
        """:return: list of Tasks"""
        request_headers = self._make_basic_request_header(simulate_failure)
        request_headers["robot_name"] = robot_name
        request_headers["status"] = status
        request_url = RequestUrls.get_all_tasks(self._server_address).text()
        response = self._session.get(url=request_url, headers=request_headers)

        ClientSession._abort_if_response_is_bad(response)

        return dict_list_to_task_list(response.json())

    def _test_server_connection(self, simulate_failure: bool) -> None:
        self.get_server_modification_time(simulate_failure)

    @staticmethod
    def _create_mock_server_session(server_address: str) -> requests.Session:
        session = requests.session()
        mock_server = ServerMock(server_address)
        mock_adapter = mock_server.get_mock_adapter()
        address_scheme = urllib.parse.urlparse(server_address).scheme
        session.mount(prefix=address_scheme, adapter=mock_adapter)
        return session

    @staticmethod
    def _make_basic_request_header(should_fail: bool) -> dict:
        """Makes a request header that can Signal mock Server to simulate request failure."""
        return {MockConstants.fail_key: MockConstants.true if should_fail else MockConstants.false}

    @staticmethod
    def _abort_if_response_is_bad(response: requests.Response) -> None:
        if not response.ok:
            raise ExecutionError(f"HTTP request failed: {response.status_code}\n{response.reason}")


import datetime
from repachain import RepaBlock, InvalidBlockException

import pytest

def test_block_creation():
    now = datetime.datetime.now()
    block = RepaBlock(0, now, "test", "prevhash")

    assert block.index == 0
    assert block.timestamp == now
    assert block.data == "test"
    assert block.previous_hash == "prevhash"
    assert block.hash is not None

def test_block_creation_with_hash():
    now = datetime.datetime.now()

    with pytest.raises(InvalidBlockException):
        block = RepaBlock(0, now, "test", "prevhash", hash="lol")

def test_block_verify():
    now = datetime.datetime.now()
    block = RepaBlock(0, now, "test", "prevhash")
    assert block.verify() == True

    with pytest.raises(InvalidBlockException):
        block.hash = "lol"
        block.verify()

def test_block_pow():
    now = datetime.datetime.now()
    block = RepaBlock(0, now, "test", "prevhash", check_hash=lambda x: x.endswith("0"))

    assert block.hash.endswith("0")

def test_block_as_dict():
    now = datetime.datetime.now()
    block = RepaBlock(0, now, "test", "prevhash")
    bdict = block.as_dict()

    assert bdict["index"] == 0
    assert bdict["timestamp"] == now.timestamp()
    assert bdict["data"] == "test"
    assert bdict["previous_hash"] == "prevhash"
    assert "nonce" in bdict
    assert "hash" in bdict

def test_block_str():
    now = datetime.datetime.now()
    block = RepaBlock(0, now, "test", "prevhash", check_hash=lambda x: x.endswith("0"))
    bstr = str(block)
    brepr = repr(block)

    assert bstr == brepr

    assert bstr.startswith("<RepaBlock: 'test' #")
    assert bstr.endswith("0>")


from __future__ import print_function

import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras import backend as K
from keras.optimizers import RMSprop
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from imblearn.over_sampling import SMOTE, ADASYN
import pickle

batch_size = 32
num_classes = 2
epochs = 20

def recall_m(y_true, y_pred):
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
        recall = true_positives / (possible_positives + K.epsilon())
        return recall

def precision_m(y_true, y_pred):
        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
        precision = true_positives / (predicted_positives + K.epsilon())
        return precision

def f1_m(y_true, y_pred):
    precision = precision_m(y_true, y_pred)
    recall = recall_m(y_true, y_pred)
    return 2*((precision*recall)/(precision+recall+K.epsilon()))

# the data, split between train and test sets
def getData(filename, rebalance):

    df = pd.read_csv(filename)
    df = df.replace('None', 0)
    df = df.loc[(df!='Stock').all(1)]
    df = df.dropna(axis=1,how='all')
    df = df.drop_duplicates()
    df = df.reset_index(drop=True)
    df = df[(df != 0).all(1)]

    df = df.drop('Debt Equity Ratio', 1)
    df = df.drop('Dividend Yield', 1)
    df = df.drop('Dividend Payout Ratio', 1)
    df = df.drop('Inventory Turnover', 1)
    df = df.drop('Receivables Growth', 1)
    df = df.drop('Debt Growth', 1)
    df = df.drop('R&D Growth', 1)
    df = df.sample(frac=1).reset_index(drop=True)
    #print(df.astype(bool).sum(axis=0))

    df['Beat Estimate'] = df['Beat Estimate'].map({'-1': 0, '1':1})

    trainSize = round(0.80 * len(df))
    validSize = round(0.90 * len(df))
    train = df[:trainSize]
    valid = df[trainSize:validSize]
    test = df[validSize:]

    if(rebalance):
        x, y = SMOTE().fit_resample(train.loc[:, 'EPS Estimate':'Asset Growth'], train.loc[:, 'Beat Estimate'])

        x = pd.DataFrame(x)
        y = pd.DataFrame(y)
        train = pd.concat([y,x], axis= 1)

    train_Y = train.loc[:, 'Beat Estimate'].values.astype(float)
    train_X = train.loc[:, 'EPS Estimate':'Asset Growth'].values.astype(float)
    valid_Y = valid.loc[:, 'Beat Estimate'].values.astype(float)
    valid_X = valid.loc[:, 'EPS Estimate':'Asset Growth'].values.astype(float)
    test_Y = test.loc[:, 'Beat Estimate'].values.astype(float)
    test_X = test.loc[:, 'EPS Estimate':'Asset Growth'].values.astype(float)

    print(train_X.shape)
    print(train_X.shape[1], 'features')
    print(train_X.shape[0], 'train samples')
    print(valid_X.shape[0], 'validation samples')
    print(test_X.shape[0], 'test samples')

    print(str(np.sum(train_Y == 0)) + ' class 0 in train')
    print(str(np.sum(train_Y == 1)) + ' class 1 in train')

    train_Y = keras.utils.to_categorical(train_Y, num_classes)
    valid_Y = keras.utils.to_categorical(valid_Y, num_classes)
    test_Y = keras.utils.to_categorical(test_Y, num_classes)

    return train_X, train_Y, valid_X, valid_Y, test_X, test_Y

def trainModel(train_X, train_Y, valid_X, valid_Y):
    model = Sequential()
    model.add(Dense(20, activation='relu', input_shape=(19,)))
    model.add(Dropout(0.2))
    model.add(Dense(15, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(15, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(15, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(15, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(num_classes, activation='softmax'))

    model.summary()

    model.compile(loss='categorical_crossentropy',
                  optimizer=RMSprop(),
                  metrics=['acc',f1_m,precision_m, recall_m])

    history = model.fit(train_X, train_Y,
                        batch_size=batch_size,
                        epochs=epochs,
                        verbose=1,
                        validation_data=(valid_X, valid_Y))
    return model, history

def testModel(model, test_X, test_Y):
    score = model.evaluate(test_X, test_Y, verbose=0)
    print('Test loss:', score[0])
    print('Test accuracy:', score[1])

def plotMetrics(history):
    # Plot the loss
    fig, (ax,ax2,ax3) = plt.subplots(3, 1, figsize=(10,6))
    ax.plot(np.sqrt(history.history['loss']), 'r', label='train')
    ax.plot(np.sqrt(history.history['val_loss']), 'b' ,label='val')
    ax.set_xlabel(r'Epoch')
    ax.set_ylabel(r'Loss')
    ax.legend()

    # Plot the accuracy
    ax2.plot(np.sqrt(history.history['acc']), 'r', label='train')
    ax2.plot(np.sqrt(history.history['val_acc']), 'b' ,label='val')
    ax2.set_xlabel(r'Epoch')
    ax2.set_ylabel(r'Accuracy')
    ax2.legend()

    # Plot the recall
    ax3.plot(np.sqrt(history.history['recall_m']), 'r', label='train')
    ax3.plot(np.sqrt(history.history['val_recall_m']), 'b' ,label='val')
    ax3.set_xlabel(r'Epoch')
    ax3.set_ylabel(r'Recall')
    ax3.legend()

    fig.savefig('stats.png')

train_X, train_Y, valid_X, valid_Y, test_X, test_Y = getData('stockData.csv', True)

model, history = trainModel(train_X, train_Y, valid_X, valid_Y)

pickle.dump(model, open('NN_model.pkl','wb'))

testModel(model, test_X, test_Y)

#plotMetrics(history)


from django.urls import path
from . import views
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path('', views.TestView.as_view(), name="test"),
    path('one/', views.newPage.as_view(), name="testListapiview"),
    path('two/', views.newPage2.as_view() , name="testCreateapiview"),
    path('three/<int:pk>/', views.NewPageThree.as_view(), name="testDeleteapiview"),
    path('<slug:param>/', views.TestApiGetView.as_view(), name='paramTest'),
    path('api/token', obtain_auth_token, name='getToken'),
]


from plotly import graph_objs as go

def build_histogram():
    names = ['Bob', 'Alex', 'Alan', 'Alyona', 'Katia']
    marks = [9, 4, 11, 10, 9]
    diag = go.Bar(x=names, y=marks)
    fig = go.Figure(data=[diag])
    fig.write_html(file='diag.html', auto_open=True)

def build_pie():
    names = ['Bob', 'Alex', 'Alan', 'Alyona', 'Katia']
    marks = [9, 4, 11, 10, 9]
    diag = go.Pie(labels=names, values=marks)
    fig = go.Figure(data=[diag])
    fig.write_html('pie_diag.html', auto_open=True)

def y(x):
    return x ** 2

def build_line_graphic():
    x_list = []
    y_list = []
    x = -10
    while x < 10:
        x_list.append(x)
        y_list.append(y(x))
        x += 1

    diag = go.Scatter(x=x_list, y=y_list)
    fig = go.Figure(data=[diag])
    fig.write_html('function.html', auto_open=True)

build_line_graphic()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
from typing import Optional

from Solution_102 import TreeNode

class Solution_1372:
    def longestZigZag(self, root: Optional[TreeNode]) -> int:
        if not root: return 0
        self.res = 0
        _, lr = self.zigzag(root.left)
        rl, _ = self.zigzag(root.right)
        self.res = max(lr + 1, rl + 1, self.res)
        return self.res

    def zigzag(self, root):
        if not root: return [-1, -1]
        _, lr = self.zigzag(root.left)
        rl, _ = self.zigzag(root.right)
        self.res = max(lr + 1, rl + 1, self.res)
        return [lr + 1, rl + 1]


# Not so shamelessly taken from
# https://stackoverflow.com/questions/5671354/how-to-programmatically-make-a-horizontal-line-in-qt

from PyQt5.QtWidgets import QFrame

class QHLine(QFrame):
    def __init__(self):
        super(QHLine, self).__init__()
        self.setFrameShape(QFrame.HLine)
        self.setFrameShadow(QFrame.Sunken)

class QVLine(QFrame):
    def __init__(self):
        super(QVLine, self).__init__()
        self.setFrameShape(QFrame.VLine)
        self.setFrameShadow(QFrame.Sunken)


#Question: Given a list of ints, find the smallest missing positive number
#Solution: Sort the list as you go through by placing every term on its index + 1th place.
#Difficulty: Hard
#Time Complexity: O(n)
#Space Complexity: O(1)

from typing import List

def firstMissingPositive(nums: List[int]) -> int:
    i, j = 0, len(nums)
    while i < j:

        #If the current number is equal to its index + 1, skip over as its already sorted
        #for example if the number 5 is in the 4th index/ 5th place
        if nums[i] == i+1: i += 1

        #Regular case, ie a number not in the correct place
        #In othe words, if a number n is within our range and the number in the nth position isnt equal to this number, swap the two
        elif nums[i] > 0 and nums[i] <= j and nums[nums[i]-1] != nums[i]:
            nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]

        #Case if the number is a duplicate, or out of our range (1 to j). So place it at the end
        else:
            j -= 1
            nums[j], nums[i] = nums[i], nums[j]

    return j + 1

def main():
    print(firstMissingPositive([1, 5, 4, 3, 2, 7, 0]))

main()


import fcntl
import glob
import os
import platform
import re
import shutil
import stat
import subprocess  # nosec
import sys
from typing import Sequence, Mapping, Optional, List

def update_key_values_file(
        path: str,
        key_values: Mapping[str, Optional[str]],
        sep: str) -> None:
    """Update key-values in a file.

    For all (key, new_value) pairs in key_values, if value is not None, update
    the value of that key in the file to new_value; otherwise remove the
    key-value pair from the file.  The file is assumed to have a key-value per
    line, with sep as separator.  A line might contain only a key, even without
    a separator, in which case the value is assumed to be empty.
    """
    with open(path) as fdesc:
        data = fdesc.read().splitlines()

    with open(path, "w") as fdesc:
        for line in data:
            key, *_ = line.split("=", maxsplit=1)
            key = key.strip()

            if key in key_values:
                new_value = key_values[key]

                # If new_value is not None, update the value; otherwise remove
                # it (i.e. don't write key-new_value back to the file).
                if new_value is not None:
                    fdesc.write(f"{key}{sep}{new_value}\n")
            else:
                # line doesn't match lines to update; write it back as is
                fdesc.write(f"{line}\n")

class Lkce:
    """Class to include user interaction related functionality"""
    # pylint: disable=too-many-instance-attributes

    def __init__(self) -> None:
        """Constructor for Lkce class"""
        self.lkce_home = "/etc/oled/lkce"
        self.lkce_bindir = "/usr/lib/oled-tools"
        self.lkce_config_file = self.lkce_home + "/lkce.conf"
        self.kdump_kernel_ver = platform.uname().release
        self.vmcore = "yes"

        self.set_defaults()

        # set values from config file
        if os.path.exists(self.lkce_config_file):
            self.read_config(self.lkce_config_file)

        # lkce as a kdump_pre hook to kexec-tools
        self.lkce_kdump_sh = self.lkce_home + "/lkce_kdump.sh"
        self.lkce_kdump_dir = self.lkce_home + "/lkce_kdump.d"
        self.kdump_conf = "/etc/kdump.conf"

        tmp = shutil.which("timeout")
        if tmp is None:
            print("timeout command not found.")
            sys.exit(1)

        self.timeout_path = tmp
    # def __init__

    # default values
    def set_defaults(self) -> None:
        """set default values"""
        self.enable_kexec = "no"
        self.vmlinux_path = "/usr/lib/debug/lib/modules/" + \
            self.kdump_kernel_ver + "/vmlinux"
        self.crash_cmds_file = self.lkce_home + "/crash_cmds_file"
        self.vmcore = "yes"
        self.max_out_files = "50"
        self.lkce_outdir = "/var/oled/lkce"
    # def set_default

    def configure_default(self) -> None:
        """Configure lkce with default values

        Creates self.crash_cmds_file and self.lkce_config_file
        """
        os.makedirs(self.lkce_home, exist_ok=True)

        if self.enable_kexec == "yes":
            print("trying to disable lkce")
            self.disable_lkce_kexec()

        self.set_defaults()

        # crash_cmds_file
        filename = self.crash_cmds_file
        content = """#
# This is the input file for crash utility. You can edit this manually
# Add your own list of crash commands one per line.
#
bt
bt -a
bt -FF
dev
kmem -s
foreach bt
log
mod
mount
net
ps -m
ps -S
runq
quit
"""
        try:
            file = open(filename, "w")
            file.write(content)
            file.close()
        except OSError:
            print(f"Unable to operate on file: {filename}")
            return

        # config file
        filename = self.lkce_config_file
        content = """##
# This is configuration file for lkce
# Use 'oled lkce configure' command to change values
##

#enable lkce in kexec kernel
enable_kexec=""" + self.enable_kexec + """

#debuginfo vmlinux path. Need to install debuginfo kernel to get it
vmlinux_path=""" + self.vmlinux_path + """

#path to file containing crash commands to execute
crash_cmds_file=""" + self.crash_cmds_file + """

#lkce output directory path
lkce_outdir=""" + self.lkce_outdir + """

#enable vmcore generation post kdump_report
vmcore=""" + self.vmcore + """

#maximum number of outputfiles to retain. Older file gets deleted
max_out_files=""" + self.max_out_files

        try:
            file = open(filename, "w")
            file.write(content)
            file.close()
        except OSError:
            print("Unable to operate on file: {filename}")
            return

        print("configured with default values")
    # def configure_default

    def read_config(self, filename: str) -> None:
        """Read config file and update the class variables"""
        if not os.path.exists(filename):
            return

        try:
            file = open(filename, "r")
        except OSError:
            print("Unable to open file: {filename}")
            return

        for line in file.readlines():
            if re.search("^#", line):  # ignore lines starting with '#'
                continue

            # trim space/tab/newline from the line
            line = re.sub(r"\s+", "", line)

            entry = re.split("=", line)
            if "enable_kexec" in entry[0] and entry[1]:
                self.enable_kexec = entry[1]

            elif "vmlinux_path" in entry[0] and entry[1]:
                self.vmlinux_path = entry[1]

            elif "crash_cmds_file" in entry[0] and entry[1]:
                self.crash_cmds_file = entry[1]

            elif "lkce_outdir" in entry[0] and entry[1]:
                self.lkce_outdir = entry[1]

            elif "vmcore" in entry[0] and entry[1]:
                self.vmcore = entry[1]

            elif "max_out_files" in entry[0] and entry[1]:
                self.max_out_files = entry[1]
    # def read_config

    def create_lkce_kdump(self) -> None:
        """create lkce_kdump.sh script.

        lkce_kdump.sh is attached as kdump_pre hook in /etc/kdump.conf
        """
        filename = self.lkce_kdump_sh
        os.makedirs(self.lkce_kdump_dir, exist_ok=True)

        mount_cmd = "mount -o bind /sysroot"  # OL7 and above

        # create lkce_kdump.sh script
        content = """#!/bin/sh
# This is a kdump_pre script
# /etc/kdump.conf is used to configure kdump_pre script

# Generate vmcore post lkce_kdump scripts execution
LKCE_VMCORE=""" + self.vmcore + """

# Timeout for lkce_kdump scripts in seconds
LKCE_TIMEOUT="120"

# Temporary directory to mount the actual root partition
LKCE_DIR="/lkce_kdump"

mkdir $LKCE_DIR
""" + mount_cmd + """ $LKCE_DIR
mount -o bind /proc $LKCE_DIR/proc
mount -o bind /dev $LKCE_DIR/dev

LKCE_KDUMP_SCRIPTS=$LKCE_DIR""" + self.lkce_kdump_dir + """/*

#get back control after $LKCE_TIMEOUT to proceed
export LKCE_KDUMP_SCRIPTS
export LKCE_DIR
""" + self.timeout_path + """ $LKCE_TIMEOUT /bin/sh -c '
echo "LKCE_KDUMP_SCRIPTS=$LKCE_KDUMP_SCRIPTS";
for file in $LKCE_KDUMP_SCRIPTS;
do
    cmd=${file#$LKCE_DIR};
    echo "Executing $cmd";
    chroot $LKCE_DIR $cmd;
done;'

umount $LKCE_DIR/dev
umount $LKCE_DIR/proc
umount $LKCE_DIR

unset LKCE_KDUMP_SCRIPTS
unset LKCE_DIR

if [ "$LKCE_VMCORE" == "no" ]; then
    echo "lkce_kdump.sh: vmcore generation is disabled"
    exit 1
fi

exit 0
"""
        try:
            file = open(filename, "w")
            file.write(content)
            file.close()
        except OSError:
            print("Unable to operate on file: {filename}")
            return

        mode = os.stat(filename).st_mode
        os.chmod(filename, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
    # def create_lkce_kdump

    def remove_lkce_kdump(self) -> int:
        """Remove lkce_kdump.sh as kdump_pre hook in /etc/kdump.conf"""
        return self.update_kdump_conf("--remove")
    # def remove_lkce_kdump()

    def update_kdump_conf(self, arg: str) -> int:
        """Add/remove /etc/kdump.conf with kdump_pre hook"""
        if not os.path.exists(self.kdump_conf):
            print(f"error: can not find {self.kdump_conf}. "
                  "Please retry after installing kexec-tools")
            return 1

        kdump_pre_line = f"kdump_pre {self.lkce_kdump_sh}"
        kdump_timeout_line = f"extra_bins {self.timeout_path}"

        with open(self.kdump_conf) as conf_fd:
            conf_lines = conf_fd.read().splitlines()

        kdump_pre_value = None
        for line in conf_lines:
            if line.startswith("kdump_pre "):
                kdump_pre_value = line

        if arg == "--remove":
            if kdump_pre_value != kdump_pre_line:
                print(f"lkce_kdump entry not set in {self.kdump_conf}")
                return 1

            # remove lkce_kdump config
            with open(self.kdump_conf, "w") as conf_fd:
                for line in conf_lines:
                    if line not in (kdump_pre_line, kdump_timeout_line):
                        conf_fd.write(f"{line}\n")

            restart_kdump_service()
            return 0

        # arg == "--add"
        if kdump_pre_value == kdump_pre_line:
            print("lkce_kdump is already enabled to run lkce scripts")
        elif kdump_pre_value:
            # kdump_pre is enabled, but it is not our lkce_kdump script
            print(f"lkce_kdump entry not set in {self.kdump_conf} "
                  "(manual setting needed)\n"
                  f"present entry in kdump.conf:\n{kdump_pre_value}\n"
                  "Hint: edit the present kdump_pre script and make it run"
                  f" {self.lkce_kdump_sh}")
            return 1
        else:
            # add lkce_kdump config
            with open(self.kdump_conf, "a") as conf_fd:
                conf_fd.write(
                    f"{kdump_pre_line}\n{kdump_timeout_line}\n")
            restart_kdump_service()

        return 0
    # def update_kdump_conf

    def report(self, subargs: List[str]) -> None:
        """Generate report from vmcore"""
        if not subargs:
            print("error: report option need additional arguments "
                  "[oled lkce help]")
            return

        d_subargs = {}
        for subarg in subargs:
            subarg.strip()
            entry = subarg.split("=", 1)

            if len(entry) < 2:
                print("error: unknown report option %s" % subarg)
                continue

            if entry[0] not in ("--vmcore", "--vmlinux",
                                "--crash_cmds", "--outfile"):

                print("error: unknown report option %s" % subarg)
                break

            d_subargs[entry[0].strip()] = entry[1].strip()
        # for

        vmcore = d_subargs.get("--vmcore", None)
        vmlinux = d_subargs.get("--vmlinux", None)
        crash_cmds = d_subargs.get("--crash_cmds", None)
        outfile = d_subargs.get("--outfile", None)

        if vmcore is None:
            print("error: vmcore not specified")
            return

        if vmlinux is None:
            vmlinux = self.vmlinux_path
        if not (os.path.exists(vmlinux) and os.path.isfile(vmlinux)):
            print("error: vmlinux '%s' not found" % vmlinux)
            return

        if crash_cmds is None:
            # use configured crash commands file
            if not (os.path.exists(self.crash_cmds_file) and
                    os.path.isfile(self.crash_cmds_file)):
                print(f"crash_cmds_file '{self.crash_cmds_file}' not found")
                return

            cmd: Sequence[str] = ("crash", vmcore, vmlinux, "-i",
                                  self.crash_cmds_file)
            cmd_input = None
        else:
            # use specified crash commands
            cmd = ("crash", vmcore, vmlinux)
            crash_cmds = crash_cmds + "," + "quit"
            cmd_input = "\n".join(crash_cmds.split(",")).encode("utf-8")

        print("lkce: executing '{}'".format(" ".join(cmd)))

        if outfile:
            with open(outfile, "w") as output_fd:
                subprocess.run(
                    cmd, input=cmd_input, stdout=output_fd, check=True,
                    shell=False)  # nosec
        else:
            subprocess.run(
                cmd, input=cmd_input, stdout=sys.stdout, check=True,
                shell=False)  # nosec
    # def report

    def configure(self, subargs: List[str]) -> None:
        """Configure lkce

        Based on subarg, you can configure with default values, show the values
        and also set to given values
        """
        if not subargs:  # default
            subargs = ["--show"]

        values_to_update = {}
        filename = self.lkce_config_file
        for subarg in subargs:
            subarg.strip()
            if subarg == "--default":
                self.configure_default()
            elif subarg == "--show":
                if not os.path.exists(filename):
                    print("config file not found")
                    return

                print("%15s : %s" % ("vmlinux path", self.vmlinux_path))
                print("%15s : %s" % ("crash_cmds_file", self.crash_cmds_file))
                print("%15s : %s" % ("vmcore", self.vmcore))
                print("%15s : %s" % ("lkce_outdir", self.lkce_outdir))
                print("%15s : %s" % ("lkce_in_kexec", self.enable_kexec))
                print("%15s : %s" % ("max_out_files", self.max_out_files))
            else:
                entry = subarg.split("=", 1)

                if len(entry) < 2:
                    print("error: unknown configure option %s" % subarg)
                    return

                if entry[0] not in ("--vmlinux_path", "--crash_cmds_file",
                                    "--lkce_outdir", "--vmcore",
                                    "--max_out_files"):
                    print("error: unknown configure option %s" % subarg)
                    return

                values_to_update[entry[0].strip("-")] = entry[1].strip()
        # for

        vmcore = values_to_update.get("vmcore", None)
        if values_to_update:
            if vmcore and self.config_vmcore(vmcore):
                return

            update_key_values_file(filename, values_to_update, sep="=")
    # def configure

    def config_vmcore(self, value: str) -> int:
        """Configure vmcore value in lkce_config_file.

        Called from configure()
        """
        if value not in ['yes', 'no']:
            print(f"error: invalid option '{value}'")
            return 1

        filename = self.lkce_kdump_sh
        if not os.path.exists(filename):
            print("error: Please enable lkce first, using 'oled lkce enable'")
            return 1

        self.vmcore = value
        self.create_lkce_kdump()
        restart_kdump_service()
        return 0
    # def config_vmcore

    def enable_lkce_kexec(self) -> None:
        """Enable lkce to generate report on crashed kernel in kexec mode"""
        if not os.path.exists(self.lkce_kdump_sh):
            self.create_lkce_kdump()

        if self.update_kdump_conf("--add") == 1:
            return

        update_key_values_file(
            self.lkce_config_file, {"enable_kexec": "yes"}, sep="=")
        print("enabled_kexec mode")
    # def enable_lkce_kexec

    def disable_lkce_kexec(self) -> None:
        """Disable lkce to generate report on crashed kernel in kexec mode"""
        if not os.path.exists(self.lkce_config_file):
            print(f"config file '{self.lkce_config_file}' not found")
            return

        if self.update_kdump_conf("--remove") == 1:
            return

        update_key_values_file(
            self.lkce_config_file, {"enable_kexec": "no"}, sep="=")

        try:
            os.remove(self.lkce_kdump_sh)
        except OSError:
            pass
        print("disabled kexec mode")
    # def disable kexec

    def status(self) -> None:
        """Show current configuration values"""
        self.configure(subargs=["--show"])

        if not os.path.exists(self.vmlinux_path):
            print(f"NOTE: {self.vmlinux_path}: file not found")
            print("kernel debuginfo rpm installed?")

        if subprocess.run(
                ("rpm", "-q", "crash"), shell=False,  # nosec
                check=False).returncode != 0:
            print("NOTE: crash is not installed")
    # def status

    def clean(self, subarg: List[str]) -> None:
        """Clean up old crash reports to save space"""
        if "--all" in subarg:
            val = input(f"lkce removes all the files in {self.lkce_outdir} "
                        "dir. do you want to proceed(yes/no)? [no]:")
            if "yes" in val:
                for file in glob.glob(f"{self.lkce_outdir}/crash*out"):
                    try:
                        os.remove(file)
                    except OSError:
                        pass
            # if "yes"
        else:
            val = input("lkce deletes all but last three "
                        f"{self.lkce_outdir}/crash*out files. "
                        "do you want to proceed(yes/no)? [no]:")
            if "yes" in val:
                crash_files = glob.glob(f"{self.lkce_outdir}/crash*out")

                # remove all crash files but the 3 newest ones
                for file in sorted(crash_files, reverse=True)[3:]:
                    try:
                        os.remove(file)
                    except OSError:
                        pass
    # def clean

    def listfiles(self) -> None:
        """List crash reports already generated"""
        dirname = self.lkce_outdir
        os.makedirs(dirname, exist_ok=True)

        print("Followings are the crash*out found in %s dir:" % dirname)
        for filename in os.listdir(dirname):
            if re.search("crash.*out", filename):
                print("%s/%s" % (dirname, filename))
        # for
    # def listfiles

# class LKCE

def restart_kdump_service() -> None:
    """Restart kdump service"""
    cmd = ("systemctl", "restart", "kdump")  # OL7 and above

    print("Restarting kdump service...")
    subprocess.run(cmd, shell=False, check=True)  # nosec
    print("done!")
# def restart_kdump_service

def usage() -> int:
    """Print usage"""
    usage_ = """Usage: """ + os.path.basename(sys.argv[0]) + """ <options>
options:
    report <report-options> -- Generate a report from vmcore
    report-options:
        --vmcore=/path/to/vmcore 		- path to vmcore
        [--vmlinux=/path/to/vmlinux] 		- path to vmlinux
        [--crash_cmds=cmd1,cmd2,cmd3,..]	- crash commands to include
        [--outfile=/path/to/outfile] 		- write output to a file

    configure [--default] 	-- configure lkce with default values
    configure [--show] 	-- show lkce configuration -- default
    configure [config-options]
    config-options:
        [--vmlinux_path=/path/to/vmlinux] 	- set vmlinux_path
        [--crash_cmds_file=/path/to/file] 	- set crash_cmds_file
        [--vmcore=yes/no]			- set vmcore generation in kdump kernel
        [--lkce_outdir=/path/to/directory] 	- set lkce output directory
        [--max_out_files=<number>] 		- set max_out_files

    enable_kexec    -- enable lkce in kdump kernel
    disable_kexec   -- disable lkce in kdump kernel
    status          -- status of lkce

    clean [--all]   -- clear crash report files
    list            -- list crash report files
"""
    print(usage_)
    sys.exit(0)
# def usage

def main() -> int:
    """Main routine"""
    lkce = Lkce()

    if len(sys.argv) < 2:
        usage()

    arg = sys.argv[1]
    if arg == "report":
        lkce.report(sys.argv[2:])

    elif arg == "configure":
        lkce.configure(sys.argv[2:])

    elif arg == "enable_kexec":
        lkce.enable_lkce_kexec()

    elif arg == "disable_kexec":
        lkce.disable_lkce_kexec()

    elif arg == "status":
        lkce.status()

    elif arg == "clean":
        lkce.clean(sys.argv[2:])

    elif arg == "list":
        lkce.listfiles()

    elif arg in ("help", "-help", "--help"):
        usage()

    else:
        print(f"Invalid option: {arg}")
        print("Try 'oled lkce help' for more information")

    return 0
# def main

if __name__ == '__main__':
    if not os.geteuid() == 0:
        print("Please run lkce as root user.")
        sys.exit(1)

    LOCK_DIR = "/var/run/oled-tools"
    try:
        if not os.path.isdir(LOCK_DIR):
            os.makedirs(LOCK_DIR)
        LOCK_FILE = LOCK_DIR + "/lkce.lock"

        FH = open(LOCK_FILE, "w")
    except OSError:
        print(f"Unable to open file: {LOCK_FILE}")
        sys.exit()

    # try lock
    try:
        fcntl.flock(FH, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:  # no lock
        print("another instance of lkce is running.")
        sys.exit()

    try:
        main()
        FH.close()
        os.remove(LOCK_FILE)
    except KeyboardInterrupt:
        print("\nInterrupted by user ctrl+c")


import public_class as public
import pandas as pd
import info
import os
from sqlalchemy import create_engine

class Storage(object):
    """docstring for Storage"""

    def __init__(self, data, day, cycle, path=r'/root/ipython/UV分析结果/'):
        # super(Storage, self).__init__()
        self.data = data
        self.day = day
        self.cycle = cycle
        self.path = path

    def toExcel(self):
        path = self.path
        troubleInfo = self.data
        weekFolder = path + '%s周对比/' % public.chineseNumber(self.cycle)
        fileName = '%s周对比_%s.xlsx' % (public.chineseNumber(
            self.cycle), str(public.getDate(self.day)))
        path = weekFolder + fileName

        if not os.path.exists(weekFolder):
            os.makedirs(weekFolder)

        writer = pd.ExcelWriter(path)
        for x in troubleInfo:
            troubleInfo[x].to_excel(writer, x)
        writer.save()
        return path

    def toMySql(self):
        troubleInfo = self.data
        outPutServer = info.getDbInfo(r'/root/ipython/user_list.xlsx',
         r'db_user')['devBase']['server']
        engine = create_engine('mysql+pymysql://%s:%s@%s:%d/%s' % (outPutServer['user'],
            outPutServer['password'], outPutServer['host'], outPutServer['port'],
            outPutServer['db']), connect_args={'charset': 'utf8'})
        for trouble in troubleInfo:
            troubleInfo[trouble]['date'] = public.getDate(self.day)
            try:
                troubleInfo[trouble].to_sql(name='%d_TROUBLE_%s_ON_%s_WEEK' % (self.cycle,
                    str.upper(trouble[7:]),public.englishNumber(self.cycle)),con=engine,
                    if_exists='append', index=True)
            except:
                pass
            troubleInfo[trouble].pop('date')


import os
import cv2
import base64
import hashlib
import numpy as np
from datetime import datetime
from werkzeug.utils import secure_filename
from flask import Flask, request, redirect, send_file, url_for, render_template

from config import *
from censorLicensePalate import *

# Load model
model = None
if CFG_MODEL == 'yolo':
    from modelYOLO import *
    model = modelYOLO()
else:
    from modelFasterRCNN import *
    model = modelFasterRCNN()

app = Flask(__name__)

# Check type HTTP
if CFG_HTTP_TYPE == 'ngrok':
    from flask_ngrok import run_with_ngrok
    run_with_ngrok(app)

# Hash file name
def getFileName():
    return hashlib.md5((str(datetime.now().time()) + "_CS406.M11").encode()).hexdigest() + ".jpg"

# Hash Image
def convertImageToBase64(image):
    return 'data:image/jpg;base64,' + base64.b64encode(cv2.imencode('.jpg', image)[1]).decode()

@app.route('/')
def default():
    return '{"messages": "error"}'

@app.route('/', methods=['POST'])
def home():
    if request.method == 'GET':
        return '{"messages": "error"}'
    fileName = getFileName()
    imageByte = request.files['image'].read()
    imageReplaceByte = request.files['imageReplace'].read()
    typeBlur = int(request.form['typeBlur'])
    kernelSize = int(request.form['kernelSize'])
    kernelDepth = int(request.form['kernelDepth'])

    if imageByte is None:
        return '{"messages": "error"}'

    imageArr = np.frombuffer(imageByte, dtype=np.uint8)
    image = cv2.imdecode(imageArr, flags=1)
    # cv2.imwrite(os.path.join(CFG_PATH_UPLOAD, fileName), image)
    listCoors = model.predict(image)
    imageResult = None

    if typeBlur == 5: # Replace image
        if imageReplaceByte is None:
            return '{"messages": "error"}'
        imageReplaceArr = np.frombuffer(imageReplaceByte, dtype=np.uint8)
        imageReplace = cv2.imdecode(imageReplaceArr, flags=1)
        imageResult = convertImage(image, listCoors).replaceImage(imageReplace)
    elif typeBlur == 1: # averageBlur
        imageResult = convertImage(image, listCoors).averageBlur(kernelSize)
    elif typeBlur == 2: # gaussianBlur
        imageResult = convertImage(image, listCoors).gaussianBlur(kernelSize)
    elif typeBlur == 3: # medianBlur
        imageResult = convertImage(image, listCoors).medianBlur(kernelSize)
    elif typeBlur == 4: # eightBitsBlur
        kernelDepth = int(request.form['kernelDepth'])
        imageResult = convertImage(image, listCoors).eightBitsBlur(kernelSize, kernelDepth)

    # cv2.imwrite(os.path.join(CFG_PATH_RESULT, fileName), imageResult)

    return '{"messages": "success", "imageSrc": "' + convertImageToBase64(image) + '", "imageDes": "' + convertImageToBase64(imageResult) + '"}'

    # return '{"messages": "success", "imageSrc": "' + request.url[:-1] + url_for('displayImageSrc', filename=fileName) + '", "imageDes": "' + request.url[:-1] + url_for('displayImageDes', filename=fileName) + '"}'

# Rule Show Image Src
@app.route('/showSrc/<filename>')
def displayImageSrc(filename):
	return redirect(url_for('static', filename='uploads/' + filename), code=301)

# Rule Show Image Des
@app.route('/showDes/<filename>')
def displayImageDes(filename):
	return redirect(url_for('static', filename='results/' + filename), code=301)

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


from django.urls import path
from . import views

# URLConf
urlpatterns = [
    path('', views.index, name="food-journal"),
    path('food-table',views.food_table,name="food-table"),
    path('create-food-item',views.new_food,name="new-food"),
    path('delete-food-item',views.del_food,name="del-food"),
    path('delete-log-entry',views.del_log,name="del-log-entry"),
    path('create-log-entry',views.new_journal_item,name="new-log-entry"),
    path('get-food-names',views.all_food_name,name="get-food-names"),
    path('set-filter',views.update_filter,name="update-filter"),
    path('cal-per-day',views.get_calories_per_day,name="cal-per-day"),
    path('fav-food',views.get_favorite_food,name="fav-food"),
]


"""api_views.py"""

import datetime, time
import json

from django.shortcuts import render
from django.template import loader
from django.urls import reverse
from predict_my_money.utils import stockAPI, portfolioAPI, \
	stockDayDatabaseInterface
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse, Http404, \
	HttpResponseBadRequest, JsonResponse
from django.views.decorators.http import require_http_methods, require_GET

from .models import User, Investor, Stock, Portfolio, Stock_Owned, Portfolio_Day
from predict_my_money.computations.recommender_interface import \
	recommend_diverse_portfolio, recommend_high_return_portfolio, \
	recommend_random_portfolio, recommend_interfacer

sapi = stockAPI()
papi = portfolioAPI()
stockDayInterface = stockDayDatabaseInterface()

# Create your views here.
def portfolio_detail(request, portfolio_id):
	portfolio = papi.getPortfolio(portfolio_id)
	storage = {}
	investor = portfolio.investor.user.first_name + " " + portfolio.investor.user.last_name
	name = portfolio.portfolio_name
	diversity = portfolio.current_diversity
	value = portfolio.current_value
	days = Portfolio_Day.objects.order_by('day').filter(portfolio=portfolio)
	daysDict = {}
	for day in days:
		daysDict[day.day.__str__()] = {'value':day.value if day.day >= portfolio.start_date else None, 'diversity':day.diversity}
	storage['investor'] = investor
	storage['name'] = name
	storage['diversity'] = diversity
	storage['value'] = value
	storage['days'] = daysDict
	return HttpResponse(json.dumps(storage), content_type="application/json")

@require_GET
def get_portfolio_tsr_plot(request):
	pid = request.GET["id"]
	portfolio = papi.getPortfolio(pid)

	if not portfolio:
		print("failed to find portfolio")
		return JsonResponse({ "data": [], error: True }, status=404)

	ownstocks = papi.getStocksOwned(pid)
	if not ownstocks:
		print("failed to find ownstocks")
		return JsonResponse({ "data": [], error: True }, status=404)

	alldays = {}
	stocksbyname = {}

	portfolio.start_date = (datetime.datetime.now() - datetime.timedelta(days=1000)).date()
	portfolio.save()

	print(portfolio.start_date)

	sdays = Portfolio_Day.objects.filter(portfolio=portfolio)

	points = []
	for pday in sdays:
		# if pday.day < portfolio.start_date:
		points.append({
			"date": pday.day.strftime("%Y-%m-%d"),
			"close": pday.value if pday.day >= portfolio.start_date else None,
			"diversity": pday.diversity
		})

	return JsonResponse({ "data": points })

@require_GET
def get_portfolio_plot(request):
	pid = request.GET["id"]
	portfolio = papi.getPortfolio(pid)

	if not portfolio:
		return JsonResponse({ "data": [], error: True }, status=404)

	ownstocks = papi.getStocksOwned(pid)
	if not ownstocks:
		return JsonResponse({ "data": [], error: True }, status=404)

	alldays = {}
	stocksbyname = {}

	for ostock in ownstocks:
		stocksbyname[ostock.stock.stock_name] = ostock.amount_owned
		for stockday in stockDayInterface.getAllDaysOrdered(ostock.stock):
			key = int(time.mktime(stockday.day.timetuple()))

			if not key in alldays:
				alldays[key] = 0
			alldays[key] += stockday.adjustedClose*ostock.amount_owned

	result = []
	keylist = list(alldays.keys())
	keylist.sort()
	for key in keylist:
		date = datetime.datetime.utcfromtimestamp(key).strftime("%Y-%m-%d")
		result.append({ "date": date, "close": alldays[key] })

	return JsonResponse({ "data": result })

@require_GET
def get_stock(request):
	ticker = request.GET["name"]
	stock = sapi.getStock(ticker)

	if not stock:
		return JsonResponse({ "data": None }, status=404)

	return JsonResponse({
		"data": {
		    "stock_name": stock.stock_name,
		    "company_name": stock.company_name,
		    "company_meta": stock.company_meta,
		    "current_high": stock.current_high,
		    "current_low": stock.current_low,
		    "current_adjusted_close": stock.current_adjusted_close,
		    "start_date": stock.start_date,
		    "end_date": stock.end_date,
		}
	})

@require_GET
def get_stock_plot(request):
	ticker = request.GET["name"]
	stock = sapi.getStock(ticker)

	if not stock:
		return JsonResponse({ "data": None }, status=404)

	interface = stockDayDatabaseInterface()
	days = interface.getAllDaysOrdered(stock)
	print('days', days)
	array = []
	for day in days:
		array.append({'date' : day.day.strftime("%Y-%m-%d"), 'close' : day.adjustedClose})

	return JsonResponse({ "data": array })

@require_GET
def gen_portfolio_price_plot(request):
	stocks = json.loads(request.GET['stocks'])
	interface = stockDayDatabaseInterface()
	alldays = {}

	for key in stocks:
		stockinfo = stocks[key]
		print(stockinfo["name"])
		stock = sapi.getStock(stockinfo["name"])
		if not stock:
			continue
		for stockday in interface.getAllDaysOrdered(stock):
			obj = {
				"name": stockinfo["name"],
				"price": stockday.adjustedClose,
				"date": stockday.day.strftime("%Y-%m-%d")
			}

			key = stockday.day.strftime("%Y-%m-%d")
			if not key in alldays:
				alldays[key] = []
			alldays[key].append(obj)

	result = []
	keylist = list(alldays.keys())
	keylist.sort()
	for key in keylist:
		result.append(alldays[key])
	    # print "%s: %s" % (key, alldays[key])

	return JsonResponse({ "data": result })

def get_recommendation(request):
	totalspend = float(request.GET['total_spend'])
	kwargs = { 'budget': totalspend }

	if "type" in request.GET and request.GET["type"] in ["random", "diverse"]:
		rtype = request.GET["type"]
	else:
		rtype = "high_return"

	timehorizon = int(request.GET['timehorizon'])
	maxinvest = float(request.GET['maxinvest'])

	a = recommend_interfacer(recommend_type=rtype, budget=totalspend, time_horizon=timehorizon, max_investment=maxinvest)
	print(a)
	ret = []
	for m in a:
		print(m, a[m])
		ret.append([m, a[m][0], a[m][1]])
	print(ret)
	return JsonResponse({ "data": ret })

def portfolio(request, id):
	portfolio = papi.getPortfolio(id)

	if not portfolio:
		return JsonResponse({ "data": [], error: true }, status=404)

	return JsonResponse({ "data": [] })

def portfolios(request):
	if request.method == "GET":
		investor = Investor.objects.get(user=request.user)
		portfolios = Portfolio.objects.filter(investor=investor)
		storage = {}
		for portfolio in portfolios:
			storage[portfolio.portfolio_name] = [portfolio.current_value, portfolio.current_diversity]
		return HttpResponse(json.dumps(storage), content_type="application/json")

	elif request.method == "POST":
		portfolio = Portfolio()
		portfolio.portfolio_name = request.POST['name']
		portfolio.start_date = datetime.datetime.today()
		portfolio.end_date = datetime.datetime.today()
		portfolio.investor = Investor.objects.get(user=request.user)
		portfolio.save()

		stocks = json.loads(request.POST["_stocks"])

		for order in stocks:
			sname = order['name']
			quantity = order['amount']

			stock = sapi.getStock(sname)
			if not stock:
				return JsonResponse({ "error": True, "message": "Stock not found." })

			owned = Stock_Owned()
			owned.portfolio = portfolio
			owned.stock = stock
			owned.bought_on = datetime.date.today()
			owned.bought_at = stock.current_high
			owned.amount_owned = quantity
			owned.save()

		return JsonResponse({ "error": False })
		# return HttpResponseRedirect(reverse('predictor:home', args=(current_user.id,)))
	else:
		return HttpResponseBadRequest("Invalid method.")


'''
Author: your name
Date: 2021-12-03 01:13:27
LastEditTime: 2021-12-03 01:13:53
LastEditors: newsun-HP-Pavilion-Gaming-Laptop-15-dk0xxx
Description: In User Settings Edit
FilePath: /pyqt5/close.py
'''

import sys
from PyQt5.QtWidgets import (QWidget, QToolTip, QDesktopWidget, QMessageBox,QTextEdit,QLabel,
    QPushButton, QApplication,QMainWindow, QAction, qApp, QHBoxLayout, QVBoxLayout,QGridLayout,
    QLineEdit)
from PyQt5.QtGui import QFont,QIcon
from PyQt5.QtCore import QCoreApplication
# ##***关闭窗口***## #
class CloseW(QWidget):

   def __init__(self):
       super().__init__()
       self.initUI()

   def initUI(self):
       qbtn = QPushButton('Quit', self)  # 创建了一个按钮。按钮是一个QPushButton类的实例。
       # 构造方法的第一个参数是显示在button上的标签文本。第二个参数是父组件。
       # 父组件是Example组件，它继承了QWiget类。
       qbtn.clicked.connect(QCoreApplication.instance().quit)
       qbtn.resize(qbtn.sizeHint())
       qbtn.move(500, 50)
       self.setGeometry(300, 100, 600, 600)
       self.setWindowTitle('excise')
       self.show()

if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = CloseW()
   sys.exit(app.exec_())