import numpy
import matplotlib.pyplot as plt
import  pylab
import dcf
import utility as util
import logistic_regression as lr
import svm
from tqdm import tqdm
from copy import deepcopy
from preprocessing import preprocess_Z_score
import matplotlib

# ======================================== FEATURES plots ==========================================
def plot_features_distr(D, labels, features, gau=False):
    n_features = len(features)
    _gau = "gau-" if gau else ""
    males = D[:, labels == 0]
    females = D[:, labels == 1]
    bins = 30

    for feature in range(n_features):
        plt.Figure()
        plt.xlabel(features[feature])

        dataset_m = males[feature, :]
        dataset_f = females[feature, :]

        plt.hist(dataset_m, bins=bins, density=True, label='male', alpha=0.4)
        plt.hist(dataset_f, bins=bins, density=True, label='female', alpha=0.4)

        plt.legend()
        plt.savefig(f"./plots/features/{_gau}/{features[feature]}.png", format="png")
        plt.show()

def plot_relation_beetween_feautures(D, labels, features):
    n_features = len(features)

    males = D[:, labels == 0]
    females = D[:, labels == 1]

    for featureA in range(n_features):
        for featureB in range(featureA, n_features):
            if featureA == featureB:
                continue
            plt.figure()
            plt.xlabel(labels[featureA])
            plt.ylabel(labels[featureB])

            plt.scatter(males[featureA, :], males[featureB, :], label='Male', alpha=0.4)
            plt.scatter(females[featureA, :], males[featureB, :], label='Female', alpha=0.4)

            plt.legend()
            plt.show()

# ============================================ CORRELATION between features plots ======================================================
def pearson_coeff(x, y):
    """
    Given two arrays evaluate the Pearson coefficient
    Parameters
    ---------
    x: numpy.array
        first array
    y: numpy.array
        second array
    """
    cov = numpy.cov(x, y)[0][1]

    x_var = numpy.var(x)
    y_var = numpy.var(y)

    return numpy.abs(cov / (numpy.sqrt(x_var) * numpy.sqrt(y_var)))

def plot_heatmap(D, features, color):
    """
    Plot the heatmap of a given dataset. This heat map will show the pearson coefficient between all the feauters.
    Parameters
    ---------
    D: dataset
    color: an optional value with the color of the heatmap
    """
    n_features = len(features)
    coeffs = numpy.zeros((n_features, n_features))

    # evaluate the person coefficient for each feature
    for i in range(n_features):
        for j in range(n_features):
            coeffs[i][j] = pearson_coeff(D[i, :], D[j, :])

    # plot the heat map
    fig, ax = plt.subplots()
    im = ax.imshow(coeffs, interpolation='nearest', cmap=color)
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")
    # Loop over data dimensions and create text annotations.
    for i in range(len(coeffs)):
        for j in range(len(coeffs)):
            text = ax.text(j, i, numpy.around(coeffs[i, j],2),
                        ha="center", va="center", color="w")
    ax.set_title("Heat map")
    fig.tight_layout()
    plt.show()

# ================================================= MIN DCFs Plots ============================================================================
def compare_min_DCF_logreg(DTR, DTE, LTR, LTE, applications, quadratic=False, preprocessing=False, weighted=False):
    lambdas = [1e-6, 2e-6, 5e-6, 1e-5, 2e-5, 5e-5, 1e-4, 2e-4, 5e-4, 1e-3, 2e-3, 5e-3, 8e-3, 1e-2, 2e-2, 5e-2, 1e-1, 0.3, 0.5, 1, 5, 10, 50, 100]
    app_labels = ['minDCF(pi=0.5)', 'minDCF(pi=0.1)', 'minDCF(pi=0.9)']
    quadratic_ = 'quadratic' if quadratic else 'linear'
    colors = ['b', 'r', 'g']
    params = {
        'weighted' : weighted
    }

    max_y = 0
    DCFs_dict = dict()

    file_prefix = lr.compute_filename_prefix(quadratic, preprocessing, weighted)
    train_minDCFs, train_lambdas = lr.load_results(file_prefix)
    PATH = f"./plots/LogReg/experimental/{file_prefix}-minDCF.png"

    for i, application in enumerate(applications):
        pi, Cfn, Cfp = application
        params['priors'] = [pi, 1-pi]

        DCFs = lr.compute_minDCF_for_lambda(DTR, DTE, LTR, LTE, application, lambdas, quadratic, params)
        DCFs_dict[application] = DCFs
        max_y = max(max_y, numpy.amax(numpy.hstack((train_minDCFs[application], DCFs))))

        plt.plot(train_lambdas, train_minDCFs[application], color=colors[i], label=f"{app_labels[i]} [Val]", linestyle='dashed')
        plt.plot(lambdas, DCFs, color=colors[i], label=f"{app_labels[i]} [Eval]")

    plt.ylim(0, max_y + 0.05)
    plt.xscale('log')
    plt.title(f"DCF {quadratic_} logistic regression")
    plt.xlabel('lambda')
    plt.ylabel('DCF')
    plt.legend()
    plt.savefig(PATH, format='png')
    plt.show()
    return lambdas, DCFs_dict

def plot_min_DCF_logreg(folds, folds_labels, k, applications, quadratic=False, preprocessing=False, weighted=False):
    lambdas = [1e-6, 2e-6, 5e-6, 1e-5, 2e-5, 5e-5, 1e-4, 2e-4, 5e-4, 1e-3, 2e-3, 5e-3, 8e-3, 1e-2, 2e-2, 5e-2, 1e-1, 0.3, 0.5, 1, 5, 10, 50, 100]
    #lambdas = [1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 5e-2, 1e-1, 0.3, 0.5, 1, 5, 10]
    app_labels = ['minDCF(pi=0.5)', 'minDCF(pi=0.1)', 'minDCF(pi=0.9)']
    colors = ['b', 'r', 'g']
    max_y = 0

    quadratic_ = "quadratic" if quadratic else "linear"

    file_prefix = lr.compute_filename_prefix(quadratic, preprocessing, weighted)
    PATH = f"./plots/LogReg/{file_prefix}-minDCF.png"

    DCFs_dict = {}

    max_y = 0
    for i, application in enumerate(applications):
        DCFs = []
        pi, Cfn, Cfp = application
        classPriors = [pi, 1-pi]
        for l in tqdm(lambdas):
            if not quadratic:
                STE = util.k_folds(folds, folds_labels, k, lr.logreg, priors=classPriors, lambda_=l, preprocessing=preprocessing, weighted=weighted)
            else:
                STE = util.k_folds(folds, folds_labels, k, lr.quadratic_logreg, priors=classPriors, lambda_=l, preprocessing=preprocessing, weighted=weighted)
            scores = numpy.hstack(STE)
            DCF = dcf.compute_min_DCF(scores, numpy.hstack(folds_labels), pi, Cfn, Cfp)
            max_y = max(max_y, DCF)
            DCFs.append(DCF)
            DCFs_dict[application] = DCFs
        plt.plot(lambdas, DCFs, color=colors[i], label=app_labels[i])

    plt.ylim(0, max_y+0.1)
    plt.xscale('log')
    plt.title(f"DCF {quadratic_} logistic regression")
    plt.xlabel('lambda')
    plt.ylabel('DCF')
    plt.legend()
    plt.savefig(PATH, format='png')
    plt.show()
    return lambdas, DCFs_dict
# ================================================= MIN DCFs SVM Plots ============================================================================
def compare_min_DCF_svm(DTR, DTE, LTR, LTE, kernel:str, evaluation_points: tuple, balanced: bool, preprocessing: bool):
    #plot features
    #Cs = [0.005, 0.02,0.05, 0.10, 0.20, 0.30, 0.5, 0.8, 1, 5, 10, 20, 50]
    Cs = [0.005, 0.05, 0.1, 0.5, 1, 5]

    colors = ['b', 'r', 'g']
    app_labels = ['minDCF(pi=0.5)', 'minDCF(pi=0.1)', 'minDCF(pi=0.9)'] if kernel != 'rbf' else ['log(\u03BB)=-1', 'log(\u03BB)=-2', 'log(\u03BB)=-3']
    balanced_ = "balanced" if balanced else "not balanced"

    file_prefix = svm.compute_filename_prefix(balanced, preprocessing)
    train_minDCFs, train_Cs = svm.load_results(file_prefix, kernel)
    PATH = f"./plots/SVM/experimental/{kernel}-{file_prefix}-minDCF.png"

    max_y = 0
    minDCFs_dict = dict()

    for i, ep in enumerate(evaluation_points):
        DCFs = []
        if kernel == 'linear':
            pi, Cfn, Cfp = ep
            params = util.build_params(priors=[pi, 1-pi], balanced=balanced, kernel=kernel)
        elif kernel == 'poly':
            pi, Cfn, Cfp = ep
            params = util.build_params(priors=[pi, 1-pi], balanced=balanced, kernel=kernel, d=2, c=1,)
        elif kernel == 'rbf':
            params = util.build_params(priors=[0.5, 0.5], balanced=balanced, kernel=kernel, gamma=ep)

        minDCFs = svm.compute_minDCF_for_parameter(DTR, DTE, LTR, LTE, ep, Cs, params)
        minDCFs_dict[ep] = minDCFs
        max_y = max(max_y, numpy.amax(numpy.hstack((train_minDCFs[ep], minDCFs))))

        minDCFs = numpy.array(minDCFs).ravel()
        plt.plot(Cs, minDCFs, color=colors[i], label=f"{app_labels[i]} [Eval]")
        train_minDCF = numpy.array(train_minDCFs[ep]).ravel()
        plt.plot(train_Cs, train_minDCF, color=colors[i], label=f"{app_labels[i]} [Val]", linestyle='dashed' )

    plt.ylim(0, max_y+0.05)
    plt.title(f"minDCF for {kernel} SVM ({balanced_})")
    plt.xscale('log')
    plt.xlabel('C')
    plt.ylabel('DCF')
    plt.legend()
    plt.savefig(PATH, format="png")
    plt.show()
    return Cs, minDCFs_dict

def plot_min_DCF_svm(folds, folds_labels, k, applications, balanced=False, preprocessing=None):

    balanced_ = "balanced" if balanced else "not balanced"
    preprocessing_ = preprocessing if preprocessing else "raw"

    PATH = f"./plots/SVM/{preprocessing_}-linear-{balanced_}-minDCF.png"

    Cs = [0.005, 0.02,0.05, 0.10, 0.20, 0.30, 0.5, 0.8, 1, 5, 10, 20, 50]
    colors = ['b', 'r', 'g']
    app_labels = ['minDCF(pi=0.5)', 'minDCF(pi=0.1)', 'minDCF(pi=0.9)']
    minDCFs_dict = {}

    max_y = 0

    for i, application in enumerate(applications):
        DCFs = []
        pi, Cfn, Cfp = application
        classPriors = [pi, 1-pi]
        for C in tqdm(Cs):
            scores = util.k_folds(folds, folds_labels, k, svm.train_SVM_linear,SVM=True, C = C, balanced=balanced, preprocessing=preprocessing)
            scores = numpy.hstack(scores)
            minDCF = dcf.compute_min_DCF(scores, numpy.hstack(folds_labels), pi, Cfn, Cfp)
            DCFs.append(minDCF)
        DCFs = numpy.array(DCFs)
        minDCFs_dict[application] = DCFs.ravel()
        plt.plot(Cs, DCFs.ravel(), color=colors[i], label=app_labels[i])

    plt.ylim(0, 1)
    plt.title(f"minDCF for linear SVM ({balanced_})")
    plt.xscale('log')
    plt.xlabel('C')
    plt.ylabel('DCF')
    plt.legend()
    plt.savefig(PATH, format="png")
    plt.show()
    return Cs, minDCFs_dict

