import torch
from torch.utils.data import Dataset
import numpy as np
import cv2
import copy
import os

class HighlightDataset(Dataset):
    def __init__(self, len_sequence, highlight_dir, non_highlight_dir, transform=None):
        self.simg_width = 16 * 14
        self.len_sequence = len_sequence
        self.highlight_dir = highlight_dir
        self.non_highlight_dir = non_highlight_dir
        self.hightlight_paths = [
            os.path.join(highlight_dir, f) for f in os.listdir(self.highlight_dir)
        ]
        self.non_hightlight_paths = [
            os.path.join(non_highlight_dir, f) for f in os.listdir(self.non_highlight_dir)
        ]
        self.transform = transform

    def __len__(self):
        return len(self.hightlight_paths) + len(self.non_hightlight_paths)

    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()
        if idx >= len(self.hightlight_paths):
            idx = idx - len(self.hightlight_paths)
            img = cv2.imread(self.non_hightlight_paths[idx])
            score = 0
        else:
            img = cv2.imread(self.hightlight_paths[idx])
            score = self.len_sequence
        imgs = np.asarray([img[:,
                               i * self.simg_width: (i+1) * self.simg_width,
                               :] for i in range(self.len_sequence)])
        sample = imgs, score
        if self.transform:
            sample = self.transform(sample)
        return sample

class ToTensor(object):
    def __call__(self, sample):
        imgs, score = sample[0], sample[1]
        # swap color axis because
        # numpy image: H x W x C
        # torch image: C X H X W
        transpoed_imgs = np.asarray([img.transpose((2, 0, 1)) for img in imgs])
        return torch.from_numpy(transpoed_imgs).float(), torch.tensor(score, dtype=torch.float)


import sys
sys.path.insert(0, "cleverhans")
from cleverhans.model import Model

# Minimal wrapper of our existing model so that we can attack them with Cleverhans

class Wrapper(Model):

    def __init__(self, model = None):
        super(Wrapper, self).__init__()

        if model is None:
            raise ValueError('model argument must be supplied.')

        self.model = model
        self.num_classes = 10

    def get_logits(self, x):
        return self.model.predict(x)


import glob
import os
import random
import shutil
import sys
from datetime import timedelta, date
import numpy as np
import tensorflow as tf

sys.path.append("../")
from utils import utils
from load_criteo import loaddualattention

FLAGS = tf.flags.FLAGS
tf.flags.DEFINE_integer("num_threads", 16, "Number of threads")
tf.flags.DEFINE_integer("max_features", 5897, "Number of max_features")
tf.flags.DEFINE_integer("embedding_size", 96, "Embedding size")
tf.flags.DEFINE_integer("seq_max_len", 160, "seq_max_len")
tf.flags.DEFINE_integer("num_epochs", 100, "Number of epochs")
tf.flags.DEFINE_integer("batch_size", 100, "Number of batch size")
tf.flags.DEFINE_float("learning_rate", 0.001, "learning rate")
tf.flags.DEFINE_float("l2_reg", 0.01, "L2 regularization")
tf.flags.DEFINE_string("loss_type", 'log_loss', "loss type {square_loss, log_loss}")
tf.flags.DEFINE_float("ctr_task_wgt", 0.4, "loss weight of ctr task")
tf.flags.DEFINE_string("optimizer", 'Adam', "optimizer type {Adam, Adagrad, GD, Momentum}")
tf.flags.DEFINE_integer("n_hidden", 256, "deep layers")
tf.flags.DEFINE_integer("n_classes", 2, "deep layers")
tf.flags.DEFINE_float("keep_prob", 0.5, "dropout rate")
tf.flags.DEFINE_string("gpus", '', "list of gpus")
tf.flags.DEFINE_boolean("batch_norm", True, "perform batch normaization (True or False)")
tf.flags.DEFINE_float("batch_norm_decay", 0.9, "decay for the moving average(recommend trying decay=0.9)")
tf.flags.DEFINE_string("data_dir", './../Criteo', "data dir")
tf.flags.DEFINE_string("dt_dir", '', "data dt partition")
tf.flags.DEFINE_string("model_dir", './../Criteo/model_Criteo_darnn', "model check point dir")
tf.flags.DEFINE_string("servable_model_dir", '', "export servable model for TensorFlow Serving")
tf.flags.DEFINE_string("task_type", 'train', "task type {train, infer, eval}")
tf.flags.DEFINE_boolean("clear_existing_model", False, "clear existing model or not")

os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpus

input = tf.placeholder(tf.float32,
                       shape=[None, FLAGS.seq_max_len, 12])
seq_len = tf.placeholder(tf.int32, shape=[None], name='seqlen')
click_label = tf.placeholder(tf.float32, shape=[None, FLAGS.seq_max_len, FLAGS.n_classes])
conversion_label = tf.placeholder(tf.float32, shape=[None], name='labels')
embedding_size = FLAGS.embedding_size
l2_reg = FLAGS.l2_reg
learning_rate = FLAGS.learning_rate
max_features = FLAGS.max_features
seq_max_len = FLAGS.seq_max_len
ctr_task_wgt = FLAGS.ctr_task_wgt
embedding_matrix = tf.Variable(
    tf.random_normal([max_features, embedding_size], stddev=0.1))
print(input.shape)
x1, x2 = tf.split(input, [2, 10], 2)
x2 = tf.to_int32(x2)
x2 = tf.nn.embedding_lookup(embedding_matrix, x2)
x2 = tf.reshape(x2, [-1, seq_max_len, 10 * embedding_size])
x = tf.concat((x1, x2), axis=2)
print(x.shape, x.shape[2])
n_input = int(x.shape[2])
# Define Variables
W = tf.Variable(tf.random_normal([FLAGS.n_classes, FLAGS.n_hidden], stddev=0.1), name='W')
U = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='U')
C = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='C')
v_a = tf.Variable(tf.random_normal([FLAGS.n_hidden], stddev=0.1), name='v_a')
W_z = tf.Variable(tf.random_normal([FLAGS.n_classes, FLAGS.n_hidden], stddev=0.1), name='W_z')
U_z = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='U_z')
C_z = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='C_z')
W_r = tf.Variable(tf.random_normal([FLAGS.n_classes, FLAGS.n_hidden], stddev=0.1), name='W_r')
U_r = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='U_r')
C_r = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='C_r')
W_s = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='W_s')
W_o = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_classes], stddev=0.1), name='W_o')
b_o = tf.Variable(tf.random_normal([FLAGS.n_classes], stddev=0.1), name='b_o')
W_h = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='W_h')
U_s = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='U_s')
W_C = tf.Variable(tf.random_normal([FLAGS.n_hidden, FLAGS.n_hidden], stddev=0.1), name='W_C')
W_x1 = tf.Variable(tf.random_normal([n_input, FLAGS.n_hidden], stddev=0.1), name='W_x1')
W_x2 = tf.Variable(tf.random_normal([n_input, FLAGS.n_hidden], stddev=0.1), name='W_x2')
W_x3 = tf.Variable(tf.random_normal([n_input, FLAGS.n_hidden], stddev=0.1), name='W_x3')
v_a2 = tf.Variable(tf.random_normal([FLAGS.n_hidden], stddev=0.1), name='v_a2')
v_a3 = tf.Variable(tf.random_normal([FLAGS.n_hidden], stddev=0.1), name='v_a3')
W_c = tf.Variable(tf.random_normal([FLAGS.n_hidden], stddev=0.1), name='W_c')
b_c = tf.Variable(tf.random_normal([1]))

index = tf.range(0, tf.shape(x)[0]) * FLAGS.seq_max_len + (seq_len - 1)
x_last = tf.gather(params=tf.reshape(x, [-1, n_input]), indices=index)
# x = tf.transpose(x, [1, 0, 2])  # seqlen*batch*dim
mask = tf.sequence_mask(seq_len, seq_max_len)
y = tf.transpose(click_label, [1, 0, 2])
y = tf.reshape(y, [-1, FLAGS.n_classes])
y = tf.split(value=y, num_or_size_splits=seq_max_len, axis=0)
with tf.name_scope('LstmNet'):
    lstm_cell = tf.contrib.rnn.BasicLSTMCell(FLAGS.n_hidden, state_is_tuple=True)
    lstm_cell = tf.nn.rnn_cell.DropoutWrapper(lstm_cell, input_keep_prob=FLAGS.keep_prob,
                                              output_keep_prob=FLAGS.keep_prob)
    states_h, last_h = tf.nn.dynamic_rnn(cell=lstm_cell, inputs=x, sequence_length=seq_len, dtype=tf.float32)

with tf.name_scope('decoder'):
    last_state_h = tf.gather(params=tf.reshape(states_h, [-1, FLAGS.n_hidden]), indices=index)
    # decoder
    state_s = tf.tanh(tf.matmul(last_state_h, W_s))
    states_s = [state_s]
    outputs = []
    output = tf.zeros(shape=[tf.shape(input)[0], FLAGS.n_classes])
    last_output = tf.nn.softmax(output)
    c = last_state_h
    for i in range(seq_max_len):
        r = tf.sigmoid(tf.matmul(last_output, W_r) + tf.matmul(states_s[i], U_r) + tf.matmul(c, C_r))
        z = tf.sigmoid(tf.matmul(last_output, W_z) + tf.matmul(states_s[i], U_z) + tf.matmul(c, C_z))
        s_hat = tf.tanh(tf.matmul(last_output, W) + tf.matmul(tf.multiply(r, states_s[i]), U) + tf.matmul(c, C))
        state_s = tf.multiply(tf.subtract(1.0, z), states_s[i]) + tf.multiply(z, s_hat)
        states_s.append(state_s)
        state_s = tf.nn.dropout(state_s, FLAGS.keep_prob)
        output = tf.matmul(state_s, W_o) + b_o
        outputs.append(output)
        if FLAGS.task_type == 'train':
            last_output = y[i]
        else:
            last_output = tf.nn.softmax(output)

