from django.shortcuts import render, redirect, HttpResponse
from utils.pay import AliPay
import json
import time
def ali():
    # 沙箱环境地址：https://openhome.alipay.com/platform/appDaily.htm?tab=info
    # 一个商户号是唯一的appid
    app_id = "2016092000554611"
    # 支付宝收到用户的支付,会向商户发两个请求,一个get请求,一个post请求，带的数据是支付成功/失败的标志，
    # 程序能收到请求，会把订单号发过来，通过订单号确定支付状态(从待支付到)是否已支付，钱到了商户号那里，商户再从商户号取钱

    # POST请求，用于最后的检测
    # 服务器地址，类比127.0.0.1，支付宝内侧用42.56.89.12，后期要放在公网的ip上，别人可以直接访问
    notify_url = "http://42.56.89.12:80/page2/"

    # GET请求，用于页面的跳转展示
    return_url = "http://42.56.89.12:80/page2/"
    # 交互数据必须要加密。支付宝返回status=100，appid=1001，向接口发POST请求，订单号、状态都有了，钱可能没付，订单状态改了，黑客可能模拟支付宝发请求。
    # 非对称性加密，公钥、私钥，在keys文件夹下面，随机字符串
    # 私钥不能丢，易被黑客窃取，能模拟请求，黑客提交100w订单，模拟支付成功，申请退款退给黑客
    merchant_private_key_path = "keys/app_private_2048.txt"
    alipay_public_key_path = "keys/alipay_public_2048.txt"
    # 生成一个AliPay的对象
    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,
        return_url=return_url,
        app_private_key_path=merchant_private_key_path,
        alipay_public_key_path=alipay_public_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥
        debug=True,  # 默认False,
    )
    return alipay

def page1(request):
    if request.method == "GET":

        return render(request, 'page1.html')
    else:
        money = float(request.POST.get('money'))
        # 生成一个对象
        alipay = ali()
        # 生成支付的url
        # 对象调用direct_pay
        query_params = alipay.direct_pay(
            subject="充气娃娃",  # 商品简单描述
            out_trade_no="x2" + str(time.time()),  # 商户订单号
            total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
        )
        # 支付宝网关，不带dev是实际地址，带dev是测试环境，向测试环境发get请求，带数据过去，生成支付宝支付的页面。
        pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)
        print(pay_url)
        # 朝这个地址发get请求，
        # 输金额，'去支付'，朝支付宝地址发请求，交易支付成功后支付宝给我发get，post俩请求，重定向到'交易付款成功，正在跳转至商户页面'
        return redirect(pay_url)

def page2(request):
    alipay = ali()
    # post请求
    if request.method == "POST":
        # 检测是否支付成功
        # 去请求体中获取所有返回的数据：状态/订单号
        from urllib.parse import parse_qs

        # 从body体拿数据，不知道是urlenco/json编码格式，转码成字符串。
        body_str = request.body.decode('utf-8')
        print(body_str)
        # 系统内置解析方法parse_qs，解析成字典格式，放在post_dict内，
        post_data = parse_qs(body_str)
        print('支付宝给我的数据:::---------',post_data)
        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]
        print('转完之后的字典',post_dict)

        # 传参字典+签名，status校验成功/失败，post_dict中的订单号可以取出来，确定订单状态
        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        print('POST验证', status)
        return HttpResponse('POST返回')

    # get请求
    else:
        # 数据转成字典
        params = request.GET.dict()
        # 拿出字典中的sign字段
        sign = params.pop('sign', None)
        # 验证的方法，通过sign把数据传过去后，校验成功/失败，不是直接状态码取出来校验
        # 调用verify方法，传参数据+sign，
        status = alipay.verify(params, sign)
        print('GET验证', status)
        return HttpResponse('支付成功')


import requests
import numpy as np
import pickle
import base64

def send_data(img):
    data = {}
    data['image'] = base64.b64encode(pickle.dumps(img)).decode('utf-8')
    data['essay'] = "test_0_topic"
    data['topic'] = "test_0_topic"
    data['Content'] = [50, "good"]
    data['Statement'] = [50, "good"]
    data['Organization'] = [50, "good"]
    data['Readability'] = [50, "good"]
    data['Grammar'] = [50, "good"]
    data['Overall'] = "good"
    res = requests.post('http://localhost:8088/api/img_upload', data=data)
    print(res)

if __name__ == "__main__":
    img = np.ones((100, 100, 3), dtype=np.uint8) * 255
    send_data(img)


from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
import logging
import functools
from travel_app import models, auth
import logging

home = Blueprint('home', __name__, url_prefix='/')

# Home page of website, before delivering app
@home.route('/',  methods=('GET', 'POST'))
def welcome():
    return render_template("welcome.html")

# app roote blueprint. All paths beyond /app require authentication as well.
iq = Blueprint('iq', __name__, url_prefix='/app')

@iq.route('/', methods=('GET','POST'))
@auth.login_required
def iqPage():
    if request.method == 'GET':

        return render_template('app/iqApp.html')

@iq.route('/createTrip', methods=('POST','GET'))
@auth.login_required
def create_trip():
    if request.method == 'POST':
        form = request.form
        name, start_date, end_date = form['TName'], form['TStart'], form['TEnd']
        try:
            trip = models.Trip()
            trip.name = name
            trip.start_date = start_date
            trip.end_date = end_date
            pairing = models.UserTripPair(trip=trip, user=g.user,admin = True)
            trip.userPairings.append(pairing)
            models.db.session.add(trip, pairing)
            models.db.session.commit()
        except Exception as e:
            logging.error("Exception in creating trip: {}".format(e))
            flash('something went wrong: {}'.format(e))
            return redirect(url_for('iq.iqPage'))
        flash('Created Trip')
        return redirect(url_for('iq.iqPage'))
    if request.method == 'GET':
        return render_template('app/createTrip.html')

@iq.before_app_request
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        # g.user = User.query.filter_by(user_id = user_id).first()
        user = models.User.query.filter_by(id=user_id).first()
        g.user = user


# -*- coding: utf-8 -*-
from flask import request, g, abort, current_app, session
from werkzeug.local import LocalProxy

known_locales = {
        'en': dict(title=u'English'),
        'be': dict(title=u'Беларуская'),
        'ru': dict(title=u'Русский')
}
all_locales = known_locales.keys()
default_locale = 'be'

def get_locale():
    url_lang = g.get('lang_code', None)
    if not url_lang is None:
        return url_lang
    if request.args.has_key('lang'):
        session['lang'] = request.args.get('lang')
    if session.has_key('lang'):
        return session.get('lang')
    return default_locale

current_locale = LocalProxy(get_locale)


import pygame #import the pygame module

screenWidth = 600 #create a variable that stores the window width
screenHeight = 400 #create a variable that stores the window height
rectWidth = 50 #create a variable that stores the rectangle's width
rectHeight = 40 #create a variable that stores the rectangle's height
pygame.init() #start pygame
#set the game window's height and width
screen = pygame.display.set_mode((screenWidth,screenHeight))
done = False #create a variable called "done" that stores the boolean value, False
is_blue = True#create a variable called "is_blue" that stores the boolean value, True
x = 30 #create a variable that stores the rectangle's x coordinate
y = 30 #create a variable that stores the rectangle's y coordinate

clock = pygame.time.Clock() #create a variable that stores the pygame clock
#so that we can control the frame rate of the game.

while not done: #if done is false, keep looping
        for event in pygame.event.get():
                if event.type == pygame.QUIT: #if the quit button is hit
                        done = True #make the game quit
                #if the event is the space bar pressed down
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue #make the color not blue

        pressed = pygame.key.get_pressed()
        #pressed is a dictionary of True and False corresponding to whether a
        #certain key was pressed
        #ex. if we press the Up arrow, pressed[pygame.K_UP] = True

        if pressed[pygame.K_UP]: #if we pressed the up key
                y -= 3
                #decrease the y position so that we can move the rectangle up
        if pressed[pygame.K_DOWN]:
                y += 3
        if pressed[pygame.K_LEFT]:
                x -= 3
        if pressed[pygame.K_RIGHT]:
                x += 3

        screen.fill((0, 0, 0)) #refresh the screen and get rid of the old frame.
        if is_blue: #if the variable is_blue is true
                color = (0, 128, 255) #change the color to whatever this is
        else: #if the variable is_blue is false, change the color to whatever THAT is
                color = (255, 100, 0)

        #draw a rectangle on the screen at position x,y with color color
        pygame.draw.rect(screen, color, pygame.Rect(x, y, rectWidth, rectHeight))
        pygame.display.flip() #display the screen
        clock.tick(60) #controls the frame rate of the game (how many times the screen changes per second)


import numpy as np
import cvxpy as cp
from cvxpylayers.torch import CvxpyLayer
import torch

# ---------------------------------------------------------------------------------------------------
# Hellinger distance: sum_t (sqrt(p_t) - sqrtq_t))^2 <= delta
# ---------------------------------------------------------------------------------------------------
class DecisionLayer:
    def __init__(self, distance="HL", n_obs=104):
        """this class creates decision layer.
        it can use hellinger distance or kl-divergance
        for defining ambiguity set.

        Args:
            name (str, optional): the ambiguity set diverganec metric.
                'HL' for 'Hellinger_distance' or 'KL' for 'kl_divergance'. Defaults to 'HL'.
        """
        names = {"KL": "kl_divergance", "HL": "Hellinger_distance"}
        self.Declayer = eval("self." + names[distance])(n_y=20, n_obs=n_obs)

    def Hellinger_distance(self, n_y=20, n_obs=104):
        """DRO layer using the Hellinger distance to define the probability ambiguity set.
        from Ben-Tal et al. (2013).
        Hellinger distance: sum_t (sqrt(p_t) - sqrtq_t))^2 <= delta

        Inputs
        n_y: number of assets
        n_obs: Number of scenarios in the dataset
        prisk: Portfolio risk function

        Variables
        z: Decision variable. (n_y x 1) vector of decision variables (e.g., portfolio weights)
        c_aux: Auxiliary Variable. Scalar. Allows us to p-linearize the derivation of the variance
        lambda_aux: Auxiliary Variable. Scalar. Allows for a tractable DR counterpart.
        xi_aux: Auxiliary Variable. Scalar. Allows for a tractable DR counterpart.
        beta_aux: Auxiliary Variable. (n_obs x 1) vector. Allows for a tractable DR counterpart.
        s_aux: Auxiliary Variable. (n_obs x 1) vector. Allows for a tractable SOC constraint.
        mu_aux: Auxiliary Variable. Scalar. Represents the portfolio conditional expected return.

        Parameters
        ep: (n_obs x n_y) matrix of residuals
        y_hat: (n_y x 1) vector of predicted outcomes (e.g., conditional expected
        returns)
        delta: Scalar. Maximum distance between p and q.
        gamma: Scalar. Trade-off between conditional expected return and model error.

        Constraints
        Total budget is equal to 100%, sum(z) == 1
        Long-only positions (no short sales), z >= 0 (specified during the cp.Variable() call)
        All other constraints allow for a tractable DR counterpart. See the Appendix in Ben-Tal et al.
        (2013).

        Objective
        Minimize xi_aux + (delta-1) * lambda_aux + (1/n_obs) * sum(beta_aux) - gamma * y_hat @ z
        """
        # Variables
        z = cp.Variable((n_y, 1), nonneg=True)
        c_aux = cp.Variable()
        lambda_aux = cp.Variable(nonneg=True)
        xi_aux = cp.Variable()
        beta_aux = cp.Variable(n_obs, nonneg=True)
        tau_aux = cp.Variable(n_obs, nonneg=True)
        mu_aux = cp.Variable()

        # Parameters
        ep = cp.Parameter((n_obs, n_y))
        y_hat = cp.Parameter(n_y)
        gamma = cp.Parameter(nonneg=True)
        delta = cp.Parameter(nonneg=True)

        # Constraints
        constraints = [cp.sum(z) == 1, mu_aux == y_hat @ z]
        for i in range(n_obs):
            constraints += [
                xi_aux + lambda_aux >= self.p_var(z, c_aux, ep[i]) + tau_aux[i]
            ]
            constraints += [beta_aux[i] >= cp.quad_over_lin(lambda_aux, tau_aux[i])]

        # Objective function
        objective = cp.Minimize(
            xi_aux
            + (delta - 1) * lambda_aux
            + (1 / n_obs) * cp.sum(beta_aux)
            - gamma * mu_aux
        )

        # Construct optimization problem and differentiable layer
        problem = cp.Problem(objective, constraints)

        return CvxpyLayer(problem, parameters=[ep, y_hat, gamma, delta], variables=[z])

    def kl_divergance(self, n_y=20, n_obs=104):
        # Variables
        z = cp.Variable((n_y, 1), nonneg=True)
        c_aux = cp.Variable()
        lambda_aux = cp.Variable(nonneg=True)
        xi_aux = cp.Variable()
        zz_aux = cp.Variable(n_obs)
        mu_aux = cp.Variable()

        # Parameters
        ep = cp.Parameter((n_obs, n_y))
        y_hat = cp.Parameter(n_y)
        gamma = cp.Parameter(nonneg=True)
        delta = cp.Parameter(nonneg=True)

        # Constraints
        constraints = [
            cp.sum(z) == 1,
            mu_aux == y_hat @ z,
        ]
        for i in range(n_obs):
            constraints += [
                self.f_lambd(lambda_aux, zz_aux[i])
                <= xi_aux - self.p_var(z, c_aux, ep[i])
            ]

        # Objective function
        objective = cp.Minimize(
            xi_aux + delta * lambda_aux + (1 / n_obs) * cp.sum(zz_aux) - gamma * mu_aux
        )

        # Construct optimization problem and differentiable layer
        problem = cp.Problem(objective, constraints)
        return CvxpyLayer(problem, parameters=[ep, y_hat, gamma, delta], variables=[z])

    ####################################################################################################
    # Define risk functions
    ####################################################################################################

    def p_var(self, z, c, x):
        """Variance
        Inputs
        z: (n x 1) vector of portfolio weights (decision variable)
        c: Scalar. Centering parameter that serves as a proxy to the expected value (auxiliary variable)
        x: (n x 1) vector of realized returns (data)

        Output: Single squared deviation.
        Note: This function is only one component of the portfolio variance, and must be aggregated
        over all scenarios 'x' to recover the complete variance
        """
        return cp.square(x @ z - c)

    ####################################################################################################
    # Define convex conjugate of adjoint of \phi divergance
    ####################################################################################################

    def f_lambd(self, lambda_aux, zz_aux_i):
        """this function calculates convex conjugate of adjoint of \pi divergance
        for kl-divergance distance.
        """
        return cp.rel_entr(lambda_aux, lambda_aux + zz_aux_i)

