from datetime import datetime as dt
import matplotlib.pyplot as plt
import numpy as np

string = \
"""size = 5, 2c iteration 0 with desired nach equilibria: [(('row', 'S2'), ('column', 'S1'))] || Time: 0:00:00.089607
size = 5, 2c iteration 1 with desired nach equilibria: [(('row', 'S2'), ('column', 'S1'))] || Time: 0:00:00.008921
size = 5, 2c iteration 2 with desired nach equilibria: [(('row', 'S2'), ('column', 'S1'))] || Time: 0:00:00.005190
size = 5, 2c iteration 3 with desired nach equilibria: [(('row', 'S2'), ('column', 'S1'))] || Time: 0:00:00.005113
size = 5, 2c iteration 4 with desired nach equilibria: [(('row', 'S2'), ('column', 'S1'))] || Time: 0:00:00.004982
size = 10, 2c iteration 0 with desired nach equilibria: [(('row', 'S5'), ('column', 'S5'))] || Time: 0:00:00.002025
size = 10, 2c iteration 1 with desired nach equilibria: [(('row', 'S5'), ('column', 'S5'))] || Time: 0:00:00.004903
size = 10, 2c iteration 2 with desired nach equilibria: [(('row', 'S5'), ('column', 'S5'))] || Time: 0:00:00.010714
size = 10, 2c iteration 3 with desired nach equilibria: [(('row', 'S5'), ('column', 'S5'))] || Time: 0:00:00.005935
size = 10, 2c iteration 4 with desired nach equilibria: [(('row', 'S5'), ('column', 'S5'))] || Time: 0:00:00.005876
size = 20, 2c iteration 0 with desired nach equilibria: [(('row', 'S2'), ('column', 'S13'))] || Time: 0:00:00.002486
size = 20, 2c iteration 1 with desired nach equilibria: [(('row', 'S2'), ('column', 'S13'))] || Time: 0:00:00.010239
size = 20, 2c iteration 2 with desired nach equilibria: [(('row', 'S2'), ('column', 'S13'))] || Time: 0:00:00.007542
size = 20, 2c iteration 3 with desired nach equilibria: [(('row', 'S2'), ('column', 'S13'))] || Time: 0:00:00.008141
size = 20, 2c iteration 4 with desired nach equilibria: [(('row', 'S2'), ('column', 'S13'))] || Time: 0:00:00.006896
size = 30, 2c iteration 0 with desired nach equilibria: [(('row', 'S26'), ('column', 'S18'))] || Time: 0:00:00.051712
size = 30, 2c iteration 1 with desired nach equilibria: [(('row', 'S26'), ('column', 'S18'))] || Time: 0:00:00.022506
size = 30, 2c iteration 2 with desired nach equilibria: [(('row', 'S26'), ('column', 'S18'))] || Time: 0:00:00.010083
size = 30, 2c iteration 3 with desired nach equilibria: [(('row', 'S26'), ('column', 'S18'))] || Time: 0:00:00.011068
size = 30, 2c iteration 4 with desired nach equilibria: [(('row', 'S26'), ('column', 'S18'))] || Time: 0:00:00.015029
size = 50, 2c iteration 0 with desired nach equilibria: [(('row', 'S27'), ('column', 'S7'))] || Time: 0:00:00.052816
size = 50, 2c iteration 1 with desired nach equilibria: [(('row', 'S27'), ('column', 'S7'))] || Time: 0:00:00.299637
size = 50, 2c iteration 2 with desired nach equilibria: [(('row', 'S27'), ('column', 'S7'))] || Time: 0:00:00.047638
size = 50, 2c iteration 3 with desired nach equilibria: [(('row', 'S27'), ('column', 'S7'))] || Time: 0:00:00.055767
size = 50, 2c iteration 4 with desired nach equilibria: [(('row', 'S27'), ('column', 'S7'))] || Time: 0:00:00.064685
size = 100, 2c iteration 0 with desired nach equilibria: [(('row', 'S33'), ('column', 'S88'))] || Time: 0:00:00.181271
size = 100, 2c iteration 1 with desired nach equilibria: [(('row', 'S33'), ('column', 'S88'))] || Time: 0:00:00.164494
size = 100, 2c iteration 2 with desired nach equilibria: [(('row', 'S33'), ('column', 'S88'))] || Time: 0:00:00.156647
size = 100, 2c iteration 3 with desired nach equilibria: [(('row', 'S33'), ('column', 'S88'))] || Time: 0:00:00.169929
size = 100, 2c iteration 4 with desired nach equilibria: [(('row', 'S33'), ('column', 'S88'))] || Time: 0:00:00.215340
size = 250, 2c iteration 0 with desired nach equilibria: [(('row', 'S77'), ('column', 'S149'))] || Time: 0:00:00.689703
size = 250, 2c iteration 1 with desired nach equilibria: [(('row', 'S77'), ('column', 'S149'))] || Time: 0:00:00.852490
size = 250, 2c iteration 2 with desired nach equilibria: [(('row', 'S77'), ('column', 'S149'))] || Time: 0:00:00.910095
size = 250, 2c iteration 3 with desired nach equilibria: [(('row', 'S77'), ('column', 'S149'))] || Time: 0:00:00.947000
size = 250, 2c iteration 4 with desired nach equilibria: [(('row', 'S77'), ('column', 'S149'))] || Time: 0:00:00.914404
size = 400, 2c iteration 0 with desired nach equilibria: [(('row', 'S123'), ('column', 'S332'))] || Time: 0:00:02.228152
size = 400, 2c iteration 1 with desired nach equilibria: [(('row', 'S123'), ('column', 'S332'))] || Time: 0:00:02.548280
size = 400, 2c iteration 2 with desired nach equilibria: [(('row', 'S123'), ('column', 'S332'))] || Time: 0:00:03.533587
size = 400, 2c iteration 3 with desired nach equilibria: [(('row', 'S123'), ('column', 'S332'))] || Time: 0:00:02.408298
size = 400, 2c iteration 4 with desired nach equilibria: [(('row', 'S123'), ('column', 'S332'))] || Time: 0:00:03.090571
size = 700, 2c iteration 0 with desired nach equilibria: [(('row', 'S622'), ('column', 'S495'))] || Time: 0:00:10.831137
size = 700, 2c iteration 1 with desired nach equilibria: [(('row', 'S622'), ('column', 'S495'))] || Time: 0:00:11.929054
size = 700, 2c iteration 2 with desired nach equilibria: [(('row', 'S622'), ('column', 'S495'))] || Time: 0:00:14.781851
size = 700, 2c iteration 3 with desired nach equilibria: [(('row', 'S622'), ('column', 'S495'))] || Time: 0:00:12.353810
size = 700, 2c iteration 4 with desired nach equilibria: [(('row', 'S622'), ('column', 'S495'))] || Time: 0:00:12.368400
size = 1000, 2c iteration 0 with desired nach equilibria: [(('row', 'S441'), ('column', 'S350'))] || Time: 0:00:27.779875
size = 1000, 2c iteration 1 with desired nach equilibria: [(('row', 'S441'), ('column', 'S350'))] || Time: 0:00:24.011225
size = 1000, 2c iteration 2 with desired nach equilibria: [(('row', 'S441'), ('column', 'S350'))] || Time: 0:00:22.359567
size = 1000, 2c iteration 3 with desired nach equilibria: [(('row', 'S441'), ('column', 'S350'))] || Time: 0:00:24.437762
size = 1000, 2c iteration 4 with desired nach equilibria: [(('row', 'S441'), ('column', 'S350'))] || Time: 0:00:36.910838"""

# For each size, we run 5 iterations of the algorithm, and we take the average time
# of the 5 iterations. We then plot the average time against the size of the game.
# We also plot the theoretical time complexity of the algorithm, which is O(n^2).
# We see that the algorithm is indeed O(n^2), as the plot is a straight line.

def get_averages(string):
    sizes = [5, 10, 20, 30, 50, 100, 250, 400, 700, 1000]
    # averages = []
    # for i in range(len(sizes)):
    #     # Get the average time for each size
    #     # Get the lines of the string
    #     lines = string.split('\n')
    #     times = [(line.split('||')[1].split(': ')[1]) for line in lines[i*5:i*5+5]]
    #     # turn the string datetimes into seconds
    #     times = [dt.strptime(time, '%H:%M:%S.%f') for time in times]
    #     times = [time.second + time.microsecond/1000000 for time in times]
    #     print(times)
    #     average = sum(times)/len(times)
    #     averages.append(average)
    # print(averages)
    # return averages

    lines = string_summer_2023.split('\n')

    # Create a dictionary of times for every size.
    times = {}

    for line in lines:
        # Get the size from the line.
        size = line.split('size = ')[1].split(',')[0]

        # Get the time from the line.
        time = dt.strptime(line.split('Time: ')[1], '%H:%M:%S.%f')

        # Format the time as seconds.
        time = time.second + time.microsecond/1000000 + time.minute*60

        print(f"for size {size}, time is {time}")

        # Add the time to the dictionary of times for the given size.
        if size in times:
            times[size].append(time)
        else:
            times[size] = [time]

    # Calculate the average time for every size.
    average_times = {}
    for size in times:
        average_times[size] = sum(times[size])/len(times[size])

    occurences = {size: len(times[size]) for size in times}
    return average_times, occurences