with tf.name_scope('dual_attention'):
    Ux = tf.matmul(x_last, W_x1)
    Ux2 = tf.matmul(x_last, W_x2)
    states_h = tf.transpose(states_h, [1, 0, 2])
    states_s = tf.stack(states_s[:-1])
    print("H", states_h.shape)
    print("S", states_s.shape)
    e2 = tf.reduce_sum(tf.multiply(tf.tanh(tf.matmul(states_h, W_h) + Ux), v_a2), reduction_indices=2)
    e3 = tf.reduce_sum(tf.multiply(tf.tanh(tf.matmul(states_s, U_s) + Ux2), v_a3), reduction_indices=2)
    e2 = tf.transpose(e2, [1, 0])
    e3 = tf.transpose(e3, [1, 0])
    print("E2", e2.shape)
    print("E3", e3.shape)

    a2 = tf.map_fn(
        lambda i: tf.concat([tf.nn.softmax(e2[i][:seq_len[i]]), tf.zeros(shape=(seq_max_len - seq_len[i]))], axis=0),
        tf.range(0, tf.shape(e2)[0]), dtype=e2.dtype)
    a3 = tf.map_fn(
        lambda i: tf.concat([tf.nn.softmax(e3[i][:seq_len[i]]), tf.zeros(shape=(seq_max_len - seq_len[i]))], axis=0),
        tf.range(0, tf.shape(e2)[0]), dtype=e2.dtype)
    a2 = tf.concat(a2, axis=0)
    a3 = tf.concat(a3, axis=0)
    a2 = tf.boolean_mask(a2, mask)
    a3 = tf.boolean_mask(a3, mask)
    print("A2", a2.shape)
    print("A3", a3.shape)
    states_h = tf.transpose(states_h, [1, 0, 2])
    states_h = tf.boolean_mask(states_h, mask)
    states_s = tf.transpose(states_s, [1, 0, 2])
    states_s = tf.boolean_mask(states_s, mask)

    def f(i):
        left = tf.reduce_sum(seq_len[:i])
        right = left + seq_len[i]
        return tf.reduce_sum(tf.multiply(tf.reshape(a2[left:right], shape=(-1, 1)), states_h[left:right]), axis=0)

    def f2(i):
        left = tf.reduce_sum(seq_len[:i])
        right = left + seq_len[i]
        return tf.reduce_sum(tf.multiply(tf.reshape(a3[left:right], shape=(-1, 1)), states_s[left:right]), axis=0)

    c2 = tf.map_fn(lambda i: f(i), tf.range(0, tf.shape(e2)[0]), dtype=a2.dtype)
    c3 = tf.map_fn(lambda i: f2(i), tf.range(0, tf.shape(e2)[0]), dtype=a3.dtype)
    print("C2,C3:", c2.shape, c3.shape)
    e4 = []
    Ux3 = tf.matmul(x_last, W_x3)
    e4.append(tf.reduce_sum(tf.multiply(tf.tanh(tf.matmul(c2, W_C) + Ux3), v_a), reduction_indices=1))
    e4.append(tf.reduce_sum(tf.multiply(tf.tanh(tf.matmul(c3, W_C) + Ux3), v_a), reduction_indices=1))
    e4 = tf.stack(e4)
    print("E4:", e4.shape)
    a4 = tf.split(tf.nn.softmax(e4, dim=0), 2, 0)
    print("A4：", a4[0].shape, a4[1].shape)
    C = tf.multiply(c2, tf.transpose(a4[0])) + tf.multiply(c3, tf.transpose(a4[1]))
    print(C.shape)

cvr = tf.reduce_sum(tf.multiply(C, W_c), axis=1) + b_c
# cvr = tf.nn.dropout(cvr, keep_prob=FLAGS.keep_prob)
pcvr = tf.nn.sigmoid(cvr)

outputs = tf.stack(outputs)
outputs = tf.transpose(outputs, [1, 0, 2])
click_pred = tf.nn.softmax(outputs)
predictions = {"pctr": click_pred, "pcvr": pcvr}
# ------bulid loss------
conversion_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=conversion_label, logits=cvr))
loss_click = tf.nn.softmax_cross_entropy_with_logits(labels=click_label, logits=outputs)
loss_click = tf.boolean_mask(loss_click, mask)  # return real seq
loss_click = tf.reduce_mean(loss_click)

loss = (1 - ctr_task_wgt) * loss_click + ctr_task_wgt * conversion_loss
for v in tf.trainable_variables():
    loss += l2_reg * tf.nn.l2_loss(v)
    '''loss_click += l2_reg * tf.nn.l2_loss(v)
    conversion_loss += l2_reg * tf.nn.l2_loss(v)'''
tf.summary.scalar('ctr_loss', loss_click)
tf.summary.scalar('ctcvr_loss', conversion_loss)

# Provide an estimator spec for `ModeKeys.EVAL`
threshold = 0.5
reshape_click_label = tf.reshape(tf.boolean_mask(click_label, mask), shape=(-1, 2))[:, 1]
reshape_click_pred = tf.reshape(tf.boolean_mask(click_pred, mask), shape=(-1, 2))[:, 1]

one_click = tf.ones_like(reshape_click_label)
zero_click = tf.zeros_like(reshape_click_label)
one_cvr = tf.ones_like(conversion_label)
zero_cvr = tf.zeros_like(conversion_label)
eval_metric_ops = {
    "CTR_AUC": tf.metrics.auc(reshape_click_label, reshape_click_pred),
    "CTR_ACC": tf.metrics.accuracy(reshape_click_label,
                                   tf.where(reshape_click_pred >= threshold, one_click, zero_click)),
    "CTCVR_AUC": tf.metrics.auc(conversion_label, pcvr),
    "CTCVR_ACC": tf.metrics.accuracy(conversion_label, tf.where(pcvr >= threshold, one_cvr, zero_cvr))
}
global_step = tf.Variable(0, trainable=False)
cov_learning_rate = tf.train.exponential_decay(learning_rate, global_step, 50000, 0.96)
optimizer = tf.train.AdamOptimizer(learning_rate=cov_learning_rate)
train_op = optimizer.minimize(loss, global_step=global_step)
saver = tf.train.Saver(max_to_keep=3)

def main(_):
    # ------check Arguments------
    if FLAGS.dt_dir == "":
        FLAGS.dt_dir = (date.today() + timedelta(-1)).strftime('%Y%m%d')
    FLAGS.model_dir = FLAGS.model_dir +  '20210101'

    print('task_type ', FLAGS.task_type)
    print('model_dir ', FLAGS.model_dir)
    print('data_dir ', FLAGS.data_dir)
    print('dt_dir ', FLAGS.dt_dir)
    print('num_epochs ', FLAGS.num_epochs)
    print('seq_max_len', FLAGS.seq_max_len)
    print('max_features', FLAGS.max_features)
    print('embedding_size ', FLAGS.embedding_size)
    print('batch_size ', FLAGS.batch_size)
    print('n_hidden', FLAGS.n_hidden)
    print('n_classes', FLAGS.n_classes)
    print('keep_prob ', FLAGS.keep_prob)
    print('loss_type ', FLAGS.loss_type)
    print('optimizer ', FLAGS.optimizer)
    print('learning_rate ', FLAGS.learning_rate)
    print('l2_reg ', FLAGS.l2_reg)
    print('ctr_task_wgt ', FLAGS.ctr_task_wgt)

    tr_files = glob.glob("%s/train/*.txt" % FLAGS.data_dir)
    random.shuffle(tr_files)
    print("train_files:", tr_files)
    te_files = glob.glob("%s/test/*.txt" % FLAGS.data_dir)
    print("test_files:", te_files)

    if FLAGS.clear_existing_model:
        try:
            shutil.rmtree(FLAGS.model_dir)
        except Exception as e:
            print(e, "at clear_existing_model")
        else:
            print("existing model cleaned at %s" % FLAGS.model_dir)
    config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False,
                            device_count={'CPU': FLAGS.num_threads})
    config.gpu_options.allow_growth = True
    if FLAGS.task_type == 'train':
        with tf.Session(config=config) as sess:
            sess.run(tf.global_variables_initializer())
            sess.run(tf.local_variables_initializer())
            if not FLAGS.clear_existing_model:
                saver.restore(sess, os.path.join(FLAGS.model_dir, 'BestModel'))
            for tr in tr_files:
                for i in range(FLAGS.num_epochs):
                    step = 0
                    tr_infile = open(tr, 'r')
                    best_auc = 0
                    while True:
                        step += 1
                        total_data, total_click_label, total_label, total_seqlen = loaddualattention(
                            FLAGS.batch_size, FLAGS.seq_max_len, 12, tr_infile)
                        feed_dict = {
                            input: total_data,
                            seq_len: total_seqlen,
                            click_label: total_click_label,
                            conversion_label: total_label
                        }
                        _, batch_loss, batch_cvr_loss, batch_click_loss, batch_eval, batch_pred = sess.run(
                            [train_op, loss, conversion_loss, loss_click, eval_metric_ops, pcvr], feed_dict=feed_dict)
                        print("Epoch:{}\tStep:{}".format(i, step))
                        print("click_AUC = " + "{}".format(batch_eval['CTR_AUC'][0]), end='\t')
                        print("conversion_AUC = " + "{}".format(batch_eval['CTCVR_AUC'][0]), end='\t')
                        print("click_ACC = " + "{}".format(batch_eval['CTR_ACC'][0]), end='\t')
                        print("conversion_ACC = " + "{}".format(batch_eval['CTCVR_ACC'][0]))
                        print("Loss = " + "{}".format(batch_loss), end='\t')
                        print("Clk Loss = " + "{}".format(batch_click_loss), end='\t')
                        print("Cov_Loss = " + "{}".format(batch_cvr_loss))
                        if step % 50 == 0:
                            saver.save(sess, os.path.join(FLAGS.model_dir, 'MyModel'), global_step=step)
                            print("Test----------------")
                            test_cvr_auc = 0.0
                            test_ctr_auc = 0.0
                            test_cvr_acc = 0.0
                            test_ctr_acc = 0.0
                            test_loss = 0
                            test_clk_loss = 0
                            test_cvr_loss = 0
                            test_step = 0
                            for te in te_files:
                                te_infile = open(te, 'r')
                                for _ in range(200):
                                    test_step += 1
                                    total_data, total_click_label, total_label, total_seqlen = loaddualattention(
                                        FLAGS.batch_size, FLAGS.seq_max_len, 12, te_infile)
                                    feed_dict = {
                                        input: total_data,
                                        seq_len: total_seqlen,
                                        click_label: total_click_label,
                                        conversion_label: total_label
                                    }
                                    batch_loss, batch_cvr_loss, batch_click_loss, batch_eval = sess.run(
                                        [loss, conversion_loss, loss_click, eval_metric_ops],
                                        feed_dict=feed_dict)
                                    test_ctr_auc += batch_eval['CTR_AUC'][0]
                                    test_cvr_auc += batch_eval['CTCVR_AUC'][0]
                                    test_ctr_acc += batch_eval['CTR_ACC'][0]
                                    test_cvr_acc += batch_eval['CTCVR_ACC'][0]
                                    test_loss += batch_loss
                                    test_cvr_loss += batch_cvr_loss
                                    test_clk_loss += batch_click_loss
                                    if len(total_data) != FLAGS.batch_size:
                                        break
                            test_ctr_auc /= test_step
                            test_cvr_auc /= test_step
                            test_cvr_acc /= test_step
                            test_ctr_acc /= test_step
                            test_loss /= test_step
                            test_clk_loss /= test_step
                            test_cvr_loss /= step

                            print("click_AUC = " + "{}".format(test_ctr_auc), end='\t')
                            print("conversion_AUC = " + "{}".format(test_cvr_auc), end='\t')
                            print("click_ACC = " + "{}".format(test_ctr_acc), end='\t')
                            print("conversion_ACC = " + "{}".format(test_cvr_acc))
                            print("Loss = " + "{}".format(test_loss), end='\t')
                            print("Clk Loss = " + "{}".format(test_clk_loss), end='\t')
                            print("Cov_Loss = " + "{}".format(test_cvr_loss))
                            if test_cvr_auc > best_auc:
                                print("Save----------------")
                                saver.save(sess, os.path.join(FLAGS.model_dir, 'BestModel'),global_step=step)
                        if len(total_data) != FLAGS.batch_size:
                            break
    if FLAGS.task_type == 'eval':
        with tf.Session(config=config) as sess:
            sess.run(tf.local_variables_initializer())
            saver.restore(sess, os.path.join(FLAGS.model_dir, 'BestModel'))
            for te in te_files:
                te_infile = open(te, 'r')
                while True:
                    total_data, total_click_label, total_label, total_seqlen = loaddualattention(
                        FLAGS.batch_size, FLAGS.seq_max_len, 12, te_infile)
                    feed_dict = {
                        input: total_data,
                        seq_len: total_seqlen,
                        click_label: total_click_label,
                        conversion_label: total_label
                    }
                    batch_loss, batch_cvr_loss, batch_click_loss, batch_eval = sess.run(
                        [loss, conversion_loss, loss_click, eval_metric_ops], feed_dict=feed_dict)
                    print("click_AUC = " + "{}".format(batch_eval['CTR_AUC'][0]), end='\t')
                    print("conversion_AUC = " + "{}".format(batch_eval['CTCVR_AUC'][0]), end='\t')
                    print("click_ACC = " + "{}".format(batch_eval['CTR_ACC'][0]), end='\t')
                    print("conversion_ACC = " + "{}".format(batch_eval['CTCVR_ACC'][0]))
                    print("Loss = " + "{}".format(batch_loss), end='\t')
                    print("Clk Loss = " + "{}".format(batch_click_loss), end='\t')
                    print("Cov_Loss = " + "{}".format(batch_cvr_loss))
                    if len(total_data) != FLAGS.batch_size:
                        break
    if FLAGS.task_type == 'infer':
        with tf.Session(config=config) as sess:
            sess.run(tf.local_variables_initializer())
            saver.restore(sess, os.path.join(FLAGS.model_dir, 'BestModel-4650'))
            for te in te_files:
                print(te)
                te_infile = open(te, 'r')
                step = 0
                pctr = np.array([])
                y = np.array([])
                pctcvr = np.array([])
                z = np.array([])
                while True:
                    step += 1
                    total_data, total_click_label, total_label, total_seqlen = loaddualattention(
                        FLAGS.batch_size, FLAGS.seq_max_len, 12, te_infile)
                    print(step)
                    if not total_seqlen:
                        break
                    feed_dict = {
                        input: total_data,
                        seq_len: total_seqlen,
                        click_label: total_click_label,
                        conversion_label: total_label
                    }
                    p_click, l_click, p_conver, l_conver = sess.run([reshape_click_pred, reshape_click_label, pcvr,
                                                                     conversion_label], feed_dict=feed_dict)
                    pctr = np.append(pctr, p_click)
                    y = np.append(y, l_click)
                    pctcvr = np.append(pctcvr, p_conver)
                    z = np.append(z, l_conver)
                    if len(total_data) != FLAGS.batch_size:
                        break
                click_result = {'loss': 0, 'acc': 0, 'auc': 0, 'f1': 0, 'ndcg': 0, 'map': 0}
                conversion_result = {'loss': 0, 'acc': 0, 'auc': 0, 'f1': 0, 'ndcg': 0, 'map': 0}
                click_result['loss'] = utils.evaluate_logloss(pctr, y)
                click_result['acc'] = utils.evaluate_acc(pctr, y)
                click_result['auc'] = utils.evaluate_auc(pctr, y)
                click_result['f1'] = utils.evaluate_f1_score(pctr, y)
                click_result['ndcg'] = utils.evaluate_ndcg(None, pctr, y, len(pctr))
                click_result['map'] = utils.evaluate_map(len(pctr), pctr, y, len(pctr))

                conversion_result['loss'] = utils.evaluate_logloss(pctcvr, z)
                conversion_result['acc'] = utils.evaluate_acc(pctcvr, z)
                conversion_result['auc'] = utils.evaluate_auc(pctcvr, z)
                conversion_result['f1'] = utils.evaluate_f1_score(pctcvr, z)
                conversion_result['ndcg'] = utils.evaluate_ndcg(None, pctcvr, z, len(pctcvr))
                conversion_result['map'] = utils.evaluate_map(len(pctcvr), pctcvr, z, len(pctcvr))
                print("Click Result")
                for k, v in click_result.items():
                    print("{}:{}".format(k, v), end='\t')
                print()
                print("Conversion Result")
                for k, v in conversion_result.items():
                    print("{}:{}".format(k, v), end='\t')