if __name__ == "__main__":
    DC = DecisionLayer("kl_divergance").Declayer


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import The0001,The0006
def Main(string):
    exc1 = The0001.Main(string)
    exc2 = The0001.Main(string)
    score = []
    id = []
    for i in range(1,len(exc1)):
        tmp=exc2[i][1]
        if tmp!=exc2[i-1][1]:
            score.append(exc1[i-1][0])
            if exc1[i-1][1] != 0:
                id.append(str(exc1[i-1][1])+exc2[i-1][1])
            else:
                id.append(exc2[i-1][1])
        elif i == len(exc1)-1:
            score.append(exc1[i][0])
            if exc1[i][1] != 0:
                id.append(str(exc1[i][1])+exc2[i][1])
            else:
                id.append(exc2[i][1])

    dataLenth = len(id)
    angles = np.linspace(0,2*np.pi,dataLenth,endpoint = False)
    data = np.concatenate((score,[score[0]]))
    angles = np.concatenate((angles,[angles[0]]))

    fig = plt.figure()
    ax = fig.add_subplot(111,polar = True)
    ax.plot(angles,data,'ro-',linewidth=2)
    ax.set_thetagrids(angles * 180/np.pi, id, fontproperties="SimHei")
    ax.set_title("hai", va='bottom', fontproperties="SimHei")
    ax.grid(True)
    plt.show()

if __name__ == '__main__':
    string = "gaoyan"
    Main(string)


import sys
from collections import deque
t = int(sys.stdin.readline())
prime = [list(map(int, sys.stdin.readline().split())) for _ in range(t)]
arr = [True] * 10001
for i in range(2, 101):
    if arr[i]:
        j = i * 2
        while j < 10001:
            arr[j] = False
            j += i
def bfs(a, b):
    q = deque()
    q.append((a, 0))
    visited = [0 for _ in range(10000)]
    visited[a] = 1
    while q:
        num, cnt = q.popleft()
        if num == b:
            return cnt
        if num < 1000:
            continue
        for i in [1, 10, 100, 1000]:
            n = num - num % (i * 10) // i * i
            for j in range(10):
                if visited[n] == 0 and arr[n]:
                    visited[n] = 1
                    q.append((n, cnt + 1))
                n += i
    return "impossible"
for i, j in prime:
    print(bfs(i, j))


import sqlite3
import os
import uuid

import numpy as np
import pandas as pd
import talib
from talib import abstract
from matplotlib import pyplot as plt
from matplotlib.pylab import date2num
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

BASE_PATH = os.path.dirname(os.path.abspath(__file__))
DATA_RANGE = 390
plt.rcParams["figure.figsize"] = (8, 5)
DB_NAME = 'db.sqlite3'
data_base = sqlite3.connect(f'{BASE_PATH}/{DB_NAME}')
stock_nums = pd.read_sql(
    'select DISTINCT 證券代號 from daily_price ORDER BY 證券代號', data_base)['證券代號'].values
DEFAULT_STOCK_LAST_DATE = pd.read_sql(
    'select DISTINCT 日期 from daily_price ORDER BY 日期 DESC limit 0, 1', data_base)['日期'].values[0].split(' ')[0]

# close data base connect
data_base.close()

plt.rcParams["figure.figsize"] = (8, 5)

def get_OBV(priceData):
    OBV = pd.DataFrame(
        {
            'close': priceData['close'].reset_index(drop=True),
            'volume': priceData['volume'].reset_index(drop=True)
        }
    )
    OBV['OBV'] = talib.OBV(OBV['close'], OBV['volume'])
    return OBV

def get_PSY(priceData, period=12):
    PSY = pd.DataFrame(
        {
            'date': priceData['date'].reset_index(drop=True),
            'close': priceData['close'].reset_index(drop=True)
        }
    )
    difference = PSY['close'][1:].reset_index(
        drop=True) - PSY['close'][:-1].reset_index(drop=True)
    difference = np.append(0, difference)
    difference_dir = np.where(difference > 0, 1, 0)
    psy_result = np.zeros((len(PSY),))
    psy_result[:period] *= np.nan
    for i in range(period, len(PSY)):
        psy_result[i] = int(
            ((difference_dir[i-period+1:i+1].sum())/period)*100)
    PSY['PSY'] = psy_result
    return PSY['PSY']

def get_DMI(priceData, period=14):
    DMI = pd.DataFrame(
        {
            'date': priceData['date'][:0:-1],
            'close': priceData['close'][:0:-1],
            'high': priceData['high'][:0:-1],
            'low': priceData['low'][:0:-1]
        }
    )
    # 重設索引 (index)
    DMI = DMI.reset_index(drop=True)
    plusDM = []
    negativeDM = []
    TR = []
    for i in range(len(DMI)-1):
        # 正趨向變動值 +DM = MAX｛Ht - Ht-1，0｝（只取正值，若為負值則設為 0）
        plusDM.append(round(max(DMI['high'][i]-DMI['high'][i+1], 0), 3))
        # 負趨向變動值 -DM = MAX｛Lt-1 - Lt，0｝（只取正值，若為負值則設為 0）
        negativeDM.append(round(max(DMI['low'][i+1]-DMI['low'][i], 0), 3))
        # TR = max{∣ Ht - Lt ∣, ∣ Ht - Ct-1 ∣, ∣ Ct-1 - Lt ∣}
        TR.append(max(abs(DMI['high'][i]-DMI['low'][i]),
                      abs(DMI['high'][i]-DMI['close'][i+1]),
                      abs(DMI['close'][i+1]-DMI['low'][i])))
        # 同一天的 +DM 與 -DM 兩數值相比，較小者設定為 0，兩數若相同則兩數皆設定為 0。
        if plusDM[i] - negativeDM[i] > 0:
            negativeDM[i] = 0.0
        elif plusDM[i] - negativeDM[i] < 0:
            plusDM[i] = 0.0
        else:
            plusDM[i] = 0.0
            negativeDM[i] = 0.0
    DMI["+DM"] = pd.Series(plusDM)
    DMI['-DM'] = pd.Series(negativeDM)
    DMI['TR'] = pd.Series(TR)

    # 計算方向指標
    # +ADMt = +ADMt-1 +（+DMt - +ADMt-1）/ n
    # -ADMt = -ADMt-1 +（-DMt - -ADMt-1）/ n
    # ATRt = ATRt-1 +（TRt - ATRt-1）/ n
    # 一般 n 採 14 日為指標的觀察週期
    # 首日 +ADMt = n 日的 +DMt 平均值
    # 首日 -ADMt = n 日的 -DMt 平均值
    # 首日 ATRt = n 日的 TRt 平均值
    # 正方向指標 +DIt = +ADMt / ATRt * 100
    # 負方向指標 -DIt = -ADMt / ATRt * 100
    DMI['+ADM'] = np.zeros((len(DMI),))
    DMI['-ADM'] = np.zeros((len(DMI),))
    DMI['ATR'] = np.zeros((len(DMI),))
    DMI['+DI'] = np.zeros((len(DMI),))
    DMI['-DI'] = np.zeros((len(DMI),))
    # DMI['DX'] = np.zeros((len(DMI),))
    # DMI['ADX'] = np.zeros((len(DMI),))
    DMI.loc[len(DMI)-1, '+ADM'] = round(sum(DMI['+DM'][:period])/period, 3)
    DMI.loc[len(DMI)-1, '-ADM'] = round(sum(DMI['-DM'][:period])/period, 3)
    DMI.loc[len(DMI)-1, 'ATR'] = round(sum(DMI['TR'][:period])/period, 3)
    for i in range(len(DMI)-2, -1, -1):
        DMI.loc[i, '+ADM'] = DMI['+ADM'][i+1] + \
            (DMI['+DM'][i] - DMI['+ADM'][i+1]) / period
        DMI.loc[i, '-ADM'] = DMI['-ADM'][i+1] + \
            (DMI['-DM'][i] - DMI['-ADM'][i+1]) / period
        DMI.loc[i, 'ATR'] = DMI['ATR'][i+1] + \
            (DMI['TR'][i] - DMI['ATR'][i+1]) / period
        DMI.loc[i, '+DI'] = round(DMI['+ADM'][i] / DMI['ATR'][i] * 100, 0)
        DMI.loc[i, '-DI'] = round(DMI['-ADM'][i] / DMI['ATR'][i] * 100, 0)
    # for i in range(len(DMI)):
        # DMI.loc[i, 'DX'] = round(abs(DMI['+DI'][i] - DMI['-DI'][i]) / (DMI['+DI'][i] + DMI['-DI'][i]) * 100, 0)
    DMI = DMI.loc[::-1]
    DMI = DMI.reset_index(drop=True)
    # DMI['ADX'] = round(talib.SMA(DMI['DX'], period), 2)
    return DMI

def buy(day, money, count, plus, stock):
    plus = plus + round(stock['close'][day]*1000)
    money = money - round(stock['close'][day]*1000)
    count = count + 1

    return money, count, plus

def sell(day, money, count, stock):
    money = money + round(stock['close'][day] * 1000) * count
    count = 0
    return money, count, 0