def plot_min_DCF_poly_svm(folds, folds_labels, k, applications, degree=2.0, balanced=False, preprocessing=None):
    balanced_ = "balanced" if balanced else "not balanced"
    preprocessing_ = "z-norm" if preprocessing else "raw"
    PATH = f"./plots/SVM/{preprocessing_}-poly{int(degree)}-{balanced_}-minDCF.png"
    Cs = [0.005, 0.05, 0.1, 0.5, 1, 5]
    colors = ['b', 'r', 'g']
    app_labels = ['minDCF(pi=0.5)', 'minDCF(pi=0.1)', 'minDCF(pi=0.9)']
    minDCFs_dict = {}
    for i, application in enumerate(applications):
        DCFs = []
        pi, Cfn, Cfp = application
        classPriors = [pi, 1-pi]
        for C in tqdm(Cs):
            scores = util.k_folds(folds, folds_labels, k, svm.train_non_linear_SVM,  SVM=True, kernel='poly', C=C, d=degree, c=1, balanced=balanced, preprocessing=preprocessing)
            scores = numpy.hstack(scores)
            minDCF = dcf.compute_min_DCF(scores, numpy.hstack(folds_labels), pi, Cfn, Cfp)
            DCFs.append(minDCF)
        DCFs = numpy.array(DCFs)
        minDCFs_dict[application] = DCFs.ravel()
        plt.ylim(0, 1)
        plt.title(f"DCF for Poly(d={int(degree)}) SVM ({balanced_})")
        plt.xscale('log')
        plt.xlabel('C')
        plt.ylabel('DCF')
        plt.plot(Cs, DCFs.ravel(), color=colors[i], label=app_labels[i])
        plt.legend()
    plt.savefig(PATH, format="png")
    plt.show()
    return Cs, minDCFs_dict

def plot_min_DCF_RBFsvm(folds, folds_labels, k, gammas, balanced=False, preprocessing=False):
    balanced_ = "balanced" if balanced else "not-balanced"
    preprocessing_ = "z-norm" if preprocessing else "raw"
    PATH = f"./plots/SVM/{preprocessing_}-RBF-{balanced_}-minDCF.png"
    Cs = [0.005, 0.01,0.02,0.05, 0.08, 0.10, 0.20, 0.30, 0.5, 0.8, 1, 3, 5, 10, 20, 50]
    colors = ['b', 'r', 'g']
    app_labels = ['log(\u03B3)=-1', 'log(\u03B3)=-2', 'log(\u03B3)=-3']

    minDCFs_dict = {}

    for i,gamma in enumerate(gammas):
        DCFs = []
        pi, Cfn, Cfp = (0.5, 1, 1)
        classPriors = [pi, 1-pi]
        for C in tqdm(Cs):
            scores = util.k_folds(folds, folds_labels, k, svm.train_non_linear_SVM, SVM=True, kernel='rbf', gamma=gamma, C=C, balanced=balanced, preprocessing=preprocessing)
            scores = numpy.hstack(scores)
            minDCF = dcf.compute_min_DCF(scores, numpy.hstack(folds_labels), pi, Cfn, Cfp)
            DCFs.append(minDCF)
        DCFs = numpy.array(DCFs)
        minDCFs_dict[gamma] = DCFs.ravel()
        plt.ylim(0, 1)
        plt.title("DCF for RBF kernel SVM")
        plt.xscale('log')
        plt.xlabel('C')
        plt.ylabel('DCF')
        plt.plot(Cs, DCFs.ravel(), color=colors[i], label=app_labels[i])
        plt.legend()
    plt.savefig(PATH, format="png")
    plt.show()

    return Cs, minDCFs_dict
# ================================================= MIN DCFs GMM Plots ============================================================================

def plot_minDCF_GMM_hist(DCFs_list: list, G: int, labels: list, filename='plot', experimental= False, title="", colors=['lightsalmon', 'orangered', 'gold', 'orange']):
    x_labels = list(map(lambda val:2**val, range(G)))
    x = numpy.arange(len(x_labels))
    width = 0.18
    _experimental = "experimental/" if experimental else ""
    path = f"./plots/GMM/{_experimental}{filename}.png"

    n_hists = len(DCFs_list)
    offsets = list( range(-int(n_hists/2) - 1, int(n_hists/2) + 2, 2))
    print("n_hist:", n_hists, "offsets", offsets)

    fig, ax = plt.subplots()
    for DCFs, offset, label, color in zip(DCFs_list, offsets, labels, colors):
        ax.bar(x + offset*width/2, DCFs, width, label=label, color=color)

    ax.set_ylabel('DCF')
    ax.set_xticks(x, x_labels)
    ax.legend()
    ax.set_title(title)
    fig.tight_layout()
    plt.savefig(path, format='png')

    plt.show()

# ================================================================ DET Plot ===================================================================
def plot_DET(llrs:list, L: numpy.array, plot_labels:list, colors: list =['r', 'b', 'm', 'g', 'y'], save_figure:bool = True, training:bool = True, multiple_labels: bool = False):
    training_ = "training" if training else "experimental"
    models = "-".join(plot_labels)
    PATH = f"./plots/evaluation/{training_}/DET_{models}.png"

    fig,ax = plt.subplots()

    if not multiple_labels:
        for llr, plot_label, color in zip(llrs, plot_labels, colors):
            print(plot_label)
            DET_points_FNR, DET_points_FPR = compute_DET_points(llr, L)
            ax.plot(DET_points_FNR, DET_points_FPR, color=color, label=plot_label)
    else:
        for llr, lbl, plot_label, color in zip(llrs, L, plot_labels, colors):
            DET_points_FNR, DET_points_FPR = compute_DET_points(llr, lbl)
            ax.plot(DET_points_FNR, DET_points_FPR, color=color, label=plot_label)
    ax.set_xlabel("FPR")
    ax.set_ylabel("FNR")

    ax.set_xscale('log')
    ax.set_yscale('log')

    ax.legend()
    if save_figure:
        plt.savefig(PATH, format='png')
    plt.show()

def compute_DET_points(llr, L):
    tresholds = numpy.concatenate([numpy.array([-numpy.inf]),numpy.sort(llr),numpy.array([numpy.inf])])
    N_label0 = (L == 0).sum()
    N_label1 = (L == 1).sum()
    DET_points_FNR = numpy.zeros(L.shape[0] +2 )
    DET_points_FPR = numpy.zeros(L.shape[0] +2 )
    for (idx,t) in enumerate(tresholds):
        pred = 1 * (llr > t)
        FNR = 1 - (numpy.bitwise_and(pred == 1, L == 1 ).sum() / N_label1)
        FPR = numpy.bitwise_and(pred == 1, L == 0).sum() / N_label0
        DET_points_FNR[idx] = FNR
        DET_points_FPR[idx] = FPR
    return DET_points_FNR, DET_points_FPR
# =============================================== ROC Plots ==================================================
def plot_ROC(llrs: list, labels: list, plot_labels: list, save_figure:bool = True, training:bool = True):
    training_ = "training" if training else "experimental"
    models = "-".join(plot_labels)
    PATH = f"./plots/evaluation/{training_}/ROC_{models}.png"

    for llr, plot_label in zip(llrs, plot_labels):
        ROC_points_TPR, ROC_points_FPR = compute_ROC_points(llr, labels)
        plt.plot(ROC_points_FPR, ROC_points_TPR, label=plot_label)

    plt.xlabel("FPR")
    plt.ylabel("TPR")
    plt.legend()
    plt.grid()

    if save_figure:
        plt.savefig(PATH, format='png')

    plt.show()

def compute_ROC_points(llr, L):
    tresholds = numpy.concatenate([numpy.array([-numpy.inf]),numpy.sort(llr),numpy.array([numpy.inf])])
    N_label0 = (L == 0).sum()
    N_label1 = (L == 1).sum()
    ROC_points_TPR = numpy.zeros(L.shape[0] +2 )
    ROC_points_FPR = numpy.zeros(L.shape[0] +2 )
    for (idx,t) in enumerate(tresholds):
        pred = 1 * (llr > t)
        TPR = numpy.bitwise_and(pred == 1, L == 1 ).sum() / N_label1
        FPR = numpy.bitwise_and(pred == 1, L == 0).sum() / N_label0
        ROC_points_TPR[idx] = TPR
        ROC_points_FPR[idx] = FPR
    return ROC_points_TPR, ROC_points_FPR

# =========================================================== Bayes Error Plot =============================================================
def bayes_error_plot(llrs: list, labels: list, plot_labels: list, log_regs: list, n_points:int = 100, colors: list = ['r', 'b', 'g', 'm', 'y'], save_figure: bool = True, training:bool = True, calibrated: bool = False, multiple_labels:bool = False):
    training_ = "training" if training else "experimental"
    models = "-".join(plot_labels)
    calibrated_ = "-calibrated" if calibrated else ""
    PATH = f"./plots/evaluation/{training_}/BEP_{models}{calibrated_}.png"

    max_y = 0
    if not multiple_labels:
        for llr, plot_label, log_reg, color in zip(llrs, plot_labels, log_regs, colors):
            p_array = numpy.linspace(-3, 3, n_points)
            minDCFs = dcf.bayes_error_points(p_array, llr, labels, True, log_reg)
            max_y = max(max_y, numpy.max(minDCFs))
            actDCFs = dcf.bayes_error_points(p_array, llr, labels, False, log_reg)
            max_y = max(max_y, numpy.max(actDCFs))
            plt.plot(p_array, minDCFs, label=f"{plot_label} minDCF", color=color, linestyle='dashed')
            plt.plot(p_array, actDCFs, label=f"{plot_label} actDCF", color=color)
    else:
        for llr, lbl, plot_label, log_reg, color in zip(llrs, labels, plot_labels, log_regs, colors):
            p_array = numpy.linspace(-3, 3, n_points)
            minDCFs = dcf.bayes_error_points(p_array, llr, lbl, True, log_reg)
            max_y = max(max_y, numpy.max(minDCFs))
            actDCFs = dcf.bayes_error_points(p_array, llr, lbl, False, log_reg)
            max_y = max(max_y, numpy.max(actDCFs))
            plt.plot(p_array, minDCFs, label=f"{plot_label} minDCF", color=color, linestyle='dashed')
            plt.plot(p_array, actDCFs, label=f"{plot_label} actDCF", color=color)

    title = "Bayes Error Plot"

    plt.yticks(numpy.arange(0, min(max_y+0.1, 1), 0.05))
    plt.title(title)
    plt.legend()

    if save_figure:
        plt.savefig(PATH, format='png')

    plt.show()


# This is a sample Python script.

#########################################: Please Don't Change :#######################################
import logging
import os
import sys
from datetime import datetime

sys.path.append(
    "/home/sonu/workspace/pro/component/"
)
sys.path.append(
    "/home/sonu/workspace/pro/utils/"
)
sys.path.append(
    "/home/sonu/workspace/pro/db_conn/"
)
from common import get_logger
from db_conn import DatabaseConnection