if __name__ == "__main__":
    tf.logging.set_verbosity(tf.logging.INFO)
    tf.app.run()


import heapq

def get_walls(matrix):
    """
    przeszukuje mape gry w celu znalezienia scian - stanow nieosiagalnych
    """
    walls = []
    limits = [0, 2, 3, 4, 5]
    for x in range(len(matrix[0])):
        for y in range(len(matrix)):
            if matrix[y][x] in limits:
                walls.append((y, x))
    return walls

class Node(object):
    def __init__(self, x, y, reachable):
        """
        Inicjalizuje nowy wezel dla danego stanu
        """
        self.reachable = reachable  # czy wezel stanu jest osiagalny (czy pole nie jest sciana)
        self.x = x  # wspolrzedna x pola
        self.y = y  # wspolrzedna y pola
        self.parent = None  # wskaznik na wezel poprzedniego stanu
        self.g = 0  # koszt dotarcia z wezla poczatkowego do danego
        self.h = 0  # koszt dotarcia z danego wezla do celu
        self.f = 0  # koszt calkowity

    def __str__(self):
        """
        Zwraca informacje o wspolrzednych wezla reprezntujacego stan w formie stringa
        """
        return '(' + str(self.x) + ',' + str(self.y) + ')'

class AStar(object):
    """
    tworzy nowy obiekt AStar
    """

    def __init__(self):
        self.opened = []  # lista otwartych stanow - pola nieprzejrzane/nieodwiedzone
        heapq.heapify(self.opened)  # kolejka priorytetowa otwartych pol do odwiedzenia
        self.closed = []  # pola zamkniete - pola juz przejrzane/odwiedzone
        self.nodes = []  # wszystkie mozliwe dostepne pola
        self.mapheight = 0  # wymiary przestrzeni stanow - mapy
        self.mapwidth = 0

    def init_grid(self, matrix):  # przeksztalcanie mapy na przestrzen stanow
        self.mapheight = len(matrix)
        self.mapwidth = len(matrix[0])
        walls = get_walls(matrix)  # znalezienie scian - wezlow dla stanow nieosiagalnych
        for y in range(self.mapheight):
            for x in range(self.mapwidth):
                if (y, x) in walls:
                    reachable = False
                else:
                    reachable = True
                self.nodes.append(Node(x, y, reachable))  # umieszczenie wezlow reprezentujacych dostepne stany na liscie

    def get_heuristic(self, node):
        """
        oblicza wartosc funkcji heurystycznej H dla danego stanu: dystans pomiedzy
        wezlem reprezentujacym dany stan, a wezlem reprezentujacym stan docelowy
        """
        return 100 * (abs(node.x - self.end.x) + abs(node.y - self.end.y))

    def get_node(self, y, x):
        """
        zwraca wezel dla danego stanu z listy wezlow wszystkich stanow
        """
        return self.nodes[y * self.mapwidth + x]

    def get_adjacent_nodes(self, node):
        """
        odpowiednik funkcji ROZSZERZAJACEJ DRZEWO
        zwraca liste nastepnikow dla wezla danego stanu
        """
        nodes = []
        if node.x < self.mapwidth - 1:
            nodes.append(self.get_node(node.y, node.x + 1))
        if node.y > 0:
            nodes.append(self.get_node(node.y - 1, node.x))
        if node.x > 0:
            nodes.append(self.get_node(node.y, node.x - 1))
        if node.y < self.mapheight - 1:
            nodes.append(self.get_node(node.y + 1, node.x))

        return nodes

    def get_path(self, path):
        """
        zwraca liste wezlow dla stanow przy kolejnych akcjach podejmowanych przez agenta
        """
        node = self.end
        while node.parent is not self.start:
            node = node.parent
            path.append((node.y, node.x))
        return list(reversed(path))

    def update_node(self, adj, node):
        """
        wybiera najlepszy wezel z listy nastepnikow konkretnego wezla dla danego stanu
        """
        adj.g = node.g + 10
        adj.h = self.get_heuristic(adj)
        adj.parent = node
        adj.f = adj.h + adj.g

    def process(self, start, end1, end2):
        """
        proces znajdowania listy wezlow stanow dla kolejnych akcji podejmowanych przez agenta
        """
        self.start = self.get_node(start[0], start[1])  # poczatkowy wezel reprezentujacy stan poczatkowy
        self.end = self.get_node(end1, end2)  # docelowy wezel reprezentujacy docelowy stan
        path = []  # lista wszystkich przebytych wezlow
        if self.end == self.start:
            return path
        # poczatkowy wezel otwiera kolejke priorytetowa
        heapq.heappush(self.opened, (self.start.f, self.start))
        while len(self.opened):
            # zdejmij wezel z kolejki
            f, node = heapq.heappop(self.opened)
            # dodaj wezel do listy zamknietych wezlow
            self.closed.append(node)
            # jezeli to docelowy wezel - zwroc liste wszystkich przebytych wezlow
            if node is self.end:
                return self.get_path(path)
            # znajdz liste nastepnikow danego wezla
            adj_nodes = self.get_adjacent_nodes(node)
            for adj_node in adj_nodes:
                if adj_node.reachable and adj_node not in self.closed:
                    if (adj_node.f, adj_node) in self.opened:
                        # jezeli nastepnik jest na otwartej liscie i jest osiagalny
                        # to sprawdz czy nowa, przechodzaca przez niego sciezka
                        # jest lepsza od starej
                        if adj_node.g > node.g + 10:
                            self.update_node(adj_node, node)
                    else:
                        self.update_node(adj_node, node)
                    # dodaj nastepnik nastepnika na otwarta liste
                    heapq.heappush(self.opened, (adj_node.f, adj_node))

def get_actions(path, start, end1, end2):
    """
    odpowiednik FUNKCJI NASTEPNIKA - zwraca liste akcji, ktore musi wykonac agent
    aby przejsc od stanu poczatkowego do stanu koncowego
    """
    path.insert(0, start)  # dodaj wezel reprezentujacy stan poczatkowy
    path.append((end1, end2))  # dodaj wezel reprezentujacy stan koncowy
    path1 = []  # zwracana lista akcji - akcja to ruch w okreslonym kierunku
    for x in range(len(path) - 1):
        if path[x][0] < path[x + 1][0]:
            path1.append('down')
        elif path[x][0] > path[x + 1][0]:
            path1.append('up')
        elif path[x][1] < path[x + 1][1]:
            path1.append('right')
        elif path[x][1] > path[x + 1][1]:
            path1.append('left')
    return path1