def check_img_file_amount_and_delete():
    list_dirs = os.listdir(f'{BASE_PATH}/static/stock/img/line_graph/')
    if len(list_dirs) + 1 > 10:
        for i in list_dirs:
            os.remove(f'{BASE_PATH}/static/stock/img/line_graph/{i}')

class TechnologyPointer:
    def __init__(self, date=DEFAULT_STOCK_LAST_DATE, stock_number='2302'):
        data_base = sqlite3.connect(f'{BASE_PATH}/{DB_NAME}')
        self.stock_number = stock_number
        self.df = pd.read_sql(f'select 日期, 證券代號, 開盤價, 收盤價, 最高價, 最低價, 成交股數 from daily_price where 證券代號="{stock_number}"',
                              data_base, parse_dates=['日期'])
        self.df.rename(columns={'收盤價': 'close', '開盤價': 'open', '最高價': 'high', '日期': 'date',
                                '最低價': 'low', '成交股數': 'volume'}, inplace=True)
        self.df.sort_values(by='date')
        data_base.close()
        self.stock = self.get_stock(date)
        self.PSY_detail = []
        self.DMI_detail = []
        self.OBV_detail = []
        self.RSI_detail = []
        self.AR_detail = []
        self.BR_detail = []
        self.KD_detail = []
        self.MA_detail = []
        # {
        #    'date': '2019-08-08',
        #    'close' : '5'
        #    'type' : 買\賣
        # }

    # 取 x 天的股市資料
    def get_stock(self, date=DEFAULT_STOCK_LAST_DATE):
        user_select_date_index = int(
            self.df.loc[self.df['date'] == date].index[0])
        stock = self.df[user_select_date_index -
                        DATA_RANGE:user_select_date_index+1].reset_index(drop=True)

        stock["AR"] = talib.SUM(self.df.high - self.df.open, timeperiod=26) / \
            talib.SUM(self.df.open - self.df.low, timeperiod=26)*100
        stock["BR"] = talib.SUM(self.df.high - self.df.close.shift(1), timeperiod=26) / \
            talib.SUM(self.df.close.shift(1) - self.df.low, timeperiod=26)*100
        stock['PSY'] = get_PSY(stock)
        stock['K'], stock['D'] = talib.STOCH(
            stock['high'], stock['low'], stock['close'])
        # 短周期6天 長周期14天
        stock['RSI6'] = talib.RSI(stock['close'], timeperiod=6)
        stock['RSI14'] = talib.RSI(stock['close'], timeperiod=14)
        stock['SMA'] = talib.SMA(stock['close'], 6)
        stock["AR"] = talib.SUM(self.df.high - self.df.open, timeperiod=26) / \
            talib.SUM(self.df.open - self.df.low, timeperiod=26)*100
        stock["BR"] = talib.SUM(self.df.high - self.df.close.shift(1), timeperiod=26) / \
            talib.SUM(self.df.close.shift(1) - self.df.low, timeperiod=26)*100

        return stock[30:].reset_index(drop=True)

    def get_PSY_profit(self, money=50000):
        cash = TOTAL_ASSETS = money
        buy_record = []
        buy_count = 0
        PSY = self.stock
        for i in range(12, len(PSY)):
            if PSY['PSY'][i] > 75:
                if buy_count >= 1:
                    if PSY['close'][i] > sum(buy_record) / len(buy_record):
                        buy_count = 0
                        cash += PSY['close'][i] * 1000 * len(buy_record)
                        buy_record.clear()
                        self.PSY_detail.append(
                            {'date': str(PSY['date'][i]).split(" ")[0], 'close': PSY['close'][i], 'type': '賣出'})
                    else:
                        pass
                        # print(f'{str(PSY["date"][i]).split(" ")[0]} 已達 PSY 賣出標準，但不適合現在賣出')
            elif PSY['PSY'][i] < 25:
                if cash >= PSY['close'][i] * 1000:
                    cash -= PSY['close'][i] * 1000
                    buy_record.append(PSY['close'][i])
                    buy_count += 1
                    self.PSY_detail.append(
                        {'date': str(PSY['date'][i]).split(" ")[0], 'close': PSY['close'][i], 'type': '買入'})
                elif cash < PSY['close'][i] * 1000:
                    # print('沒錢辣')
                    pass

        cash += float(PSY['close'][-1:]) * 1000 * len(buy_record)
        return (cash-TOTAL_ASSETS) / TOTAL_ASSETS

    def get_DMI_profit(self, money=50000):
        cash = TOTAL_ASSETS = 50000
        buy_record = []
        buy_count = 0
        DMI = get_DMI(self.stock)
        for i in range(1, len(DMI)-1, 1):
            if DMI['+DI'][i-1] < DMI['-DI'][i-1]:
                if DMI['+DI'][i] >= DMI['-DI'][i]:
                    if DMI['+DI'][i+1] > DMI['-DI'][i+1]:
                        if cash >= DMI['close'][i] * 1000:
                            cash -= DMI['close'][i] * 1000
                            buy_record.append(DMI['close'][i])
                            buy_count += 1
                            self.DMI_detail.append(
                                {'date': str(DMI['date'][i]).split(" ")[0], 'close': DMI['close'][i], 'type': '買入'})
                        elif cash < DMI['close'][i] * 1000:
                            pass
                            # print('沒錢辣')
            elif DMI['+DI'][i-1] > DMI['-DI'][i-1]:
                if DMI['+DI'][i] <= DMI['-DI'][i]:
                    if DMI['+DI'][i+1] < DMI['-DI'][i+1]:
                        if buy_count > 1:
                            if DMI['close'][i] > sum(buy_record) / len(buy_record):
                                buy_count = 0
                                cash += DMI['close'][i] * \
                                    1000 * len(buy_record)
                                buy_record.clear()
                                self.DMI_detail.append(
                                    {'date': str(DMI['date'][i]).split(" ")[0], 'close': DMI['close'][i], 'type': '賣出'})
                            else:
                                pass
                                # print(f'{str(DMI["date"][i]).split(" ")[0]} 已達 DMI 賣出標準，但不適合現在賣出')
        cash += float(DMI['close'][-1:]) * 1000 * len(buy_record)
        return (cash-TOTAL_ASSETS) / TOTAL_ASSETS

    def get_OBV_profit(self, money=50000):
        count = 0
        plus = 0
        cash = money
        OBV = get_OBV(self.stock)
        for i in range(1, len(OBV["OBV"])):
            if (OBV["OBV"][i] < 0) and (OBV["OBV"][i - 1] > 0 and cash >= self.stock['close'][i] * 1000):
                cash, count, plus = buy(
                    i, cash, count, plus, self.stock)
                self.OBV_detail.append(
                    {'date': str(self.stock['date'][i]).split(" ")[0], 'close': self.stock['close'][i], 'type': '買入'})
            elif (OBV["OBV"][i] > 0) and (OBV["OBV"][i - 1] < 0):
                if(count > 0 and round(self.stock['close'][i] * 1000) > plus/count):
                    cash, count, plus = sell(i, cash, count, self.stock)
                    #print(tpname," 指標",str(stock.index[day]).split(" ")[0], round(stock[tpname][day], 2), "進行賣出","張數", count ,"金額",round(stock['close'][day]*1000) * count, "剩餘金額: ", money)
                    self.OBV_detail.append(
                        {'date': str(self.stock['date'][i]).split(" ")[0], 'close': self.stock['close'][i], 'type': '賣出'})

        return ((cash + self.stock["close"][len(self.stock)-1] * count * 1000) - money) / money

    def get_AR_profit(self, money=50000):
        count = 0
        plus = 0
        cash = money
        for i in range(1, len(self.stock["AR"])):
            # print(self.stock["AR"][i])
            if (self.stock["AR"][i] < 120 and cash >= self.stock['close'][i] * 1000):
                cash, count, plus = buy(i, cash, count, plus, self.stock)
                self.AR_detail.append(
                    {'date': str(self.stock['date'][i]).split(" ")[0], 'close': self.stock['close'][i], 'type': '買入'})
            elif (self.stock["AR"][i] > 150):
                if(count > 0 and round(self.stock['close'][i] * 1000) > plus/count):
                    cash, count, plus = sell(i, cash, count, self.stock)
                    self.AR_detail.append(
                        {'date': str(self.stock['date'][i]).split(" ")[0], 'close': self.stock['close'][i], 'type': '賣出'})

        return ((cash + self.stock["close"][len(self.stock)-1] * count * 1000) - money) / money

    def get_BR_profit(self, money=50000):
        count = 0
        plus = 0
        cash = money
        for i in range(1, len(self.stock["BR"])):
            if (self.stock["BR"][i] < 50 and cash >= self.stock['close'][i] * 1000):
                cash, count, plus = buy(i, cash, count, plus, self.stock)
                self.BR_detail.append(
                    {'date': str(self.stock['date'][i]).split(" ")[0], 'close': self.stock['close'][i], 'type': '買入'})
            elif (self.stock["BR"][i] > 400):
                if(count > 0 and round(self.stock['close'][i] * 1000) > plus/count):
                    cash, count, plus = sell(i, cash, count, self.stock)
                    self.BR_detail.append(
                        {'date': str(self.stock['date'][i]).split(" ")[0], 'close': self.stock['close'][i], 'type': '賣出'})

        return ((cash + self.stock["close"][len(self.stock)-1] * count * 1000) - money) / money

    def get_KD_profit(self, money=50000):

        funds = money
        # 股票張數
        thousand_shares = 0
        # 買入點的價錢
        closing_price_buy = []

        # KD鈍化變數
        KAbove80 = 0
        KUnder20 = 0
        KAbove80ThreeDays = False
        KUnder20ThreeDays = False

        # 當天KD狀態
        KBiggerThanDToday = False

        # 前一天KD狀態
        KBiggerThanDOneDayBefore = False
        # if 第一天的 K > D:
        #     KBiggerThanDOneDayBefore = True

        for date, close, K, D in zip(self.stock['date'], self.stock['close'], self.stock['K'], self.stock['D']):

            # 判斷KD鈍化
            if K > 80:
                KAbove80 += 1
            elif K < 20:
                KUnder20 += 1
            else:
                KAbove80 = 0
                KUnder20 = 0

            if KAbove80 >= 3:
                KAbove80ThreeDays = True
            else:
                KAbove80ThreeDays = False

            if KUnder20 >= 3:
                KUnder20ThreeDays = True
            else:
                KUnder20ThreeDays = False

            if K > D:
                KBiggerThanDToday = True
            else:
                KBiggerThanDToday = False

            # 1張股票的價錢
            thousand_shares_price = close * 1000

            # 黃金交叉，買入
            if KBiggerThanDToday and not(KBiggerThanDOneDayBefore) and not(KAbove80ThreeDays) and not(KUnder20ThreeDays):
                if funds >= thousand_shares_price:
                    funds = funds - thousand_shares_price
                    thousand_shares += 1
                    closing_price_buy.append(close)
                    self.KD_detail.append(
                        {'date': str(date).split(" ")[0], 'close': close, 'type': '買入'})
                    # print(date, 'close =', close, 'K =', round(K,2), 'D =', round(D,2), 'KD黃金交叉 買入')
            elif KUnder20ThreeDays:
                if funds >= thousand_shares_price:
                    funds = funds - thousand_shares_price
                    thousand_shares += 1
                    closing_price_buy.append(close)
                    self.KD_detail.append(
                        {'date': str(date).split(" ")[0], 'close': close, 'type': '買入'})
                    # print(date, 'close =', close, 'K =', round(K,2), 'D =', round(D,2), 'K<20 3天了 買入')
            # 死亡交叉，賣出
            elif not(KBiggerThanDToday) and KBiggerThanDOneDayBefore and not(KAbove80ThreeDays) and not(KUnder20ThreeDays) and len(closing_price_buy) > 0:
                if close > sum(closing_price_buy) / len(closing_price_buy):
                    funds = funds + thousand_shares * thousand_shares_price
                    thousand_shares = 0
                    closing_price_buy = []
                    self.KD_detail.append(
                        {'date': str(date).split(" ")[0], 'close': close, 'type': '賣出'})
                    # print(date, 'close =', close, 'K =', round(K,2), 'D =', round(D,2), 'KD死亡交叉 賣出')
            elif KAbove80ThreeDays and len(closing_price_buy) > 0:
                if close > sum(closing_price_buy) / len(closing_price_buy):
                    funds = funds + thousand_shares * thousand_shares_price
                    thousand_shares = 0
                    closing_price_buy = []
                    self.KD_detail.append(
                        {'date': str(date).split(" ")[0], 'close': close, 'type': '賣出'})
                    # print(date, 'close =', close, 'K =', round(K,2), 'D =', round(D,2), 'K>80 3天了 賣出')
            # #其他資訊
            # else:
            #     print(date, ',close =', close, ',K =', round(K,2), ',D =', round(D,2), ',KD info',end = ' ')
            #     print(',K > 80幾天',KAbove80,',K > 80 3天', KAbove80ThreeDays,',K<20幾天',KUnder20,',K<20 3天',KUnder20ThreeDays,',K>D',KBiggerThanDToday,',昨天K>D',KBiggerThanDOneDayBefore)

            KBiggerThanDOneDayBefore = KBiggerThanDToday
        return (funds + thousand_shares * thousand_shares_price - money)/money

    def get_RSI_profit(self, money=50000):

        funds = money
        # 股票張數
        thousand_shares = 0
        # 買入點的價錢
        closing_price_buy = []
        # 交叉變數
        RSIShort_under_RSILong_today = False
        RSIShort_under_RSILong_yesterday = False

        for date, closing_price, RSIShort, RSILong in zip(self.stock['date'], self.stock['close'], self.stock['RSI6'], self.stock['RSI14']):

            if RSIShort < RSILong:
                RSIShort_under_RSILong_today = True
            else:
                RSIShort_under_RSILong_today = False

            # 1張股票的價錢
            thousand_shares_price = closing_price * 1000

            # RSI<20，買入信號
            if RSIShort < 20 or RSILong < 20:
                if funds >= thousand_shares_price:
                    funds = funds - thousand_shares_price
                    thousand_shares += 1
                    closing_price_buy.append(closing_price)
                    self.RSI_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '買入'})
                    # print(date, ',close =', closing_price, ',RSI6 =', round(RSIShort,2), ',RSI14 =', round(RSILong,2), ',RSI6 OR RSI14 < 20 買入')
            # RSI黃金交叉，買入信號
            elif not(RSIShort_under_RSILong_today) and RSIShort_under_RSILong_yesterday:
                if funds >= thousand_shares_price:
                    funds = funds - thousand_shares_price
                    thousand_shares += 1
                    closing_price_buy.append(closing_price)
                    self.RSI_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '買入'})
                    # print(date, ',close =', closing_price, ',RSI6 =', round(RSIShort,2), ',RSI14 =', round(RSILong,2), ',RSI黃金交叉 買入')
            # RSI>80，賣出信號
            elif (RSIShort > 80 or RSILong > 80) and len(closing_price_buy) > 0:
                if closing_price > sum(closing_price_buy) / len(closing_price_buy):
                    funds = funds + thousand_shares * thousand_shares_price
                    thousand_shares = 0
                    closing_price_buy = []
                    self.RSI_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '賣出'})
                    # print(date, ',close =', closing_price, ',RSI6 =', round(RSIShort,2), ',RSI14 =', round(RSILong,2), ',RSI6 OR RSI14 > 80 賣出')
            # RSI死亡交叉，賣出信號
            elif RSIShort_under_RSILong_today and not(RSIShort_under_RSILong_yesterday) and len(closing_price_buy) > 0:
                if closing_price > sum(closing_price_buy) / len(closing_price_buy):
                    funds = funds + thousand_shares * thousand_shares_price
                    thousand_shares = 0
                    closing_price_buy = []
                    self.RSI_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '賣出'})
                    # print(date, ',close =', closing_price, ',RSI6 =', round(RSIShort,2), ',RSI14 =', round(RSILong,2), ',RSI死亡交叉 賣出')

            RSIShort_under_RSILong_yesterday = RSIShort_under_RSILong_today
        return (funds + thousand_shares * thousand_shares_price - money)/money

    def get_MA_profit(self, money=50000):

        funds = money
        # 股票張數
        thousand_shares = 0
        # 買入點的價錢
        closing_price_buy = []

        closing_price_above_MA_yesterday = False
        closing_price_yesterday = 0
        sma_yesterday = 0
        closing_price_slope_yesterday = 0

        for date, closing_price, sma in zip(self.stock['date'], self.stock['close'], self.stock['SMA']):

            # 乖離率
            BIAS = (closing_price - sma) / sma

            # 斜率(趨勢用)
            closing_price_slope = (closing_price - closing_price_yesterday) / 1
            sma_slope = (sma - sma_yesterday) / 1
            # print(sma_slope)
            # 今天收盤價在移動平均線上面
            if closing_price > sma:
                closing_price_above_MA_today = True
            else:
                closing_price_above_MA_today = False

            # 1張股票的價錢
            thousand_shares_price = closing_price * 1000

            # A點:收盤價突破移動平均線(所以要看前一天收盤價是否在MA以下)，買入訊號
            if not(closing_price_above_MA_yesterday) and closing_price_above_MA_today:
                if funds >= thousand_shares_price:
                    funds = funds - thousand_shares_price
                    thousand_shares += 1
                    closing_price_buy.append(closing_price)
                    self.MA_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '買入'})
                    # print(date, ',close =', closing_price, ',MA =', round(sma,2), ',A點買入')
            # #B點:乖離不大，趨勢發展，預期乖離變大，為買入訊號。(沒跌破均線)
            # elif BIAS < 0.3 and closing_price_above_MA_today and closing_price_slope > 0 :
            #     if funds >= thousand_shares_price :
            #         funds = funds - thousand_shares_price
            #         thousand_shares += 1
            #         closing_price_buy.append(closing_price)
            #         print(date, ',close =', closing_price, ',MA =', round(sma,2), ',B點買入')
            # C點:MA持續上升，股價急跌，跌破均線後的反彈點，且均線仍在上升，此為急跌後反彈的買進訊號
            elif sma_slope > 0 and closing_price_slope_yesterday < 0 and not(closing_price_above_MA_today) and closing_price_slope > 0:
                if funds >= thousand_shares_price:
                    funds = funds - thousand_shares_price
                    thousand_shares += 1
                    closing_price_buy.append(closing_price)
                    self.MA_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '買入'})
                    # print(date, ',close =', closing_price, ',MA =', round(sma,2), ',C點買入')
            # D點:價格自高點跌破均線，且跌深，價格偏離均線很多(假設值)，可能修正，為買進訊號
            elif sma - closing_price < 3 and closing_price_slope_yesterday < 0 and closing_price_slope > 0:
                if funds >= thousand_shares_price:
                    funds = funds - thousand_shares_price
                    thousand_shares += 1
                    closing_price_buy.append(closing_price)
                    self.MA_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '買入'})
                    # print(date, ',close =', closing_price, ',MA =', round(sma,2), ',D點買入')
            # E點:處上漲階段，價格短期漲幅過大(假設值)，導致與平均線偏離太多(假設值)，預期短期會有獲利賣壓，價格會有修正，為賣出訊號
            elif closing_price_slope > 0.5 and closing_price - sma > 3 and len(closing_price_buy) > 0:
                if closing_price > sum(closing_price_buy) / len(closing_price_buy):
                    funds = funds + thousand_shares * thousand_shares_price
                    thousand_shares = 0
                    closing_price_buy = []
                    self.MA_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '賣出'})
                    # print(date, ',close =', closing_price, ',MA =', round(sma,2), ',E點賣出')
            # F點:趨勢往下跑且股價從上跌破MA，趨勢反轉、死亡交叉，為賣出訊號
            elif closing_price_above_MA_yesterday and not(closing_price_above_MA_today) and len(closing_price_buy) > 0:
                if closing_price > sum(closing_price_buy) / len(closing_price_buy):
                    funds = funds + thousand_shares * thousand_shares_price
                    thousand_shares = 0
                    closing_price_buy = []
                    self.MA_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '賣出'})
                    # print(date, ',close =', closing_price, ',MA =', round(sma,2), ',F點賣出')
            # #G點:乖離不大(假設值)，趨勢加速發展(可能要設閥值)，預期乖離擴大，價格下跌速度快，且股價沒有突破MA，為賣出訊號
            # elif BIAS < 0.3 and closing_price_slope > 0 and not(closing_price_above_MA_today and len(closing_price_buy) > 0):
                # if closing_price > sum(closing_price_buy) / len(closing_price_buy):
                #     funds = funds + thousand_shares * thousand_shares_price
                #     thousand_shares = 0
                #     closing_price_buy = []
                #     print(date, ',close =', closing_price, ',MA =', round(sma,2), ',G點賣出')
            # H點:股價突破MA後迅速拉回，為假突破訊號，表示趨勢持續，此時MA仍然向下，為賣出訊號
            elif closing_price_above_MA_yesterday and not(closing_price_above_MA_today) and sma_slope < 0 and len(closing_price_buy) > 0:
                if closing_price > sum(closing_price_buy) / len(closing_price_buy):
                    funds = funds + thousand_shares * thousand_shares_price
                    thousand_shares = 0
                    closing_price_buy = []
                    self.MA_detail.append(
                        {'date': str(date).split(" ")[0], 'close': closing_price, 'type': '賣出'})
                    # print(date, ',close =', closing_price, ',MA =', round(sma,2), ',H點賣出')

            # 紀錄前一天的狀態
            closing_price_above_MA_yesterday = closing_price_above_MA_today
            sma_yesterday = sma
            closing_price_slope_yesterday = (
                closing_price - closing_price_yesterday) / 1
        return (funds + thousand_shares * thousand_shares_price - money)/money

    def get_all_detail(self, money=50000):
        self.get_PSY_profit(money)
        self.get_DMI_profit(money)
        self.get_OBV_profit(money)
        self.get_AR_profit(money)
        self.get_BR_profit(money)
        self.get_KD_profit(money)
        self.get_RSI_profit(money)
        self.get_MA_profit(money)

        return {
            'details': {
                'PSY': self.PSY_detail,
                'DMI': self.DMI_detail,
                'OBV': self.OBV_detail,
                'RSI': self.RSI_detail,
                'AR': self.AR_detail,
                'BR': self.BR_detail,
                'KD': self.KD_detail,
                'MA': self.MA_detail
            }
        }

    def get_RSI_image(self) -> str:
        df = self.get_stock()
        plt.figure()
        plt.plot(df['date'], df['RSI6'])
        plt.plot(df['date'], df['RSI14'])
        plt.plot(df['date'], df['close'], color='black')
        plt.title("RSI")
        plt.legend(["RSI6", "RSI14", "Close"], loc='best', shadow=True)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_PSY_image(self) -> str:
        df = self.get_stock()
        plt.figure()
        plt.plot(df['date'], df['PSY'])
        plt.plot(df['date'], df['close'], color='black')
        plt.title("PSY")
        plt.legend(["PSY", "Close"], loc='best', shadow=True)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_MA_image(self) -> str:
        df = self.get_stock()
        plt.figure()
        plt.plot(df['date'], df['SMA'])
        plt.plot(df['date'], df['close'], color='black')
        plt.title("SMA")
        plt.legend(["SMA", "Close"], loc='best', shadow=True)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_AR_image(self) -> str:
        df = self.get_stock()
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(df['date'], df['AR'], label="AR")
        plt.title("AR")
        ax.legend(loc=0)
        ax2 = ax.twinx()
        ax2.plot(df['date'], df['close'], color='black', label="close")
        ax2.legend(loc=2)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_BR_image(self) -> str:
        df = self.get_stock()
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(df['date'], df['BR'], label="BR")
        plt.title("BR")
        ax.legend(loc=0)
        ax2 = ax.twinx()
        ax2.plot(df['date'], df['close'], color='black', label="close")
        ax2.legend(loc=2)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_KD_image(self) -> str:
        df = self.get_stock()
        plt.figure()
        plt.plot(df['date'], df['K'])
        plt.plot(df['date'], df['D'])
        plt.plot(df['date'], df['close'], color='black')
        plt.title("KD")
        plt.legend(["K", "D", "Close"], loc='best', shadow=True)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_OBV_image(self) -> str:
        df = self.get_stock()
        temp = get_OBV(self.stock)

        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(df['date'], temp['OBV'], label="OBV")
        ax.set_ylim([0, 80000000])
        plt.title("OBV")
        ax.legend(loc=2)
        ax2 = ax.twinx()
        ax2.plot(df['date'], df['close'], color='black', label="close")
        ax2.legend(loc=0)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_DMI_image(self) -> str:
        df = self.get_stock()
        temp = get_DMI(self.stock)
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(df['date'][1:], temp['+DM'], label="+DM")
        ax.plot(df['date'][1:], temp['-DM'], label="-DM")
        plt.title("DMI")
        ax.legend(loc=2)
        ax2 = ax.twinx()
        ax2.plot(df['date'], df['close'], color='black', label="close")
        ax2.legend(loc=0)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'

    def get_CLOSE_image(self) -> str:
        df = self.get_stock()
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(df['date'], df['close'], label="close", color='black')
        plt.title("CLOSE")
        ax.legend(loc=2)
        plt.rcParams["figure.figsize"] = (15, 5)
        img_name = str(uuid.uuid1())
        check_img_file_amount_and_delete()
        plt.savefig(f'{BASE_PATH}/static/stock/img/line_graph/{img_name}.png')
        return f'/static/stock/img/line_graph/{img_name}.png'