def log_setup():
    """This funtion is require for log_confi.yaml file."""
    path = os.path.dirname(os.path.realpath(__file__))
    log_dir = os.path.join(path, "log")
    os.makedirs(log_dir, exist_ok=True)
    log_path = os.path.join(path, log_dir, "running_log.log")
    filelog = logging.handlers.TimedRotatingFileHandler(
        log_path, when="midnight", backupCount=5
    )
    return filelog

#########################################: Please Code write Below :#######################################

STAGE_01 = "Connection Establish"
STAGE_02 = ""
STAGE_03 = ""
STAGE_04 = ""

def main():
    logger = get_logger(logger_name="sample")
    logger.info("main logging initialized")
    try:
        start_time = datetime.now()
        logger.info(f"<<<<<<< The start of {STAGE_01} has begun. >>>>>>>")
        database_connection = DatabaseConnection()
        snowflake_connection = database_connection.get_snowflake_connection()
        logger.info(f"<<<<<<< {STAGE_01} has been completed. >>>>>>>")

        cux = snowflake_connection.cursor()
        cux.execute("select current_timestamp();")
        result = cux.fetchone()
        logger.info(f"test connection succeed at {str(result)}")

        end_time = datetime.now()
        logger.info(
            "The project has been successfully executed, with a runtime of {0}.".format(
                end_time - start_time
            )
        )

    except Exception as e:
        logger.exception(f"getting error message {str(e)}")

if __name__ == "__main__":
    main()


from django.urls import resolve, reverse

from .. import views
from .test_recipes_base import RecipesTestBase

class RecipesSearchViewTest(RecipesTestBase):
    def test_search_view_function_is_correct(self):
        view = resolve(reverse('recipes:search'))
        self.assertIs(view.func, views.search)

    def test_search_loads_correct_template(self):
        response = self.client.get(reverse('recipes:search') + '?q=test')
        self.assertTemplateUsed(response, 'recipes/pages/search.html')

    def test_search_raises_404_if_no_search_term(self):
        response = self.client.get(reverse('recipes:search'))
        self.assertEqual(response.status_code, 404)

    def test_search_term_is_on_page_title_and_escaped(self):
        response = self.client.get(reverse('recipes:search') + '?q=<test>')
        self.assertIn('Search for "<test>"',
                      response.content.decode('utf-8'))

    def test_search_can_find_by_title(self):
        title1 = 'This is recipe one'
        title2 = 'This is recipe two'

        recipe1 = self.create_recipe(
            slug='one', title=title1, author={'username': 'one'})
        recipe2 = self.create_recipe(
            slug='two', title=title2, author={'username': 'two'})

        search_url = reverse('recipes:search')

        response1 = self.client.get(f'{search_url}?q={title1}')
        response2 = self.client.get(f'{search_url}?q={title2}')
        response3 = self.client.get(f'{search_url}?q=this')

        self.assertIn(recipe1, response1.context['recipes'])
        self.assertNotIn(recipe2, response1.context['recipes'])

        self.assertIn(recipe2, response2.context['recipes'])
        self.assertNotIn(recipe1, response2.context['recipes'])

        self.assertIn(recipe1, response3.context['recipes'])
        self.assertIn(recipe2, response3.context['recipes'])


import pygame, sys #기본세팅
import random, time #내가 추가한 것
from pygame.locals import *

#Set up pygame.
pygame.init()

#상수 정의
SCREEN =8

BLACK = (0,0,0)
GREEN = (0, 128, 0)
WHITE = (255, 255, 255)
BLUE = (0,0,255)
RED = (255,0,0)
YELLOW = (255,204,51)

screen = pygame.display.set_mode((600,400), 0,32)
pygame.display.set_caption("Othello")

#화면 세팅
screen.fill(GREEN)

#가로 줄 긋기
for x in range(0, 8):
    if x==0:
        continue
    else:
        pygame.draw.line(screen, BLACK, [0,x*50],[400,x*50],5)

#세로 줄 긋기
for y in range(0,9):
    if y==0:
        continue
    else:
        pygame.draw.line(screen, BLACK, [y*50,0],[y*50,400],5)

#오른쪽에 상태창 만들기
pygame.draw.rect(screen, WHITE, [403,0,200,400])

#각 위치에서의 블럭값들 초기화
screenArr = [] #리스트 안에 리스트. 열을 나누기 위함.

for y in range(0,SCREEN):
    colList =[]
    for x in range(0,SCREEN):
        colList.append(0)

    screenArr.append(colList)

screenArr[3][3]=2
screenArr[3][4]=1
screenArr[4][3]=1
screenArr[4][4]=2

#변수
currentTurn =1 #현재 턴- 플레이어 :1 컴퓨터 :2

diagnoalScreenArr =[] #대각선 검사를 위한 변수, 3차원 배열

for i in range(0,4):
    rowList =[]
    for y in range(0,SCREEN):
        colList =[]
        for x in range(0,SCREEN):
            colList.append(0)

        rowList.append(colList)

    diagnoalScreenArr.append(rowList)

#함수
def changeTurn(pTurn):
    if pTurn ==1: #플레이어의 턴을 컴퓨터의 턴으로 전환
        return 2
    elif pTurn ==2:
        return 1
    else:
        return -1 #오류인 경우

def changeArrxToX(arrx): #x, y를 arrx, arry로 바꿔서 리턴.
    for x in range(0,SCREEN):
        if arrx==x:
            return 25*(arrx*2+1)

def changeArryToY(arry):
    for y in range(0,SCREEN):
        if arry ==y:
            return 25*(arry*2+1)

def viewGameScreen(): #screen이 해당 값들을 가지면 해당 블럭 출력
    for arry in range(0,SCREEN):
        for arrx in range(0,SCREEN):
            if screenArr[arry][arrx] ==1: #플레이어
                pygame.draw.circle(screen, BLACK, [changeArrxToX(arrx),changeArryToY(arry)], 20)
            elif screenArr[arry][arrx] ==2: #컴퓨터
                pygame.draw.circle(screen, WHITE, [changeArrxToX(arrx),changeArryToY(arry)], 20)
            elif screenArr[arry][arrx] ==3: #컴퓨터의 블럭 랜덤위치
                pygame.draw.circle(screen, BLUE, [changeArrxToX(arrx),changeArryToY(arry)], 20)
            elif screenArr[arry][arrx] ==4: #게임이 끝난후 빈 공간이 있을 때 사용
                pygame.draw.circle(screen, GREEN, [changeArrxToX(arrx),changeArryToY(arry)], 20)

def changeMousePosXToArrx(mousePosX):
    for i in range(0,SCREEN):
        if mousePosX < 50 * (i+1) -5 and mousePosX > 50*i +5:
            return i
    else:
        return -1 #오류일 경우

def changeMousePosYToArry(mousePosY):
    for i in range(0,SCREEN):
        if mousePosY < 50 * (i+1) -5 and mousePosY > 50*i +5: #경계 안쪽
            return i
    else: #화면의 검은색 경계 부분
        return -1 #오류일 경우

def checkIfTherisBlock(pScreenArr): #해당 자리에 블럭이 현재 있는지 없는지
    #iScreenArr : screenArr을 매개변수로 받아야하는데 헷갈릴까봐
    #parameter에서 p를 따옴
    if pScreenArr == 1 or pScreenArr ==2: #플레이어 또는 컴퓨터의 블럭
        return 1 #블럭이 이미 있음을 리턴
    else:
        return 0 #블럭이 해당자리에 없음을 리턴

def setDiagonalCnt(): #대각선 검사를 위해 미리 대각선 개수 설정

    #왼쪽 위 방향 대각선
    diagonalDir =0

    for row in range(0,SCREEN):
        for col in range(7, row-1,-1):
            diagnoalScreenArr[diagonalDir][row][col]=row

        remainingCol = row
        num =0

        for col in range(0, remainingCol):
            diagnoalScreenArr[diagonalDir][row][col] = num
            num=num+1

    #오른쪽 위 방향 대각선
    diagonalDir =1

    for row in range(0,SCREEN):
        for col in range(0, SCREEN-row):
            diagnoalScreenArr[diagonalDir][row][col]=row

        remainingCol = 7 -row
        num =row

        for col in range(remainingCol, SCREEN):
            diagnoalScreenArr[diagonalDir][row][col] = num
            num = num-1

    #왼쪽 아래 방향 대각선
    diagonalDir =2

    for row in range(7, -1, -1):
        for col in range(7, 6-row, -1):
            diagnoalScreenArr[diagonalDir][row][col] = 7-row

        remainingCol = 7-row
        num =0

        for col in range(0, remainingCol):
            diagnoalScreenArr[diagonalDir][row][col] = num
            num = num+1

    #오른쪽 아래 대각선 개수
    diagonalDir =3

    for row in range(7, -1, -1):
        for col in range(0, 1+row):
            diagnoalScreenArr[diagonalDir][row][col] =7-row

        remainingCol = row+1
        num = 6-row

        for col in range(remainingCol, SCREEN):
            diagnoalScreenArr[diagonalDir][row][col] = num
            num = num-1

#setDiagonalCnt()함수 시각적 확인
##setDiagonalCnt()
##for x in range(0,8):
##    print(diagnoalScreenArr[0][x])