def plot_averages(string, quadratic=True):
    # sizes = [5, 10, 20, 30, 50, 100, 250, 400, 700, 1000]
    # averages = get_averages(string)

    averages_dict, occurences_dict = get_averages(string)
    sizes = [int(size) for size in averages_dict.keys()]
    sizes.sort()
    averages = [averages_dict[str(size)] for size in sizes]

    for size, average in zip(sizes, averages):
        print(f"size {size} has square {size**2} and average {average} over {occurences_dict[str(size)]} occurences")

    # plt.plot(sizes, [size**2 for size in sizes])
    # fit a quadratic curve to the data
    if quadratic:
        fit = np.polyfit(sizes, averages, 2)
        fit_fn = np.poly1d(fit)
        # draw the fit curve fit_fn(sizes) for a range from 0 to 1000
        x = np.linspace(5, max(sizes), 1000)
        # plt.plot(x, fit_fn(x), '--k', label='Quadratic fit', linewidth=1, color='dodgerblue', alpha=0.8)
        plt.plot(x, fit_fn(x), '--k', label='Quadratic fit', linewidth=1.2, color='#00A6B7', alpha=0.8)
        plt.xticks(np.arange(0, max(sizes)+1, 100))
        # give them 45 degree angle
        plt.xticks(rotation=45)

        # plt.plot(sizes, averages, label='Average Time', linewidth=1, color='red')
        # make the color FF6805
        plt.plot(sizes, averages, label='Average Time', linewidth=1.5, color='#FF7F00')
        # label the points with how many times they occured

        # plot the data points
        # plt.scatter(sizes, averages, color='red', s=15)
        plt.scatter(sizes, averages, color='#FF7F00', s=25, zorder=3)
        plt.xlabel('Number of strategies ($n$)', fontsize=15)

        plt.ylabel('Average CPU time (seconds)', fontsize=15)
        plt.title('Average time to change payoffs to new Nash equilibrium')
        # make the y numbers integers and not 1.0e7
        plt.ticklabel_format(style='plain')
        for size, average in zip(sizes, averages):
            plt.text(size, average, occurences_dict[str(size)], fontsize=8, color='black', alpha=0.8)
        # add thin gridlines
        plt.grid(linewidth=0.2)

        # legends
        plt.legend(loc='upper left')

        plt.savefig('large_games_quadratic.png', dpi=300)

        plt.show()

    else: # linear
        sizes = [size**2 for size in sizes]
        fit = np.polyfit(sizes, averages, 1)
        fit_fn = np.poly1d(fit)
        x = np.linspace(25, max(sizes), 1000)
        plt.xticks(np.arange(0, max(sizes)+1, 100000))
        # give them 45 degree angle
        plt.xticks(rotation=45)

        # plt.plot(x, fit_fn(x), '--k', label='Linear fit', linewidth=1, color='dodgerblue', alpha=0.8)
        plt.plot(x, fit_fn(x), '--k', label='Linear fit', linewidth=1.2, color='#00A6B7', alpha=0.8)
        # plt.plot(sizes, averages, label='Average Time', linewidth=1, color='red')
        # make the color FF6805
        plt.plot(sizes, averages, label='Average Time', linewidth=1.5, color='#FF7F00')
        # plt.scatter(sizes, averages, color='red', s=15)
        plt.scatter(sizes, averages, color='#FF7F00', s=25, zorder=3)
        plt.xlabel('Size of game ($n^2$)', fontsize=15)
        for size, average in zip(sizes, averages):
            plt.text(size, average, occurences_dict[str(int(np.sqrt(size)))], fontsize=10, color='black', alpha=0.8, zorder=4)

        # calculate R^2
        residuals = np.polyfit(sizes, averages, 1)
        r_squared = 1 - (np.var(residuals) / np.var(averages))
        r2 = np.corrcoef(sizes, averages)[0, 1]**2
        print(f"R^2 is {r_squared}")
        print(f"R^2 is {r2}")
        # Calculate residuals
        residuals = averages - fit_fn(sizes)

        # Calculate total sum of squares
        total_sum_squares = np.sum((averages - np.mean(averages))**2)

        # Calculate residual sum of squares
        residual_sum_squares = np.sum(residuals**2)

        # Calculate R^2
        r_squared = 1 - (residual_sum_squares / total_sum_squares)

        print("R^2:", r_squared)

        plt.ylabel('Average CPU time (seconds)', fontsize=15)
        plt.title('Average time to change payoffs to new Nash equilibrium')
        # make the y numbers integers and not 1.0e7
        plt.ticklabel_format(style='plain')
        # add thin gridlines
        plt.grid(linewidth=0.2)

        # legends
        plt.legend(loc='upper left')

        plt.savefig('large_games_linear.png', dpi=300)

        plt.show()

# load the file "log Summer 2023.txt" into a string
string_summer_2023 = open('log Summer 2023.txt', 'r').read()
# string_summer_2023 = open('log2.txt', 'r').read()
# string_summer_2023 = open('log Summer 2023 2.txt', 'r').read()
string_summer_2023 = open('log_eristwo.txt', 'r').read()
# plot_averages(string_summer_2023, quadratic=False)
plot_averages(string_summer_2023, quadratic=False)
plot_averages(string_summer_2023, quadratic=True)
# print(get_averages(string_summer_2023))

# 58627   ee869   RUN   normal     eris2n4     hn008       job_740    Jun 29 00:54
# 58632   ee869   PEND  normal     eris2n4                 job_895    Jun 29 00:54
# 58633   ee869   PEND  normal     eris2n4                 job_920    Jun 29 00:54
# 58634   ee869   PEND  normal     eris2n4                 job_950    Jun 29 00:54
# 58635   ee869   PEND  normal     eris2n4                 job_975    Jun 29 00:54
# 61369   ee869   PEND  normal     eris2n4                 job_20     Jun 29 12:22
# 61370   ee869   PEND  normal     eris2n4                 job_315    Jun 29 12:22
# 61371   ee869   PEND  normal     eris2n4                 job_385    Jun 29 12:22
# 61372   ee869   PEND  normal     eris2n4                 job_445    Jun 29 12:22
# 61373   ee869   PEND  normal     eris2n4                 job_500    Jun 29 12:22
# 61374   ee869   PEND  normal     eris2n4                 job_550    Jun 29 12:22
# 61375   ee869   PEND  normal     eris2n4                 job_590    Jun 29 12:22
# 61376   ee869   PEND  normal     eris2n4                 job_630    Jun 29 12:22
# 61377   ee869   PEND  normal     eris2n4                 job_670    Jun 29 12:22
# 61378   ee869   PEND  normal     eris2n4                 job_705    Jun 29 12:22
# 61379   ee869   PEND  normal     eris2n4                 job_740    Jun 29 12:22
# 61380   ee869   PEND  normal     eris2n4                 job_775    Jun 29 12:22
# 61381   ee869   PEND  normal     eris2n4                 job_805    Jun 29 12:22
# 61382   ee869   PEND  normal     eris2n4                 job_835    Jun 29 12:22
# 61383   ee869   PEND  normal     eris2n4                 job_865    Jun 29 12:22
# 61384   ee869   PEND  normal     eris2n4                 job_895    Jun 29 12:22
# 61385   ee869   PEND  normal     eris2n4                 job_920    Jun 29 12:22
# 61386   ee869   PEND  normal     eris2n4                 job_950    Jun 29 12:22
# 61387   ee869   PEND  normal     eris2n4                 job_975    Jun 29 12:22

# bkill 61369
# bkill 61370
# bkill 61371
# bkill 61372
# bkill 61373
# bkill 61374
# bkill 61375
# bkill 61376
# bkill 61377
# bkill 61378
# bkill 61379
# bkill 61380
# bkill 61381
# bkill 61382
# bkill 61383
# bkill 61384
# bkill 61385
# bkill 61386
# bkill 61387


from modules.entities import EntityTracker
from modules.bow import BoW_encoder
from  modules.lstm_net import LSTM_net
from modules.embed import UtteranceEmbed
from modules.actions import ActionTracker
from modules.data_utils import Data
# from modules.entity_tracker import GoogleEntityTracker
import modules.util as util

import numpy as np
import sys

class InteractiveSession():

    def __init__(self):

        et = EntityTracker()
        self.bow_enc = BoW_encoder()
        self.emb = UtteranceEmbed()
        at = ActionTracker(et)

        obs_size = self.emb.dim + self.bow_enc.vocab_size + et.num_features
        self.action_templates = at.get_action_templates()
        action_size = at.action_size
        nb_hidden = 128

        self.net = LSTM_net(obs_size=obs_size,
                       action_size=action_size,
                       nb_hidden=nb_hidden)

        # restore checkpoint
        self.net.restore()

    def interact(self):
        # create entity tracker
        et = EntityTracker()

        # neural entity tracker
        # g_et = GoogleEntityTracker()

        # create action tracker
        at = ActionTracker(et)

        # reset network
        self.net.reset_state()

        # begin interaction loop
        while True:

            # get input from user
            u = raw_input(':: ')

            # check if user wants to begin new session
            if u == 'clear' or u == 'reset' or u == 'restart':
                self.net.reset_state()
                et = EntityTracker()
                at = ActionTracker(et)
                print('')

            # check for exit command
            elif u == 'exit' or u == 'stop' or u == 'quit' or u == 'q':
                break

            else:
                # ENTER press : silence
                if not u:
                    u = '<SILENCE>'

                # encode
                u_ent, u_entities = et.extract_entities(u, is_test=True)
                # u_ent, u_entities = g_et.extract_entities(u)
                u_ent_features = et.context_features()
                u_emb = self.emb.encode(u_ent)
                u_bow = self.bow_enc.encode(u_ent)
                # concat features
                features = np.concatenate((u_ent_features, u_emb, u_bow), axis=0)
                # get action mask
                action_mask = at.action_mask()

                # forward
                prediction = self.net.forward(features, action_mask)
                # print('prediction: ', prediction)
                print(u_entities)
                if self.handle_api_call(prediction, u_ent_features):
                    if prediction == 1:
                        print('>> api_call ' + u_entities['<location>'])
                    if prediction == 2:
                        print('>> api_call ' + u_entities['<objectives>'] + ' ' + u_entities['<patient_name>'] + ' ' + u_entities['<address>'])
                    if prediction == 3:
                        print('>> api_call ' + u_entities['<objectives>'] + ' ' + u_entities['<patient_name>'] + ' ' + u_entities['<address>'] + ' ' + u_entities['<time>'])
                    if prediction == 4:
                        print('>> api_call ' + u_entities['<patient_name>'] + ' ' + u_entities['<address>'] + ' ' + u_entities['<time>'] + ' ' + u_entities['<dr_name>'])
                else:
                    if self.handle_response(prediction):
                        response = self.action_templates[prediction]
                        response = response.split(' ')
                        if prediction == 5 or prediction == 7 or prediction == 12:
                            response = [r.replace('<patient_name>', u_entities['<patient_name>']) for r in response]
                            print('>> ' + ' '.join(response))
                        else:
                            response = [r.replace('<patient_name>', u_entities['<patient_name>']) for r in response]
                            response = [r.replace('<objectives>', u_entities['<objectives>']) for r in response]
                            print('>> ' + ' '.join(response))
                    else:
                        # prediction = self.action_post_process(prediction, u_entities)
                        print('>> ' + self.action_templates[prediction])
                        # if all(u_ent_featur == 1 for u_ent_featur in u_ent_features) and (prediction == 10):
                        #     break

    def handle_api_call(self, prediction, u_ent_features):
        expected = [1,2,3,4]
        if prediction in expected:
            return True
        else:
            return False

    def handle_response(self, prediction):
        expected = [5,7,10,12]
        if prediction in expected:
            return True
        else:
            return False

    def action_post_process(self, prediction, u_entities):
        attr_mapping_dict = {
            4: '<patient_name>',
            6: '<patient_name>',
            9: ['<patient_name>', '<objectives>'],
            11: '<patient_name>'
        }

        # find exist and non-exist entity
        exist_ent_index = [key for key, value in u_entities.items() if value != None]
        non_exist_ent_index = [key for key, value in u_entities.items() if value == None]

        # if predicted key is already in exist entity index then find non exist entity index
        # and leads the user to input non exist entity.

        if prediction in attr_mapping_dict:
            pred_key = attr_mapping_dict[prediction]
            if pred_key in exist_ent_index:
                for key, value in attr_mapping_dict.items():
                    if value == non_exist_ent_index[0]:
                        return key
            else:
                return prediction
        else:
            return prediction