import yaml

def replace_placeholders(section, data: dict):
    section = section.replace("\n", " \\\\\n")  # prepare linebreaks for latex
    for key, value in data.items():
        section = section.replace(f"[{key}]", value)
    return section

def prepare_template(template_file, data: dict):
    with open(template_file, "r", encoding="utf-8") as file:
        # Load the YAML data
        template = yaml.safe_load(file)

    params = template.pop("params")
    for param in params:

        if param["key"] not in data.keys():

            raise KeyError(str(param) + " missing")

    with open("letter.tex", encoding="utf-8") as f:
        letter = f.read()

    template.pop("metadata")
    for key, value in template.items():
        modified_value = replace_placeholders(value, data)
        letter = letter.replace(":" + key, modified_value)

    return letter


import threading
import time
import psutil

from pynput import keyboard

from database import create_table_if_not_exists, insert_data_into_table
from app_stats import AppStats
from logger import (
    reset_counters,  # Add this line
    on_press as logger_on_press,
    on_release as logger_on_release, get_logger_data,
)

# Initialize AppStats
app_stats = AppStats()

def on_press(key):
    global keystroke_counter, erase_keys_counter, press_press_intervals, press_release_intervals, word_lengths, word_counter, last_press_time
    logger_on_press(key)  # Call the on_press function from logger.py