def InspectIfItCanBePlacedInPlace(pArrx, pArry, changeValue, pCurrentTurn): #해당 위치에 블럭을 놓을 수 있는 자리인지 검사
    returnValue=0

    if 1==checkIfTherisBlock(screenArr[pArry][pArrx]):
        return 0

    #대각선 검사
    for diagonalValue in range(0,4):
        if diagnoalScreenArr[diagonalValue][pArry][pArrx] != 0:

            if diagonalValue==0: #왼쪽 위방향
                if screenArr[pArry-1][pArrx-1] == changeTurn(pCurrentTurn):
                    for a in range(1, diagnoalScreenArr[diagonalValue][pArry][pArrx]+1):
                        if screenArr[pArry-a][pArrx-a]==0:
                            break
                        elif screenArr[pArry-a][pArrx-a] ==pCurrentTurn:
                            for b in range(1, a):
                                if changeValue ==True:
                                    screenArr[pArry-b][pArrx-b] =pCurrentTurn
                            returnValue =1
                            break

            if diagonalValue ==1: #오른쪽 위 방향
                if screenArr[pArry-1][pArrx+1] == changeTurn(pCurrentTurn):
                    for a in range(1, diagnoalScreenArr[diagonalValue][pArry][pArrx]+1):
                        if screenArr[pArry-a][pArrx+a]==0:
                            break
                        elif screenArr[pArry-a][pArrx+a]==pCurrentTurn:
                            for b in range(1, a):
                                if changeValue ==True:
                                    screenArr[pArry-b][pArrx+b]=pCurrentTurn
                            returnValue =1
                            break

            if diagonalValue ==2: #왼쪽 아래 방향
                if screenArr[pArry+1][pArrx-1] == changeTurn(pCurrentTurn):
                    for a in range(1, diagnoalScreenArr[diagonalValue][pArry][pArrx]+1):
                        if screenArr[pArry+a][pArrx-a]==0:
                            break
                        elif screenArr[pArry+a][pArrx-a]==pCurrentTurn:
                            for b in range(1, a):
                                if changeValue ==True:
                                    screenArr[pArry+b][pArrx-b]=pCurrentTurn
                            returnValue =1
                            break

            if diagonalValue ==3: #오른쪽 아래 방향
                if screenArr[pArry+1][pArrx+1] == changeTurn(pCurrentTurn):
                    for a in range(1, diagnoalScreenArr[diagonalValue][pArry][pArrx]+1):
                        if screenArr[pArry+a][pArrx+a]==0:
                            break
                        elif screenArr[pArry+a][pArrx+a]==pCurrentTurn:
                            for b in range(1, a):
                                if changeValue ==True:
                                    screenArr[pArry+b][pArrx+b]=pCurrentTurn
                            returnValue =1
                            break

    #행 검사 - 위 방향으로 검사
    if pArry != 0: #pArry가 0이면 검사할 때 리스트 인덱스 넘어감
        if screenArr[pArry-1][pArrx] == changeTurn(pCurrentTurn):
            for a in range(pArry-1, -1, -1):
                if screenArr[a][pArrx] ==0:
                    break
                elif screenArr[a][pArrx] ==pCurrentTurn:
                    for b in range(pArry-1, a,-1):
                        if changeValue ==True:
                            screenArr[b][pArrx] =pCurrentTurn
                    returnValue =1
                    break

    #행 검사 - 아래  방향으로 검사
    if pArry != SCREEN-1:
        if screenArr[pArry+1][pArrx] == changeTurn(pCurrentTurn):
            for a in range(pArry+1, SCREEN):
                if screenArr[a][pArrx] ==0:
                    break
                elif screenArr[a][pArrx]==pCurrentTurn:
                    for b in range(pArry+1, a):
                        if changeValue ==True:
                            screenArr[b][pArrx]=pCurrentTurn
                    returnValue =1
                    break

    #열 검사 - 왼쪽 방향으로 검사
    if pArrx !=0:
        if screenArr[pArry][pArrx-1] == changeTurn(pCurrentTurn):
            for a in range(pArrx-1, -1,-1):
                if screenArr[pArry][a] ==0:
                    break
                elif screenArr[pArry][a] ==pCurrentTurn:
                    for b in range(pArrx-1, a, -1):
                        if changeValue ==True:
                            screenArr[pArry][b] =pCurrentTurn
                    returnValue =1
                    break

    #열 검사 - 오른쪽 방향으로 검사
    if pArrx != SCREEN-1:
        if screenArr[pArry][pArrx+1] == changeTurn(pCurrentTurn):
            for a in range(pArrx+1, SCREEN):
                if screenArr[pArry][a] ==0:
                    break
                elif screenArr[pArry][a] ==pCurrentTurn:
                    for b in range(pArrx+1, a):
                        if changeValue ==True:
                            screenArr[pArry][b] =pCurrentTurn
                    returnValue =1
                    break

    return returnValue #놓을 수 있는 곳이  없을 경우:0   있을 경우 :1

def calculateComputerRandomPlace(randomComputerNum): #컴퓨터가 놓는 위치 랜덤으로 계산
    randNum=0
    randNum = random.randrange(1, randomComputerNum+1)
    return randNum

def setWhereComputerCanPutBlock():
    randomComputerNum =1
    tmpRow=-1
    tmpCol=-1
    noMeaningStorage=0
    computerRandomPlace =[]

    #computerRandomPlace 모두 0으로 초기화(8x8 2차원 배열)
    for y in range(0,SCREEN):
        colList =[]
        for x in range(0,SCREEN):
            colList.append(0)

        computerRandomPlace.append(colList)

    for row in range(0, SCREEN):
        for col in range(0,SCREEN):
            if InspectIfItCanBePlacedInPlace(col, row, False, currentTurn) ==1:
                computerRandomPlace[row][col] = randomComputerNum
                randomComputerNum = randomComputerNum +1

    randomComputerNum = calculateComputerRandomPlace(randomComputerNum-1) #-1하는 이유 맨 마지막에 +1돼서 끝나기 때문

    for row in range(0,SCREEN):
        for col in range(0,SCREEN):
            if computerRandomPlace[row][col] == randomComputerNum:
                screenArr[row][col] =3 #컴퓨터가 랜덤으로 놓을위치 파랑색으로 설정
                tmpRow = row
                tmpCol = col

    #컴퓨터가 랜덤으로 놓을 위치 미리 보여주기
    viewGameScreen()
    pygame.display.update()

    #해당 위치 원래 컴퓨터 블럭색으로 변경
    time.sleep(2)
    noMeaningStorage = InspectIfItCanBePlacedInPlace(tmpCol, tmpRow, True, currentTurn)
    screenArr[tmpRow][tmpCol] = 2 #컴퓨터가 랜덤으로 놓을위치 원래색인 하얀색으로 변경

    viewGameScreen()
    pygame.display.update()

def moveNextTurnWhenBlockCanNotPutPlace(): #둘 곳이 없을 경우 다음턴으로 넘어간다.
    global currentTurn
    global isClick
    cannotPutPlaceCnt =0

    for row in range(0,SCREEN):
        for col in range(0,SCREEN):
            if screenArr[row][col] == 0:
                if InspectIfItCanBePlacedInPlace(col,row,False, currentTurn)==1:
                    cannotPutPlaceCnt = cannotPutPlaceCnt+1

    if cannotPutPlaceCnt ==0 :
        currentTurn = changeTurn(currentTurn)
        print(currentTurn,"의 유저가 놓을 곳이 없습니다. ")
        clearStateScreen(False)
        printTurnInformation() #플레이어 -> 컴퓨터 턴 : 컴퓨터 턴 출력
        time.sleep(1)

def viewGameResult():
    font = pygame.font.SysFont("arial",20,True)
    playerBlockCnt =0
    computerBlockCnt =0

    for row in range(0,SCREEN):
        for col in range(0,SCREEN):
            if screenArr[row][col] ==1:
                playerBlockCnt = playerBlockCnt+1
            elif screenArr[row][col] ==2:
                computerBlockCnt = computerBlockCnt+1
            screenArr[row][col] = 4

    tmpBlockCnt =0
    isFirstCheck = False

    for row in range(0,SCREEN):
        for col in range(0,SCREEN):
            if (tmpBlockCnt < playerBlockCnt) and isFirstCheck == False:
                screenArr[row][col] =1
                tmpBlockCnt = tmpBlockCnt+1
            else:
                if isFirstCheck == False:
                    isFirstCheck = True
                    tmpBlockCnt =0
                if tmpBlockCnt < computerBlockCnt:
                    screenArr[row][col] =2
                    tmpBlockCnt = tmpBlockCnt+1

    print("컴퓨터 블럭 개수 : ", computerBlockCnt)
    print("플레이어 블럭 개수 : ", playerBlockCnt)
    print("tmpBlockCnt : ", tmpBlockCnt)

    clearStateScreen(True)

    if computerBlockCnt < playerBlockCnt:
        printWinner("Player")
    elif computerBlockCnt > playerBlockCnt:
        printWinner("Computer")
    else: #동점
        printWinner("Draw")

    viewGameScreen()
    printBlockCnt(playerBlockCnt, computerBlockCnt)
    pygame.display.update()
    print("개수 출력화면까지 끝")
    time.sleep(3)
    #이후 다시 게임을 다시할지 시작화면으로갈지 끌지 선택.
    sys.exit()

def ifNoOneDoNotPutBlock():
    enablePutBlock= [True,True]

    for row in range(0,SCREEN):
        for col in range(0,SCREEN):
            #플레이어 검사와 검퓨터 모두 블럭을 둘 곳이 없을 경우
            if 1==InspectIfItCanBePlacedInPlace(col,row,False,1):
                #print("플레이어 : (",row,col,") : 0")
                enablePutBlock[0] = False
            if 1==InspectIfItCanBePlacedInPlace(col,row,False,2):
                #print("컴퓨터   : (",row,col,") : 0")
                enablePutBlock[1] = False

    if enablePutBlock[0] ==True and enablePutBlock[1] ==True:
        return True
    else:
        return False

def checkGameOver():
    spaceFilledCnt =0

    for row in range(0,SCREEN):
        for col in range(0,SCREEN):
            if screenArr[row][col] ==1 or screenArr[row][col] ==2:
                spaceFilledCnt= spaceFilledCnt+1

    if spaceFilledCnt == SCREEN * SCREEN or ifNoOneDoNotPutBlock() == True:
        clearStateScreen(True)
        printGameOverText()
        printCalculateGameResult()
        time.sleep(5) #결과 집계중 5초동안 띄운 뒤 결과 보여주기
        viewGameResult()

def printTurn(pTurn):
    if pTurn ==1:
        return "Player"
    elif pTurn ==2:
        return "Computer"
    else:
        return "Error"

def clearStateScreen(isGameOver):
    clearScreenScaleY =145

    if isGameOver == True:
        clearScreenScaleY = 400

    pygame.draw.rect(screen, WHITE, [403,0,200,clearScreenScaleY])
    pygame.display.update()

def printTurnInformation():
    userTextFont = pygame.font.SysFont("arial",20, True)
    userTextContentFont = pygame.font.SysFont("arial",20)

    userText = userTextFont.render("Current Turn : ", True, BLACK)
    userTextContent = userTextContentFont.render(printTurn(currentTurn), True, BLACK)

    screen.blit(userText, (410,100))
    screen.blit(userTextContent, (525,100))
    pygame.display.update()

def printUserColorInformation():
    font = pygame.font.SysFont("arial",20,True)
    playerColor = font.render("Player Color : ", True, BLACK)
    computerColor = font.render("Computer Color : ", True, BLACK)

    screen.blit(playerColor, (410,150))
    screen.blit(computerColor, (410,200))

    pygame.draw.rect(screen, GREEN, (548, 148, 30, 30))
    pygame.draw.circle(screen, BLACK, [563, 163], 10)
    pygame.draw.rect(screen, GREEN, (548, 198, 30, 30))
    pygame.draw.circle(screen, WHITE, [563, 213], 10)

    pygame.display.update()

def printGameOverText():
    font = pygame.font.SysFont("arial",30,True)
    text = font.render("-Game Over-", True, RED)

    screen.blit(text, (425,50))
    pygame.display.update()

def printCalculateGameResult(): #게임 결과 계산중 이라고 출력
    font = pygame.font.SysFont("arial",15)
    text = font.render("~Calculating Game Result~", True, BLACK)

    screen.blit(text, (425,100))
    pygame.display.update()

def printWinner(winner):

    winnerFont = pygame.font.SysFont("arial",40)
    winnerContentFont = pygame.font.SysFont("arial",30)

    if winner != "Draw":
        winnerText = winnerFont.render("Winner", True, RED)
    else:
        winnerText = winnerFont.render("Result", True, RED)
    winnerContentText = winnerContentFont.render("-"+winner+"-", True, YELLOW)

    screen.blit(winnerText, (450,50))
    if winner == "Computer":
        screen.blit(winnerContentText, (440,100))
    elif winner == "Plyaer":
        screen.blit(winnerContentText, (460,100))
    else:
        screen.blit(winnerContentText, (460,100))
    pygame.display.update()

def printBlockCnt(playerBlockCnt, computerBlockCnt):
    font = pygame.font.SysFont("arial",20)

    playerBlockCntText = font.render("Player Block : "+ str(playerBlockCnt), True, BLACK)
    computerBlockCntText = font.render("Computer Block : " + str(computerBlockCnt), True, BLACK)

    screen.blit(playerBlockCntText, (440,200))
    screen.blit(computerBlockCntText, (430,225))
    pygame.display.update()

def printReplayButton():
    font = pygame.font.SysFont("arial",40)
    replayBtnText = font.render("Replay", True, WHITE,2)
    screen.blit(replayBtnText, (100,200))