if __name__ == '__main__':
    # create interactive session
    isess = InteractiveSession()
    # begin interaction
    isess.interact()


import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
from models.EM import EM
from torch.distributions import Categorical
from models.initializer import initialize_weights

# constants
# number of vector signal (lstm gates)
N_VSIG = 3
# number of scalar signal (sigma)
N_SSIG = 1
# the ordering in the cache
scalar_signal_names = ['input strength']
vector_signal_names = ['f', 'i', 'o']
sigmoid = nn.Sigmoid()

class LCALSTM_after(nn.Module):

    def __init__(
            self, input_dim, output_dim, rnn_hidden_dim, dec_hidden_dim,
            kernel='cosine', dict_len=2, weight_init_scheme='ortho',
            cmpt=.8, em_gate=.3, add_penalty_dim=True
    ):
        super(LCALSTM_after, self).__init__()
        self.cmpt = cmpt
        self.em_gate = em_gate
        if add_penalty_dim:
            self.input_dim = input_dim + 1
        else:
            self.input_dim = input_dim
        # self.input_dim = input_dim + 1
        self.rnn_hidden_dim = rnn_hidden_dim
        self.n_hidden_total = (N_VSIG + 1) * rnn_hidden_dim + N_SSIG
        # rnn module
        self.i2h = nn.Linear(self.input_dim, self.n_hidden_total)
        self.h2h = nn.Linear(rnn_hidden_dim, self.n_hidden_total)
        # deicion module
        self.ih = nn.Linear(rnn_hidden_dim, dec_hidden_dim)
        self.actor = nn.Linear(dec_hidden_dim, output_dim)
        self.critic = nn.Linear(dec_hidden_dim, 1)
        # memory
        self.hpc = nn.Linear(
            rnn_hidden_dim + rnn_hidden_dim + dec_hidden_dim, N_SSIG
        )
        self.em = EM(dict_len, rnn_hidden_dim, kernel)
        # the RL mechanism
        self.weight_init_scheme = weight_init_scheme
        self.init_model()

    def init_model(self):
        # add name fields
        self.n_ssig = N_SSIG
        self.n_vsig = N_VSIG
        self.vsig_names = vector_signal_names
        self.ssig_names = scalar_signal_names
        # init params
        initialize_weights(self, self.weight_init_scheme)

    def get_init_states(self, scale=.1, device='cpu'):
        h_0_ = sample_random_vector(self.rnn_hidden_dim, scale)
        c_0_ = sample_random_vector(self.rnn_hidden_dim, scale)
        return (h_0_, c_0_)

    def forward(self, x_t, hc_prev, beta=1):
        # unpack activity
        (h_prev, c_prev) = hc_prev
        h_prev = h_prev.view(h_prev.size(1), -1)
        c_prev = c_prev.view(c_prev.size(1), -1)
        x_t = x_t.view(x_t.size(1), -1)
        # transform the input info
        preact = self.i2h(x_t) + self.h2h(h_prev)
        # get all gate values
        gates = preact[:, : N_VSIG * self.rnn_hidden_dim].sigmoid()
        c_t_new = preact[:, N_VSIG * self.rnn_hidden_dim + N_SSIG:].tanh()
        # split input(write) gate, forget gate, output(read) gate
        f_t = gates[:, :self.rnn_hidden_dim]
        o_t = gates[:, self.rnn_hidden_dim:2 * self.rnn_hidden_dim]
        i_t = gates[:, -self.rnn_hidden_dim:]
        # new cell state = gated(prev_c) + gated(new_stuff)
        c_t = torch.mul(c_prev, f_t) + torch.mul(i_t, c_t_new)
        # make 1st decision attempt
        h_t = torch.mul(o_t, c_t.tanh())
        dec_act_t = F.relu(self.ih(h_t))
        # recall / encode
        # hpc_input_t = torch.cat([c_t, dec_act_t], dim=1)
        # inps_t = sigmoid(self.hpc(hpc_input_t))
        # [inps_t, comp_t] = torch.squeeze(phi_t)
        m_t = self.recall(c_t, self.em_gate)
        hpc_input_t = torch.cat([m_t, c_t, dec_act_t], dim=1)
        em_g_t = sigmoid(self.hpc(hpc_input_t))
        cm_t = c_t + m_t * em_g_t
        self.encode(cm_t)
        # make final dec
        h_t = torch.mul(o_t, cm_t.tanh())
        dec_act_t = F.relu(self.ih(h_t))
        pi_a_t = _softmax(self.actor(dec_act_t), beta)
        value_t = self.critic(dec_act_t)
        # reshape data
        h_t = h_t.view(1, h_t.size(0), -1)
        cm_t = cm_t.view(1, cm_t.size(0), -1)
        # scache results
        scalar_signal = [em_g_t, 0, 0]
        vector_signal = [f_t, i_t, o_t]
        misc = [h_t, m_t, cm_t, dec_act_t, self.em.get_vals()]
        cache = [vector_signal, scalar_signal, misc]
        return pi_a_t, value_t, (h_t, cm_t), cache

    def recall(self, c_t, inps_t, comp_t=None):
        """run the "pattern completion" procedure

        Parameters
        ----------
        c_t : torch.tensor, vector
            cell state
        leak_t : torch.tensor, scalar
            LCA param, leak
        comp_t : torch.tensor, scalar
            LCA param, lateral inhibition
        inps_t : torch.tensor, scalar
            LCA param, input strength / feedforward weights

        Returns
        -------
        tensor, tensor
            updated cell state, recalled item

        """
        if comp_t is None:
            comp_t = self.cmpt

        if self.em.retrieval_off:
            m_t = torch.zeros_like(c_t)
        else:
            # retrieve memory
            m_t = self.em.get_memory(c_t, leak=0, comp=comp_t, w_input=inps_t)
        return m_t

    def encode(self, cm_t):
        if not self.em.encoding_off:
            self.em.save_memory(cm_t)

    def pick_action(self, action_distribution):
        """action selection by sampling from a multinomial.

        Parameters
        ----------
        action_distribution : 1d torch.tensor
            action distribution, pi(a|s)

        Returns
        -------
        torch.tensor(int), torch.tensor(float)
            sampled action, log_prob(sampled action)

        """
        m = Categorical(action_distribution)
        a_t = m.sample()
        log_prob_a_t = m.log_prob(a_t)
        return a_t, log_prob_a_t

    def init_em_config(self):
        self.flush_episodic_memory()
        self.encoding_off()
        self.retrieval_off()

    def flush_episodic_memory(self):
        self.em.flush()

    def encoding_off(self):
        self.em.encoding_off = True

    def retrieval_off(self):
        self.em.retrieval_off = True

    def encoding_on(self):
        self.em.encoding_off = False

    def retrieval_on(self):
        self.em.retrieval_off = False

def sample_random_vector(n_dim, scale=.1):
    return torch.randn(1, 1, n_dim) * scale

def _softmax(z, beta):
    """helper function, softmax with beta

    Parameters
    ----------
    z : torch tensor, has 1d underlying structure after torch.squeeze
        the raw logits
    beta : float, >0
        softmax temp, big value -> more "randomness"

    Returns
    -------
    1d torch tensor
        a probability distribution | beta

    """
    assert beta > 0
    # softmax the input to a valid PMF
    pi_a = F.softmax(torch.squeeze(z / beta), dim=0)
    # make sure the output is valid
    if torch.any(torch.isnan(pi_a)):
        raise ValueError(f'Softmax produced nan: {z} -> {pi_a}')
    return pi_a


"""
Contains all the machinery for dealing with threads.
"""
from __future__ import annotations

import threading
from typing import Any, Callable, Dict, Optional

import wx

class ThreadResult(wx.PyEvent):
    """Simple event to carry arbitrary result data."""

    def __init__(self, data: Any, event_type: int):
        """Initialises a result event for the thread.

        Args:
            data: The data to be passed to the main thread.
            event_type: The type of event.
        """
        wx.PyEvent.__init__(self)
        self.SetEventType(event_type)
        self.data = data

class WorkerThread(threading.Thread):
    """Worker Thread Class."""

    def __init__(
        self,
        target: Callable,
        on_abort: Optional[Callable] = None,
        on_complete: Optional[Callable] = None,
        on_error: Optional[Callable] = None,
        daemon: Optional[bool] = None,
    ):
        """Configures and start a new thread executing the target action.

        Args:
            target: The function to be executed
            on_abort: Function to be called if the thread aborts. Takes as only argument
                the output of the target function when that one aborts.
            on_complete: Function to be called if the thread finished normally. Takes as
                only argument the output of the target function when that one finishes.
            on_error: Function to be called if anything bad happens in the thread. Takes
                as only argument the exception catched.
        """
        super(WorkerThread, self).__init__(target=target, daemon=daemon)
        self._on_abort = on_abort
        self._on_complete = on_complete
        self._on_error = on_error
        self._event_on_abort = wx.NewEventType()
        self._event_on_complete = wx.NewEventType()
        self._event_on_error = wx.NewEventType()
        self.abort = False

    def connect_events(self, window: wx.Frame) -> None:
        """Connect the complete, abort and error events to the functions to execute.

        Args:
            window: The main window of the program.
        """
        window.Connect(-1, -1, self._event_on_abort, self.on_abort)
        window.Connect(-1, -1, self._event_on_complete, self.on_complete)
        window.Connect(-1, -1, self._event_on_error, self.on_error)

    def run(self):
        """Run worker thread and deals with the wrapping up accordingly."""
        try:
            result = self._target()

            if self.abort:
                ThreadPool().post_event(ThreadResult(result, self._event_on_abort))
            else:
                ThreadPool().post_event(ThreadResult(result, self._event_on_complete))

        except Exception as err:
            ThreadPool().post_event(ThreadResult(err.args[0], self._event_on_error))

    def on_abort(self, event: ThreadResult):
        """To execute when the thread execution is aborted.

        Args:
            event: The event object with the relevant output data
        """
        if self._on_abort is not None:
            self._on_abort(event.data)

    def on_complete(self, event: ThreadResult):
        """To execute when the thread execution is completed normally.

        Args:
            event: The event object with the relevant output data
        """
        if self._on_complete is not None:
            self._on_complete(event.data)

    def on_error(self, event: ThreadResult):
        """To execute when the thread ends with an error.

        Args:
            event: The exception raised
        """
        if self._on_error is not None:
            self._on_error(event.data)