def on_release(key):
    global keystroke_counter, erase_keys_counter, press_press_intervals, press_release_intervals, word_lengths, word_counter, last_press_time
    logger_on_release(key)

def get_cpu_percent():
    return psutil.cpu_percent()

def get_ram_percent():
    return psutil.virtual_memory().percent

def get_bytes_sent_received():
    net_io_counters = psutil.net_io_counters()
    return net_io_counters.bytes_sent, net_io_counters.bytes_recv

# Set up a timer to run the insert_data_into_table function every minute
def insert_data_timer():
    threading.Timer(5, insert_data_timer).start()
    current_time = time.time()
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(current_time))
    active_apps_count, current_app, penultimate_app, current_app_foreground_time, current_app_average_processes, current_app_stddev_processes = app_stats.update()

    # Get data from logger.py
    keystroke_counter, erase_keys_counter, press_press_intervals, press_release_intervals, word_lengths, word_counter = get_logger_data()

    # Calculate erase_keys_percentage
    erase_keys_percentage = (erase_keys_counter / keystroke_counter) * 100 if keystroke_counter > 0 else 0

    # Collect CPU and RAM usage
    cpu_percent = get_cpu_percent()
    ram_percent = get_ram_percent()

    # Collect network traffic
    bytes_sent, bytes_received = get_bytes_sent_received()
    print(f'keystroke_counter{keystroke_counter}')

    # Insert data into database
    insert_data_into_table(timestamp, keystroke_counter, erase_keys_counter, erase_keys_percentage,
                           press_press_intervals, press_release_intervals, word_lengths, active_apps_count,
                           current_app, penultimate_app, current_app_foreground_time, current_app_average_processes,
                           current_app_stddev_processes, cpu_percent, ram_percent, bytes_sent, bytes_received)

    # Reset the counters in logger.py
    reset_counters()

if __name__ == '__main__':
    print("Starting the main script...")
    # Create the database table if it doesn't exist
    create_table_if_not_exists()

    # Set up the keyboard listener
    listener = keyboard.Listener(on_press=on_press,
                                 on_release=on_release)  # Update the listener to include both on_press and on_release
    listener.start()

    # Call the insert_data_timer() function to start the timer
    insert_data_timer()

    # Keep the program running
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        listener.stop()


# -*- coding: utf-8 -*-
import pandas as pd
import argparse
from Bio import SeqIO
import re,os
import shutil

parser = argparse.ArgumentParser()
parser.add_argument('-f', metavar='[fasta]', required=True, help='fasta file')
parser.add_argument('-d', metavar='[plasmid detail]', required=True, help='plasmid detail file')
parser.add_argument('-p', metavar='[prefix]', required=True, help='prefix of file')
parser.add_argument('-dir', metavar='[dir]', required=True, help='output dir')
args = parser.parse_args()

fasta = args.f
detail = args.d
prefix = args.p
dir = args.dir

def run():
    dict ={}
    if os.path.exists(dir +"/seq_dir"):
        shutil.rmtree(dir +"/seq_dir")
    os.mkdir(dir +"/seq_dir")
    with open(detail) as f:
        lines = f.readlines()
        for line in lines[1:]:
            lin = line.strip().split("\t")
            dict[lin[5]] = lin[4]
    with open(prefix+"_assembly_details.xls","w") as f,open(prefix+"_assembly_summary.xls","w") as k, open("plasmid.type.xls","w") as s:
        k.write("Chromosome No.\tPlasmid No.\tGenome Size (bp)\tG+C (%)\n")
        chrr = []
        plsmid = []
        total_len = 0
        gc_total = 0
        for iterator in SeqIO.parse(fasta, "fasta"):
            SeqIO.write(iterator, dir +"/seq_dir/"+iterator.id + ".fasta", "fasta")
            if re.search("Plasmid", iterator.id) or re.search("plasmid", iterator.id):
                plsmid.append(iterator)
                gene = iterator.id[0].lower()+iterator.id[-1]+"_gene"
                print(iterator.id,gene)
                s.write("{}\t{}\n".format(iterator.id, gene))
            elif re.search("Chromosome", iterator.id) or re.search("chromosome", iterator.id):
                chrr.append(iterator)
            a = iterator.seq.upper().count("A")
            t = iterator.seq.upper().count("T")
            c = iterator.seq.upper().count("C")
            g = iterator.seq.upper().count("G")
            hh = g + c
            gc_total +=hh
            total = len(iterator.seq)
            total_len +=total
            gc = float(g+c)/total*100
            f.write("{}\t{}\t{}\t{}\n".format(iterator.id, total, gc, "A:"+str(a)+";T:"+str(t)+";G:"+str(g)+";C:"+str(c)))
        print(len(chrr))
        if len(chrr) >= 1:
            SeqIO.write(chrr, "chromosome.fasta", "fasta")
        if len(plsmid) >= 1:
            SeqIO.write(plsmid, "plasmid.fasta", "fasta")
        gc = float(gc_total)/total_len*100
        dd =len(chrr)
        ff = len(plsmid)
        k.write("{}\t{}\t{}\t{}\n".format(dd, ff, total_len, gc))

if __name__ == '__main__':
    run()


from django.urls import path
from .import views

urlpatterns = [
    path('',views.Admin, name='Admin'),
    path("AddLaw",views.AddLaw, name='AddLaw'),
    path("getLaw",views.getLaw, name='getLaw'),
    path('ViewLaw', views.ViewLaw, name='ViewLaw'),
    path('delete/<int:id>/',views.delete, name='delete'),
    path('edit/<int:eid>/', views.edit, name='edit'),
    path('UpdateLaw/<int:id>/',views.UpdateLaw,name='UpdateLaw'),
    path('ViewLawyerReq', views.ViewLawyerReq, name='ViewLawyerReq'),
    path('AcceptLawyerReq/<int:LRAid>/', views.AcceptLawyerReq, name='AcceptLawyerReq'),
    path('RejectLawyerReq/<int:LRDid>/', views.RejectLawyerReq, name='RejectLawyerReq'),
    path('ViewLawyers', views.ViewLawyers, name='ViewLawyers'),
    path('ViewUserReq', views.ViewUserReq, name='ViewUserReq'),
    path('AcceptUserReq/<int:UAid>/', views.AcceptUserReq, name='AcceptUserReq'),
    path('RejectUserReq/<int:UDid>/', views.RejectUserReq, name='RejectUserReq'),
    path('ViewCases', views.ViewCases, name='ViewCases'),
    path('ViewUsers', views.ViewUsers, name='ViewUsers')
]


import streamlit as st
import pandas as pd
import numpy as np
from sqlalchemy import create_engine, desc

#Erstellt einen Dataframe aus einem sqlite database file
@st.cache
def create_df(table, root):
  #engine = create_engine('sqlite:///' + root) #Auskommentiert, da Sample-Datensatz aus CSV eingelesen wird zu Demnonstrationszwecken
  #df = pd.read_sql(table, engine)             #Auskommentiert, da Sample-Datensatz aus CSV eingelesen wird zu Demnonstrationszwecken
  df = pd.read_csv(table)
  df['Datum'] = pd.to_datetime(df['Datum'])
  df.loc[(df.Linie == None),'Linie'] = 'Sonstige'
  return df

#Funktion, die DataFrame für die Karte erstellt
def create_map(df, table, zeitfilter, date, day, line_choice, stop_choice):
  if zeitfilter == 'Datum': df = df[df['Datum'].isin(date)]
  else: df = df[df['Wochentag'].isin(day)]
  df = df[df['Linie'].isin(line_choice)]
  df = df[df['Haltestelle_Ort'].isin(stop_choice)]
  if table == 'Fahrtanfragen_avg': df = df.groupby(['Haltestelle_Ort']).mean()
  else: df = df.groupby(['Haltestelle_Ort']).median()
  df.index.name = 'Haltestelle_Ort'
  df = df.reset_index()
  df['Verspätung_in_Sekunden'] = df['Verspätung_in_Sekunden'].round(0)
  df_result = df.sort_values(by=['Verspätung_in_Sekunden'], ascending=False)
  return df_result

#Funktion, die DataFrame für Historgamm erstellt
def create_hist(df, table, zeitfilter, date, day, line_choice, stop_choice):
  if zeitfilter == 'Datum': df = df[df['Datum'].isin(date)]
  else: df = df[df['Wochentag'].isin(day)]
  df = df[df['Linie'].isin(line_choice)]
  df = df[df['Haltestelle_Ort'].isin(stop_choice)]
  if table == 'Fahrtanfragen_avg': df = df.groupby(['Stunde_des_Tages']).mean()
  else: df = df.groupby(['Stunde_des_Tages']).median()
  df = df.drop(['lng', 'lat'], axis=1)
  df = df.round(0)
  df_result = df.reset_index()
  return df_result