def printGoStartScreenButton():
    font = pygame.font.SysFont("arial",40)
    goStartScreenBtnText = font.render("Go StartScreen", True, WHITE,2)
    screen.blit(goStartScreenBtnText, (300,200))

#둘다 블럭을  놓을 수 없는 경우
##for row in range(0,SCREEN):
##        for col in range(0,SCREEN):
##            screenArr[row][col] =2
##screenArr[2][6] =1
##screenArr[2][2] =1
##screenArr[3][3] =1
##screenArr[4][4] =1
##screenArr[4][6] =1
##screenArr[5][5] =1
##screenArr[7][7] =1
##screenArr[6][7] =0

##
##for row in range(0,SCREEN):
##    for col in range(0,SCREEN):
##        screenArr[row][col] =2
##
##screenArr[2][2]=1
##screenArr[1][0]=0
##screenArr[2][0]=0
##screenArr[3][0]=0

setDiagonalCnt()
viewGameScreen()
printTurnInformation()
printUserColorInformation()

printReplayButton()
printGoStartScreenButton()

#Game Loop
while True:
    checkGameOver()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            mousePosToArr = []
            mousePosToArr.append(changeMousePosXToArrx(pygame.mouse.get_pos()[0]))
            mousePosToArr.append(changeMousePosYToArry(pygame.mouse.get_pos()[1]))

            if not(mousePosToArr[0] ==-1 or mousePosToArr[1] ==-1):
                if InspectIfItCanBePlacedInPlace(mousePosToArr[0],mousePosToArr[1], True, currentTurn) ==1:
                    mousePos = pygame.mouse.get_pos() #자료형 : tuple
                    screenArr[changeMousePosYToArry(mousePos[1])][changeMousePosXToArrx(mousePos[0])] =1 #클릭한 곳 색깔 바꾸기
                    currentTurn = changeTurn(currentTurn) #턴 바꾸기
                    clearStateScreen(False)
                    printTurnInformation() #플레이어 -> 컴퓨터 턴 : 컴퓨터 턴 출력

    viewGameScreen()
    pygame.display.update()

    moveNextTurnWhenBlockCanNotPutPlace()

    if currentTurn ==2 :
        time.sleep(2)
        setWhereComputerCanPutBlock()
        currentTurn = changeTurn(currentTurn)
        clearStateScreen(False)
        printTurnInformation() #컴퓨터 -> 플레이어 턴 : 컴퓨터 턴 출력


print('1')

#from src.__init__ import main

from flask import Flask, request
from flask_restx import Api, Namespace, fields, Resource

## local
from settings import model_path, vocab_path, cnn_path
from torch import nn

# from src.controller.analyzeController import Analyze
from src.controller.keywordController import Keyword
from src.controller.testController import Sample
from src.controller.divideHighlightController import Divide_Highlight

if __name__ == "__main__" :
    from load_models import koBERT_CNN_Classifier
    prediction = koBERT_CNN_Classifier(model_path=model_path, vocab_path=vocab_path, cnn_path=cnn_path)
    # app.run(debug=True, host='0.0.0.0')

class Classifier(nn.Module):
    def __init__(self,
                     hidden_size=768,
                     num_classes=8,
                     dr_rate=0.0):
        super(Classifier, self).__init__()
            # 16, 2848
            # 32, 5696
            # 1312
        self.kernel_num = 16
        self.conv1d_maxpooling1 = nn.Sequential(
                nn.Conv1d(hidden_size, self.kernel_num, 4, stride=2),
                nn.ReLU(),
                nn.MaxPool1d(2, 1),
                nn.Dropout(dr_rate)
            )
        self.conv1d_maxpooling2 = nn.Sequential(
                nn.Conv1d(hidden_size, self.kernel_num, 8, stride=2),
                nn.ReLU(),
                nn.MaxPool1d(2, 1),
                nn.Dropout(dr_rate)
            )
        self.conv1d_maxpooling3 = nn.Sequential(
                nn.Conv1d(hidden_size, self.kernel_num, 16, stride=2),
                nn.ReLU(),
                nn.MaxPool1d(2, 1),
                nn.Dropout(dr_rate)
            )

        self.classifier = nn.Linear(1312, num_classes)

    def forward(self, x) :
        out1 = self.conv1d_maxpooling1(x.transpose(1, 2))
        out2 = self.conv1d_maxpooling2(x.transpose(1, 2))
        out3 = self.conv1d_maxpooling3(x.transpose(1, 2))
        out = torch.cat((out1, out2, out3), 2)
        out = out.reshape(out.size(0), -1)
        return  self.classifier(out)

#from load_models import koBERT_CNN_Classifier
from settings import model_path, cnn_path, vocab_path

from torch import nn
import torch

from src.preprocessor.textPreprocessor import textPreprocessor

print('2')

app = Flask(__name__)
api = Api(
    app,
    version='0.1',
    title="PS HELPER API Server",
    description="PS HELPER API 문서입니다.",
    terms_url="/",
    contact_url="donghoon149@gmail.com / hmcck27@gmail.com",
    license="MIT"
)

Analyze = Namespace(
    name="Analyze Algorithm",
    description='문제 지문을 받고 적절한 알고리즘 태그를 반환합니다.',
)

api.add_namespace(Divide_Highlight, '/api/v1/divide_highlight')
api.add_namespace(Keyword, '/api/v1/keyword')
api.add_namespace(Analyze, '/api/v1/analyze')
api.add_namespace(Sample, '/api/v1/test')

# Model 객체 생성
analyze_fields = Analyze.model('Problem', {
    'problem_id': fields.Integer(description='문제 번호', required=True, example="1007"),
    'content': fields.String(description='문제 지문', required=True,
                             example="평면 상에 N개의 점이 찍혀있고, 그 점을 집합 P라고 하자. 하지만 집합 P의 벡터 매칭은 벡터의 집합인데, 모든 벡터는 집합 P의 한 점에서 시작해서, 또 다른 점에서 끝나는 벡터의 집합이다. 또, P에 속하는 모든 점은 한 번씩 쓰여야 한다.V에 있는 벡터의 개수는 P에 있는 점의 절반이다.평면 상의 점이 주어졌을 때, 집합 P의 벡터 매칭에 있는 벡터의 합의 길이의 최솟값을 출력하는 프로그램을 작성하시오."),
    'input': fields.String(description='문제 입력사항', required=False,
                           example="첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 다음과 같이 구성되어있다. 테스트 케이스의 첫째 줄에 점의 개수 N이 주어진다. N은 짝수이다. 둘째 줄부터 N개의 줄에 점의 좌표가 주어진다. N은 20보다 작거나 같은 자연수이고, 좌표는 절댓값이 100,000보다 작거나 같은 정수다. 모든 점은 서로 다르다."),
})

algorithm_fields = fields.Wildcard(fields.String)

analyze_response = Analyze.model('Problem_response', {
    'problem_id': fields.String(description='문제 번호', required=True, example="1007"),
    'problem_url': fields.String(description="문제 url", required=True, example="www.psHelper.de"),
    'algorithm_type': algorithm_fields
})

''' test '''
print('sdfsdfsdfsdf')

@Analyze.route('')
class AnalyzeController(Resource):

    @Analyze.expect(analyze_fields)
    @Analyze.response(201, "Success", analyze_response)
    def post(self):
        content = request.json.get('content')
        text_preprocessor = textPreprocessor()
        '''
            TO-DO
            0. preprocess text
            1. analyze the description
        '''
        preprocessed_text = text_preprocessor.preprocessing(content)
        # tag = TagAnalyzer.findTag(preprocessed_text)
        tag,ratio = prediction.predict(preprocessed_text)
        # print(content)

        return {
                   'problem_id': request.json.get('problem_id'),
                   'problem_url': "https://www.acmicpc.net/problem/" + str(request.json.get('problem_id')),
                   'algorithm_type' : tag,
                   'algorithm_ratio' : ratio
               }, 201

print('sdfsdfwerwer')

# class Classifier(nn.Module):
#     def __init__(self,
#                  hidden_size=768,
#                  num_classes=8,
#                  dr_rate=0.0):
#         super(Classifier, self).__init__()
#         # 16, 2848
#         # 32, 5696
#         # 1312
#         self.kernel_num = 16
#         self.conv1d_maxpooling1 = nn.Sequential(
#             nn.Conv1d(hidden_size, self.kernel_num, 4, stride=2),
#             nn.ReLU(),
#             nn.MaxPool1d(2, 1),
#             nn.Dropout(dr_rate)
#         )
#         self.conv1d_maxpooling2 = nn.Sequential(
#             nn.Conv1d(hidden_size, self.kernel_num, 8, stride=2),
#             nn.ReLU(),
#             nn.MaxPool1d(2, 1),
#             nn.Dropout(dr_rate)
#         )
#         self.conv1d_maxpooling3 = nn.Sequential(
#             nn.Conv1d(hidden_size, self.kernel_num, 16, stride=2),
#             nn.ReLU(),
#             nn.MaxPool1d(2, 1),
#             nn.Dropout(dr_rate)
#         )
#
#         self.classifier = nn.Linear(1312, num_classes)
#
#     def forward(self, x) :
#       out1 = self.conv1d_maxpooling1(x.transpose(1, 2))
#       out2 = self.conv1d_maxpooling2(x.transpose(1, 2))
#       out3 = self.conv1d_maxpooling3(x.transpose(1, 2))
#       out = torch.cat((out1, out2, out3), 2)
#       out = out.reshape(out.size(0), -1)
#       return  self.classifier(out)

#if __name__ == "__main__":
#    app.run(debug=True, host='0.0.0.0')


import logging

logger = logging.getLogger(__name__)

def app(environ, start_response):
    path = environ.get('PATH_INFO', '')
    if path == '/exception':
        raise Exception('My exception!')

    data = "Request on %s \n" % path
    logger.info(data, extra={'tags': ['role:web', 'env:prod']})
    start_response("200 OK", [
          ("Content-Type", "text/plain"),
          ("Content-Length", str(len(data)))
      ])
    return iter([data])


import sqlite3
import time
from telethon import TelegramClient
from telethon import sync, events
import re
import json

db = sqlite3.connect('Account.db')
cur = db.cursor()

x = 1
m = 0

while(True):
    if x == 23:
        print("Всего добыто:")
        print(m)
        break
    cur.execute(f"SELECT PHONE FROM Account WHERE ID = '{x}'")
    time.sleep(0.4)
    Phone = str(cur.fetchone()[0])
    print("Входим в аккаунт: " + Phone)

    cur.execute(f"SELECT API_ID FROM Account WHERE ID = '{x}'")
    time.sleep(0.4)
    api_id = str(cur.fetchone()[0])
    cur.execute(f"SELECT API_HASH FROM Account WHERE ID = '{x}'")
    time.sleep(0.4)
    api_hash = str(cur.fetchone()[0])
    session = str("anon" + str(x))
    client = TelegramClient(session, api_id, api_hash)
    client.start()

    dlgs = client.get_dialogs()
    for dlg in dlgs:
        if dlg.title == 'LTC Click Bot':
            tegmo = dlg

    client.send_message('LTC Click Bot', "/balance")
    time.sleep(3)
    msgs = client.get_messages(tegmo, limit=1)

    for mes in msgs:
        str_a = str(mes.message)
        zz = str_a.replace('Available balance: ', '')
        qq = zz.replace(' LTC', '')
        print(qq)
        waitin = float(qq)

    m = m + waitin
    #print(m)
    x = x + 1
    time.sleep(1)