import torch
import torch.nn as nn
from torch import Tensor
import torchvision
from collections import OrderedDict
from unet import UNet
from EfficientNetV2 import efficientnetv2_s

def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)

def conv_block(in_planes: int):
    layers = []
    layers.append(conv1x1(in_planes, in_planes))
    layers.append(nn.BatchNorm2d(in_planes))
    layers.append(nn.ReLU(inplace=True))
    layers.append(conv1x1(in_planes, in_planes))
    layers.append(nn.BatchNorm2d(in_planes))
    layers.append(nn.Sigmoid())
    return nn.Sequential(*layers)

class CWN(nn.Module):
    def __init__(
            self,
            baseline: nn.Module,
            in_planes: int,
            classes: int,
            k: list = []
    ) -> None:
        super(CWN, self).__init__()
        self.baseline = baseline
        self.in_planes = in_planes
        self.classes = classes
        self.k = k

        self.global_avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.conv_block1 = conv_block(self.in_planes)
        self.conv_block2 = conv_block(1)

        self.conv1 = conv1x1(self.in_planes, sum(self.k))
        self.bn1 = nn.BatchNorm2d(sum(self.k))
        self.relu = nn.ReLU(inplace=True)
        self.dropout = nn.Dropout(p=0.5)
        self.global_maxpool = nn.AdaptiveMaxPool2d((1, 1))
        self.conv_block3 = conv_block(self.classes)
        self.conv_block4 = conv_block(1)

        self.fc1 = nn.Linear(self.in_planes, self.in_planes // 2)
        self.relu = nn.ReLU(inplace=True)
        self.fc2 = nn.Linear(self.in_planes // 2, self.classes)

    def forward(self, x: Tensor) -> Tensor:
        x = self.baseline(x)

        # chanel
        out1 = self.global_avgpool(x)
        out1 = self.conv_block1(out1)
        C_A = torch.mul(out1, x)

        # sapce
        out2 = torch.mean(x, dim=-3, keepdim=True)
        out2 = self.conv_block2(out2)
        S_A = torch.mul(out2, x)

        # category
        out3 = self.conv1(x)
        out3 = self.bn1(out3)
        out3 = self.relu(out3)
        out3 = self.dropout(out3)

        out3 = list(torch.split(out3, self.k, 1))
        for i, item in enumerate(out3):
            out3[i] = torch.mean(out3[i], dim=1, keepdim=False)
        S = torch.stack(out3, 1)

        out3 = self.global_maxpool(S)
        out3 = self.conv_block3(out3)
        T_A1 = torch.mul(S, out3)

        out3 = torch.mean(T_A1, dim=1, keepdim=True)
        out3 = self.conv_block4(out3)
        T_A2 = torch.mul(x, out3)

        out = (C_A + S_A + T_A2)/3
        out = self.global_avgpool(out)
        out = out.flatten(1)
        out = self.fc1(out)
        out = self.relu(out)
        out = self.fc2(out)

        return out

def cwn(model_name='efficientnet', num_classes=5, K=[]):
    if model_name == 'densenet121':
        baseline = torchvision.models.densenet121(pretrained=False)
        state_dict = torch.load("BaseLine/densenet121-a639ec97.pth")
        new_state_dict = OrderedDict()
        for k, v in state_dict.items():
            if 'denseblock' in k:
                param = k.split(".")
                k = ".".join(param[:-3] + [param[-3] + param[-2]] + [param[-1]])
            new_state_dict[k] = v
        baseline.load_state_dict(new_state_dict)
        baseline = nn.Sequential(*list(baseline.children())[:-1])
        inplace = 1024
    elif model_name == "unet":
        baseline = UNet(3, 2)
        baseline.load_state_dict(torch.load('BaseLine/unet_carvana_scale0.5_epoch2.pth'))
        inplace = 2
    elif model_name == "resnet50":
        baseline = torchvision.models.resnet50(pretrained=False)
        baseline.load_state_dict(torch.load('BaseLine/resnet50-0676ba61.pth'))
        baseline = nn.Sequential(*list(baseline.children())[:-2])
        inplace = 2048
    else:
        baseline = efficientnetv2_s()
        baseline.load_state_dict(torch.load('BaseLine/pre_efficientnetv2-s.pth'))
        baseline = nn.Sequential(*list(baseline.children())[:-1])
        inplace = 256

    return CWN(baseline, inplace, num_classes, K)


import numpy as np
import matplotlib.pyplot as plt

def MetNaiva(f, a, b, n, x):
    X = np.linspace(a, b, n+1)
    Y = f(X)
    A = np.vander(X)
    C = np.linalg.solve(A, Y)
    C = np.flip(C)
    y = 0
    for i in range(n+1):
        y += C[i] * x ** i
    return y

def f(x):
    return np.exp(2*x)
#
a = - 1
b = 1

def PlotInterpolare(f, a, b, n, metoda):
    plt.title('n = {val}'.format(val=n))
    X = np.linspace(a, b, n+1)
    x_grafic = np.linspace(a, b, 50*n+1)
    Pn = []
    for x in x_grafic:
        Pn.append(metoda(f, a, b, n, x))
    plt.plot(x_grafic, f(x_grafic), c='g', linewidth=1)
    plt.plot(x_grafic, Pn, c='r', linestyle='dotted', linewidth=1)
    for el in X:
        plt.scatter(el, f(el), c='b')
    plt.legend(['Functia f', 'Polinomul de interpolare Lagrange'])
    plt.show()

for i in range(1, 5):
    PlotInterpolare(f, a, b, i, MetNaiva)

def PlotInterpolareEroare(f, a, b, n, metoda):
    plt.title('Eroare absoluta pt n = {val}'.format(val=n))
    X = np.linspace(a, b, n+1)
    x_grafic = np.linspace(a, b, 50*n+1)
    Pn = []
    for x in x_grafic:
        Pn.append(metoda(f, a, b, n, x))
    plt.plot(x_grafic, abs(f(x_grafic) - Pn), c='r')
    plt.show()

for i in range(1, 5):
    PlotInterpolareEroare(f, a, b, i, MetNaiva)

#Rezolvare Ex2

def MetLagrange(f, a, b, n, x):
    X = np.linspace(a, b, n + 1)
    Y = f(X)
    y = 0
    for k in range(n+1):
        L = 1
        for i in range(n + 1):
            if i != k:
                L = L * (x-X[i])/(X[k] - X[i])
        y = y + L * Y[k]
    return y

for i in range(1, 5):
    PlotInterpolare(f, a, b, i, MetLagrange)

for i in range(1, 5):
    PlotInterpolareEroare(f, a, b, i, MetLagrange)


# -*- coding: utf-8 -*-
from odoo import models, fields

class ResConfigSettings(models.TransientModel):
    _inherit = "res.config.settings"

    refund_employee_ids = fields.Many2many('hr.employee',config_parameter='pos_product_brand.refund_employee_ids')

class PosConfigSettings(models.Model):
    _inherit = "pos.config"


import os

# 必须在加载 加之前
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d, %d" % (0, 30)

import random
import pygame
from pygame.locals import *
from math import pi, sin, cos

pygame.init()
# 获取显示器大小
screen_width, screen_height = pygame.display.get_desktop_sizes()[0]

ICON = "./icon.png"
TITLE = "见到你时我的心"
WIDTH = 800
HEIGHT = 800
main_loops = True
# 心形中心点
center_x = screen_width / 2
center_y = screen_height / 2
#
screen = pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)
pygame.display.set_caption(TITLE)
pygame.mouse.set_visible(False)
try:
    pygame.display.set_icon(pygame.image.load(ICON))
except:
    pass

bottomlefttip_h = "[f:全屏/窗口][s:闪烁][t:跳动][+/-:频率][esc:退出]: "
bottomlefttip = bottomlefttip_h
bottomrighttip_h = "[鼠标位置]: "
bottomrighttip = bottomrighttip_h
HOT_PINK = (255,105,180)

class Particle():
    def __init__(self, pos, size, f):
        # (left, top, width, height)
        self.pos = pos.copy()
        self.pos0 = pos.copy()
        self.size = size
        self.f = f

    def draw(self, center_x, center_y):
        """
        Rect((left, top), (width, height)) -> Rect
        :return:
        """

        pygame.draw.rect(screen, HOT_PINK,
                         pygame.Rect((self.size * self.f * self.pos[0] + center_x, -self.size * self.f * self.pos[1] + center_y),
                            (self.pos[2], self.pos[3])),
                         0)

    def update(self, t):
        # 全部一个呼吸系数
        # df = 1 + (2 - 1.5 ) * sin(t * 3) / 8
        # df = 1 +  (heartbeatmplitude )*sin(t * 3) / 8

        # 外内，内快，参数外小内大
        df = 1 + (2 - 1.5 * self.f) * sin(t * 3) / 8
        self.pos[0] = self.pos0[0] * df
        self.pos[1] = self.pos0[1] * df

class MouseParticle():

    def __init__(self, pos):
        # (left, top, width, height)
        self.pos = pos.copy()
        self.particles = []
        self.xiaoshishudu = .8
        self.xiaoshishuduxishu = 1.2

        self.show = .5
        no_p = 50
        # dt 离散点数
        dt = 2 * pi / no_p
        t = 0
        while t <= 2 * pi:
            # 正向随机分面
            l = mu - abs(random.gauss(mu, sigma) - mu)
            # 双向分布
            # l=random.gauss(mu, sigma)
            # l=1，表示画一个线
            # l=1

            xleft = l * 16 * sin(t) ** 3
            ytop = l * (13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
            t += dt
            self.particles.append(Particle([xleft, ytop, static_wh[0], static_wh[1]], 1, l))

    def draw(self):
        """
        Rect((left, top), (width, height)) -> Rect
        :return:
        """
        if not self.show:
            return
        if self.xiaoshishudu < 0.000005:
            self.show = 0

        for p in self.particles:
            p.draw(self.pos[0], self.pos[1])

        self.update()

    def update(self):
        self.xiaoshishudu = self.xiaoshishudu ** self.xiaoshishuduxishu
        for p in self.particles:
            p.update(self.xiaoshishudu)

    def jiashudu(self):
        if self.xiaoshishuduxishu < 3:
            self.xiaoshishuduxishu += .1

    def jianshudu(self):
        if self.xiaoshishuduxishu > 1.1:
            self.xiaoshishuduxishu -= .1

mouseParticleList = []

particles = []

"""
若随机变量X服从一个数学期望为μ、方差为σ^2的正态分布，记为N(μ，σ^2)
期望值μ决定了其位置，其标准差σ决定了分布的幅度。当μ = 0,σ = 1时的正态分布是标准正态分布

心形公式
    x=16*sin(t)**3
    y=13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
"""
# 均值，心形的大小
mu = 1.1
# 是标准差，辐射范围
sigma = .15

# 静态心形点的大小
static_wh = (1.5, 1.5)
# 动态心形点大小，
dynamic_wh = (1, 2)
# 心跳幅度
heartbeatmplitude = 1.2

# 心形大小
size = 15

# 外部开关
waiweikaiguan = True
# 跳动开关
tiaodongkaiguan = True
# 窗口，全屏
fullscreenkaiguan = False
# 跳动频率
jumpfreq=30

no_p = 10000
# dt 离散点数
dt = 2 * pi / no_p
t = 0

#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++
# 3万个点

def init_dynamic_particles():
    # dt 离散点数
    global t
    # 初始化跳动心形点
    while t <= 2 * pi:
        # 正向随机分面
        l = mu - abs(random.gauss(mu, sigma) - mu)
        # 双向分布
        # l=random.gauss(mu, sigma)
        # l=1，表示画一个线
        # l=1

        xleft = l * 16 * sin(t) ** 3
        ytop = l * (13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t))
        t += dt
        particles.append(Particle([xleft, ytop, static_wh[0], static_wh[1]], size, l))

# def draw():
#     screen.clear()
#     for i in range(len(x)):
#         screen.draw.filled_rect(Rect((x[i]*10+center_x, -y[i]*10+center_y), (4, 4)), 'pink')

def show_ynamic_particles():
    for p in particles:
        p.draw(center_x, center_y)

def show_static_particles():
    # 3万个点
    # no_p = 20000
    # dt 离散点数
    t = 0
    while waiweikaiguan and t < 2 * pi:
        f = random.gauss(mu, sigma * 2)
        x = 16 * sin(t) ** 3
        y = 13 * cos(t) - 5 * cos(2 * t) - 2 * cos(3 * t) - cos(4 * t)
        # uniform成下一个实数，它在 [x,y] 范围内
        pygame.draw.rect(screen, HOT_PINK,
                         Rect((17 * f * x + center_x, -17 * f * y + center_y), (random.uniform(.5, 3), random.uniform(.5, 3))),
                         0
                         )
        # screen.draw.filled_rect(
        #     Rect((17 * f * x + center_x, -17 * f * y + center_y), (random.uniform(.5, 3), random.uniform(.5, 3))),
        #     'hot pink')
        t += dt * 2

def show_mouse_particles():
    global mouseParticleList
    t = []
    for p in mouseParticleList:
        if p.show:
            t.append(p)
            p.draw()
        else:
            break
    mouseParticleList = t

def add_mouse_particles(pos):
    global mouseParticleList
    mouseParticleList = [MouseParticle(pos)] + mouseParticleList

def draw_text(sc, str, position, pos:tuple , color, background="black", fontsize=24, name=None):
    text = pygame.font.SysFont(name, fontsize).render(str, True, color, background)
    textRect = text.get_rect()
    if position.startswith("c"):
        textRect.center = pos
    elif position.startswith("m"):
        pass
    elif position.startswith("bottomleft"):
        textRect.bottomleft=pos
    elif position.startswith("bottomright"):
        textRect.bottomright=pos
    elif position.startswith("topleft"):
        textRect.topleft=pos
    elif position.startswith("topright"):
        textRect.topright=pos
    else:
        try:
            raise AttributeError("position")  # 假装这里有异常，一般针对难以复现的异常
        except:
            print("""postion
                    # bottomleft=(100, 100)
                    # topleft=(100, 100)
                    # topright=(100, 100)
                    # bottomright=(100, 100)
                    #
                    # midtop=(100, 100)
                    # midleft=(100, 100)
                    # midbottom=(100, 100)
                    # midright=(100, 100)
                    # center=(100, 100)""")

    sc.blit(text, textRect)

    # bottomleft=(100, 100)
    # topleft=(100, 100)
    # topright=(100, 100)
    # bottomright=(100, 100)
    #
    # midtop=(100, 100)
    # midleft=(100, 100)
    # midbottom=(100, 100)
    # midright=(100, 100)
    # center=(100, 100)
    # centerx
    # centery

def draw():
    # 清空全部内容
    screen.fill("black")
    # 显示区域
    draw_text(screen, "显示文字", "center", (center_x, center_y), HOT_PINK, "black", 24, "SimSun")
    draw_text(screen, bottomlefttip, "bottomleft", (0, center_y * 2), HOT_PINK, "black", 12, "SimSun")
    draw_text(screen, bottomrighttip, "bottomright", (center_x * 2, center_y * 2), HOT_PINK, "black", 12, "SimSun")

    # 显示动态心形
    show_ynamic_particles()
    """
        初始化外部心形情况
    """
    show_static_particles()
    # 显示鼠标
    show_mouse_particles()
    """
        screen.draw.text("ccccccccc\nbbbbbbbbb", center=(100, 100), color='hot pink', background="black", fontsize=24)
        screen.draw.text("1", bottomleft=(100, 100), color=(200, 200, 200), background="black")
        screen.draw.text("2", topleft=(100, 100), color=(200, 200, 200), background="black")
        screen.draw.text("3", topright=(100, 100), color=(200, 200, 200), background="black")
        screen.draw.text("4", bottomright=(100, 100), color=(200, 200, 200), background="black")

        screen.draw.text("5", midtop=(100, 100), color=(200, 200, 200), background="black")
        screen.draw.text("6", midleft=(100, 100), color=(200, 200, 200), background="black")
        screen.draw.text("7", midbottom=(100, 100), color=(200, 200, 200), background="black")
        screen.draw.text("8", midright=(100, 100), color=(200, 200, 200), background="black")
    """
    #刷新一下画面，将画的东西显示到画面上
    pygame.display.update()

def update(dt):
    # dt 1/fps 两帧之间的时间间隔 单位是秒
    global t
    t += dt
    if tiaodongkaiguan:
        for p in particles:
            p.update(t)

# 加载背景音乐
def musicloops(path):
    pygame.mixer.init()
    try:
        pygame.mixer.music.load(path)
        pygame.mixer.music.play(-1)
    except:
        pass

def on_mouse_down(pos, button):
    # print(pos, button)
    global bottomrighttip
    bottomrighttip = bottomrighttip_h + str(pos) + str(button)

def on_mouse_up(pos, button):
    pass

def on_mouse_move(pos, rel, buttons):
    # print(pos, rel, buttons)
    global bottomrighttip
    bottomrighttip = bottomrighttip_h + str(pos)
    # 更新状态
    add_mouse_particles([pos[0], pos[1]])

def on_key_down(key):
    global screen
    global bottomlefttip, fullscreenkaiguan, waiweikaiguan, tiaodongkaiguan
    bottomlefttip = bottomlefttip_h + pygame.key.name(key)
    global center_x, center_y
    global jumpfreq

    if key == K_f:
        if fullscreenkaiguan:
            # screen =
            pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
            # 发现从pygame.FULLSCREEN，到pygame.RESIZABLE调用一次不起作用
            pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE)
            center_x = WIDTH / 2
            center_y = HEIGHT / 2
            pass
            pygame.mouse.set_visible(True )
        else:
            # pygame.display.set_mode((screen_width, screen_height), pygame.NOFRAME)
            # screen =
            pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)
            pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)
            center_x = screen_width / 2
            center_y = screen_height / 2
            pygame.mouse.set_visible(False)
        # , pygame.NOFRAME
        fullscreenkaiguan = not fullscreenkaiguan
        bottomlefttip += " 全屏"+str(fullscreenkaiguan)
    elif key == K_ESCAPE:
        global main_loops
        main_loops=False
    elif key == K_SPACE:
        pass
    elif key == K_s:
        waiweikaiguan = not waiweikaiguan
        bottomlefttip += " 闪烁"+str(waiweikaiguan)

    elif key == K_t:
        tiaodongkaiguan = not tiaodongkaiguan
        bottomlefttip += " 跳动"+str(tiaodongkaiguan)

    elif key == K_KP_PLUS or key == K_PLUS:
        if jumpfreq>5:
            jumpfreq-=5
        bottomlefttip += " 频率=" + str(jumpfreq)
    elif key == K_KP_MINUS or key == K_MINUS:
        if jumpfreq<60:
            jumpfreq+=5
        bottomlefttip += " 频率=" + str(jumpfreq)
    elif key == K_MENU:
        pass
    else:
        bottomlefttip += " 无动作 "