#Funktion, die ein Numpy Array aus Haltestellen erstellt
@st.cache
def create_stoplist(root):
  df = create_df('Fahrtanfragen_avg', root)
  df = df['Haltestelle_Ort'].unique()
  arr = np.sort(df)
  return arr


import undetected_chromedriver as uc

def iniciar_webdriver(headless=False,pos="max"):
    options = uc.ChromeOptions()
    options.add_argument("--pasword-store=basic")
    options.add_experimental_option(
        "prefs",
        {
            "credentials_enable_service":False,
            "profile.password_manager_enabled":False
        }
    )

    driver = uc.Chrome(
        options=options,
        log_level=3,
        headless=headless
    )

    if not headless:
        driver.maximize_window()
        if pos!="max":
            ancho,alto = driver.get_window_size().values()
            if pos == "left":
                driver.set_window_rect(x=0,y=0,width=ancho//2,height=alto)
            elif pos == "right":
                driver.set_window_rect(x=ancho//2,y=0,width=ancho//2,height=alto)
    return driver


import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error

home_data_filepath = '/Users/jaredroberts/Downloads/train.csv'
home_data = pd.read_csv(home_data_filepath)

features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']
y = home_data.SalePrice
X = home_data[features]

iowa_model = DecisionTreeRegressor(random_state=1)
iowa_model.fit(X, y)

print('First in-sample prediction: ', iowa_model.predict(X.head()))
print('Actual target value for homes: ', y.head().tolist())

# tolist simply changes an array into a list

train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=1)

# Now using training data

iowa_model.fit(train_X, train_y)

val_predictions = iowa_model.predict(val_X)
print('Predictions with training data: ', iowa_model.predict(X.head()))
print('Actual target value for homes: ', y.head().tolist())

print('The mean absolute error is: ', mean_absolute_error(val_y, val_predictions))

# UNDERFITTING AND OVERFITTING
# max_leaf_nodes = argument to control over/under fitting

def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)
    model.fit(train_X, train_y)
    preds_value = model.predict(val_X)
    mae = mean_absolute_error(val_y, preds_value)
    return mae

# This function helps us calculate mae for different values of max_leaf_nodes

for max_leaf_nodes in [5, 50, 500, 5000]:
    my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
    print('Max leaf nodes: %d  \t\t Mean Absolute Error: %d' %(max_leaf_nodes, my_mae))


# -*- coding: utf-8 -*-

import numpy as np
from scipy.interpolate import RegularGridInterpolator
from dedalus.core import coords, distributor, basis, field
from dedalus.tools.cache import CachedFunction
from dedalus.core.basis import BallBasis
from dedalus.extras.flow_tools import GlobalArrayReducer
from mpi4py import MPI

@CachedFunction
def build_ball(shape, dtype, radius=1, dealias=3 / 2):
    """Build ball basis."""
    c = coords.SphericalCoordinates('phi', 'theta', 'r')
    d = distributor.Distributor((c,))
    b = basis.BallBasis(c, shape, radius=radius, dealias=(dealias, dealias, dealias), dtype=dtype)
    return c, d, b

@CachedFunction
def build_cartesian_unit_vectors(basis):
    """Build cartesian unit vector fields for a spherical basis."""
    b = basis
    d = basis.dist
    c = basis.coordsystem
    dtype = basis.dtype
    phi, theta, r = b.local_grids()
    ex = field.Field(dist=d, bases=(b,), tensorsig=(c,), dtype=dtype)
    ex['g'][0] = - np.sin(phi)
    ex['g'][1] = np.cos(theta) * np.cos(phi)
    ex['g'][2] = np.sin(theta) * np.cos(phi)
    ey = field.Field(dist=d, bases=(b,), tensorsig=(c,), dtype=dtype)
    ey['g'][0] = np.cos(phi)
    ey['g'][1] = np.cos(theta) * np.sin(phi)
    ey['g'][2] = np.sin(theta) * np.sin(phi)
    ez = field.Field(dist=d, bases=(b,), tensorsig=(c,), dtype=dtype)
    ez['g'][0] = 0
    ez['g'][1] = - np.sin(theta)
    ez['g'][2] = np.cos(theta)
    return ex, ey, ez

def extend_spherical_coords(basis, scales=1, reverse_theta=True):
    """Extend spherical coords to include all boundaries."""
    # Fix scales
    if not isinstance(scales, (list, tuple, np.ndarray)):
        scales = (scales,) * 3
    # Build local grids
    phi, theta, r = basis.local_grids(scales)
    # Repeat first phi point
    phi_ext = np.concatenate([phi, [[[2 * np.pi]]]], axis=0)
    # Add theta endpoints
    theta_ext = np.concatenate([[[[np.pi]]], theta, [[[0]]]], axis=1)
    # Add radial endpoints
    if isinstance(basis, BallBasis):
        r_ext = np.concatenate([[[[0]]], r, [[[1]]]], axis=2)
    else:
        raise NotImplementedError("Shell not yet implemented.")
    # Reverse theta
    if reverse_theta:
        theta_ext = theta_ext[:, ::-1, :]
    return phi_ext, theta_ext, r_ext

def extend_spherical_scalar(field, scales=1, reverse_theta=True):
    """Extend scalar field data to include boundary values."""
    basis = field.domain.bases[0]
    if not isinstance(basis, BallBasis):
        raise NotImplementedError("Shell not yet implemented.")
    # Fix scales
    if not isinstance(scales, (list, tuple, np.ndarray)):
        scales = (scales,) * 3
    # Build extended data
    field.require_scales(scales)
    shape = np.array(field['g'].shape) + np.array([1, 2, 2])
    data_ext = np.zeros(shape=shape, dtype=field.dtype)
    # Copy interior data
    data_ext[:-1, 1:-1, 1:-1] = field['g']
    # Interpolate to outer radius
    field_outer = field(r=basis.radial_basis.radius).evaluate()
    field_outer.require_scales(scales)
    data_ext[:-1, 1:-1, -1:] = field_outer['g']
    # Duplicate phi = 0 for phi = 2π
    data_ext[-1, :, :] = data_ext[0, :, :]
    # Average around poles
    data_ext[:, 0, :] = np.mean(data_ext[:, 1, :], axis=0)[None, :]
    data_ext[:, -1, :] = np.mean(data_ext[:, -2, :], axis=0)[None, :]
    # Average around origin
    data_ext[:, :, 0] = np.mean(data_ext[:, :, 1])[None, None]
    # Reverse theta
    if reverse_theta:
        data_ext = data_ext[:, ::-1, :]
    return data_ext

def build_spherical_interpolator(*fields, scales=1, bounds_error=False, **kw):
    """Build low-order interpolator for scalar fields in spherical coordinates."""
    basis = fields[0].domain.bases[0]
    coords_ext = extend_spherical_coords(basis, scales)
    coords_ext_flat = [c.ravel() for c in coords_ext]
    fields_ext = [extend_spherical_scalar(f, scales) for f in fields]
    fields_ext = np.squeeze(np.stack(fields_ext, axis=-1))
    return RegularGridInterpolator(coords_ext_flat, fields_ext, bounds_error=bounds_error, **kw)

def build_cartesian_interpolator(*args, **kw):
    spherical_interpolator = build_spherical_interpolator(*args, **kw)
    return lambda p: spherical_interpolator(cartesian_to_spherical(p))

def cartesian_to_spherical(p):
    """Convert [[x, y, z]] to [[phi, theta, r]] point sets."""
    p = np.array(p)
    x = p[..., 0]
    y = p[..., 1]
    z = p[..., 2]
    r = (x**2 + y**2 + z**2) ** 0.5
    phi = np.arctan2(y, x) % (2 * np.pi)
    theta = np.arccos(z / r)
    q = np.zeros_like(p)
    q[..., 0] = phi
    q[..., 1] = theta
    q[..., 2] = r
    return q

def create_integration_weigths(fields, dtype, radius=1):
    b = fields[0]
    d = fields[1]
    p = field.Field(dist=d, bases=(b,), dtype=dtype)
    weight_theta = b.local_colatitude_weights(b.domain.dealias[1])
    weight_r = b.local_radial_weights(b.domain.dealias[2])
    reducer = GlobalArrayReducer(d.comm_cart)
    p.require_scales(p.domain.dealias)
    int_norm = np.sum(weight_r * weight_theta * (0 * p['g'] + 1))
    int_norm = reducer.reduce_scalar(int_norm, MPI.SUM)
    int_correction = 4 / 3 * np.pi * radius**3 / int_norm
    return (weight_r, weight_theta, int_correction), reducer

def integrate_scalar(weights, reducer, field):
    # weights = (weights_r, weights_theta,  int_correction)
    field.require_scales(field.domain.dealias)
    field_int = np.sum(weights[0] * weights[1] * field['g'])
    field_int = reducer.reduce_scalar(field_int, MPI.SUM)
    return field_int * weights[2]


from unittest2 import TestCase

from datetime import datetime, timedelta
import securitybot.util as util

class VarTest(TestCase):
    def test_hours(self):
        assert util.OPENING_HOUR < util.CLOSING_HOUR, 'Closing hour must be after opening hour.'

class NamedTupleTest(TestCase):
    def test_empty(self):
        tup = util.tuple_builder()
        assert tup.answer is None
        assert tup.text == ''

    def test_full(self):
        tup = util.tuple_builder(True, 'Yes')
        assert tup.answer is True
        assert tup.text == 'Yes'

class BusinessHoursTest(TestCase):
    def test_weekday(self):
        '''Test business hours during a weekday.'''
        # 18 July 2016 is a Monday. If this changes, please contact the IERS.
        morning = datetime(year=2016, month=7, day=18, hour=util.OPENING_HOUR,
                           tzinfo=util.LOCAL_TZ)
        assert util.during_business_hours(morning)
        noon = datetime(year=2016, month=7, day=18, hour=12, tzinfo=util.LOCAL_TZ)
        assert util.during_business_hours(noon), \
            'This may fail if noon is no longer during business hours.'
        afternoon = datetime(year=2016, month=7, day=18, hour=util.CLOSING_HOUR - 1,
                             minute=59, second=59, tzinfo=util.LOCAL_TZ)
        assert util.during_business_hours(afternoon)

        breakfast = datetime(year=2016, month=7, day=18, hour=util.OPENING_HOUR - 1, minute=59,
                             second=59, tzinfo=util.LOCAL_TZ)
        assert not util.during_business_hours(breakfast)
        supper = datetime(year=2016, month=7, day=18, hour=util.CLOSING_HOUR,
                          tzinfo=util.LOCAL_TZ)
        assert not util.during_business_hours(supper)

    def test_weekend(self):
        '''Test "business hours" during a weekend.'''
        # As such, 17 July 2016 is a Sunday.
        sunday_morning = datetime(year=2016, month=7, day=17, hour=util.OPENING_HOUR,
                                  tzinfo=util.LOCAL_TZ)
        assert not util.during_business_hours(sunday_morning)