#! /usr/bin/env python
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile # get the api
from scipy.signal import fftconvolve, convolve, stft, butter
import numpy as np
from scipy import signal
import warnings
warnings.filterwarnings("ignore")

from numpy import array, diff, where, split
from scipy import arange

# fs, data = wavfile.read('Ding.wav') # load OG file
# a = data.T[0]

# fs2, data2 = wavfile.read('Long.wav') # load the data
# a2 = data2.T[0]

# d = fftconvolve(a, a2)
# print(d.shape)
# for i in range(len(d)):
# 	if d[i] > 0.85: #Tune this for the DING
# 		print('Do something')
# 		break
# plt.plot(d)
# plt.show()

#import keyboard

def findPeak(magnitude_values, noise_level=2000):

    splitter = 0
    # zero out low values in the magnitude array to remove noise (if any)
    magnitude_values = np.asarray(magnitude_values)
    low_values_indices = magnitude_values < noise_level  # Where values are low
    magnitude_values[low_values_indices] = 0  # All low values will be zero out

    indices = []

    flag_start_looking = False

    both_ends_indices = []

    length = len(magnitude_values)
    for i in range(length):
        if magnitude_values[i] != splitter:
            if not flag_start_looking:
                flag_start_looking = True
                both_ends_indices = [0, 0]
                both_ends_indices[0] = i
        else:
            if flag_start_looking:
                flag_start_looking = False
                both_ends_indices[1] = i
                # add both_ends_indices in to indices
                indices.append(both_ends_indices)

    return indices

def extractFrequency(indices, freq_bins, freq_threshold=2):

    extracted_freqs = []

    for index in indices:
        freqs_range = freq_bins[index[0]: index[1]]
        avg_freq = round(np.average(freqs_range))

        if avg_freq not in extracted_freqs:
            extracted_freqs.append(avg_freq)

    # group extracted frequency by nearby=freq_threshold (tolerate gaps=freq_threshold)
    group_similar_values = split(extracted_freqs, where(diff(extracted_freqs) > freq_threshold)[0]+1 )

    # calculate the average of similar value
    extracted_freqs = []
    for group in group_similar_values:
        extracted_freqs.append(round(np.average(group)))

    #print("freq_components", extracted_freqs)
    return extracted_freqs

import pyaudio

ding_left = np.load('ding_select_floor2_left_mic.npy')
ding_right = np.load('ding_select_floor7_right_mic.npy')

CHUNK = 4096 # number of data points to read at a time
RATE = 48000 # time resolution of the recording device (Hz)

p=pyaudio.PyAudio() # start the PyAudio class
stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
              frames_per_buffer=CHUNK) #uses default input device

while 1:
	data_buffer = np.array([])
	# create a numpy array holding a single read of audio data
	for i in range(10): #to it a few times just to see
	    data = np.frombuffer(stream.read(CHUNK),dtype=np.int16)
	    data_buffer = np.concatenate([data_buffer, data])

	fs = RATE
	# f1, t1, ding_left2 = signal.stft(ding_left, fs, nperseg=1000)
	# f2, t2, ding_right2 = signal.stft(ding_right, fs, nperseg=1000)
	# f,t,data_buffer2= signal.stft(data_buffer, fs, nperseg=1000)

	number_samples = len(data_buffer)

	freq_bins = arange(number_samples) * RATE/number_samples

	#ding_left2 = fft(ding_left)
	#ding_right2 = fft(ding_right)
	data_buffer_fft = fft(data_buffer)
	#data_buffer_fft = np.fft.fftfreq(len(data_buffer), data_buffer)
	#print(data_buffer2)

	normalization_data = data_buffer_fft/number_samples
	magnitude_values = normalization_data[range(len(data_buffer_fft)//2)]
	magnitude_values = np.abs(magnitude_values)

	indices = findPeak(magnitude_values=magnitude_values, noise_level=100)
	frequencies = extractFrequency(indices, freq_bins)

	#print(frequencies)

	# amp = 2 * np.sqrt(2)
	# plt.pcolormesh(t1, f1, np.abs(ding_left), vmin=0)
	# plt.pcolormesh(t2, f2, np.abs(ding_right), vmin=0)
	# plt.ylabel('Frequency [Hz]')
	# plt.xlabel('Time [sec]')
	# plt.show()
	#x = np.abs(data_buffer2).mean()
	x = max(frequencies)
	#x = x/1000
	print(x)
	if x > 750 and x < 800:
		print("RIGHT DING MAYBE")
	# if x > 270 and x < 350:
	# 	print("LEFT DING MAYBE")
	# if x > 1300 and x < 1400:
	# 	print("RIGHT DING MAYBE")
	# if x > 500 and x < 550:
	# 	print("LEFT DING MAYBE")

	#print(np.abs(data_buffer).max())
	# d_left = convolve(ding_left, data_buffer)
	# d_right = convolve(ding_right, data_buffer)

	# dlmax = d_left.mean()
	# drmax = d_right.mean()
	#print("left ding is:" +str(dlmax) + "right ding is:" +str(drmax))
	#print("right new is:" + str(d_right_fft.mean()))
	#FLOOR 7
	# if dlmax > 20173224741.999992:
	# 	print('Left DING')
	# if drmax > 30888468567.000004:
	# 	print('Right DING')
	# if dlmax > 10008361056.999992:
	# 	print('Left DING')
	# if drmax > 2000511377.789566:

	# 	print('Right DING')

# data_buffer = np.load('ding2.npy')[73000: 130000]

# np.save('ding_select.npy', data_buffer)
# plt.plot(data_buffer)
# plt.show()
# d = fftconvolve(a, data)
# plt.plot(d)
# print(d.max())
# plt.show()

# close the stream gracefully
stream.stop_stream()
stream.close()
p.terminate()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('user_profile', '0003_remove_userprofile_title'),
    ]

    operations = [
        migrations.CreateModel(
            name='RegistrationPath',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=100)),
            ],
        ),
        migrations.AlterField(
            model_name='userprofile',
            name='mobile_number',
            field=models.CharField(max_length=11, null=True, blank=True),
        ),
        migrations.AddField(
            model_name='userprofile',
            name='registration_path',
            field=models.ForeignKey(blank=True, to='user_profile.RegistrationPath', null=True),
        ),
    ]


import os
import cv2 as cv
import numpy as np

people = []

for i in os.listdir(r'C:\Users\Atul\Downloads\OpenCV_course\opencv-course-master\Resources\Faces\train'):
    people.append(i)  #each folder in the faces folder corresponds to one person ben affleck,mindy,etc and name of folder is person's name so we store target variables

DIR = r'C:\Users\Atul\Downloads\OpenCV_course\opencv-course-master\Resources\Faces\train'

haar_cascade = cv.CascadeClassifier('haar_face.xml')  #calling haarcascade detector

# Creating the training set
features = []
labels = []

def create_train():  #loop over all folders in the training folder and then loop over all images within and store in training set. Within each image detect only the face and crop it out using haarcascade face detector
    for person in people:
        path = os.path.join(DIR, person)   #to get path for folder of each person
        label = people.index(person)  #text classes need to be converted to numerical categories

        for img in os.listdir(path):
            img_path = os.path.join(path, img)  #create path for each image in each person's folder

            img_array = cv.imread(img_path)
            gray = cv.cvtColor(img_array, cv.COLOR_BGR2GRAY)

            faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors=4)

            for (x,y,w,h) in faces_rect:
                faces_roi = gray[y:y+h ,x:x+w]   #cropping out just the face from the image

                features.append(faces_roi)
                labels.append(label)

create_train()
print('Training data created -------------')

features = np.array(features, dtype='object')  #all pixels of each image are flattened out to a single row of all pixel values for an image
labels = np.array(labels)

face_recognizer = cv.face.LBPHFaceRecognizer_create()  #instantiating out in-built face recognizer model

# Train recognizer on features list and labels list
face_recognizer.train(features,labels)

face_recognizer.save('face_trained.yml')  # OpenCv allows us to save our trained model as a yaml which can be reused in other files instead of going through the entire training process again
np.save('features.npy', features)
np.save('labels.npy', labels)


from unittest import mock

import bson
import pytest

from test.tools import anything, in_any_order
from slivka import JobStatus
from slivka.db.documents import JobRequest, ServiceState
from slivka.db.helpers import delete_many, insert_many, pull_many
from slivka.scheduler import Runner, Scheduler
from slivka.scheduler.runners import Job, RunnerID
from slivka.scheduler.scheduler import (
    ERROR,
    REJECTED,
    ExecutionDeferred,
    ExecutionFailed,
)

def new_runner(service, name, command=None, args=None, env=None):
    return Runner(
        RunnerID(service, name),
        command=command or [],
        args=args or [],
        outputs=[],
        env=env or {},
    )

@pytest.fixture()
def mock_batch_start():
    with mock.patch.object(Runner, "batch_start") as mock_method:
        yield mock_method

@pytest.fixture()
def mock_check_status():
    with mock.patch.object(Runner, "check_status") as mock_method:
        yield mock_method

@pytest.fixture()
def mock_submit():
    with mock.patch.object(Runner, "submit") as mock_method:
        yield mock_method

def test_group_requests(job_directory):
    scheduler = Scheduler(job_directory)
    runner1 = new_runner("example", "runner1")
    runner2 = new_runner("example", "runner2")
    scheduler.add_runner(runner1)
    scheduler.add_runner(runner2)
    scheduler.selectors["example"] = lambda inputs: inputs.get("use")

    requests = [
        JobRequest(service="example", inputs={"use": "runner1"}),
        JobRequest(service="example", inputs={"use": "runner2"}),
        JobRequest(service="example", inputs={"use": None}),
        JobRequest(service="example", inputs={"use": "runner1"}),
    ]
    grouped = scheduler.group_requests(requests)
    assert grouped == {
        runner1: in_any_order(requests[0], requests[3]),
        runner2: in_any_order(requests[1]),
        REJECTED: in_any_order(requests[2]),
    }

def test_group_requests_if_runner_does_not_exist(job_directory):
    scheduler = Scheduler(job_directory)
    runner1 = new_runner("example", "runner1")
    scheduler.add_runner(runner1)
    scheduler.selectors["example"] = lambda inputs: "runner2"

    requests = [JobRequest(service="example", inputs={})]
    grouped = scheduler.group_requests(requests)
    assert grouped == {ERROR: in_any_order(*requests)}

def create_requests(count=1, service="example"):
    return [
        JobRequest(
            _id=bson.ObjectId(), service=service, inputs={"input": "val%d" % i}
        )
        for i in range(count)
    ]

def test_start_requests_if_successful_start(job_directory, mock_batch_start):
    scheduler = Scheduler(job_directory)
    runner = new_runner("example", "example")
    requests = [
        JobRequest(
            _id=bson.ObjectId(), service="example", inputs={"input": "val"}
        ),
        JobRequest(
            _id=bson.ObjectId(), service="example", inputs={"input": "val2"}
        ),
    ]
    mock_batch_start.side_effect = lambda inputs, cwds: (
        [Job("%04x" % i, cwd) for i, cwd in enumerate(cwds)]
    )
    started = scheduler._start_requests(runner, requests)
    assert started == in_any_order(
        *((req, Job("%04x" % i, anything())) for i, req in enumerate(requests))
    )