# pgzrun.go()

def event():
    global center_x, center_y

    for event in pygame.event.get():

        # if event.type not in [KEYDOWN, MOUSEMOTION, MOUSEBUTTONDOWN, MOUSEBUTTONUP]:
        #     print(event)

        if event.type == QUIT:
            global main_loops
            main_loops = False

        elif event.type == KEYDOWN:
        # 键盘被按下 unicode 、key 、mod
            on_key_down(event.key)
        # https://blog.csdn.net/qq_41556318/article/details/86304649
        # http://t.zoukankan.com/liquancai-p-13235734.html
        elif event.type == MOUSEMOTION:
        # MOUSEMOTION 鼠标移动  pos 、rel 、buttons
        # <Event(1024-MouseMotion {'pos': (289, 464), 'rel': (2, -5), 'buttons': (0, 0, 0), 'touch': False, 'window': None})>
            on_mouse_move(event.pos, event.rel, event.buttons)
        elif event.type == MOUSEBUTTONDOWN:
        # MOUSEBUTTONDOWN 鼠标被按下pos 、button
        # <Event(1025-MouseButtonDown {'pos': (289, 464), 'button': 1, 'touch': False, 'window': None})>
            on_mouse_down(event.pos, event.button)
        elif event.type == MOUSEBUTTONUP:
        # MOUSEBUTTONUP鼠标被放开pos 、button
            on_mouse_up(event.pos, event.button)

        elif event.type == VIDEORESIZE:
            center_x = event.w / 2
            center_y = event.h / 2

        elif event.type == WINDOWMAXIMIZED:
            # 窗口最大化
            print(event)
        elif event.type == WINDOWMINIMIZED:
            # 窗口最大化
            print(event)
            pygame.mixer.music.pause()
        elif event.type == WINDOWRESTORED:
            # 重新显示
            pygame.mixer.music.unpause()
        elif event.type == WINDOWSHOWN:
            print(event)

        elif event.type == ACTIVEEVENT:
            # print(pygame.mixer.music.get_busy())
            # try:
            #     if event.gain and not pygame.mixer.music.get_busy():
            #         #显示内容
            #         pygame.mixer.music.pause()
            #     elif not event.gain and pygame.mixer.music.get_busy():
            #         pygame.mixer.music.pause()
            # except:
            #     pass
            pass

if __name__ == '__main__':
    musicloops("bfa.mp3")
    # 初始化动态心形点，只执行一次
    init_dynamic_particles()

    # Run the game loop.
    while main_loops:
        event()
        update(1/jumpfreq)
        draw()

    pygame.quit()

# pyinstaller -F -c -w -i favicon.ico --clean xx-pygame.py
# cxfreeze xg.py --target-dir x --base-name=win32gui


from odoo import api, fields, models
from odoo.exceptions import UserError