class ExpirationTimeTest(TestCase):
    def test_same_day(self):
        '''Test time delta within the same day.'''
        date = datetime(year=2016, month=7, day=18, hour=util.OPENING_HOUR, tzinfo=util.LOCAL_TZ)
        td = timedelta(hours=((util.CLOSING_HOUR - util.OPENING_HOUR) % 24) / 2)
        after = date + td
        assert util.get_expiration_time(date, td) == after

    def test_next_weekday(self):
        '''Test time delta overnight.'''
        date = datetime(year=2016, month=7, day=18, hour=util.CLOSING_HOUR - 1,
                        tzinfo=util.LOCAL_TZ)
        next_date = datetime(year=2016, month=7, day=19, hour=util.OPENING_HOUR + 1,
                             tzinfo=util.LOCAL_TZ)
        assert util.get_expiration_time(date, timedelta(hours=2)) == next_date

    def test_edge_weekday(self):
        '''Test time delta overnight just barely within range.'''
        date = datetime(year=2016, month=7, day=18, hour=util.CLOSING_HOUR - 1, minute=59,
                        second=59, tzinfo=util.LOCAL_TZ)
        td = timedelta(seconds=1)
        after = datetime(year=2016, month=7, day=19, hour=util.OPENING_HOUR,
                         tzinfo=util.LOCAL_TZ)
        assert util.get_expiration_time(date, td) == after

    def test_next_weekend(self):
        '''Test time delta over a weekend.'''
        date = datetime(year=2016, month=7, day=15, hour=util.CLOSING_HOUR - 1,
                        tzinfo=util.LOCAL_TZ)
        next_date = datetime(year=2016, month=7, day=18, hour=util.OPENING_HOUR + 1,
                             tzinfo=util.LOCAL_TZ)
        assert util.get_expiration_time(date, timedelta(hours=2)) == next_date

    def test_edge_weekend(self):
        '''Test time delta over a weekend just barely within range.'''
        date = datetime(year=2016, month=7, day=15, hour=util.CLOSING_HOUR - 1, minute=59,
                        second=59, tzinfo=util.LOCAL_TZ)
        td = timedelta(seconds=1)
        after = datetime(year=2016, month=7, day=18, hour=util.OPENING_HOUR,
                         tzinfo=util.LOCAL_TZ)
        assert util.get_expiration_time(date, td) == after


import sqlite3

# connection = sqlite3.connect('app.db')
# cursor = connection.cursor()
#
# cursor.execute('create table groceries (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)')

connection_notes = sqlite3.connect('notes.db', check_same_thread=False)
cursor_notes = connection_notes.cursor()

cursor_notes.execute('create table notes (id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT)')
# groceries = ["Apples",
#              "Bananas",
#              "Strawberries",
#              "Avocados",
#              "Bell Peppers",
#              "Carrots",
#              "Broccoli",
#              "Garlic",
#              "Lemons",
#              "Onion",
#              "Parsley",
#              "Cilantro",
#              "Basil",
#              "Potatoes",
#              "Spinach",
#              "Tomatoes"]
#
# for i in groceries:
#     cursor.execute(f"insert into groceries (name) values (?)", [i])
#
# connection.commit()
# connection.close()
#

print(cursor_notes.fetchall())


import tensorflow as tf
from dis_model_dns import DIS
#import cPickle
import pickle
import numpy as np
import multiprocessing # 多进程

cores = multiprocessing.cpu_count()#计算计算机的cpu核心数
print(cores) # 四核
#########################################################################################
# Hyper-parameters
#########################################################################################
# 用户id一直到了942，项目id纸看到了1329，需要核对训练数据集包含多少不同的用户，多少不同的项目
# movieLens 100K 数据集包括 943 个用户对 1682 部电影的100000个电影的评分（1~5）
EMB_DIM = 5
USER_NUM = 943
ITEM_NUM = 1683
DNS_K = 5  # 从候选集中随机选择 5 个作为
all_items = set(range(ITEM_NUM)) #range() 函数可创建一个整数列表，set()返回一个无序不重复元素集
#print(all_items)
workdir = 'ml-100k/'
DIS_TRAIN_FILE = workdir + 'dis-train.txt'
DIS_MODEL_FILE = workdir + "model_dns.pkl"
#########################################################################################
# Load data
#########################################################################################
user_pos_train = {}
#with open(workdir + 'movielens-100k-train.txt')as fin:
with open(workdir + 'movielens-100k-train-gai.txt')as fin: #with open的好处，不需要每次都 f.close()
    for line in fin:
        line = line.split() #通过指定分隔符对字符串进行切片，如果参数 num 有指定值，则分隔 num+1 个子字符串
        #print(line)
        uid = int(line[0])
        iid = int(line[1])
        r = float(line[2])
        if r > 3.99:
            if uid in user_pos_train:
                user_pos_train[uid].append(iid)
               # print("in")
            else:
                user_pos_train[uid] = [iid]
                #print("not")
#print(user_pos_train) # 用户喜欢*哪些项目（评分大于3.99）{0:[],1:[]...}

user_pos_test = {}
with open(workdir + 'movielens-100k-test-gai.txt')as fin:
    for line in fin:
        line = line.split()
        uid = int(line[0])
        iid = int(line[1])
        r = float(line[2])
        if r > 3.99:
            if uid in user_pos_test:
                user_pos_test[uid].append(iid)
            else:
                user_pos_test[uid] = [iid]

#all_users = user_pos_train.keys() #dict.keys() 2中以列表的形式返回一个字典的所有键值，3返回的不再是一个列表，而是一个可读的view
#all_users.sort() # 用于数组排序
all_users = sorted(user_pos_train)
#print(all_users)
# python 中定义一个函数要使用 def 语句，依次写出函数名、括号、括号中的参数和冒号，return 语句返回
def generate_dns(sess, model, filename):
    data = []
    for u in user_pos_train:
        pos = user_pos_train[u]
        all_rating = sess.run(model.dns_rating, {model.u: u})
        all_rating = np.array(all_rating) # 构造函数
        print(all_rating)
        neg = []
        candidates = list(all_items - set(pos)) # 候选集：所有项目 -- 用户喜欢的项目（剩下的是为评分的和评分小于等于3.99的）

        for _ in range(len(pos)):
            choice = np.random.choice(candidates, DNS_K) # 以多大的概率，从候选集中选择 几个 数据
            choice_score = all_rating[choice]
            print(choice_score)
            neg.append(choice[np.argmax(choice_score)]) # .argmax() 取出choice_score 中最大值对应的索引

        for i in range(len(pos)):
            data.append(str(u) + '\t' + str(pos[i]) + '\t' + str(neg[i]))

    with open(filename, 'w')as fout:
        fout.write('\n'.join(data))

def dcg_at_k(r, k): # 折扣增益
    r = np.asfarray(r)[:k] # 把一个普通的数组转为一个浮点类型的数组
    return np.sum(r / np.log2(np.arange(2, r.size + 2)))

def ndcg_at_k(r, k): # 归一化折扣增益
    dcg_max = dcg_at_k(sorted(r, reverse=True), k)
    if not dcg_max:
        return 0.
    return dcg_at_k(r, k) / dcg_max

def simple_test_one_user(x):
    rating = x[0]
    u = x[1]

    test_items = list(all_items - set(user_pos_train[u]))
    item_score = []
    for i in test_items:
        item_score.append((i, rating[i]))

    item_score = sorted(item_score, key=lambda x: x[1], reverse=True)
    item_sort = [x[0] for x in item_score]

    r = []
    for i in item_sort:
        if i in user_pos_test[u]:
            r.append(1)
        else:
            r.append(0)

    p_3 = np.mean(r[:3]) # 求均值
    p_5 = np.mean(r[:5])
    p_10 = np.mean(r[:10])

    ndcg_3 = ndcg_at_k(r, 3)
    ndcg_5 = ndcg_at_k(r, 5)
    ndcg_10 = ndcg_at_k(r, 10)

    return np.array([p_3, p_5, p_10, ndcg_3, ndcg_5, ndcg_10])

def simple_test(sess, model):
    result = np.array([0.] * 6)
    pool = multiprocessing.Pool(cores)
    batch_size = 128
    #test_users = user_pos_test.keys()
    test_users = list(user_pos_test.keys())
    test_user_num = len(test_users)
    index = 0
    while True:
        if index >= test_user_num:
            break
        user_batch = test_users[index:index + batch_size]
        index += batch_size

        user_batch_rating = sess.run(model.all_rating, {model.u: user_batch})
        user_batch_rating_uid = zip(user_batch_rating, user_batch)
        batch_result = pool.map(simple_test_one_user, user_batch_rating_uid)
        for re in batch_result:
            result += re

    pool.close()
    ret = result / test_user_num
    ret = list(ret)
    return ret

def generate_uniform(filename):
    data = []
    #print 'uniform negative sampling...'
    print('uniform negative sampling...')
    for u in user_pos_train:
        pos = user_pos_train[u]
        candidates = list(all_items - set(pos))
        neg = np.random.choice(candidates, len(pos))
        pos = np.array(pos)

        for i in range(len(pos)):
            data.append(str(u) + '\t' + str(pos[i]) + '\t' + str(neg[i]))

    with open(filename, 'w')as fout:
        fout.write('\n'.join(data))

def main():
    np.random.seed(70) # 利用随机数种子，每次生成的随机数相同
    param = None
    discriminator = DIS(ITEM_NUM, USER_NUM, EMB_DIM, lamda=0.1, param=param, initdelta=0.05, learning_rate=0.05)

    config = tf.ConfigProto() # 配置session 运行参数&&GPU设备指定
    config.gpu_options.allow_growth = True
    #config.gpu_options.per_process_gpu_memory_fraction = 0.4  #占用40%显存
    sess = tf.Session(config=config)
    sess.run(tf.global_variables_initializer()) # 初始化模型的参数

    dis_log = open(workdir + 'dis_log_dns.txt', 'w')
    #print "dis ", simple_test(sess, discriminator)
    print("dis",simple_test(sess,discriminator))
    best_p5 = 0.

    # generate_uniform(DIS_TRAIN_FILE) # Uniformly sample negative examples

    #for epoch in range(80):
    for epoch in range(10):
        generate_dns(sess, discriminator, DIS_TRAIN_FILE)  # dynamic negative sample
        with open(DIS_TRAIN_FILE)as fin:
            for line in fin:
                line = line.split()
                u = int(line[0])
                i = int(line[1])
                j = int(line[2])
                _ = sess.run(discriminator.d_updates,
                             feed_dict={discriminator.u: [u], discriminator.pos: [i],
                                        discriminator.neg: [j]})

        result = simple_test(sess, discriminator)
        #print "epoch ", epoch, "dis: ", result
        print("epoch",epoch,"dis:",result)
        if result[1] > best_p5:
            best_p5 = result[1]
            discriminator.save_model(sess, DIS_MODEL_FILE)
            #print "best P@5: ", best_p5
            print("best p@5",best_p5)

        buf = '\t'.join([str(x) for x in result])
        dis_log.write(str(epoch) + '\t' + buf + '\n')
        dis_log.flush()

    dis_log.close()

if __name__ == '__main__':
    main()


#!/usr/bin/python3

import contextlib
import os
import fcntl
import re
import struct
import sys
from typing import Iterable

def if_open(dev: str) -> int:
    TUNSETIFF = 0x400454CA
    TUNSETOWNER = TUNSETIFF + 2
    IFF_TUN = 0x0001
    IFF_TAP = 0x0002
    IFF_NO_PI = 0x1000

    try:
        fd = os.open("/dev/net/tun", os.O_RDWR)
    except PermissionError as e:
        raise SystemExit(e)

    if_flags = None
    if dev.startswith("tun"):
        if_flags = IFF_TUN | IFF_NO_PI
    elif dev.startswith("tap"):
        if_flags = IFF_TAP | IFF_NO_PI

    fcntl.ioctl(fd, TUNSETIFF, struct.pack("16sH", str.encode(dev), if_flags))

    # for setting to owner
    # fcntl.ioctl(fd, TUNSETOWNER, 1000)

    return fd

def device_exists(dev: str) -> bool:
    return os.path.exists("/sys/devices/virtual/net/%s" % dev)

def valid_device_name(dev: str) -> None:
    if not re.search(r"^t(ap|un)[0-9]+$", dev):
        raise ValueError("device should be of form tun0-tun255 or tap0-tap255")

    if_num = int(dev[3:])
    if if_num > 255:
        raise ValueError("device should be of form tun0-tun255 or tap0-tap255")

@contextlib.contextmanager
def closing_fd(fd: int) -> Iterable[int]:
    try:
        yield fd
    finally:
        os.close(fd)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("need to specify a tun/tap device (eg tun1 or tap2)")

    d = sys.argv[1]
    valid_device_name(d)

    if device_exists(d):
        raise SystemExit("ERROR: device '%s' already exists" % d)
        sys.exit(1)

    found = False
    with closing_fd(if_open(d)) as fd:
        if device_exists(d):
            found = True
            print("PASS")
        else:
            print("FAIL")

    if not found:
        sys.exit(1)