def test_start_requests_deferred_execution_if_error_raised(
    job_directory, mock_batch_start
):
    scheduler = Scheduler(job_directory)
    runner = new_runner("example", "example")
    requests = create_requests(2)
    mock_batch_start.side_effect = OSError
    with pytest.raises(ExecutionDeferred):
        scheduler._start_requests(runner, requests)

def test_start_request_failed_execution_if_too_many_errors_raised(
    job_directory, mock_batch_start
):
    scheduler = Scheduler(job_directory)
    runner = new_runner("example", "example")
    requests = create_requests(3)
    scheduler.set_failure_limit(0)
    mock_batch_start.side_effect = OSError
    with pytest.raises(ExecutionFailed):
        scheduler._start_requests(runner, requests)

class TestJobStatusUpdates:
    @pytest.fixture()
    def requests(self, database):
        requests = create_requests(5)
        insert_many(database, requests)
        yield requests
        delete_many(database, requests)

    @pytest.fixture()
    def scheduler(self, job_directory):
        scheduler = Scheduler(job_directory)
        runner = new_runner("example", "example")
        scheduler.add_runner(runner)
        scheduler.selectors["example"] = lambda inputs: "example"
        return scheduler

    @pytest.mark.parametrize("status", list(JobStatus))
    def test_check_status_updates_requests(
        self,
        scheduler,
        requests,
        database,
        mock_batch_start,
        mock_check_status,
        status,
    ):
        # must start the job, before moving to status check stage
        mock_batch_start.side_effect = lambda inputs, cwds: (
            [Job("%04x" % i, cwd) for i, cwd in enumerate(cwds)]
        )
        mock_check_status.return_value = status
        scheduler.main_loop()
        pull_many(database, requests)
        assert all(req.state == status for req in requests)

    def test_submit_deferred_job_status_not_updated(
        self, scheduler, requests, database, mock_submit
    ):
        mock_submit.side_effect = OSError
        scheduler.main_loop()
        pull_many(database, requests)
        assert all(req.state == JobStatus.ACCEPTED for req in requests)

    def test_submit_failed_job_status_set_to_error(
        self, scheduler, requests, database, mock_submit
    ):
        mock_submit.side_effect = OSError
        scheduler.set_failure_limit(0)
        scheduler.main_loop()
        pull_many(database, requests)
        assert all(req.state == JobStatus.ERROR for req in requests)

class TestServiceStatusUpdates:
    @pytest.fixture(autouse=True)
    def requests(self, database):
        requests = create_requests(5)
        insert_many(database, requests)
        yield requests
        delete_many(database, requests)

    @pytest.fixture()
    def scheduler(self, job_directory):
        scheduler = Scheduler(job_directory)
        runner = new_runner("example", "default")
        scheduler.add_runner(runner)
        return scheduler

    def test_service_start_successful(
        self, database, scheduler, mock_submit, mock_check_status
    ):
        mock_submit.side_effect = lambda cmd: Job("0x00", cmd.cwd)
        mock_check_status.return_value = JobStatus.QUEUED
        scheduler.main_loop()
        state = ServiceState.find_one(
            database, service="example", runner="default"
        )
        assert state.state == ServiceState.OK

    def test_service_start_soft_fail(self, database, scheduler, mock_submit):
        mock_submit.side_effect = OSError
        scheduler.main_loop()
        state = ServiceState.find_one(
            database, service="example", runner="default"
        )
        assert state.state == ServiceState.WARNING

    def test_service_start_hard_fail(self, database, scheduler, mock_submit):
        scheduler.set_failure_limit(0)
        mock_submit.side_effect = OSError
        scheduler.main_loop()
        state = ServiceState.find_one(
            database, service="example", runner="default"
        )
        assert state.state == ServiceState.DOWN

    @pytest.mark.xfail(reason="service status should not rely on erroneous jobs")
    def test_service_check_status_returned_all_errors(
        self, database, scheduler, mock_submit, mock_check_status
    ):
        mock_submit.side_effect = lambda cmd: Job("0x00", cmd.cwd)
        mock_check_status.return_value = JobStatus.ERROR
        scheduler.main_loop()
        state = ServiceState.find_one(
            database, service="example", runner="default"
        )
        assert state.state == ServiceState.DOWN

    def test_service_check_status_throws_exception(
        self, database, scheduler, mock_submit, mock_check_status
    ):
        mock_submit.side_effect = lambda cmd: Job("0x00", cmd.cwd)
        mock_check_status.side_effect = Exception
        scheduler.main_loop()
        state = ServiceState.find_one(
            database, service="example", runner="default"
        )
        assert state.state == ServiceState.WARNING


from django.urls import path
from . import views

# register app namespace which is going to be used in URL names
app_name = "my_app"

urlpatterns = [
    path("", views.example_view, name="example"),
    path("variable/", views.variable_view, name="variable")
]


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

from __future__ import division, print_function, unicode_literals

__all__ = ["IterativeTwoDSearch"]

import os
import h5py
import numpy as np

from .two_d_search import TwoDSearch
from ._grid_search import grid_search

class IterativeTwoDSearch(TwoDSearch):

    cache_ext = ".h5"
    query_parameters = dict(
        min_period=(None, True),
        max_period=(None, True),
        delta_log_period=(None, False),
        dt=(None, False),
        alpha=(None, False),
        npeaks=(3, False),
        mask_frac=(2.0, False),
        min_points=(500, False),
        min_transits=(3, False),
    )

    def get_alpha(self, query, parent_response):
        a = query.get("alpha", None)
        if a is not None:
            return float(a)
        lcs = parent_response.model_light_curves
        n = sum(len(lc.time) for lc in lcs)
        k = parent_response.nbasis
        return k * np.log(n)

    def get_result(self, query, parent_response):
        periods = self.get_period_grid(query, parent_response)
        dt = self.get_offset_spacing(query, parent_response)
        alpha = self.get_alpha(query, parent_response)

        # Get the parameters of the time grid from the 1-d search.
        time_spacing = parent_response.time_spacing
        mean_time = parent_response.mean_time_1d
        tmin = parent_response.min_time_1d - mean_time
        tmax = parent_response.max_time_1d - mean_time
        time_grid = np.arange(0, tmax-tmin, time_spacing)

        # Get the results of the 1-d search.
        depth_1d = np.array(parent_response.depth_1d)
        depth_ivar_1d = np.array(parent_response.depth_ivar_1d)
        dll_1d = np.array(parent_response.dll_1d)

        # Find the peaks.
        peaks = []
        for _ in range(query["npeaks"]):
            # Run a 2D search.
            results = grid_search(query["min_transits"], alpha,
                                  tmin, tmax, time_spacing, depth_1d,
                                  depth_ivar_1d, dll_1d, periods, dt)
            (t0_2d, phic_same, phic_same_2, phic_variable, depth_2d,
             depth_ivar_2d) = results

            # Profile over duration.
            inds = np.arange(len(phic_same)), np.argmax(phic_same, axis=1)
            t0_2d = t0_2d[inds]
            depth_2d = depth_2d[inds]
            depth_ivar_2d = depth_ivar_2d[inds]
            phic_same = phic_same[inds]
            phic_variable = phic_variable[inds]
            phic_same_2 = phic_same_2[inds]

            # Find the top peak.
            s2n = depth_2d * np.sqrt(depth_ivar_2d)
            top_peak = np.argmax(s2n)
            p, t0 = periods[top_peak], t0_2d[top_peak]
            duration = query["durations"][inds[1][top_peak]]

            # Save the peak.
            peaks.append(dict(
                period=p, t0=(t0 + tmin + mean_time) % p,
                duration=duration,
                depth=depth_2d[top_peak],
                depth_ivar=depth_ivar_2d[top_peak],
                s2n=s2n[top_peak],
                phic_same=phic_same[top_peak],
                phic_same_second=phic_same_2[top_peak],
                phic_variable=phic_variable[top_peak],
                duty_cycle=np.sum(depth_ivar_1d > 0.0) / len(depth_ivar_1d),
                data_span=tmax - tmin,
            ))

            # Mask out these transits.
            m = (np.abs((time_grid-t0+0.5*p) % p-0.5*p)
                 < query["mask_frac"]*duration)
            depth_1d[m] = 0.0
            depth_ivar_1d[m] = 0.0
            dll_1d[m] = 0.0
            if (np.sum(np.any(depth_ivar_1d > 0.0, axis=1))
                    < query["min_points"]):
                break

        return dict(
            peaks=peaks,
        )

    def save_to_cache(self, fn, response):
        try:
            os.makedirs(os.path.dirname(fn))
        except os.error:
            pass

        # Parse the peaks into a structured array.
        peaks = response["peaks"]
        if len(peaks):
            dtype = [(k, np.float64) for k in sorted(peaks[0].keys())]
            peaks = [tuple(peak[k] for k, _ in dtype) for peak in peaks]
            peaks = np.array(peaks, dtype=dtype)

        with h5py.File(fn, "w") as f:
            f.create_dataset("peaks", data=peaks, compression="gzip")

    def load_from_cache(self, fn):
        if os.path.exists(fn):
            with h5py.File(fn, "r") as f:
                try:
                    peaks = [dict((k, peak[k]) for k in peak.dtype.names)
                             for peak in f["peaks"]]
                    return dict(
                        peaks=peaks,
                    )
                except KeyError:
                    pass
        return None


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

from high2low import Changer_low as ch_low
import utils as util
#from low2high import Changer_high as ch_high
import is_horl as is_horl

txt = input("Enter Korean Sentence: ")
ch = ch_low()
#ch_high = ch_high()

hi = is_horl.isHigh()
detect=hi.isThisHigh(txt)

# 높임말
if detect ==1:
    hi.getState(detect)
    output = ch.processText(txt)
    print("Converted Result:", output)
# 반말
else:
    hi.getState(detect)
    output = util.tohigh(txt)
    print("Converted Result:", output)


#!/opt/csw/bin/python
# coding=utf-8

import re
import fileinput
from time import time
from datetime import datetime

urlRe = re.compile('(http://www\.|https://www\.|http://|https://|www\.)(?P<link>\S+)')
youtubeUrlRe = re.compile('(youtube\.com/watch\?v=|youtube\.com/watch\?.*&v=|youtu.be/)(?P<id>[A-Za-z0-9_-]{11})')

def getResponseType():
    return "MSG"

def get(msg, author, folder):
    urls = re.findall(urlRe, msg)
    if (not urls):
        return
    urls = [prepareUrl(url) for url in urls if not is4chan(url)]
    urls = list(set(urls))

    f = open(folder + "/links.txt","r")
    lines = f.readlines()
    f.close()

    response = []
    for index, line in enumerate(lines):
        if not urls:
            break;
        data = line.rstrip().split(" ")
        found = None
        for url in urls:
            if (data[0] != url):
                continue
            count = int(data[1])
            countStr = "(x" + str(count) + ")" if count > 1 else ""
            nick = "<" + data[2] + ">"
            firstTime = datetime.fromtimestamp(int(data[3])).strftime("%d/%m/%Y %H:%M:%S")
            response.append("old!!! " + countStr + " Algselt linkis " + nick + " " + firstTime)
            lines[index] = buildLine(data[0], count + 1, data[2], data[3])
            found = url
        if found is not None:
            urls.remove(found)
    f = open(folder + "/links.txt","w")
    for line in lines:
        f.write(line)
    for url in urls:
        timestamp = str(int(time()))
        line = buildLine(url, 1, author, timestamp)
        f.write(line)
    f.close()
    return response