class ThreadPool:

    _instance: Optional[ThreadPool] = None

    def __new__(cls, window: Optional[wx.Frame] = None):
        if window is None and cls._instance is None:
            raise ValueError(
                "The first time it is called, 'window' must be a wx.Frame object."
            )
        elif cls._instance is None:
            cls._instance = object.__new__(cls)
            cls._instance._window = window
            cls._instance._workers = {}
        return cls._instance

    def __init__(self, window: Optional[wx.Frame] = None):
        self._window: wx.Frame
        self._workers: Dict[int, WorkerThread]

    def run_thread(
        self,
        target: Callable,
        on_abort: Optional[Callable] = None,
        on_complete: Optional[Callable] = None,
        on_error: Optional[Callable] = None,
        daemon: Optional[bool] = None,
    ) -> int:
        """Runs a new thread executing the target callable on it.

        The thread will run until:
            - The 'target' function returns
            - An exception is raised

        The target function might finish because it has completed what it was doing. In
        that case, 'on_complete' is executed after returning from `target`.

        It might also finish because it is monitoring the value of
        `ThreadPool().query_abort()` and this is `True`. In that case, target should
        return with an appropriate value and `on_abort` is then executed.

        Finally, an exception might occur in the thread. In this case, the exception
        is caught and `on_error` is executed.

        `on_complete`, `on_abort` and `on_error` are all executed in the main thread.

        Args:
            target: The function to be executed in a separate thread.
            on_abort: The function to be executed when the target function is aborted.
                Takes as input the value returned by target.
            on_complete: The function to be executed when the target function is
                completed normally. Takes as input the value returned by target.
            on_error: The function to be executed when an exception is raised in the
                target. Takes as input the exception raised.
            daemon: If the function is a daemonic function.

        Returns:
            The id number for the thread, needed if it is to be aborted externally.
        """
        thread = WorkerThread(target, on_abort, on_complete, on_error, daemon)
        thread.connect_events(self._window)
        thread.start()
        self._workers[thread.ident] = thread
        return thread.ident

    def query_abort(self) -> bool:
        """Checks if the current thread is to be aborted."""
        return self._workers[threading.get_ident()].abort

    def abort_thread(self, ident: int) -> None:
        """Flags the thread with `ident` to be aborted.

        Args:
            ident: The id of the thread
        """
        self._workers[ident].abort = True

    def post_event(self, event: ThreadResult):
        """Adds an event to the event loop of the main thread."""
        wx.PostEvent(self._window, event)


# -*- coding: utf-8 -*-
#Nissan.py

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

from google.colab import files

uploaded = files.upload()

nissan= pd.read_csv(io.BytesIO(uploaded['Nissan.csv']))
nissan

namedum = pd.get_dummies(nissan.Name)
nissan = nissan.join(namedum)
colourdum = pd.get_dummies(nissan.Color,prefix="is")
nissan=nissan.join(colourdum)
enginedum = pd.get_dummies(nissan['Engine Type'])
nissan=nissan.join(enginedum)
Bodydum = pd.get_dummies(nissan['Body Type'])
nissan=nissan.join(Bodydum)
nissan.drop(['Name', 'Color', 'Engine Type', 'Body Type'], axis=1, inplace=True)

nissan['Anti lock Braking System']=nissan['Anti lock Braking System'].fillna(0)

nissan.shape

Y = nissan.Price

nissan.drop(['Price'], axis=1, inplace=True)
X=nissan

from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2,random_state=0)

model = keras.models.Sequential()

model.add(keras.layers.Dense(128, activation='relu', input_shape=(149,)))
model.add(keras.layers.Dense(64, activation='relu'))
model.add(keras.layers.Dense(16, activation='relu'))
model.add(keras.layers.Dense(8, activation='relu'))
model.add(keras.layers.Dense(1, activation='linear'))

keras.optimizers.Adam(lr=0.00001, beta_1=0.9, beta_2=0.999, amsgrad=False)
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mean_absolute_percentage_error'])

keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False)
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mse','mae','acc'])

model.fit(X, Y, epochs=4500,batch_size=35, callbacks=[keras.callbacks.EarlyStopping(patience=3)])

pred=model.predict(X_test, batch_size=1)

actual=pd.DataFrame(Y_test)
pred=pd.DataFrame(pred)

pred.columns=['Pred']

actual.shape

a=[]
for i in range (212):
  a.append(i)
actual.index=a

nissan=pd.concat([pred, actual], axis=1)

nissan

from sklearn import metrics
import sklearn.metrics as sm
print("Mean absolute error =", round(sm.mean_absolute_error(nissan.Pred, nissan.Price)))
print("Mean squared error =", round(sm.mean_squared_error(nissan.Pred, nissan.Price)))
print("Median absolute error =", round(sm.median_absolute_error(nissan.Pred, nissan.Price)))
print("Explain variance score =", (sm.explained_variance_score(nissan.Pred, nissan.Price)))
print("R2 score =", (sm.r2_score(nissan.Pred, nissan.Price)))

plt.figure(figsize=(100,200))
fig, ax = plt.subplots()
ax.plot(nissan.index,nissan['Pred'],color='blue',marker='o')
ax.plot(nissan.index,nissan['Price'], color='orange',marker='*')

pred=0
act=0
for i in range (212):
  pred=pred+nissan.Pred[i]
  act=act+nissan.Price[i]

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
langs = ['Actual','Predicted']
students = [act,pred]
ax.bar(langs[0],students[0],color='black')
ax.bar(langs[1],students[1],color='blue')
plt.show()

import numpy as np
import matplotlib.pyplot as plt
import random
a=random.randrange(212)
b=random.randrange(212)
c=random.randrange(212)
d=random.randrange(212)
e=random.randrange(212)
f=random.randrange(212)
g=random.randrange(212)
h=random.randrange(212)
i=random.randrange(212)
j=random.randrange(212)
data= [[nissan.Pred[a],nissan.Pred[b],nissan.Pred[c],nissan.Pred[d],nissan.Pred[e],nissan.Pred[f],nissan.Pred[g],nissan.Pred[h],nissan.Pred[i],nissan.Pred[j]],
     [nissan.Price[a],nissan.Price[b],nissan.Price[c],nissan.Price[d],nissan.Price[e],nissan.Price[f],nissan.Price[g],nissan.Price[h],nissan.Price[i],nissan.Price[j]]]

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
X=np.arange(10)
ax.bar(X + 0.00, data[0], color = 'b', width = 0.25,)
ax.bar(X + 0.25, data[1], color = 'black', width = 0.25,)
ax.legend(labels=['Predicted', 'Actual'])


import shutil
import sys
from pathlib import Path

import numpy as np
from Cython.Build import cythonize
from Cython.Compiler.Errors import CompileError
from Cython.Distutils.build_ext import build_ext
from setuptools.dist import Distribution
from setuptools.extension import Extension

# C Extensions

C_COMPILE = True
USE_CYTHON = True

if C_COMPILE:
    package_data: dict = {}
    if USE_CYTHON:
        extensions = [
            Extension(
                "velocyto.speedboosted",
                include_dirs=[np.get_include()],
                sources=["src/velocyto/speedboosted.pyx"],
                extra_compile_args=[
                    "-fopenmp",
                    "-ffast-math",
                    "-O3"
                ],  # NOTE optional flags -O3 -ffast-math -march=native
                extra_link_args=["-fopenmp"],
            )
        ]
        extensions = cythonize(
            extensions,
            include_path=[np.get_include()],
            compiler_directives={"language_level": 3}
            )
    else:
        extensions = [
            Extension(
                "velocyto.speedboosted",
                ["src/velocyto/speedboosted.c"],
                extra_compile_args=["-fopenmp", "-ffast-math"],
                extra_link_args=["-fopenmp"],
            )
        ]
else:
    extensions = []
    if "darwin" in sys.platform:
        compiled = "src/velocyto/speedboosted.cpython-36m-darwin.so"
    elif "win" in sys.platform:
        sys.stdout.write("Sorry, we do not support (or like) Windows OS")
        sys.exit()
    elif "linux" in sys.platform:
        compiled = "src/velocyto/speedboosted.cpython-36m-x86_64-linux-gnu.so"
    package_data = {"velocyto": [compiled]}

class BuildFailed(Exception):
    pass

class ExtBuilder(build_ext):
    # This class allows C extension building to fail.

    built_extensions = []

    def run(self):
        try:
            build_ext.run(self)
        except (FileNotFoundError):
            print(
                "  Unable to build the C extensions, "
                "velocyto will use the pure python code instead."
            )

    def build_extension(self, ext):
        try:
            build_ext.build_extension(self, ext)
        except (CompileError, ValueError):
            print(
                f"  Unable to build the '{ext.name}' C extension, velocyto "
                f"will use the pure python version of the extension."
            )

def build(setup_kwargs):
    """
    This function is mandatory in order to build the extensions.
    """
    distribution = Distribution(
        {
            "name": "src/velocyto",
            "ext_modules": cythonize(
                extensions, compiler_directives={"language_level": "3"}
            ),
        }
    )
    distribution.package_dir = "velocyto"

    cmd = ExtBuilder(distribution)
    cmd.ensure_finalized()
    cmd.run()

    # Copy built extensions back to the project
    for output in cmd.get_outputs():
        output = Path(output)
        relative_extension = Path("src").joinpath(output.relative_to(cmd.build_lib))
        if not output.exists():
            continue

        shutil.copyfile(output, relative_extension)
        mode = relative_extension.stat().st_mode
        mode |= (mode & 0o444) >> 2
        relative_extension.chmod(mode)

    return setup_kwargs

if __name__ == "__main__":
    build({})