class ResCurrency(models.Model):
    _inherit = 'res.currency'

    @api.model
    def _get_conversion_rate(self, from_currency, to_currency, company, date):
        if self.env.context.get('force_fx_rate'):
            fx_rate = self.env.context.get('force_fx_rate')
        elif hasattr(self.env.context, 'force_fx_rate'):
            fx_rate = self.env.context.force_fx_rate
        else:
            return super()._get_conversion_rate(from_currency, to_currency, company, date)

        if from_currency == company.currency_id:
            return 1.0 / fx_rate
        elif to_currency == company.currency_id:
            return fx_rate
        else:
            raise UserError("A forced currency rate must be from or to the company currency. {} -> {}".format(
                from_currency.code,
                to_currency.code,
            ))


from libvirt import libvirtError
from libvirttestapi.src import sharedmod
from libvirttestapi.repos.storage import storage_common
from libvirttestapi.utils import process

required_params = ('poolname', 'sourcehost', 'sourcepath',)
optional_params = {'targetpath': '/tmp/netfs_test',
                   'xml': 'xmls/netfs_pool.xml',
                   }

def set_virt_use_nfs(logger):
    cmd = 'setsebool virt_use_nfs on'
    ret = process.run(cmd, shell=True, ignore_status=True)
    if ret.exit_status != 0:
        logger.error("cmd failed: %s" % cmd)

    return 0

def define_netfs_pool(params):
    """Define a netfs type storage pool from xml"""
    logger = params['logger']
    poolname = params['poolname']
    xmlstr = params['xml']

    conn = sharedmod.libvirtobj['conn']

    if not storage_common.check_pool(conn, poolname, logger):
        logger.error("%s storage pool is defined" % poolname)
        return 1

    logger.debug("storage pool xml:\n%s" % xmlstr)

    set_virt_use_nfs(logger)

    pool_num1 = conn.numOfDefinedStoragePools()
    logger.info("original storage pool define number: %s" % pool_num1)
    storage_common.display_pool_info(conn, logger)

    try:
        logger.info("define %s storage pool" % poolname)
        conn.storagePoolDefineXML(xmlstr, 0)
        pool_num2 = conn.numOfDefinedStoragePools()
        logger.info("current storage pool define number: %s" % pool_num2)
        storage_common.display_pool_info(conn, logger)
        if storage_common.check_pool_define(poolname, logger) and pool_num2 > pool_num1:
            logger.info("define %s storage pool is successful" % poolname)
        else:
            logger.error("%s storage pool is undefined" % poolname)
            return 1
    except libvirtError as e:
        logger.error("API error message: %s, error code is %s"
                     % (e.get_error_message(), e.get_error_code()))
        return 1

    return 0


# finding substring in given string
s="durgasoftdurgasofthydrabaaddurgasoftsoftsoft"
sb="soft"
i=0
j=0
while i<len(s):
    if sb[j]!=s[i]:
        i+=1
        continue
    elif sb[j]==s[i]:
        print(sb[j],end="")
        j+=1
        i+=1
        if j>=len(sb):
            print(" At Index: ",i-j)
            j=0
            continue


# ImagePreprocess.py
# 因为从网上找的数据集中的图片大小不一致，不方便之后构建特征集，因此先对所有图片进行大小设置
from PIL import Image   # 调入图片处理类
import os.path
import glob  # 文件操作类
# 将图片的大小统一设置为28*28像素
def convertjpg(jpgfile, outdir, width=28, height=28):
    img=Image.open(jpgfile)
    try:
        new_img = img.resize((width, height), Image.BILINEAR)
        new_img.save(os.path.join(outdir, os.path.basename(jpgfile)))
    except Exception as e:
        print(e)
# 对训练集和测试集中的图片进行大小标准化处理
for jpgfile in glob.glob(r".\trainImages\*.png"):
    convertjpg(jpgfile, r".\trainImages")
for jpgfile in glob.glob(r".\testImages\*.png"):
    convertjpg(jpgfile, r".\testImages")


import os
import sys
import tempfile
import logging
import fcntl
import errno
import signal
from signal import SIGABRT,  SIGILL, SIGINT, SIGSEGV, SIGTERM, signal, SIGQUIT
import atexit

def signal_handler(signal, frame):
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGQUIT, signal_handler)
    signal.signal(signal.SIGTSTP, signal_handler)

def single_process():
    filename = os.path.abspath(sys.argv[0])
    lock_file_name = filename.lstrip('/').replace('/', '_') + '.lock'

    lock_file_path = os.path.join(
        tempfile.gettempdir(), lock_file_name)
    fd = os.open(lock_file_path, os.O_CREAT | os.O_RDWR, 0o660)
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError as e:
        if e.errno in (errno.EACCES, errno.EAGAIN):
            logging.error(
                '%s RUNNING . QUIT' % filename
            )
            sys.exit(0)
        else:
            raise

    def exit(signal, frame):
        os.close(fd)
        os.remove(lock_file_path)
        sys.exit(signal)

    for sig in (SIGABRT,  SIGILL, SIGINT, SIGSEGV, SIGTERM, SIGQUIT):
        signal(sig, exit)
    atexit.register(lambda: exit(0, 0))

if __name__ == "__main__":

    single_process()

    def test():
        from time import sleep
        from datetime import datetime
        for i in range(3):
            print(datetime.now())
            sleep(1)
    test()


from django.core.exceptions import ObjectDoesNotExist
from django.db import models

from profiles.models import UserProfile
from shopping.models import Item

class CartManager(models.Manager):
    """A custom manager for the Cart model.

    This manager provides a method for getting or creating a cart for a given user.

    """
    def get_or_create_by_user(self, user: UserProfile) -> "Cart":
        """Gets or creates a cart for a given user.

        Args:
            user: A UserProfile object representing the user to get or create a cart for.

        Returns:
            A Cart object representing the user's cart.

        """

        try:
            return user.cart
        except ObjectDoesNotExist:
            return self.create(user_profile=user)

class Cart(models.Model):
    """A model representing a user's shopping cart.

    Attributes:
        user_profile: A ForeignKey field linking to the UserProfile model representing the user who owns the cart.
        items: A ManyToManyField representing the items in the cart and their quantities.

    Properties:
        total_cost: An integer representing the total cost of all items in the cart.

    """
    user_profile: models.ForeignKey = models.OneToOneField(UserProfile, on_delete=models.CASCADE)
    items: models.ManyToManyField = models.ManyToManyField(Item, related_name="carts")

    objects = CartManager()

    @property
    def total_cost(self) -> int:
        """Calculates the total cost of all items in the cart.

        Returns:
            An integer representing the total cost of all items in the cart.

        """
        return self.items.aggregate(models.Sum("price"))["price__sum"] or 0

    def __str__(self) -> str:
        """Returns a string representation of the cart.

        Returns:
            A string representing the cart and its owner.

        """
        return f"{self.user_profile}'s cart"


import os
import psycopg2
import random
import sqlite3
import telebot
import time

types_dict = {
    0: 'Отжимания',
    10: 'Бег',
    20: 'Пресс'
}
push_ups = {
    1: 'Узким хватом',
    2: 'Средним хватом',
    3: 'Широким хватом',
    4: 'Задние',
}

def get_key(my_dict, val):
    for key, value in my_dict.items():
        if val == value:
            return key
    return None

keyboard_basic = telebot.types.ReplyKeyboardMarkup(True)
keyboard_activity = telebot.types.ReplyKeyboardMarkup(True, True)
keyboard_push_ups = telebot.types.ReplyKeyboardMarkup(True, True)
keyboard_basic.row('Внести данные', 'График')
for key in types_dict:
    keyboard_activity.add(types_dict[key])
for key in push_ups:
    keyboard_push_ups.add(push_ups[key])

DATABASE_URL = os.environ['DATABASE_URL']
token = os.environ.get('token', None)
bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Бот для статистики упражнений', reply_markup=keyboard_basic)

@bot.message_handler(content_types=['text'])
def send_text(message):
    chat_id = message.chat.id
    if message.text.lower() == 'привет':
        bot.send_message(chat_id, 'Приветствую тебя, мой ,белый хозяин!')
    elif message.text.lower() == 'внести данные':
        bot.send_message(chat_id, 'Выберите упражнение', reply_markup=keyboard_activity)
        bot.register_next_step_handler(message, choose_type)
    elif message.text.lower() == 'график':
        connection = psycopg2.connect(DATABASE_URL, sslmode='require')
        cursor = connection.cursor()
        try:
            cursor.execute(
                "SELECT type, result, date FROM measurements WHERE chat_id = %s ORDER BY date;"
                % chat_id
            )
        except:
            pass
        data = cursor.fetchall()
        for measurement in data:
            res = 'type: ' + str(measurement[0]) + ', result: ' + measurement[1] + ', date: ' + measurement[2]
            bot.send_message(chat_id, res, reply_markup=keyboard_basic)
        connection.close()

def choose_type(message):
    if message.text == types_dict[0]:
        bot.send_message(message.chat.id, 'Выберите тип отжимания', reply_markup=keyboard_push_ups)
        bot.register_next_step_handler(message, choose_type)
    else:
        bot.send_message(message.chat.id, 'Введите результаты тренировки')
        global activity_type
        activity_type = get_key(types_dict, message.text)
        if activity_type is None:
            activity_type = get_key(push_ups, message.text)
        # print(message, activity_type)
        bot.register_next_step_handler(message, enter_data)

def enter_data(message):
    conn = psycopg2.connect(DATABASE_URL, sslmode='require')
    cursor = conn.cursor()
    global activity_type
    try:
        cursor.execute(
            "INSERT INTO measurements (chat_id, type, result, date) VALUES (%s, %i, %s, %s)"
            % (message.chat.id, activity_type, message.text, time.strftime("%Y-%m-%d", time.gmtime()))
        )
        conn.commit()
    except Exception as exc:
        print(exc)
        bot.send_message(message.chat.id, 'Произошла какая-то ошибка', reply_markup=keyboard_basic)
    else:
        bot.send_message(message.chat.id, 'Данные успешно записаны!', reply_markup=keyboard_basic)
    conn.close()

# Executing
while True:
    try:
        bot.polling(none_stop=True)

    except Exception as e:
        print(e)
        time.sleep(15)


# https://leetcode.com/problems/implement-strstr/description/

"""
Implement strStr() - http://www.cplusplus.com/reference/cstring/strstr/.

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
"""

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

haystack = "hello"
needle = "ll"
x = Solution()
print(x.strStr(haystack, needle))


from PyPDF2 import PdfReader
import json

def convert_pdf_to_word_list(pdf_path):
    word_list = []

    # Abrir o arquivo PDF
    with open(pdf_path, 'rb') as file:
        pdf_reader = PdfReader(file)

        # Iterar pelas páginas do PDF
        for page in pdf_reader.pages:
            text = page.extract_text()

            # Dividir o texto em palavras
            words = text.split()

            # Adicionar as palavras à lista geral
            word_list.extend(words)

    return word_list

# Exemplo de uso
pdf_path = './arquivo.pdf'
word_list = convert_pdf_to_word_list(pdf_path)