import re
from dataclasses import dataclass, asdict
from distutils.util import strtobool
from typing import List

from fb4.widgets import LodTable
from flask import Blueprint, request, jsonify, send_file
from spreadsheet.spreadsheet import ExcelDocument

from corpus.datasources.openresearch import OREvent, OREventSeries
from corpus.eventseriescompletion import EventSeriesCompletion

class EventSeriesBlueprint():
    """
    API service for event series data
    """

    def __init__(self, app, name: str, template_folder:str=None, appWrap=None):
        '''
        construct me

        Args:
            name(str): my name
            template_folder(str): the template folder
        '''
        self.name = name
        if template_folder is not None:
            self.template_folder = template_folder
        else:
            self.template_folder = 'eventseries'
        self.blueprint = Blueprint(name, __name__, template_folder=self.template_folder,url_prefix="/eventseries")
        self.app = app
        self.appWrap = appWrap

        @self.blueprint.route('/<name>')
        def getEventSeries(name: str):
            return self.getEventSeries(name)

        app.register_blueprint(self.blueprint)

    def getEventSeries(self, name: str):
        '''
        Query multiple datasources for the given event series

        Args:
            name(str): the name of the event series to be queried
        '''
        multiQuery = "select * from {event}"
        idQuery = f"""select source,eventId from event where lookupAcronym LIKE "{name} %" order by year desc"""
        dictOfLod = self.appWrap.lookup.getDictOfLod4MultiQuery(multiQuery, idQuery)
        if request.values.get("bk"):
            bkParam = request.values.get("bk")
            allowedBks = bkParam.split(",") if bkParam else None
            self.filterForBk(dictOfLod.get("tibkat"), allowedBks)
        reduceRecords = request.values.get("reduce")
        if reduceRecords is not None and (reduceRecords == "" or bool(strtobool(reduceRecords))):
            for source in ["tibkat", "dblp"]:
                sourceRecords = dictOfLod.get(source)
                if sourceRecords:
                    reducedRecords = EventSeriesCompletion.filterDuplicatesByTitle(sourceRecords)
                    dictOfLod[source] = reducedRecords
        return self.convertToRequestedFormat(name, dictOfLod)

    @staticmethod
    def filterForBk(lod:List[dict], allowedBks:List[str]):
        """
        Filters the given dict to only include the records with their bk in the given list of allowed bks
        Args:
            lod: list of records to filter
            allowedBks: list of allowed bks
        """
        if lod is None or allowedBks is None:
            return
        mainclassBk = set()
        subclassBk = set()
        allowNullValue = False
        for bk in allowedBks:
            if bk.isnumeric():
                mainclassBk.add(bk)
            elif re.fullmatch(r"\d{1,2}\.\d{2}", bk):
                subclassBk.add(bk)
            elif bk.lower() == "null" or bk.lower() == "none":
                allowNullValue = True
        def filterBk(record:dict) -> bool:
            keepRecord: bool = False
            bks = record.get("bk")
            if bks is not None:
                bks = set(bks.split("⇹"))
                recordMainclasses = {bk.split(".")[0] for bk in bks}
                if mainclassBk.intersection(recordMainclasses) or subclassBk.intersection(bks):
                    keepRecord = True
            elif bks is None and allowNullValue:
                keepRecord = True
            return keepRecord
        lod[:] = [record for record in lod if filterBk(record)]

    def generateSeriesSpreadsheet(self, name:str, dictOfLods: dict) -> ExcelDocument:
        """

        Args:
            name(str): name of the series
            dictOfLods: records of the series from different sources

        Returns:
            ExcelDocument
        """
        spreadsheet = ExcelDocument(name=name)
        # Add completed event sheet and add proceedings sheet
        eventHeader = [
            "item",
            "label",
            "description",
            "Ordinal",
            "OrdinalStr",
            "Acronym",
            "Country",
            "City",
            "Title",
            "Series",
            "Year",
            "Start date",
            "End date",
            "Homepage",
            "dblp",
            "dblpId",
            "wikicfpId",
            "gndId"]
        proceedingsHeaders = ["item", "label", "ordinal", "ordinalStr", "description", "Title", "Acronym",
                              "OpenLibraryId", "oclcId", "isbn13", "ppnId", "gndId", "dblpId", "doi", "Event",
                              "publishedIn"]
        eventRecords = []
        for lod in dictOfLods.values():
            eventRecords.extend(lod)
        completedBlankEvent = EventSeriesCompletion.getCompletedBlankSeries(eventRecords)
        eventSheetRecords = []
        proceedingsRecords = []
        for year, ordinal in completedBlankEvent:
            eventSheetRecords.append({**{k: None for k in eventHeader}, "Ordinal": ordinal, "Year": year})
            proceedingsRecords.append({**{k: None for k in proceedingsHeaders}, "ordinal": ordinal})
        if not eventSheetRecords:
            eventSheetRecords = [{k: None for k in eventHeader}]
            proceedingsRecords = [{k: None for k in proceedingsHeaders}]
        spreadsheet.addTable("Event", eventSheetRecords)
        spreadsheet.addTable("Proceedings", proceedingsRecords)

        for lods in [dictOfLods, asdict(MetadataMappings())]:
            for sheetName, lod in lods.items():
                if isinstance(lod, list):
                    lod.sort(key=lambda record: 0 if record.get('year',0) is None else record.get('year',0))
                spreadsheet.addTable(sheetName, lod)
        return spreadsheet

    def convertToRequestedFormat(self, name:str, dictOfLods: dict):
        """
        Converts the given dicts of lods to the requested format.
        Supported formats: json, html
        Default format: json

        Args:
            dictOfLods: data to be converted

        Returns:
            Response
        """
        formatParam = request.values.get('format', "")
        if formatParam.lower() == "html":
            tables = []
            for name, lod in dictOfLods.items():
                tables.append(LodTable(name=name, lod=lod))
            template = "cc/result.html"
            title = "Query Result"
            result = "".join([str(t) for t in tables])
            html = self.appWrap.render_template(template, title=title, activeItem="", result=result)
            return html
        elif formatParam.lower() == "excel":
            spreadsheet = self.generateSeriesSpreadsheet(name, dictOfLods)
            return send_file(spreadsheet.toBytesIO(), as_attachment=True, download_name=spreadsheet.filename, mimetype=spreadsheet.MIME_TYPE)
        else:
            return jsonify(dictOfLods)

@dataclass
class MetadataMappings:
    """
    Spreadsheet metadata mappings
    """
    WikidataMapping: list = None
    SmwMapping: list = None

    def __init__(self):
        self.WikidataMapping = [
             {'Entity': 'Event series', 'Column':None, 'PropertyName': 'instanceof', 'PropertyId': 'P31', 'Value': 'Q47258130'},
             {'Entity': 'Event series', 'Column': 'Acronym', 'PropertyName': 'short name', 'PropertyId': 'P1813', 'Type': 'text'},
             {'Entity': 'Event series', 'Column': 'Title', 'PropertyName': 'title', 'PropertyId': 'P1476', 'Type': 'text'},
             {'Entity': 'Event series', 'Column': 'Homepage', 'PropertyName': 'official website', 'PropertyId': 'P856', 'Type': 'url'},
             {'Entity': 'Event', 'Column':None, 'PropertyName': 'instanceof', 'PropertyId': 'P31', 'Value': 'Q2020153'},
             {'Entity': 'Event', 'Column': 'Series', 'PropertyName': 'part of the series', 'PropertyId': 'P179'},
             {'Entity': 'Event', 'Column': 'Ordinal', 'PropertyName': 'series ordinal', 'PropertyId': 'P1545', 'Type': 'string', 'Qualifier': 'part of the series'},
             {'Entity': 'Event', 'Column': 'Acronym', 'PropertyName': 'short name', 'PropertyId': 'P1813', 'Type': 'text'},
             {'Entity': 'Event', 'Column': 'Title', 'PropertyName': 'title', 'PropertyId': 'P1476', 'Type': 'text'},
             {'Entity': 'Event', 'Column': 'Country', 'PropertyName': 'country', 'PropertyId': 'P17', 'Lookup': 'Q3624078'},
             {'Entity': 'Event', 'Column': 'City', 'PropertyName': 'location', 'PropertyId': 'P276', 'Lookup': 'Q515'},
             {'Entity': 'Event', 'Column': 'Start date', 'PropertyName': 'start time', 'PropertyId': 'P580', 'Type': 'date'},
             {'Entity': 'Event', 'Column': 'End date', 'PropertyName': 'end time', 'PropertyId': 'P582', 'Type': 'date'},
             {'Entity': 'Event', 'Column': 'gndId', 'PropertyName': 'GND ID', 'PropertyId': 'P227', 'Type': 'extid'},
             {'Entity': 'Event', 'Column': 'dblpUrl', 'PropertyName': 'describedAt', 'PropertyId': 'P973', 'Type': 'url'},
             {'Entity': 'Event', 'Column': 'Homepage', 'PropertyName': 'official website', 'PropertyId': 'P856', 'Type': 'url'},
             {'Entity': 'Event', 'Column': 'wikicfpId', 'PropertyName': 'WikiCFP event ID', 'PropertyId': 'P5124', 'Type': 'extid'},
             {'Entity': 'Event', 'Column': 'dblpId', 'PropertyName': 'DBLP event ID', 'PropertyId': 'P10692', 'Type': 'extid'},
             {'Entity': 'Proceedings', 'Column':None, 'PropertyName': 'instanceof', 'PropertyId': 'P31', 'Value': 'Q1143604'},
             {'Entity': 'Proceedings', 'Column': 'Acronym', 'PropertyName': 'short name', 'PropertyId': 'P1813', 'Type': 'text'},
             {'Entity': 'Proceedings', 'Column': 'Title', 'PropertyName': 'title', 'PropertyId': 'P1476', 'Type': 'text'},
             {'Entity': 'Proceedings', 'Column': 'OpenLibraryId', 'PropertyName': 'Open Library ID', 'PropertyId': 'P648', 'Type': 'extid'},
             {'Entity': 'Proceedings', 'Column': 'ppnId', 'PropertyName': 'K10plus PPN ID', 'PropertyId': 'P6721', 'Type': 'extid'},
             {'Entity': 'Proceedings', 'Column': 'Event', 'PropertyName': 'is proceedings from', 'PropertyId': 'P4745', 'Lookup': 'Q2020153'},
             {'Entity': 'Proceedings', 'Column': 'publishedIn', 'PropertyName': 'published in', 'PropertyId': 'P1433', 'Lookup': 'Q39725049'},
             {'Entity': 'Proceedings', 'Column': 'oclcId', 'PropertyName': 'OCLC work ID','PropertyId': 'P5331', 'Type': 'extid'},
             {'Entity': 'Proceedings', 'Column': 'isbn13', 'PropertyName': 'ISBN-13', 'PropertyId': 'P212', 'Type': 'extid'},
             {'Entity': 'Proceedings', 'Column': 'doi', 'PropertyName': 'DOI', 'PropertyId': 'P356', 'Type': 'extid'},
             {'Entity': 'Proceedings', 'Column': 'dblpId', 'PropertyName': 'DBLP event ID', 'PropertyId': 'P10692', 'Type': 'extid'},
             ]

        self.SmwMapping = [
            *[{"Entity":"Event",
               "Column":r.get("templateParam"),
               "PropertyName":r.get("name"),
               "PropertyId":r.get("prop"),
               "TemplateParam": r.get("templateParam")
               } for r in OREvent.propertyLookupList
              ],
            *[{"Entity": "Event series",
               "Column": r.get("templateParam"),
               "PropertyName": r.get("name"),
               "PropertyId": r.get("prop"),
               "TemplateParam": r.get("templateParam")
               } for r in OREventSeries.propertyLookupList
              ]
        ]