import django_tables2 as tables
from ..models import Statistic, Repository
from django.contrib.humanize.templatetags.humanize import intcomma
from django_tables2.utils import A
from django.db.models import F

class ColumnNumber(tables.Column):
    def render(self,value):
        return intcomma(value)

class StatTable(tables.Table):
    author_total = ColumnNumber(verbose_name='Author Total', attrs={"th": {"class": "num"}})
    commit_total = ColumnNumber(verbose_name='Commit Total', attrs={"th": {"class": "num"}})
    files_changed = ColumnNumber(verbose_name='Files Changed', attrs={"th": {"class": "num"}})
    repo_tags = tables.TemplateColumn(
        """

            {% load query_tags %}
            {%for tag in record.repo_tags%}

{{ tag }}

            {%endfor%}

        """, verbose_name='Tags', attrs={"td": {"class": "no-padding"}})
    repo_last_pulled = tables.DateTimeColumn(verbose_name='Last Pulled', format='m\/d\/y P')
    repo_last_scanned = tables.DateTimeColumn(verbose_name='Last Scanned', format='m\/d\/y P')
    lines_added = ColumnNumber(verbose_name='Lines Added', attrs={"th": {"class": "lines"}})
    lines_removed = ColumnNumber(verbose_name='Lines Removed', attrs={"th": {"class": "lines"}})
    repo = tables.TemplateColumn('{{ record.repo }}', accessor='repo.name', attrs={"td": {"class": "repo"}})

    class Meta:
        attrs = {'class': 'metrics'}
        model = Statistic
        exclude = (
            'author',
            'lines_changed',
            'repo_last_pulled',
            'id',
            'file',
            'interval',
            'start_date'
        )
        sequence = ('repo', 'repo_tags', 'repo_last_scanned', 'repo_last_pulled', 'commit_total', 'author_total', '...' )
        template_name = 'table.html'

    # def render_repo(self, record):
    #     return str(record.repo)
    # def order_repo(self, QuerySet, is_descending):
    #     QuerySet = QuerySet.annotate(
    #         repo=F('repo')
    #     ).order_by(('-' if is_descending else '') + 'repo')
    #     return (QuerySet, True)

class AuthorStatTable(tables.Table):
    author_total = ColumnNumber(verbose_name='Author Total', attrs={"th": {"class": "num"}})
    commit_total = ColumnNumber(verbose_name='Commit Total', attrs={"th": {"class": "num"}})
    files_changed = ColumnNumber(verbose_name='Files Changed', attrs={"th": {"class": "num"}})
    lines_added = ColumnNumber(verbose_name='Lines Added', attrs={"th": {"class": "lines"}})
    lines_removed = ColumnNumber(verbose_name='Lines Removed', attrs={"th": {"class": "lines"}})
    author = tables.TemplateColumn('{{ record.author }}',
        accessor='author.email', attrs={"td": {"class": "repo"}})

    class Meta:
        attrs = {'class': 'metrics'}
        model = Statistic
        exclude = (
            'lines_changed',
            'repo_last_pulled',
            'repo',
            'repo_last_scanned',
            'id',
            'file',
            'author_total',
            'interval',
            'start_date'
        )
        sequence = ('author', 'commit_total', 'author_total', '...' )
        template_name = 'table.html'


# Dalio, Brian A.
# dalioba
# 2019-10-14
#----------------------------------------------------------------------
class DrawData() :
  def __init__( self, inputFile = None ) :
    self.m_FileName = '<unknown>'
    self.m_Width    = 0
    self.m_Height   = 0
    self.m_Lines    = []
    self.m_Polygons = []

    if inputFile is not None :
      self.loadFile( inputFile )

  def getWidth( self ) :
    return self.m_Width

  def getHeight( self ):
    return self.m_Height

  def getLines( self ) :
    return self.m_Lines

  def getPolygons( self ) :
    return self.m_Polygons

  #---------------------------------------
  def dump( self ) :
    print( f'#-- DrawData({self.m_FileName!r}) --' )
    print( f'# Canvas size  : ({self.getWidth():4d}, {self.getHeight():4d})' )
    print( f'# Num lines    : {len(self.getLines()):5d}' )
    print( f'# Num polygons : {len(self.getPolygons()):5d}' )
    print(  '#---------------------------------------')

  #---------------------------------------
  def loadFile( self, fName ) :
    self.m_FileName = fName

    with open( fName, 'r' ) as fp :
      lines = fp.read().replace('\r', '' ).split( '\n' )

    for ( index, line ) in enumerate( lines, start = 1 ) :
      line = line.strip()
      if ( line == '' or line[0] == '#' ) :
        continue

      if line[0] == 'c' :
        try :
          _, w, h = line.split()

          w = int( w )
          h = int( h )

          self.m_Width = w
          self.m_Height = h

        except :
          print( f'Line {index} is a malformed canvas spec.' )

      elif line[0] == 'l' :
        try :
          coords = list( [ float( c ) for c in line.split()[1:] ] )

          if len( coords ) != 4 :
            print( f'Line {index} is a malformed line spec.' )

          else :
            self.m_Lines.append( coords )

        except :
          print( f'Line {index} is a malformed line spec.' )

      elif line[0] == 'p' :
        try :
          coords = list( [ float( c ) for c in line.split()[1:] ] )

          if len( coords ) % 2 != 0 :
            print( f'Line {index} is a malformed polygon spec.' )

          else :
            self.m_Polygons.append( coords )

        except :
          print( f'Line {index} is a malformed polygon spec.' )

      else :
        print( f'Line {index} \'{line}\' is unrecognized.' )

#----------------------------------------------------------------------


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 23 12:49:56 2018