# Salvar a lista de palavras em um arquivo JSON
output_path = 'pdf.json'
with open(output_path, 'w') as file:
    json.dump(word_list, file, indent=4)

print(f"Arquivo JSON salvo em: {output_path}")


import h5py
import numpy as np
import os
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import time

def split_train_test(images, labels, train_percent, random_seed = 0):
    np.random.seed(random_seed)
    images_labels = np.hstack((images, labels.reshape(len(labels), 1)))
    perm = np.random.permutation(len(images_labels))
    number_of_samples = len(images_labels)
    train_end = int(train_percent * number_of_samples)
    train = images_labels[perm[:train_end], :]
    test = images_labels[perm[train_end:], :]

    return train[:, 0 : -1].astype(np.float32), train[:, -1].astype(np.int32), test[:, 0 : -1].astype(np.float32), test[:, -1].astype(np.int32)

def pca(images, num_pc, mean_source = None):
    dim = images.shape[1]
    if num_pc > dim or num_pc < 1:
        num_pc = dim

    if mean_source is None:
        mean_source = images

    # de-mean the data:
    data_mean = images.mean(axis = 0)
    data = images - data_mean
    # get covariance matrix:
    mat_cov = np.cov(data.T) / data.shape[0]
    # eigen decomposition
    eig_values, eig_vecs = np.linalg.eig(mat_cov)
    # sort the eigenvectors in eigen-value descending order
    sort_idx = eig_values.argsort()[::-1]
    eig_values = eig_values[sort_idx]
    eig_vecs = eig_vecs[:, sort_idx]
    # get largest num_pc eigenvectors
    selected_pcs = eig_vecs[:, :num_pc]

    data_low_dim = data.dot(selected_pcs)

    data_reconstructed = data_low_dim.dot(selected_pcs.T) + data_mean

    ## debug code
    #plt.figure()
    #plt.imshow(data[0].reshape(28, 28), cmap=plt.get_cmap('gray'))
    #plt.show()
    #plt.imshow(data_reconstructed[0].reshape(28, 28),cmap=plt.get_cmap('gray'))
    #plt.show()

    return data_low_dim, data_reconstructed

class ConfusionMatrixHelper:

    # the x axis stands for predicted, y axis stands for truth
    @staticmethod
    def get_confusion_matrix(predicted, truth, number_of_labels):
        conf_mat = np.zeros((number_of_labels, number_of_labels), dtype=np.int32)
        num_records = predicted.size
        for i in range(num_records):
            conf_mat[truth[i]][predicted[i]] += 1

        return conf_mat

    @staticmethod
    def get_accuracy_by_confusion_matrix(conf_mat):
        return float(conf_mat.trace()) / np.sum(conf_mat)

    @staticmethod
    def plot_confusion_mat(predicted, truth, number_of_labels, title = ""):
        plt.figure(figsize=(10,7))
        conf_mat = ConfusionMatrixHelper.get_confusion_matrix(predicted, truth, number_of_labels)
        ax = sns.heatmap(conf_mat, annot=True, fmt="d")
        plt.ylabel('True')
        plt.xlabel('Predicted')

        accuracy = ConfusionMatrixHelper.get_accuracy_by_confusion_matrix(conf_mat)
        plt.title(title + "; Accuracy: {}".format(accuracy))
        plt.show()


#!/usr/bin/python3
"""
Test Driven Doc Lazy Matrix mul

"""

import numpy

def lazy_matrix_mul(m_a, m_b):
    """
    function that multiplies 2 matrices by using the module NumPy
    Returns: new matrix
    """
    if type(m_a) is str or type(m_b) is str:
        raise TypeError("Scalar operands are not allowed, use '*' instead")
    for i in m_a:
        for j in i:
            if type(j) is str:
                raise TypeError("invalid data type for einsum")
    for a in m_b:
        for b in a:
            if type(b) is str:
                raise TypeError("invalid data type for einsum")
    return numpy.dot(m_a, m_b)


import csv

with open('Utilities/loanapp.csv') as csvFile:
    csvReader=csv.reader(csvFile,delimiter=',')
    print(csvReader)
    listCSV=list(csvReader)
    print(listCSV)
    name=[]
    stats=[]
    for row in listCSV:
        print(row)
        name.append(row[0])
        stats.append(row[1])
print(name)
print(stats)
csvFile.close()
with open('Utilities/loanapp.csv','a') as csvWriteFile:
    csvWriter=csv.writer(csvWriteFile)
    csvWriterEachRow = csvWriter.writerow(["Shob","Rejected"])
csvWriteFile.close()


from collections import defaultdict

with open('segments.txt') as f:
    sequences = [l.strip() for l in f.readlines()]

patterns = []
outputs = []

for s in sequences:
    pattern, output = [w.strip() for w in s.split('|')]
    pattern = [set(p) for p in pattern.split(' ')]
    output = [set(o) for o in output.split(' ')]

    patterns.append(pattern)
    outputs.append(output)

uniques = 0

for o in outputs:
    for v in o:
        if len(v) == 2 or len(v) == 3 or len(v) == 4 or len(v) == 7:
            uniques += 1

print(uniques)

integer_outputs = []

for i in range(len(outputs)):
    int_out = []
    one, four, seven = None, None, None
    sequence = patterns[i] + outputs[i]

    for s in sequence:
        if len(s) == 2:
            one = s
        elif len(s) == 4:
            four = s
        elif len(s) == 3:
            seven = s

    for v in outputs[i]:
        if len(v) == 2:
            int_out.append(1)
        elif len(v) == 4:
            int_out.append(4)
        elif len(v) == 3:
            int_out.append(7)
        elif len(v) == 7:
            int_out.append(8)
        elif len(v) == 6:
            if four and v.issuperset(four):
                int_out.append(9)
            elif (one and v.issuperset(one)) or (seven and v.issuperset(seven)):
                int_out.append(0)
            elif one or four or seven:
                int_out.append(6)
        elif len(v) == 5:
            if (one and v.issuperset(one)) or (seven and v.issuperset(seven)):
                int_out.append(3)
            elif four and len(v.intersection(four)) == 2:
                int_out.append(2)
            elif four:
                int_out.append(5)
            else:
                print('yikes')

    integer_outputs.append(int_out)

final_integers = []

for o in integer_outputs:
    integer = int(''.join([str(i) for i in o]))
    final_integers.append(integer)

print(final_integers)

print(sum(final_integers))


import sys
from PyQt5.QtWidgets import QMainWindow, QApplication

import mainwindow
import captor_thread
import time

class UserFilter:
    def __init__(self, SrcIp = "", DstIp = "", SrcPort = "", DstPort = "", Protocol = 0):
        ###过滤条件
        self.SrcIp = SrcIp
        self.DstIp = DstIp

        self.SrcPort = SrcPort
        self.DstPort = DstPort
        ##  0:ALL
        ##  1:IP
        ##  2:UDP
        ##  3:TCP
        ##  4:ICMP
        ##  5:ARP
        self.Protocol = Protocol

userfilter = UserFilter()

cur_thread = None

def StartCaptor():
    current_index = ui.comboBox.currentIndex()
    global cur_thread
    cur_thread = captor_thread.start_thread(ui, userfilter, current_index)

def StopCaptor():
    # cur_thread.stop_pcap = True
    if cur_thread is None or cur_thread.capture is None:
        return
    cur_thread.capture.stop()
    # cur_thread.join()

def FilterRule():

    global userfilter

    if len(userfilter.SrcIp) != 0:
        ui.srcip.setText(userfilter.SrcIp)
    if len(userfilter.DstIp) != 0:
        ui.dstip.setText(userfilter.DstIp)
    if len(userfilter.SrcPort) != 0:
        ui.srcport.setText(userfilter.SrcPort)
    if len(userfilter.DstPort) != 0:
        ui.dstport.setText(userfilter.DstPort)
    ui.protocol.setCurrentIndex(userfilter.Protocol)

    ui.FilterWidget.setVisible(True)

def FilterOK():
    global userfilter
    userfilter.Protocol = ui.protocol.currentIndex()
    userfilter.SrcIp = ui.srcip.text()
    userfilter.DstIp = ui.dstip.text()
    userfilter.SrcPort = ui.srcport.text()
    userfilter.DstPort = ui.dstport.text()

    ui.FilterWidget.setVisible(False)

def FilterCancel():
    ui.FilterWidget.setVisible(False)

def CloseWidget():
    if cur_thread is None or cur_thread.capture is None:
        MainWindow.close()
        return
    cur_thread.capture.stop()
    MainWindow.close()

def ShowText(Item):
    if Item is None:
        return
    ui.Text_Edit.setText(str(Item.text()))
    ui.Hex_Edit.setText(' '.join([hex(ord(i))[2:] for i in str(Item.text())]))

def SaveAsFile():
    Itemlist = ui.tableWidget.selectedItems()

    for Item in Itemlist:
        cur_time = time.time()
        with open(str(cur_time), 'w') as file:
            for line in str(Item.text()):
                file.write(line)
            file.close()

##获取设备列表

device_names = captor_thread.GetDevices()

##应用窗口运行
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = mainwindow.Ui_MainWindow()
ui.setupUi(MainWindow)

##在下拉框展示设备列表
for device in device_names:
    ui.comboBox.addItem(device)

MainWindow.show()

##开始抓包：：
##开启一个thread
ui.btn_start.clicked.connect(StartCaptor)

ui.btn_stop.clicked.connect(StopCaptor)

ui.btn_filter.clicked.connect(FilterRule)

ui.btn_ok.clicked.connect(FilterOK)

ui.btn_cancel.clicked.connect(FilterCancel)

ui.btn_quit.clicked.connect(CloseWidget)

ui.tableWidget.itemClicked.connect(ShowText)

ui.btn_save.clicked.connect(SaveAsFile)

print(userfilter.SrcIp)

sys.exit(app.exec_())


from django.db.models import Q
from django.http import HttpResponseRedirect
from django.shortcuts import render
from schedule_advisor.forms import ClassSearchForm, AdviseeChoiceForm
from schedule_advisor.models import Schedule, Class, User
from django.contrib import messages

def search_view(request):
    results = None
    if request.method == "POST":
        form = ClassSearchForm(request.POST)
        if form.is_valid():
            # results = ClassSearchForm.get_results(form.cleaned_data)
            results = ClassSearchForm.get_results_from_database(form.cleaned_data)
    else:
        form = ClassSearchForm()
    return render(
        request, "schedule_advisor/index.html", {"form": form, "results": results}
    )
def home_view(request):
    return render(
        request, "schedule_advisor/home.html"
    )