def buildLine(url, count, nick, timestamp):
    count = str(count)
    return url + " " + count + " " + nick + " " + timestamp + "\n"

def is4chan(url):
    return "4cdn.org" in url[1]

def prepareUrl(url):
    url = url[1]
    youtubeUrl = re.findall(youtubeUrlRe, url)
    if (youtubeUrl):
        return youtubeUrl[0][1]
    if url[-1:] == "/":
        url = url[:-1]
    return url


import fitz
from loguru import logger

def get_page_from_sheet(sheet: str, pdf_fpath=None, doc=None):
    """
    Get the page number from the sheet.
    """

    if (pdf_fpath is not None) and (doc is not None):
        raise ValueError("Only one of pdf_fpath or doc can be specified.")

    if pdf_fpath:
        doc = fitz.open(pdf_fpath)

    # check each page
    for i in range(len(doc)-1, -1, -1):  # iterate backwards over all pages
        page = doc[i]
        # define the rectangles representing the corners of the page
        parts = 4
        corners = [
            fitz.Rect(0, 0, page.rect.width / parts, page.rect.height / parts),  # top left
            fitz.Rect(page.rect.width / parts, 0, page.rect.width, page.rect.height / parts),  # top right
            fitz.Rect(0, page.rect.height / parts, page.rect.width / parts, page.rect.height),  # bottom left
            fitz.Rect(page.rect.width / parts, page.rect.height / parts, page.rect.width, page.rect.height)  # bottom right
        ]
        # check each of the four corners of the page for the sheet number
        for corner in corners:
            matches = page.search_for(sheet, hit_max=1, area=corner)
            if matches:  # if the sheet number is found
                logger.info(f"Sheet number {sheet} found on page {i} at location {matches[0]}")
                return i, matches[0]  # return the page number (0-indexed)

    return None  # if the sheet number is not found on any page


from django.shortcuts import render

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q
from .serializer import GetCommentSerializer,AddCommentModelserializer,AddReplyCommentModelSerializer
from .models import Comment
from rest_framework.pagination import PageNumberPagination
from rest_framework import generics

# class GetComments (APIView):
#     def get (self,request,id):
#         comment = Comment.objects.filter(Q(product__id=id) & Q(reply=None) & Q(status=True))
#         serializer = GetCommentSerializer(comment,many=True)
#         return Response(serializer.data , status=status.HTTP_200_OK)

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 3
    page_size_query_param = 'page_size'
    max_page_size = 10

class GetComments (generics.ListAPIView):
        # queryset = Product.objects.filter(category=8)
        serializer_class = GetCommentSerializer
        pagination_class = StandardResultsSetPagination
        lookup_url_kwarg = "id"

        def get_queryset(self):
            id_product = self.kwargs.get(self.lookup_url_kwarg)
            comment = Comment.objects.filter(Q(product__id=id_product) & Q(reply=None) & Q(status=True)).order_by("-id")
            return comment

class AddComment (APIView):
    permission_classes=[IsAuthenticated]
    def post(self,request):
        serializer = AddCommentModelserializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['user']=request.user
        serializer.save()
        return Response(status=status.HTTP_200_OK)

class AddReplyComment(APIView):
    permission_classes=[IsAuthenticated]
    def post (self , request):
        serializer = AddReplyCommentModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['user']=request.user
        serializer.save()
        return Response(status=status.HTTP_200_OK)


"""empty message

Revision ID: b7c0cfa43719
Revises: 25279a0b5c75
Create Date: 2016-11-02 00:02:18.768539

"""

# revision identifiers, used by Alembic.
revision = 'b7c0cfa43719'
down_revision = '25279a0b5c75'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('twilio', sa.Column('state_number', sa.String(length=255), nullable=True))
    op.add_column('user', sa.Column('state_number', sa.String(length=255), nullable=True))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('user', 'state_number')
    op.drop_column('twilio', 'state_number')
    ### end Alembic commands ###


from django.test import TestCase
from django.urls import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.utils.html import escape

from lists.views import home_page, view_list
from lists.models import Item, List
from lists.forms import STR_EMPYT_LIST_ERROR, ItemForm, ExistingListItemForm

# Create your tests here.

class SmokeTest(TestCase):
    def test_bad_maths(self):
        self.assertEqual(1 + 1, 2)

class HomePageTest(TestCase):
    def test_root_url_resolves_to_home_page_view(self):
        found = resolve("/")
        self.assertEqual(found.func, home_page)

    def test_0001_home_page_returns_correct_html(self):
        request = HttpRequest()
        response = home_page(request)
        content = response.content.decode("utf-8-sig").encode('utf-8')
        # print(f'{type(content) =}, {content}')

        self.assertTrue(content.startswith(b"<html>"))
        self.assertIn(b'<title>To-Do Lists</title>', content)
        self.assertTrue(content.endswith(b"</html>"))
        # failed for csrf
        # self.assertEqual(response.content.decode(), render_to_string('home.html'))

    '''
    def test_0004_home_page_displays_all_list_item(self):
        list_ = List.objects.create()
        Item.objects.create(text='itemey 1', list=list_)
        Item.objects.create(text='itemey 2', list=list_)
        request = HttpRequest()
        response = view_list(request)
        self.assertIn('itemey 1', response.content.decode())
        self.assertIn('itemey 2', response.content.decode())
    '''

class ListViewTest(TestCase):
    '''
    def test_users_list_template(self):
        response = self.client.get('/lists/all/')

        self.assertTemplateUsed(response, 'list.html')
    '''

    def test_0002_users_list_template(self):
        list_ = List.objects.create()
        response = self.client.get(f'/lists/{list_.id}/')

        self.assertTemplateUsed(response, 'list.html')

    def test_0002a_users_list_template(self):
        list_ = List.objects.create()
        response = self.client.get(f'/lists/{list_.id}/')
        self.assertIsInstance(response.context['form'], ExistingListItemForm)
        self.assertContains(response, 'name="text"')

    def test_0003_display_only_items_for_that_list(self):
        list1 = List.objects.create()
        Item.objects.create(text='itemey 1.1', list=list1)
        Item.objects.create(text='itemey 1.2', list=list1)
        list2 = List.objects.create()
        Item.objects.create(text='itemey 2.1', list=list2)
        Item.objects.create(text='itemey 2.2', list=list2)
        response = self.client.get(f"/lists/{list1.id}/")
        content = response.content.decode("utf-8-sig").encode('utf-8')
        # print(f'{type(content) =}, {content}')

        self.assertContains(response, 'itemey 1.1')
        self.assertContains(response, 'itemey 1.2')
        self.assertNotContains(response, 'itemey 2.1')
        self.assertNotContains(response, 'itemey 2.2')

    """
    def test_display_all_items(self):
        list_ = List.objects.create()
        Item.objects.create(text='itemey 1', list=list_)
        Item.objects.create(text='itemey 2', list=list_)
        response = self.client.get("/lists/all/")

        self.assertContains(response, 'itemey 1')
        self.assertContains(response, 'itemey 2')
    """

    def test_0005_passes_correst_list_to_templeate(self):
        list2 = List.objects.create()
        list1 = List.objects.create()
        response = self.client.get(f'/lists/{list1.id}/')
        self.assertEqual(response.context['list'], list1)

    def test_0006_validation_error_end_up_on_list_page(self):
        list_ = List.objects.create()
        response = self.client.post(f'/lists/{list_.id}/', data={"text": ''})
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'list.html')

        content = response.content.decode("utf-8-sig").encode('utf-8')
        # print(f'test_0006_validation_error_end_up_on_list_page {type(content) =}, {content}')

        self.assertContains(response, escape("You can't have an empty list item"))

    def post_invalid_input(self):
        list_ = List.objects.create()
        response = self.client.post(f'/lists/{list_.id}/', data={"text": ''})
        return response

    def test_0007_invalid_input_nothing_saved_to(self):
        self.post_invalid_input()
        self.assertEqual(Item.objects.count(), 0)

    def test_0008_invalid_input_renders_list_template(self):
        response = self.post_invalid_input()
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'list.html')

    def test_0009_invalid_input_passes_form_to_template(self):
        response = self.post_invalid_input()
        self.assertIsInstance(response.context['form'], ExistingListItemForm)

    def test_0010_invalid_input_shows_error_on_page(self):
        response = self.post_invalid_input()
        self.assertContains(response, escape(STR_EMPYT_LIST_ERROR))

class NewListTest(TestCase):
    def test_0001_saving_a_POST_request(self):
        # print(f'Before post')
        self.client.post('/lists/new', data={'text': 'A new list item'})

        # print(f'{Item.objects.count()}, {Item.objects =}')
        self.assertEqual(Item.objects.count(), 1)
        new_item = Item.objects.first()
        self.assertEqual(new_item.text, 'A new list item')

    def test_0003_home_page_redirect_after_post(self):
        response = self.client.post('/lists/new', data={'text': 'A new list item'})
        list_ = List.objects.first()
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response['location'], f'/lists/{list_.id}/')

    def test_0004a_validation_errors_are_sent_back_to_home_page_template(self):
        response = self.client.post('/lists/new', data={'text': ''})
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'home.html')

    def test_0004b_validation_errors_are_sent_back_to_home_page_template(self):
        response = self.client.post('/lists/new', data={'text': ''})
        self.assertContains(response, escape(STR_EMPYT_LIST_ERROR))

    def test_0004c_validation_errors_are_sent_back_to_home_page_template(self):
        response = self.client.post('/lists/new', data={'text': ''})
        self.assertIsInstance(response.context['form'], ItemForm)

    def test_0005_invalid_list_items_arent_saved(self):
        response = self.client.post('/lists/new', data={'text': ''})
        self.assertEqual(List.objects.count(), 0)
        self.assertEqual(Item.objects.count(), 0)

class NewItemTest(TestCase):
    def test_0001_can_save_a_POST_request_to_an_existing_list(self):
        list2 = List.objects.create()
        list1 = List.objects.create()
        response = self.client.post(f'/lists/{list1.id}/',
                                    data={'text': 'A new list item for existing list'})
        # print(f'test_0001_can_save_a_POST_request_to_an_existing_list: {response.status_code}, {response = }')
        # print(f'{list(Item.objects.all()) = }')
        self.assertEqual(Item.objects.count(), 1)
        new_item = Item.objects.first()
        self.assertEqual(new_item.text, 'A new list item for existing list')
        self.assertEqual(new_item.list, list1)

    def test_0002_redirect_to_list_view(self):
        list2 = List.objects.create()
        list1 = List.objects.create()
        response = self.client.post(f'/lists/{list1.id}/',
                                    data={'text': 'A new list item for existing list'})
        self.assertRedirects(response, f'/lists/{list1.id}/')


"""
    3
   / \
  9  20
    /  \
   15   7
return its zigzag level order traversal as:
[
  [3],
  [20,9],
  [15,7]
]
"""
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

import collections
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []

        queue = collections.deque([root])
        z_traversal = []
        num_level = 0
        while queue:
            level = collections.deque([])
            for i in range(len(queue)):
                head = queue.popleft()
                # KEY: different order to put in list
                if num_level % 2 == 0:
                    level.append(head.val)
                else:
                    level.appendleft(head.val)

                if head.left:
                    queue.append(head.left)
                if head.right:
                    queue.append(head.right)
            z_traversal.append(level)
            num_level += 1

        return z_traversal