@author: drugo
"""

# LEGGO I FILE

import os
import subprocess
# Open a file
path = "/home/drugo/pyModis/scripts"
dirs = os.listdir( path )

# This would print all the files and directories
for files in dirs:
    fileHDFinput = files
    #print(fileHDFinput)
    fileTIFoutput = fileHDFinput.replace('.hdf', '.tif')
    #print(fileTIFoutput)
    first = 'modis_convert.py -s "( 0 1 )" -o '
    second =' -g 500 -e 32632 '
    stringToLaunch =first+fileTIFoutput+second+fileHDFinput
    print(stringToLaunch)
    os.system(stringToLaunch)


# 导入requests库
import requests
# 导入BeautSoup库
from bs4 import BeautifulSoup

# 定义请求头，请求头可以使爬虫伪装成浏览器
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}
# 定义连接网络的列表
url_list = ['http://www.kugou.com/yy/rank/home/{0}-8888.html'.format(str(i)) for i in range(1, 24)]

for url in url_list:
    # 利用requests模块连接网络，它可以打开并读取从网络获取的对象
    html = requests.get(url, headers=headers)
    # BeautifulSoup通过定位HTML标签来格式化和组织复杂的网络信息
    soup = BeautifulSoup(html.text, 'lxml')
    # 将歌曲名称，作者存放到列表里面
    rank_list = soup.select('#rankWrap > div.pc_temp_songlist > ul > li > span.pc_temp_num')
    # 将歌曲名称存放到列表里面
    name_list = soup.select('#rankWrap > div.pc_temp_songlist > ul > li > a')
    # 将歌曲时间存放到列表里面
    time_list = soup.select('#rankWrap > div.pc_temp_songlist > ul > li > span.pc_temp_tips_r > span')
    # 将名次，歌名，时间依次打印出来
    for rank, name, time in zip(rank_list, name_list, time_list):
        # get_txet()是为了提取文字，去除其他字符。strip（）是为了去除空白字符
        print(rank.get_text().strip(), name.get_text().strip(), time.get_text().strip())


import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.signal as sig
import os
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression
from pandas.plotting import autocorrelation_plot

def left_to_right(origin, N):
    ret = origin.loc[N, range(1,21)]
    ret.index = pd.date_range('1975', periods=20, freq='AS')
    ret = pd.DataFrame(data=ret)
    ret.columns = ['values']
    return ret

def standard(origin):
    print("bon",origin)
    vals = origin.values
    min_max = preprocessing.MinMaxScaler()
    val_scaled = min_max.fit_transform(vals)
    ret = pd.DataFrame(val_scaled)
    ret.index = pd.date_range('1975', periods=20, freq='AS')
    ret.columns = ['values']
    return ret

def de_trend(origin):
    X = [i for i in range(0, len(origin))]
    X = np.reshape(X, (len(X), 1))
    y = observe.values
    model = LinearRegression()
    model.fit(X, y)
    trend = model.predict(X)

    ret = pd.DataFrame(data=sig.detrend(origin['values']))
    ret.index = pd.date_range('1975', periods=20, freq='AS')
    ret.columns = ['values']
    return ret, trend

def stationary_test(df):
    rolmean = df.rolling(5).mean()
    rolstd = df.rolling(5).std()
    orig = plt.plot(df, color='blue',label='Original')
    mean = plt.plot(rolmean, color='red', label='Rolling Mean')
    std = plt.plot(rolstd, color='black', label = 'Rolling Std')
    plt.legend(loc='best')
    plt.title('Rolling Mean & Standard Deviation')
    plt.show()

    result = adfuller(df['values'])
    print('ADF Statistic: {}'.format(result[0]))
    print('p-value: {}'.format(result[1]))
    print('Critical Values:')
    for key, value in result[4].items():
        print('\t{}: {}'.format(key, value))

path = os.path.abspath("M3TrainingSet.xlsx")
xls = pd.ExcelFile(path)
original_data = pd.read_excel(xls)

original_data = pd.read_excel(xls)#, 'M3Year')

#observe = original_data.loc[0:146,5]
#observe.index = original_data.loc[0:146,'Series'] These are for top to bottom

observe = left_to_right(original_data, 0) #select which series to investigate

print(observe.head()) #Checking that the right data is selected

scaled = standard(observe) #scaling the data

notrend, trend = de_trend(scaled) #detrending the data

print(trend)

stationary_test(observe) #checking if data is non-stationary (p-value>0.05)

#rolling_mean = observe.rolling(5).mean()
#df_log_minus_mean = observe - rolling_mean
#df_log_minus_mean.dropna(inplace=True)
#stationary_test(df_log_minus_mean)

stationary_test(notrend)

plt.plot(scaled, label='scaled')
plt.plot(notrend, label='detrended')
plt.title('Financial data starting in 1975')
plt.xlabel('Year', fontsize=10)
plt.legend()
plt.show()

autocorrelation_plot(notrend['values'])
plt.title('Autocorrelation plot')
plt.show()

result = seasonal_decompose(notrend, model='additive')
result.plot()
plt.show()

model = ARIMA(notrend, order=(2,1,0))
resultsar = model.fit(disp=-1)
plt.plot(notrend)
plt.plot(resultsar.fittedvalues, color='red')
plt.title('ARIMA fittedvalues')
plt.show()

resultsar.plot_predict(1,25)
plt.title('ARIMA predicted values')
plt.show()

print(resultsar.fittedvalues)


from datetime import datetime, timedelta, date
from copy import deepcopy
from collections import OrderedDict, defaultdict, Callable
from flask import render_template, current_app, request
import plotly
import pandas as pd
import numpy as np
from sqlalchemy import func
from sqlalchemy.orm import aliased

from .common.base import BaseView
from .common.function import *
from db import *

def get_current_team_cats_count(cats):
    cat_filter = or_(1==2)
    for cat in cats:
        cat_filter = or_(cat_filter, Issue.category==Category.query.filter_by(c_name=cat).first())

    status_filter = or_(Issue.state==State.query.filter_by(s_name='Ongoing').first(), \
        Issue.state==State.query.filter_by(s_name='New').first())

    ret = Issue.query.filter(and_(status_filter, cat_filter )). \
                        add_columns(func.count(Issue.team_id)).group_by(Issue.team_id).all()
    team_name = []
    team_count = []
    for x, c in ret:
        team_name.append(x.team.g_name)
        team_count.append(c)
    return team_name, team_count

def get_days_cats_team_count(cats, from_date, to_date):
    teams = [x[0] for x in Group.query.filter_by(in_ps=True).with_entities(Group.g_name).all()]
    Group_T = aliased(Issue.team)
    date_filter = and_(Issue.out_date >= from_date, Issue.out_date <= to_date)

    cat_filter = or_(1==2)
    for cat in cats:
        cat_filter = or_(cat_filter, Issue.category==Category.query.filter_by(c_name=cat).first())

    ret = Issue.query.filter(and_(date_filter, cat_filter) ).outerjoin(Group_T, Issue.team).with_entities( \
            Group_T.g_name.label('team'), Issue.out_date).add_columns(func.count(Issue.out_date)).\
                group_by(Issue.out_date, 'team').all()
    res = dict()
    day_cal = (to_date - from_date).days + 1
    for x in teams:
        days = [from_date+timedelta(days=i) for i in range(day_cal)]
        res[x] = OrderedDict(zip(days, [0]*day_cal))
    for team, day, count in ret:
        res[team][day]=count
    counts = []
    for team in teams:
        counts.append(list())
        for day, count in res[team].items():
            counts[-1].append(count)

    return teams, counts

def moving_average(a, n=4) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

def get_weeks_cats_team_count(cats, from_date, to_date, mo_avg=False):
    day_cal = (to_date - from_date).days + 1
    week_cal = int(day_cal / 7)
    teams, counts = get_days_cats_team_count(cats, from_date, to_date)
    for t in range(len(teams)):
        tmp_list = []
        for w in range(week_cal):
            tmp_list.append(sum(counts[t][w*7:(w*7+7)]))
        counts[t] = deepcopy(tmp_list)
        if mo_avg:
            counts[t] = list(moving_average(counts[t]))
    return teams, counts

def get_productivity(teams, counts, to_date):
    week_cal = len(counts[0])
    oldest_day = to_date - timedelta(days=(week_cal-1)*7)
    for k, team in enumerate(teams):
        member_json = Group.query.filter_by(g_name=team).with_entities(Group.member).first()[0]
        j = 0
        for i in range(0, week_cal*7, 7):
            tmp_day = oldest_day+timedelta(days=i)
            # print(team, tmp_day, member_json)
            team_count = get_team_member(member_json, tmp_day)
            counts[k][j] /= team_count
            j += 1
    return teams, counts

class OrderedDefaultdict(OrderedDict):
    def __init__(self, default_factory=None, *args, **kwargs):
        if not (default_factory is None
                or isinstance(default_factory, Callable)):
            raise TypeError('first argument must be callable or None')
        super(OrderedDefaultdict, self).__init__(*args, **kwargs)
        self.default_factory = default_factory

    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key,)
        self[key] = value = self.default_factory()
        return value

def get_weeks_cycle_time(cats, from_date, to_date):
    teams = [x[0] for x in Group.query.filter_by(in_ps=True).with_entities(Group.g_name).all()]
    Group_T = aliased(Issue.team)
    day_cal = (to_date - from_date).days + 1
    week_cal = int(day_cal / 7)
    date_filter = and_(Issue.out_date >= from_date, Issue.out_date <= to_date)

    cat_filter = or_(1==2)
    for cat in cats:
        cat_filter = or_(cat_filter, Issue.category==Category.query.filter_by(c_name=cat).first())

    ret = Issue.query.filter(and_(date_filter, cat_filter) ).outerjoin(Group_T, Issue.team).with_entities( \
            Group_T.g_name.label('team'), Issue.out_date, Issue.in_date).all()

    # assert current_app.debug == False
    res = dict()
    for team in teams:
        days = [from_date+timedelta(days=i) for i in range(day_cal)]
        res[team] = OrderedDict(zip(days, [[] for _ in range(day_cal)]))
    for team, out_day, in_day in ret:
        res[team][out_day].append(in_day)
    counts = []
    for team in teams:
        counts.append(list())
        for outday, in_day_list in res[team].items():
            total_day_count = 0
            total_count = 0
            for one_in_day in in_day_list:
                total_day_count += (outday - one_in_day).days
                total_count += 1
            counts[-1].append((total_count, total_day_count))

    week_counts = []
    for team_counts in counts:
        week_counts.append([])
        for week in range(week_cal):
            count_total_list = list(zip(*team_counts[week*7:week*7+7]))
            week_total_count = sum(count_total_list[1])
            week_count = sum(count_total_list[0])
            week_counts[-1].append(week_total_count/week_count if week_count else 0)

    return teams, week_counts

class MetricView(BaseView):
    def get(self, m_id=None):
        # assert current_app.debug == False
        if m_id is None:
            categories = Category.select()
            return render_template('metric.html', categories=categories)
        else:
            args = dict(request.args)
            from_date = args.pop('from_date')[0] if 'from_date' in args else ''
            to_date = args.pop('to_date')[0] if 'to_date' in args else ''
            cats = list(args.keys())

            if m_id == 1:
                team_name, team_count = get_current_team_cats_count(cats)
                fig = {
                    'data': [{
                        'labels': team_name,
                        'values': team_count,
                        'type': 'pie'
                    }],
                    'layout': {'title': 'LRC New/Ongoing '+' '.join(cats)}
                }
                return get_json(fig), 200

            elif m_id == 2:
                if from_date and to_date:
                    from_date = date(*map(int, from_date.split('-')))
                    to_date = date(*map(int, to_date.split('-')))
                    day_cal = (to_date - from_date).days + 1
                else:
                    to_date = date.today()
                    day_cal = 30
                    from_date = to_date - timedelta(days=day_cal-1)

                teams, counts = get_days_cats_team_count(cats, from_date, to_date)
                x = [str(from_date+timedelta(days=i)) for i in range(day_cal)]

                data = []
                for i in range(len(teams)):
                    data.append({
                        'x':  x,
                        'y': counts[i],
                        'name':  teams[i],
                        'mode':  'lines+markers',
                        'line': {
                            'shape':  'spline'
                        }
                    })
                layout = dict(title = 'Resolved '+' '.join(cats) + '(in 30 days)',
                            xaxis = dict(title = 'Date'),
                            yaxis = dict(title = 'Resolved count'),
                            )
                fig = dict(data=data, layout=layout)
                return get_json(fig), 200

            elif m_id == 3:
                if from_date and to_date:
                    from_date = date(*map(int, from_date.split('-')))
                    to_date = date(*map(int, to_date.split('-')))
                    day_cal = (to_date - from_date).days + 1
                else:
                    to_date = date.today()
                    day_cal = 30
                    from_date = to_date - timedelta(days=day_cal-1)

                teams, counts = get_days_cats_team_count(cats, from_date, to_date)
                x = [str(from_date+timedelta(days=i)) for i in range(day_cal)]

                data = []
                for i in range(len(teams)):
                    data.append({
                        'x' : x,
                        'y' : counts[i],
                        'name' : teams[i],
                        'type': 'bar'
                    })
                layout = dict(title = 'Daily PS/Team relative resolved ' +' '.join(cats),
                            xaxis = dict(title = 'Date'),
                            yaxis = dict(title = 'Resolved count'),
                            barmode = 'relative'
                            )
                fig = dict(data=data, layout=layout)
                return get_json(fig), 200

            elif m_id == 4:
                if to_date:
                    to_date = date(*map(int, to_date.split('-')))
                else:
                    to_date = date.today()
                week_cal = 17
                day_cal = week_cal * 7
                from_date = to_date - timedelta(days=day_cal-1)

                teams, counts = get_weeks_cats_team_count(cats, from_date, to_date, mo_avg=True)
                teams.append('PS Total')

                week_count = len(counts[0])
                ps_total = [0]*week_count
                for team in counts:
                    for i in range(week_count):
                        ps_total[i] += team[i]
                counts.append(ps_total)

                x = []
                for i in range(0, week_cal*7, 7):
                    tmp = (from_date+timedelta(days=i)).isocalendar()[:2]
                    x.append(str(tmp[0])+'-'+str(tmp[1]))

                data = []
                for i in range(len(teams)):
                    data.append({
                        'x': x,
                        'y': counts[i],
                        'name': teams[i],
                        'mode': 'lines+markers',
                        'shape': 'spline',
                        'line': {
                            'shape':  'spline'
                        }
                    })
                layout = dict(title = 'Resolved '+' '.join(cats) + ' (Rolling Average of 4 weeks)',
                            xaxis = dict(title = 'Week'),
                            yaxis = dict(title = 'Resolved count'),
                            )
                fig = dict(data=data, layout=layout)
                return get_json(fig), 200

            elif m_id == 5:
                if to_date:
                    to_date = date(*map(int, to_date.split('-')))
                else:
                    to_date = date.today()
                week_cal = 14
                day_cal = week_cal * 7
                from_date = to_date - timedelta(days=day_cal-1)

                teams, counts = get_weeks_cats_team_count(cats, from_date, to_date)
                teams, counts = get_productivity(teams, counts, to_date)

                x = []
                for i in range(0, week_cal*7, 7):
                    tmp = (from_date+timedelta(days=i)).isocalendar()[:2]
                    x.append(str(tmp[0])+'-'+str(tmp[1]))

                data = []
                for i in range(len(teams)):
                    data.append({
                        'x': x,
                        'y': counts[i],
                        'name': teams[i],
                        'mode': 'lines+markers',
                        'shape': 'spline',
                        'line': {
                            'shape':  'spline'
                        }
                    })
                layout = dict(title = 'Team productivity of '+' '.join(cats),
                            xaxis = dict(title = 'Week'),
                            yaxis = dict(title = 'Productivity'),
                            )
                fig = dict(data=data, layout=layout)
                return get_json(fig), 200

            elif m_id == 6:
                if to_date:
                    to_date = date(*map(int, to_date.split('-')))
                else:
                    to_date = date.today()
                week_cal = 14
                day_cal = week_cal * 7
                from_date = to_date - timedelta(days=day_cal-1)

                teams, counts = get_weeks_cycle_time(cats, from_date, to_date)

                x = []
                for i in range(0, week_cal*7, 7):
                    tmp = (from_date+timedelta(days=i)).isocalendar()[:2]
                    x.append(str(tmp[0])+'-'+str(tmp[1]))

                data = []
                for i in range(len(teams)):
                    data.append({
                        'x': x,
                        'y': counts[i],
                        'name': teams[i],
                        'mode': 'lines+markers',
                        'shape': 'spline',
                        'line': {
                            'shape':  'spline'
                        }
                    })
                layout = dict(title = 'Team Cycle Time of '+' '.join(cats),
                            xaxis = dict(title = 'Week'),
                            yaxis = dict(title = 'Cycle Time (days)'),
                            )
                fig = dict(data=data, layout=layout)
                return get_json(fig), 200


# -*- coding: utf-8 -*-
import numpy as np
import math
import os
import json

def rssi2distance( x, p , height=1.6 ):

	w, b = p
	return ( 10**( ( x + 55 - b )/(-10*w) ) ) *height

def conver_distance( x ):

	if x < 1.6:
		return 0

	return (x**2 - 1.6**2) ** 0.5

def xy_dis( x1, y1, x2, y2):
	return ( math.pow( (x1-x2), 2 ) + math.pow( (y1-y2), 2 ) ) ** 0.5

def process_correct( circles , point , min_err = 3 , rate = 1.5 ):
	#circles 三个定位的圆心及半径
	#point初步定位点
	#初步定位点到最小的圆的圆心距离 > min_err 且是半径的rate倍 才启动修正
	circles = sorted( circles )

	r  = circles[0][0]
	cx = circles[0][1][0]
	cy = circles[0][1][1]

	px = point[0]
	py = point[1]

	dis_center = xy_dis( px,py, cx, cy )

	if dis_center > min_err and dis_center > rate*r :

		c = r/dis_center

		x01 = c*abs(px-cx)+cx
		y01 = c*abs(py-cy)+cy

		x02 = c*abs(px-cx)-cx
		y02 = c*abs(py-cy)-cy

		dis_p1 = xy_dis( px,py , x01, y01 )
		dis_p2 = xy_dis( px,py , x02, y02 )

		if dis_p1 > dis_p2:
			return [ x02, y02 ]
		else:
			return [ x01, y01 ]

	else:
		return point

def location( tensor ):

	A = []
	b = []

	for i in range( 0 , len(tensor) ):
		d1	  = tensor[0][0]
		x1,y1 = tensor[0][1]

		di	  = tensor[i][0]
		xi,yi = tensor[i][1]

		a1 = 2*(x1 - xi )
		a2 = 2*(y1 - yi )

		A.append( [a1,a2] )

		b1 = x1**2 - xi**2 + y1**2 - yi**2 + di**2 - d1**2

		b.append([b1])

	ma = np.mat(A)
	mb = np.mat(b)

	return (ma.T*ma).I*(ma.T)*mb

def find_center( p0, p1, p2, d0, d1, d2 ):

	l = [ [p0,d0] , [p1,d1],[p2,d2] ]
	l = sorted( l )

	mn  = l[0]
	mid = l[1]
	mx = l[2]

	a0 = mn[0] + mn[1]
	a2 = mx[0] - mx[1]

	#最中间的取2次值
	mid1 = mid[0] + mid[1]
	mid2 = mid[0] - mid[1]

	k1 = abs( mid1-a0) + abs(mid1-a2)
	k2 = abs( mid2-a0) + abs(mid2-a2)

	if k1 < k2:
		return ( a0 + a2 + mid1 ) / 3.0
	else:
		return ( a0 + a2 + mid2 ) / 3.0

def process_singular_matrix( mats ):

	p0 = mats[0]
	p1 = mats[1]
	p2 = mats[2]

	#beacon的位置
	p0x, p0y = p0[1]
	p1x, p1y = p1[1]
	p2x, p2y = p2[1]

	#到beacon的距离
	d0 = p0[0]
	d1 = p1[0]
	d2 = p2[0]

	#找到直线
	if abs( p0x - p1x) < 0.5 and abs( p1x - p2x ) < 0.5:
		x = p0x
		y = find_center( p0y, p1y, p2y, d0, d1, d2 )

	if abs( p0y - p1y ) < 0.5 and abs( p1y - p2y ) < 0.5:
		y = p0y
		x = find_center( p0x, p1x, p2x, d0, d1, d2 )

	return np.mat( [ x,y ] )

def load_3D_print( file_path  ):

		file_path += '_3D'

		if not os.path.exists( file_path ):
			return [],[],[],[]

		param = [0]*4

		file = open( file_path )

		count = 0
		for line in file.readlines():
			line = line.strip()

			if len(line) < 5:
				continue

			param[count] = json.loads(line)
			count += 1

		return param[0],param[1],param[2],param[3]

def process_3d(position, test_x , floor ):

		iBeaconX, iBeaconY, pp , floors  = load_3D_print( position )
		vec = []

		if position == 'B31':
			del test_x[33]
			del test_x[35]
			test_x[34] = -999.0

		rssis = np.array( test_x )

		for i in range(0,len(iBeaconX) ):

			index    = rssis.argmax()
			max_rssi = rssis.max()

			if floor != 0 and floors[index] != floor:
				rssis[index] = -999.0
				continue

			p = pp[index]

			d = conver_distance( rssi2distance( max_rssi,p ) )

			rssis[index] = -999.0

			vec.append( [d, [ iBeaconX[index], iBeaconY[index] ] ] )

			if len(vec) == 3:
				break

		try:

			if len(vec) < 3:
				return -3, "input data error"

			if ( abs( vec[0][1][0] - vec[1][1][0] ) < 0.5 and abs( vec[0][1][0] - vec[2][1][0] ) < 0.5 ) or \
		   		( abs( vec[0][1][1] - vec[1][1][1] ) < 0.5 and abs( vec[0][1][1] - vec[2][1][1] ) < 0.5 ) :
				find = process_singular_matrix( vec )

			else:
				find = location(vec)

		except Exception as e:
			find = process_singular_matrix( vec )

		loc_x = round( find.getA1()[0] ,3 )
		loc_y = round( find.getA1()[1] , 3)

		loc_x, loc_y = process_correct( vec, [loc_x, loc_y] )

		return loc_x, loc_y


from xai.brain.wordbase.nouns._spin import _SPIN

#calss header
class _SPINS(_SPIN, ):
	def __init__(self,):
		_SPIN.__init__(self)
		self.name = "SPINS"
		self.specie = 'nouns'
		self.basic = "spin"
		self.jsondata = {}


# -*- coding: utf-8 -*-
n=int(input('Quantidade de divisores a serem mostrados:'))
a=int(input('Número 1:'))
b=int(input('Número 2:'))
múltiplo=1
for termo in range(a,n+1,1):
    if múltiplo%a==0 or múltiplo%b==0:
        múltiplo=múltiplo+1
        print(múltiplo)


# N, K = map(int, input().split())
#
#
# def func(n, k):
#     dict = {}
#     for i in range(1, n + 1):
#         dict[i] = 1
#
#     target = 1
#     cnt = 0
#     rot = 0
#
#     while True:
#         if dict[target] == 1 and rot == k - 1:
#             dict[target] = 0
#             cnt += 1
#             rot = 0
#         elif dict[target] == 0:
#             target += 1
#             if target > n:
#                 target -= n
#         else:
#             rot += 1
#             target += 1
#             if target > n:
#                 target -= n
#
#         if cnt == (n - k + 1):
#             break
#
#     x = []
#     for i in range(1, n + 1):
#         if dict[i] == 1:
#             x.append(i)
#     return x[-1]
#
#
# print(func(N, K))

N, K, M = map(int, input().split())
pivot = K
tmp = 1
cnt = 0

idx = 0
for i in range(1, N + 1):
    idx = (idx + K) % i
    cnt += 1
    if idx + 1 == M:
        print(cnt)
        exit()


# 问题：我们有一个元素序列，想知道序列中出现次数最多的元素是什么。

# 解决方案：collections 模块中的 Counter 类下辈 为此类问题所设计的。
# 它有个方法方法可以直接告诉我们  most_common()

words = [
    'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
    'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
    'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
    'my', 'eyes', "you're", 'under'
]

from collections import Counter

word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)        # [('eyes', 8), ('the', 5), ('look', 4)]

# tips：Counter 也可手动增加(更新)计数，还可以和各种数学运算操作结合使用。

1、数据结构和算法/1.12、找出序列中出现次数最多的元素.py

1.12、找出序列中出现次数最多的元素.py


from core.game.Card import Card
from core.game.IPlayer import IPlayer
from core.game.GameEngineHelper import GameEngineHelper
from core.game.PlayerGameHelper import PlayerGameHelper
from core.game.GamePlayer import GamePlayer
from typing import List

INITIAL_HAND_SIZE: int = 7
MIN_REQUIRED_PLAYERS: int = 2
MAX_REQUIRED_PLAYERS: int = 10

class GameEngine:
    def __init__(self, players: List[IPlayer], rounds_per_match: int):
        players_count = len(players)
        self._players: List[IPlayer] = players
        if players_count < MIN_REQUIRED_PLAYERS or players_count > MAX_REQUIRED_PLAYERS:
            raise ValueError('Amount of players must be at least 2 and cannot exceed 10')
        self._roundsPerMatch: int = rounds_per_match
        self._deck: List[Card] = GameEngineHelper.create_game_deck()

    def __get_game_players(self, players: List[IPlayer]) -> List[GamePlayer]:
        game_players = []
        for index, player in enumerate(players):
            player_hand = self.__draw_cards(INITIAL_HAND_SIZE)
            game_player = GamePlayer(player, player_hand, index)
            game_players.append(game_player)
        return game_players

    def __draw_cards(self, draw_count: int) -> List[Card]:
        drawn_cards = []
        for n in range(draw_count):
            drawn_cards.append(self._deck.pop(0))
        return drawn_cards

    def __create_player_game_helper(self, active_player: GamePlayer, last_card_played: Card):
        hand = active_player.hand
        last_card_played = last_card_played
        card_pile = []
        deck_count = len(self._deck)
        opp_hand_count = []
        return PlayerGameHelper(hand, last_card_played, card_pile, deck_count, opp_hand_count)

    def start(self):
        current_round: int = 0

        while current_round <= self._roundsPerMatch:
            # At the beginning of every round, get a fresh list of players and resent round variables.
            round_players = self.__get_game_players(self._players)
            self._deck = GameEngineHelper.create_game_deck()
            current_round += 1
            round_won = False
            round_winner = None
            print('- Round {0}'.format(current_round))

            # Keep playing the same round until a winner is chosen.
            while not round_won:
                active_player: GamePlayer = None
                last_card_played = self.__draw_cards(1)

                # Main game loop starts here, loop through each player until a player has 0 cards.
                for game_player in round_players:
                    active_player = game_player.player
                    active_player_game_helper = self.__create_player_game_helper(game_player, last_card_played)
                    game_player.player.set_game_helper(active_player_game_helper)
                    player_action = game_player.player.take_turn()
                    print('{} uses action {}'.format(active_player.get_player_name(), player_action.action))
                    print('{}'.format(player_action.card.get_card_text()))

                    # Until game loop is actually implemented, remove a card from the player's hand.
                    game_player.hand.pop()

                    # After the card has been played, if that player has no more cards, they win the round.
                    if len(game_player.hand) <= 0:
                        round_won = True
                        print('{} won the round!'.format(active_player.get_player_name()))
                        round_winner = active_player

        # After all rounds have been played, handle any Match over logic here
        print('Match is over!')


from django.conf.urls import url

from . import views

app_name='tutor4u'
urlpatterns = [
    # ex: /polls/
    url(r'^$', views.index, name='index'),
    url(r'^tutor$', views.tutor_signup, name='signup2'),
    # url(r'^signup_tutor$', views.tutorsignup, name='tutorsignup'),
    url(r'^signup_complete$', views.signup_complete, name='signup_complete'),
    # ex: /polls/5/
    url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
    # ex: /polls/5/results/
    #url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
    # ex: /polls/5/vote/
    url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
    url(r'^form_upload$', views.form_upload, name='form_upload'),
    url(r'^signup$', views.tutee_signup, name='signup'),
    url(r'^signup_action$', views.signup_action, name='signup_action'),
    url(r'^result/(?P<user_id>[0-9]+)$',views.results, name='results'),
    url(r'^tutorresults/(?P<user_id>[0-9]+)$',views.tutorresults, name='tutorresults'),
    url(r'^user_login$', views.user_login, name='user_login'),
    url(r'^about$',views.about, name='about'),
    url(r'^locations$',views.locations, name='locations'),
    url(r'^subjects$',views.subjects, name='subjects'),
    url(r'^lv$',views.lv, name='lv')
]


from django.test import TestCase
from django.urls import reverse
from ..models import Product

class ProductViewTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        Product.objects.create(name="Test Product", category="cat1", nutrition_grade="e")
        for category in ["cat1", "cat2", "cat3", "cat4"]:
            for grade in ["a", "b", "c", "d", "e"]:
                for e in range(60):  # Creating 60 instances for each different grades
                    Product.objects.create(nutrition_grade=grade, category=category)

    def test_product(self):
        product = Product.objects.all()[0]
        product_url = reverse('product', args=[product.pk])
        response = self.client.get(product_url)
        self.assertEquals(response.context['prod'], Product.objects.get(pk=product.pk))
        self.assertEquals(response.status_code, 200)
        # When launching all tests only : products.models.Product.DoesNotExist: Product matching query does not exist. ;

    def test_search_product(self):
        # Testing with correct input
        response = self.client.post('/products/search', {'research':'Test Product'})
        self.assertEquals(response.status_code, 200)
        # Testing with incorrect input
        response = self.client.post('/products/search', {'research':'WrongInput'})
        self.assertEquals(response.status_code, 302)


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

from django.db import models, migrations
from django.conf import settings
import uuid

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Assignment',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('title', models.TextField()),
                ('total_value', models.DecimalField(decimal_places=5, max_digits=10)),
                ('is_discrete', models.BooleanField()),
                ('upper_bound', models.DecimalField(default=0.0, max_digits=10, decimal_places=5)),
                ('lower_bound', models.DecimalField(default=100.0, max_digits=10, decimal_places=5)),
            ],
            options={
                'verbose_name_plural': 'assignments',
                'verbose_name': 'assignment',
            },
        ),
        migrations.CreateModel(
            name='AssignmentType',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('name', models.TextField()),
                ('weight', models.DecimalField(decimal_places=5, max_digits=10)),
            ],
            options={
                'verbose_name_plural': 'assignments types',
                'verbose_name': 'assignment type',
            },
        ),
        migrations.CreateModel(
            name='ContinuousScore',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('value', models.DecimalField(decimal_places=5, max_digits=10)),
                ('assignment', models.ForeignKey(to='score_book.Assignment')),
            ],
            options={
                'verbose_name_plural': 'scores',
                'verbose_name': 'score',
            },
        ),
        migrations.CreateModel(
            name='Course',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('year', models.IntegerField()),
                ('full_name', models.TextField()),
                ('abbr_name', models.TextField()),
                ('location', models.TextField()),
            ],
            options={
                'verbose_name_plural': 'courses',
                'verbose_name': 'course',
            },
        ),
        migrations.CreateModel(
            name='DiscreteScore',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('assignment', models.ForeignKey(to='score_book.Assignment')),
            ],
            options={
                'verbose_name_plural': 'scores',
                'verbose_name': 'score',
            },
        ),
        migrations.CreateModel(
            name='DiscreteScoreSystem',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('course', models.ForeignKey(to='score_book.Course')),
            ],
            options={
                'verbose_name_plural': 'score systems',
                'verbose_name': 'score system',
            },
        ),
        migrations.CreateModel(
            name='DiscreteScoreType',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('numeric_value', models.DecimalField(decimal_places=5, max_digits=10)),
                ('text_value', models.TextField()),
                ('image_value', models.ImageField(upload_to='')),
                ('real_value', models.DecimalField(decimal_places=5, max_digits=10)),
                ('course', models.ForeignKey(to='score_book.Course')),
                ('score_system', models.ManyToManyField(to='score_book.DiscreteScoreSystem')),
            ],
            options={
                'verbose_name_plural': 'score types',
                'verbose_name': 'score type',
            },
        ),
        migrations.CreateModel(
            name='Instructor',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('ucinetid', models.TextField()),
                ('preferred_name', models.TextField(default='')),
                ('courses', models.ManyToManyField(to='score_book.Course')),
            ],
            options={
                'ordering': ['ucinetid'],
                'verbose_name': 'instructor',
                'verbose_name_plural': 'instructors',
            },
        ),
        migrations.CreateModel(
            name='Quarter',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('name', models.TextField()),
                ('number', models.IntegerField()),
            ],
            options={
                'ordering': ['number'],
                'verbose_name': 'quarter',
                'verbose_name_plural': 'quarters',
            },
        ),
        migrations.CreateModel(
            name='Section',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('name', models.TextField()),
                ('number', models.IntegerField()),
                ('course', models.ForeignKey(to='score_book.Course')),
                ('instructors', models.ManyToManyField(to='score_book.Instructor')),
            ],
            options={
                'verbose_name_plural': 'sections',
                'verbose_name': 'section',
            },
        ),
        migrations.CreateModel(
            name='Student',
            fields=[
                ('id', models.UUIDField(editable=False, primary_key=True, default=uuid.uuid4, serialize=False)),
                ('ucinetid', models.TextField()),
                ('preferred_name', models.TextField(default='')),
                ('studentid', models.PositiveIntegerField()),
                ('courses', models.ManyToManyField(to='score_book.Course')),
                ('sections', models.ManyToManyField(to='score_book.Section')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ['ucinetid'],
                'verbose_name': 'student',
                'verbose_name_plural': 'students',
            },
        ),
        migrations.AddField(
            model_name='section',
            name='students',
            field=models.ManyToManyField(to='score_book.Student'),
        ),
        migrations.AddField(
            model_name='instructor',
            name='sections',
            field=models.ManyToManyField(to='score_book.Section'),
        ),
        migrations.AddField(
            model_name='instructor',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
        ),
        migrations.AddField(
            model_name='discretescoresystem',
            name='possible_values',
            field=models.ManyToManyField(to='score_book.DiscreteScoreType'),
        ),
        migrations.AddField(
            model_name='discretescore',
            name='student',
            field=models.ForeignKey(to='score_book.Student'),
        ),
        migrations.AddField(
            model_name='discretescore',
            name='value',
            field=models.ForeignKey(to='score_book.DiscreteScoreType'),
        ),
        migrations.AddField(
            model_name='course',
            name='instructors',
            field=models.ManyToManyField(to='score_book.Instructor'),
        ),
        migrations.AddField(
            model_name='course',
            name='quarter',
            field=models.ForeignKey(to='score_book.Quarter'),
        ),
        migrations.AddField(
            model_name='course',
            name='students',
            field=models.ManyToManyField(to='score_book.Student'),
        ),
        migrations.AddField(
            model_name='continuousscore',
            name='student',
            field=models.ForeignKey(to='score_book.Student'),
        ),
        migrations.AddField(
            model_name='assignmenttype',
            name='course',
            field=models.ForeignKey(to='score_book.Course'),
        ),
        migrations.AddField(
            model_name='assignment',
            name='assignment_type',
            field=models.ForeignKey(to='score_book.AssignmentType'),
        ),
        migrations.AddField(
            model_name='assignment',
            name='course',
            field=models.ForeignKey(to='score_book.Course'),
        ),
        migrations.AddField(
            model_name='assignment',
            name='discrete_score_system',
            field=models.ForeignKey(to='score_book.DiscreteScoreSystem'),
        ),
    ]