def schedule_view(request):
    days_of_week = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
    ]
    days_from_abbrev = {day[:2]: day for day in days_of_week}
    if not request.user.is_authenticated:
        messages.add_message(request, messages.ERROR, "You are not logged in!")
        return HttpResponseRedirect("/")
    u = User.objects.get_or_create(username=request.user.username)[0]
    if u.is_advisor:
        messages.add_message(request, messages.ERROR, "You are not a student!")
        return HttpResponseRedirect("/")
    schedule = Schedule.objects.get_or_create(connected_user_id=u.id)[0]
    schedule_by_day = {day: list() for day in days_of_week}
    for cl in schedule.classes.all():
        for day in cl.meeting_days():
            if day not in days_from_abbrev:
                schedule_by_day[day] = [cl]
            else:
                schedule_by_day[days_from_abbrev[day]].append(cl)
    for day, classes in schedule_by_day.items():
        if day not in days_of_week:
            classes.sort(key=lambda c: c.name)
            continue
        abbrev = day[:2]
        classes.sort(
            key=lambda c: tuple(
                int(i) for i in c.meeting_days()[abbrev][0].split(".")[:3]
            )
        )
    return render(
        request,
        "schedule_advisor/schedule.html",
        {
            "schedule_by_day": schedule_by_day,
            "days_of_week": days_of_week,
            "schedule": schedule,
        },
    )

def class_schedule_change_view(request):
    u = User.objects.get_or_create(username=request.user.username)[0]
    if u.is_advisor:
        messages.add_message(request, messages.ERROR, "You are not a student!")
        return HttpResponseRedirect("/")
    if request.method == "POST":
        action = request.POST["action"]
        try:
            if action == "Add to Schedule":
                schedule = Schedule.objects.get_or_create(
                    connected_user_id=request.user.id
                )[0]
                new_class = Class.objects.get_or_create(
                    semester=request.POST["semester"],
                    class_number=int(request.POST["class_number"]),
                )[0]
                schedule.add_class(new_class)
                schedule.reset_advisor()
                messages.add_message(
                    request, messages.SUCCESS, "Course successfully added to schedule!"
                )
            elif action == "Remove from Schedule":
                schedule = Schedule.objects.get_or_create(
                    connected_user_id=request.user.id
                )[0]
                old_class = Class.objects.get_or_create(
                    semester=request.POST["semester"],
                    class_number=int(request.POST["class_number"]),
                )[0]
                schedule.remove_class(old_class)
                schedule.reset_advisor()
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    "Course successfully removed from schedule!",
                )
            else:
                messages.add_message(
                    request, messages.ERROR, "Unable to update schedule!"
                )
        except:
            messages.add_message(request, messages.ERROR, "Unable to update schedule!")
        # https://stackoverflow.com/questions/35796195/how-to-redirect-to-previous-page-in-django-after-post-request
        return HttpResponseRedirect(request.headers.get("referer", "/"))

def advisor_view(request):
    u = User.objects.get_or_create(username=request.user.username)[0]
    if not u.is_advisor:
        messages.add_message(request, messages.ERROR, "You are not an advisor!")
        return HttpResponseRedirect("/")
    else:
        schedules = None
        days_of_week = None
        schedule_by_day = None
        query = None
        advisees = User.objects.filter(advisor=request.user)
        if request.method == "GET":
            query = request.GET.get("q", None)
            if query:
                query = User.objects.filter(
                    Q(is_advisor=False)
                    & (
                        Q(first_name__icontains=query)
                        | Q(last_name__icontains=query)
                        | Q(username__icontains=query)
                    )
                )
        elif request.method == "POST":
            advisee_id = request.POST.get("advisee_id")
            schedules = Schedule.objects.filter(connected_user_id=advisee_id)
            days_of_week = [
                "Sunday",
                "Monday",
                "Tuesday",
                "Wednesday",
                "Thursday",
                "Friday",
                "Saturday",
            ]
            days_from_abbrev = {day[:2]: day for day in days_of_week}
            u = User.objects.get_or_create(id=advisee_id)[0]
            schedule = Schedule.objects.get_or_create(connected_user_id=u.id)[0]
            schedule_by_day = {day: list() for day in days_of_week}
            for cl in schedule.classes.all():
                for day in cl.meeting_days():
                    if day not in days_from_abbrev:
                        schedule_by_day[day] = [cl]
                    else:
                        schedule_by_day[days_from_abbrev[day]].append(cl)
            for day, classes in schedule_by_day.items():
                if day not in days_of_week:
                    classes.sort(key=lambda c: c.name)
                    continue
                abbrev = day[:2]
                classes.sort(
                    key=lambda c: tuple(
                        int(i) for i in c.meeting_days()[abbrev][0].split(".")[:3]
                    )
                )
        return render(
            request,
            "schedule_advisor/advisor_schedules.html",
            {
                "advisees": advisees,
                "schedules": schedules,
                "days_of_week": days_of_week,
                "schedule_by_day": schedule_by_day,
                "query": query,
            },
        )

def advisee_change_view(request):
    u = User.objects.get_or_create(username=request.user.username)[0]
    if not u.is_advisor:
        messages.add_message(request, messages.ERROR, "You are not an advisor!")
        return HttpResponseRedirect("/")
    else:
        action = request.POST["action"]
        try:
            if action == "Add":
                advisee = User.objects.get_or_create(username=request.POST["advisee"])[
                    0
                ]
                advisor = User.objects.get_or_create(username=request.POST["advisor"])[
                    0
                ]
                advisee.advisor = advisor
                advisee.save()
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    f"You are now the advisor for {advisee.get_full_name()}!",
                )
            elif action == "Remove":
                advisee = User.objects.get_or_create(username=request.POST["advisee"])[
                    0
                ]
                advisee.advisor = None
                advisee.save()
                messages.add_message(
                    request,
                    messages.SUCCESS,
                    f"You are no longer the advisor for {advisee.get_full_name()}!",
                )
            else:
                messages.add_message(
                    request, messages.ERROR, "Unable to update schedule!"
                )
        except:
            messages.add_message(
                request,
                messages.ERROR,
                "Unable to edit advisor information for student!",
            )
        # https://stackoverflow.com/questions/35796195/how-to-redirect-to-previous-page-in-django-after-post-request
        return HttpResponseRedirect(request.headers.get("referer", "/"))

def class_schedule_visible_view(request):
    if request.method == "POST":
        try:
            u = User.objects.get_or_create(username=request.user.username)[0]
            if u.is_advisor:
                messages.add_message(request, messages.ERROR, "You are not a student!")
                return HttpResponseRedirect("/")
            if not u.advisor:
                messages.add_message(request, messages.ERROR, "You do not have an advisor!")
                return HttpResponseRedirect("/")
            s = Schedule.objects.get_or_create(connected_user=u)[0]
            visibility = request.POST.get("visible", False)
            s.visible = visibility == "on"
            s.reset_advisor()
            messages.add_message(
                request,
                messages.SUCCESS,
                f"Your schedule is{'' if visibility else ' no longer'} visible to {u.advisor.get_full_name()}!",
            )
        except:
            messages.add_message(
                request,
                messages.ERROR,
                "Unable to edit schedule visibility!",
            )
        return HttpResponseRedirect(request.headers.get("referer", "/"))

def schedule_approval_view(request):
    u = User.objects.get_or_create(username=request.user.username)[0]
    if not u.is_advisor:
        messages.add_message(request, messages.ERROR, "You are not an advisor!")
        return HttpResponseRedirect("/")
    if request.method == "POST":
        try:
            schedule = Schedule.objects.get_or_create(id=int(request.POST["schedule"]))[0]
            schedule_user: User = schedule.connected_user
            if schedule_user.advisor != u:
                messages.add_message(request, messages.ERROR, "You are not this student's advisor!")
                return HttpResponseRedirect("/schedules")
            decision = request.POST["decision"]
            if decision == "true":
                decision = True
                messages.add_message(
                    request, messages.SUCCESS, "You have approved this schedule!"
                )
            elif decision == "false":
                decision = False
                messages.add_message(
                    request, messages.SUCCESS, "You have rejected this schedule!"
                )
            else:
                decision = None
            schedule.approved = decision
            schedule.save()
        except:
            messages.add_message(
                request,
                messages.ERROR,
                "Unable to update schedule approval status!",
            )
    return HttpResponseRedirect(request.headers.get("referer", "/"))


import pytest
import tensorflow as tf

from garage.np.baselines import LinearFeatureBaseline
from garage.sampler import singleton_pool
from garage.tf.algos import VPG
from garage.tf.envs import TfEnv
from garage.tf.experiment import LocalTFRunner
from garage.tf.plotter import Plotter
from garage.tf.policies import CategoricalMLPPolicy
from tests.fixtures import snapshot_config, TfGraphTestCase

class TestLocalRunner(TfGraphTestCase):

    def test_session(self):
        with LocalTFRunner(snapshot_config):
            assert tf.compat.v1.get_default_session() is not None, (
                'LocalTFRunner() should provide a default tf session.')

        sess = tf.compat.v1.Session()
        with LocalTFRunner(snapshot_config, sess=sess):
            assert tf.compat.v1.get_default_session() is sess, (
                'LocalTFRunner(sess) should use sess as default session.')

    def test_singleton_pool(self):
        max_cpus = 8
        with LocalTFRunner(snapshot_config, max_cpus=max_cpus):
            assert max_cpus == singleton_pool.n_parallel, (
                'LocalTFRunner(max_cpu) should set up singleton_pool.')

    def test_train(self):
        with LocalTFRunner(snapshot_config) as runner:
            env = TfEnv(env_name='CartPole-v1')

            policy = CategoricalMLPPolicy(name='policy',
                                          env_spec=env.spec,
                                          hidden_sizes=(8, 8))

            baseline = LinearFeatureBaseline(env_spec=env.spec)

            algo = VPG(env_spec=env.spec,
                       policy=policy,
                       baseline=baseline,
                       max_path_length=100,
                       discount=0.99,
                       optimizer_args=dict(
                           tf_optimizer_args=dict(learning_rate=0.01, )))

            runner.setup(algo, env)
            runner.train(n_epochs=1, batch_size=100)

    def test_external_sess(self):
        with tf.compat.v1.Session() as sess:
            with LocalTFRunner(snapshot_config, sess=sess):
                pass
            # sess should still be the default session here.
            tf.no_op().run()

    def test_set_plot(self):
        with LocalTFRunner(snapshot_config) as runner:
            env = TfEnv(env_name='CartPole-v1')

            policy = CategoricalMLPPolicy(name='policy',
                                          env_spec=env.spec,
                                          hidden_sizes=(8, 8))

            baseline = LinearFeatureBaseline(env_spec=env.spec)

            algo = VPG(env_spec=env.spec,
                       policy=policy,
                       baseline=baseline,
                       max_path_length=100,
                       discount=0.99,
                       optimizer_args=dict(
                           tf_optimizer_args=dict(learning_rate=0.01, )))

            runner.setup(algo, env)
            runner.train(n_epochs=1, batch_size=100, plot=True)

            assert isinstance(runner.plotter, Plotter), (
                'self.plotter in LocalTFRunner should be set to Plotter.')

    def test_call_train_before_set_up(self):
        with pytest.raises(Exception):
            with LocalTFRunner(snapshot_config) as runner:
                runner.train(n_epochs=1, batch_size=100)

    def test_call_save_before_set_up(self):
        with pytest.raises(Exception):
            with LocalTFRunner(snapshot_config) as runner:
                runner.save(0)