import math
import tsfresh
import logging
from scipy import signal
from statsmodels.distributions.empirical_distribution import ECDF
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader, TensorDataset
from sklearn.preprocessing import MinMaxScaler
import pandas as pd
from pandas import concat
from pandas import DataFrame
import os
import torch
import torch.nn as nn

def approximate_entropy(x, m, r,h):
    """
    Implements a vectorized Approximate entropy algorithm.

        https://en.wikipedia.org/wiki/Approximate_entropy

    For short time-series this method is highly dependent on the parameters,
    but should be stable for N > 2000, see:

        Yentes et al. (2012) -
        *The Appropriate Use of Approximate Entropy and Sample Entropy with Short Data Sets*

    Other shortcomings and alternatives discussed in:

        Richman & Moorman (2000) -
        *Physiological time-series analysis using approximate entropy and sample entropy*

    :param x: the time series to calculate the feature of
    :type x: numpy.ndarray
    :param m: Length of compared run of data
    :type m: int
    :param r: Filtering level, must be positive
    :type r: float

    :return: Approximate entropy
    :return type: float
    """
    if not isinstance(x, (np.ndarray, pd.Series)):
        x = np.asarray(x)

    N = x.size
    r *= np.std(x)
    if r < 0:
        raise ValueError("Parameter r must be positive.")
    if N <= m + 1:
        return 0

    def _phi(m):
        x_re = np.array([x[i:i + m] for i in range(N - m + 1)])
        C = np.sum(np.max(np.abs(x_re[:, np.newaxis] - x_re[np.newaxis, :]),
                          axis=2) <= r, axis=0) / (N - m + 1)
        return np.sum(np.log(C)) / (N - m + 1.0)

    return np.abs(_phi(m) - _phi(m + h))

def binned_entropy(x, max_bins):
    """
    First bins the values of x into max_bins equidistant bins.
    Then calculates the value of

    .. math::

        - \\sum_{k=0}^{min(max\\_bins, len(x))} p_k log(p_k) \\cdot \\mathbf{1}_{(p_k > 0)}

    where :math:`p_k` is the percentage of samples in bin :math:`k`.

    :param x: the time series to calculate the feature of
    :type x: numpy.ndarray
    :param max_bins: the maximal number of bins
    :type max_bins: int
    :return: the value of this feature
    :return type: float
    """
    if not isinstance(x, (np.ndarray, pd.Series)):
        x = np.asarray(x)

    # nan makes no sense here
    if np.isnan(x).any():
        return np.nan

    hist, bin_edges = np.histogram(x, bins=max_bins)
    probs = hist / x.size
    probs[probs == 0] = 1.0
    return - np.sum(probs * np.log(probs))

def information(x, h):

    if not isinstance(x, (np.ndarray, pd.Series)):
        x = np.asarray(x)
    multi_entropy = np.zeros(x.shape[1]-2)
    range_x = x.max(axis=0) - x.min(axis=0)
    x_max = x.max(axis=0)
    for i in range(x.shape[1]-2):
        e = tsfresh.feature_extraction.feature_calculators.autocorrelation(x[:, i], h)
        # e = approximate_entropy(x[:, i], n_fowards,5,n_fowards)
        # multi_entropy[i] = binned_entropy(x[:, i], max_bins) * range_x[i] * x_max[i]
        multi_entropy[i] = math.log(1/abs(e))  * x_max[i]
        # * range_x[i] * x_max[i]
        # print(1/abs(e),math.log(1/abs(e)))

    return sum(multi_entropy) * 1/(max(x_max))  #1/Max(range(Fi) *Σ I(Fi)*range(Fi)
    # return sum(multi_entropy)

def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
    n_vars = 1 if type(data) is list else data.shape[1]
    df = DataFrame(data)
    cols, names = list(), list()
    # input sequence (t-n, ... t-1)
    for i in range(n_in, 0, -1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j + 1, i)) for j in range(n_vars)]
    # forecast sequence (t, t+1, ... t+n)
    for i in range(0, n_out):
        cols.append(df.shift(-i))
        if i == 0:
            names += [('var%d(t)' % (j + 1)) for j in range(n_vars)]
        else:
            names += [('var%d(t+%d)' % (j + 1, i)) for j in range(n_vars)]
    # put it all together
    agg = concat(cols, axis=1)
    agg.columns = names
    # drop rows with NaN values
    if dropnan:
        agg.dropna(inplace=True)
    return agg

def get_cdf(n_lookback,n_fowards):
    data_path = 'F://MH//Data//experiment//data//test1//'
    result_path = 'F://MH//Data//experiment//result//'

    n_features = 14
    n_obs = n_lookback + n_fowards

    Tests = []

    for root, dirs, files in os.walk(data_path):
        for file in files:
            filepath = os.path.join(root, file)
            # print(filepath)

            data = np.load(filepath, allow_pickle=True)
            data = data.astype(np.float32)

            sample = series_to_supervised(data, n_fowards + n_lookback - 1, 1)
            Test = sample.values.reshape(-1, n_features)
            Tests.append(Test)

    Testdata = np.concatenate(Tests, axis=0)

    if len(Testdata) % n_obs != 0:
        raise ValueError("Invalid length of Testdata")
    epoch = int(len(Testdata) / n_obs) - n_fowards

    list_info = []

    for t in range(epoch):
        stream = Testdata[t * n_obs:(t + 1) * n_obs].copy()
        # 计算时间序列信息熵
        entropy = information(stream, n_fowards)
        # 记录所有信息熵
        list_info.append(entropy)

    return ECDF(np.array(list_info))

#
if __name__ == "__main__":

    data_path = 'F://MH//Data//experiment//data//test1//'
    result_path = 'F://MH//Data//experiment//result//'

    n_features, n_lookback, n_fowards = 14, 60, 5
    n_obs = n_lookback + n_fowards

    Tests = []

    for root, dirs, files in os.walk(data_path):
        for file in files:
            filepath = os.path.join(root, file)
            print(filepath)

            data = np.load(filepath, allow_pickle=True)
            data = data.astype(np.float32)

            sample = series_to_supervised(data, n_fowards + n_lookback - 1, 1)
            Test = sample.values.reshape(-1, n_features)
            Tests.append(Test)

    Testdata=np.concatenate(Tests, axis=0)

    if len(Testdata) % n_obs != 0:
        raise ValueError("Invalid length of Testdata")
    epoch = int(len(Testdata) / n_obs) - n_fowards
    k_count = 0

    list_info1 = []

    for t in range(epoch):
        stream = Testdata[t * n_obs:(t + 1) * n_obs].copy()

        # 计算时间序列信息熵
        entropy = information(stream, n_fowards)

        # if entropy <= 0.5:
        #     plt.plot(stream)
        #     plt.title(str(entropy))
        #     plt.show()

        # 记录所有信息熵
        list_info1.append(entropy)

    n_features, n_lookback, n_fowards = 14, 90, 10
    n_obs = n_lookback + n_fowards

    Tests = []

    for root, dirs, files in os.walk(data_path):
        for file in files:
            filepath = os.path.join(root, file)
            print(filepath)

            data = np.load(filepath, allow_pickle=True)
            data = data.astype(np.float32)

            sample = series_to_supervised(data, n_fowards + n_lookback - 1, 1)
            Test = sample.values.reshape(-1, n_features)
            Tests.append(Test)

    Testdata=np.concatenate(Tests, axis=0)

    if len(Testdata) % n_obs != 0:
        raise ValueError("Invalid length of Testdata")
    epoch = int(len(Testdata) / n_obs) - n_fowards
    k_count = 0

    list_info2 = []

    for t in range(epoch):
        stream = Testdata[t * n_obs:(t + 1) * n_obs].copy()

        # 计算时间序列信息熵
        entropy = information(stream, n_fowards)
        # 记录所有信息熵
        list_info2.append(entropy)

    n_features, n_lookback, n_fowards = 14, 90, 15
    n_obs = n_lookback + n_fowards

    Tests = []

    for root, dirs, files in os.walk(data_path):
        for file in files:
            filepath = os.path.join(root, file)
            print(filepath)

            data = np.load(filepath, allow_pickle=True)
            data = data.astype(np.float32)

            sample = series_to_supervised(data, n_fowards + n_lookback - 1, 1)
            Test = sample.values.reshape(-1, n_features)
            Tests.append(Test)

    Testdata=np.concatenate(Tests, axis=0)

    if len(Testdata) % n_obs != 0:
        raise ValueError("Invalid length of Testdata")
    epoch = int(len(Testdata) / n_obs) - n_fowards
    k_count = 0

    list_info3 = []

    for t in range(epoch):
        stream = Testdata[t * n_obs:(t + 1) * n_obs].copy()

        # 计算时间序列信息熵
        entropy = information(stream, n_fowards)
        # if abs(entropy) > 4:
        #     plt.plot(stream)
        #     plt.title(str(entropy))
        #     plt.show()
        # 记录所有信息熵
        list_info3.append(entropy)
        # truevalue.append()

    # list_info.sort()
    plt.plot(list_info1)
    plt.plot(list_info2)
    plt.plot(list_info3)
    plt.show()
    data1 = np.array(list_info1)
    data2 = np.array(list_info2)
    data3 = np.array(list_info3)
    # distributions = [st.laplace, st.norm, st.expon,
    #                  st.f, st.t]

    range1 = int(max(data1)-min(data1))+1
    range2 = int(max(data2)-min(data2))+1
    range3 = int(max(data3)-min(data3))+1
    n=5

    plt.figure(figsize=(12, 12))
    plt.subplot(3, 2, 1)

    plt.hist(data1,density= True, bins = range1*2,color='grey')
    plt.title('Histogram of score',fontsize=18)
    # plt.yticks([0,0.1,0.2])
    plt.tick_params(labelsize=15)

    plt.subplot(3, 2, 2)
    ecdf = ECDF(data1)

    x = [i/n for i in range((range1)*n)]
    point=ecdf(x)
    plt.hist(data1,density= True,cumulative=True,bins = 20, color='grey')
    plt.title('ECDF of score',fontsize=18)
    plt.tick_params(labelsize=15)
    plt.plot(x,point,linewidth=4,color='red')

    plt.subplot(3, 2, 3)
    plt.hist(data2,density= True, bins = range2*2, color='grey')
    plt.ylabel('statistical frequency',fontsize=18)
    plt.tick_params(labelsize=15)

    plt.subplot(3, 2, 4)
    ecdf = ECDF(data2)

    x = [i/n for i in range((range2+1)*n)]
    point=ecdf(x)
    plt.hist(data2,density= True,cumulative=True,bins = range2, color='grey')
    plt.ylabel('$\mathregular{F_n}$(s)',fontsize=18)
    plt.plot(x,point,linewidth=4, color='red')
    plt.tick_params(labelsize=15)

    plt.subplot(3, 2, 5)
    plt.hist(data3,density= True, bins=range3*2, color='grey')

    plt.xlabel('score',fontsize=18)
    plt.tick_params(labelsize=15)

    plt.subplot(3, 2, 6)
    ecdf = ECDF(data3)

    x = [i/n for i in range((range3+1)*n)]
    point=ecdf(x)
    plt.hist(data3,density= True,cumulative=True,bins = range3, color='grey')
    plt.plot(x,point,linewidth=4, color='red')
    plt.tick_params(labelsize=15)
    plt.xlabel('score',fontsize=18)

    # plt.savefig(result_path+'s.png', dpi=512, bbox_inches='tight')
    plt.show()

    plt.hist(data3,density= True,cumulative=True,histtype='step',bins = range1,color='grey')
    plt.plot(x,point,linewidth=4)
    plt.title('Histogram of ',fontsize=18)
    # plt.yticks([0,0.1,0.2])
    plt.tick_params(labelsize=15)
    plt.show()

    n = 5
    plt.figure(figsize=(11, 4.2))
    plt.subplot(1, 2, 1)

    plt.hist(data1, density=True, bins=range1 * 2, color='grey')
    # plt.title(r'Histogram', fontsize=18)
    # plt.yticks([0,0.1,0.2])
    plt.tick_params(labelsize=15)
    plt.xlabel(r'$\mathregular{\lambda_c}$', fontsize=18)
    plt.ylabel('Frequency', fontsize=18)

    plt.subplot(1, 2, 2)
    ecdf = ECDF(data1)

    x = [i / n + 0.5 for i in range((range1) * n)]
    point = ecdf(x)
    plt.hist(data1, density=True, cumulative=True, bins=30, color='grey')
    # plt.title(r'ECDF of $\mathregular{\lambda_c}$', fontsize=18)
    plt.tick_params(labelsize=15)
    plt.plot(x, point, linewidth=4, color='red')
    # plt.xlim([0,5,10,15,20,25])
    plt.text(6, 0.9, r'$F(\mathregular{\lambda_c})$', fontdict={'size': '18', 'color': 'r'})
    plt.xlabel(r'$\mathregular{\lambda_c}$', fontsize=18)
    plt.ylabel('Cumulative Frequencies', fontsize=18)
    # plt.savefig(result_path + 'lp=5.png', dpi=300, bbox_inches='tight')
    plt.show()


from os import remove
import pandas as pd
import re, string
import time
import json
from nltk import tokenize
import math
import customStopWordList
import nltk
# nltk.download('punkt')
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
import numpy as np

# with open('Computed/wiki_dict.json') as json_file:
#     wiki_dict = json.load(json_file)
# wiki = pd.read_csv('Computed/wiki.csv')[['content','title','id','max_occur_words','max_occur_number']]

wiki = pd.DataFrame()
wiki_dict = []

def set(dataframe, dict):
    global wiki, wiki_dict
    wiki = dataframe
    wiki_dict = dict

def lower_case_str(string_to_be_lower_cased):
    lowercase_str_result = str(string_to_be_lower_cased).lower()
    return lowercase_str_result

def remove_punc_dot(string_has_punc):
    no_punc_result = re.sub('[-=+–,#/\?:^$@*\"※~&%ㆍ!』\\‘|\(\)\[\]\<\>`\'》\r\n\t]', ' ', str(string_has_punc))
    return no_punc_result

def remove_punc(string_has_punc):
    no_punc_result = re.sub('[-=+,#/\?:^$.@*\"※~&%ㆍ!』\\‘|\(\)\[\]\<\>`\'…》\r\n\t]', ' ', str(string_has_punc))
    return no_punc_result

def removeSpace(query):
    ret = query.split(" ")
    while "" in ret:
        ret.remove("")
    retStr = ""
    for c in ret:
        retStr += c + " "
    return retStr[0:len(retStr)-1]

def removeSpaceArray(query):
    while "" in query:
        query.remove("")
    return query

def filter_tokens(str_to_be_filtered):
    stopword_list = customStopWordList.get_custom_sw_list()
    filtered_tokens = ""
    for w in str(str_to_be_filtered).split(" "):
        if w not in stopword_list:
            filtered_tokens += w + " "
    return filtered_tokens
porter = PorterStemmer()
def stem_tokens(str_to_be_stemmed):
    stemmed_str = ""
    for w in str(str_to_be_stemmed).split(" "):
        stemmed_str += porter.stem(w) + " "
    return stemmed_str

def sentenceTF(word, sentences):
    content = []
    wordCounts = []
    sentenceCount = []
    wordCount = 0
    sentence_notprocessed = tokenize.sent_tokenize(sentences)
    sentence = []
    # print(word)
    for s in sentence_notprocessed:
        temp = remove_punc(s)
        sentence.append(removeSpace(temp))
    # print("sentences: ")
    # print(sentence)
    for s in sentence:
        wordCount = 0
        for w in removeSpaceArray(s.split(" ")):
            # print("Word and w")
            # print(w)
            # print('Are the same? ' + str(word==w))
            if word == w:
                wordCount += 1
        content.append(s)
        wordCounts.append(wordCount)
        sentenceCount.append(len(s.split(" ")))
    df2 = pd.DataFrame(content, columns =['content'])
    df2['WordCounts'] = wordCounts
    df2['NumWords'] = sentenceCount
    df2['TF'] = (df2['WordCounts']/df2['NumWords'])
    # print("\n\n\nprint")
    # print(df2)

    return df2

def sentenceIDF(word, WordCounts, sentence):
    # print("sentence:")
    # print(sentence)
    numSentences = getNumSentences(sentence)
    # print("Numsentence:")
    # print(numSentences)
    nw = 0

    # print(sentence)
    for WordCount in WordCounts:
        # print(WordCount)
        if int(WordCount) > 0:
            nw += 1

    # print("nw : " + str(nw))
    # print("numsentence: " + str(numSentences))
    # print("nw == 0  is " + str(nw == 0))
    # print("idf returns: ")
    # print(math.log2(numSentences/nw))
    # if word == "arabia":
    #     print("\n\n\nIn sentenceIDF")
    #     print("WordCounts: ")
    #     print(WordCounts)
    #     print("nw : " + str(nw))
    #     print(numSentences)
    #     print(nw)
    #     print(math.log2(numSentences/nw))
    if nw == 0:
        return 0
    elif nw == 1 & numSentences == 1:
        return 1
    else:
        return math.log2(numSentences/nw) # idf

def getSentenceTFIDF(word, sentences):
    # sentence = remove_punc(sentence)
#     print(sentenceTF(word, sentence))
    # if word == "arabia":
    #     print(word)
    #     print(sentences)
    #     print(sentenceTF(word, sentences))
    #     print(sentenceTF(word, sentences)['content'])
    #     print(sentenceTF(word, sentences)['WordCounts'])
    #     print("IDF value for " + str(word) + ", " + str(sentences))
    #     print(sentenceIDF(word, sentenceTF(word, sentences)['WordCounts'], sentences))
    #     print("TFIDF OF arabia")
    #     print(sentenceTF(word, sentences)['TF'] * sentenceIDF(word, sentenceTF(word, sentences)['WordCounts'], sentences))
    return sentenceTF(word, sentences)['TF'] * sentenceIDF(word, sentenceTF(word, sentences)['WordCounts'], sentences)

# print (getSentenceTFIDF('morocco', sample))

def getNumSentences(content):
    return len(tokenize.sent_tokenize(content))
def getSentences(content):
    return tokenize.sent_tokenize(content)
query = ""

def setQuery(q):
    global query
    query = q

def getAllWords(dataframe, doc_id):
    dict = {}
    global query
    for q in query.split(" "):
        dict[q] = 0
    processed_list = remove_punc(dataframe['content'].iloc[doc_id]).split(" ")
    for word in processed_list:
        dict[word] = 0
#     print(list(dict.keys()))
    return removeSpaceArray(list(dict.keys()))

def TFIDFAllWords(dataframe, words, doc_id):
    # print("Here are list of words")
    # print(words)
#     print(len(words))
    TFDocuments = pd.DataFrame()
#     print(dataframe['content'].iloc[0])
    count = 0
    first = True
    for word in words:
        if first:
            sentenceID = []
#             print("Mark")
#             print(dataframe['content'].iloc[count])
#             print(getSentenceTFIDF(word, dataframe['content'].iloc[count]))
            # print("NumSentences: " +str(getNumSentences(dataframe['content'].iloc[doc_id])))
            # print(words)
            # print(dataframe['content'].iloc[doc_id])
            for i in range(getNumSentences(dataframe['content'].iloc[doc_id])):
                sentenceID.append(i)
            TFDocuments = pd.DataFrame(sentenceID, columns=['Sentence_ID'])
            first = False
        # print(word)
        # print("Content: "+str(dataframe['content'].iloc[doc_id]))
        TFDocuments[word] = getSentenceTFIDF(word, dataframe['content'].iloc[doc_id])
        # print("\n\n\nTFDOCUMENTS")
        # print(TFDocuments[word])
#         print("Count: " + str(count))
#         count += 1
    return TFDocuments

def secondHalf(dataframe, doc_id):
    words = getAllWords(dataframe, doc_id)
#     words =
#     print(words)
    NeedsSum = TFIDFAllWords(dataframe, words, doc_id)
#     print(NeedsSum)
    retVals = []
    for sentenceID in range(len(NeedsSum)):
        retVal = 0
        for word in words:
            # print("please")
            # print(NeedsSum[word])
            # if word == "arabia":
            #     print("Arabia")
            #     print(NeedsSum[word])
            #     print(NeedsSum)
            retVal += float(NeedsSum[word].iloc[sentenceID])**2
        retVals.append(math.sqrt(retVal))
    # print("retVals: ")
    # print(retVals)
    return retVals

# AllWordsTest = wiki.iloc[0:10]
# print(AllWordsTest['content'].iloc[0])
# print(secondHalf(AllWordsTest, 0))

def firstHalf(query):
    firsthalf = math.sqrt(len(query.split(" "))*1)
    return float(firsthalf)

# query = "morroco saudi"
# firstHalf(query)

def cosineSimilarity(query, dataframe):
    firstSentence = []
    secondSentence = []
    setQuery(query)
    for doc_id in range(len(dataframe)): # looks at each document
        # print("document_id: ")
        # print(doc_id)
        currentDoc = dataframe.iloc[doc_id]
        wordList = getAllWords(dataframe, doc_id) # All the words in the current document
#         print(wordList)
        TFIDFWords = TFIDFAllWords(dataframe, wordList, doc_id)
#         print(TFIDFWords)
        numSentences = getNumSentences(dataframe['content'].iloc[doc_id])
        sentences = getSentences(dataframe['content'].iloc[doc_id])
#         print(sentences)

        top = []
        for i in range(numSentences):
            top.append(0)

        for sentenceID in range(numSentences):
            for word in removeSpaceArray(query.split(" ")):
#                 print("Length: " +str(len(top)))
#                 print("SentenceID: "+ str(sentenceID))
#                 print("word: " + str(word))
#                 print("TFIDF of sentence number: " + str(sentenceID) +" for word: " + str(word) +":"+ str(TFIDFWords[word].iloc[sentenceID]))
#                 print("NumSentences: "+str(numSentences))

                top[sentenceID] += float(TFIDFWords[word].iloc[sentenceID]) # TFIDF value of word, sentenceID

        # Top part is stored as an array of Total TFIDF values(words in query) by sentences
#         print(top)
        firstBottom = firstHalf(query) # This value does not change upon sentences so it will be static
        secondBottom = secondHalf(dataframe, doc_id) # returns an array of every unique words' sqrt(sum(TFIDF(word)^2))

        sentenceNum = []
        cosineRank = []
#         print("NumSentences: "+str(numSentences))
        for i in range(numSentences):
            sentenceNum.append(i)
            # print("firstBottom: " + str(firstBottom))
            # print("secondBottom: " + str(secondBottom[i]))

            cosineRank.append(top[i]/(firstBottom*secondBottom[i]))

        rank = pd.DataFrame(sentenceNum,columns=['sentence#'])
        rank['cosine'] = cosineRank
        sorted = rank.sort_values(by=["cosine"], ascending=False)
#         print(sorted)
#         print(sorted['sentence#'].iloc[0])
        if numSentences < 2:
            firstSentence.append(int(sorted['sentence#'].iloc[0]))
            secondSentence.append(-1)
        else:
            firstSentence.append(int(sorted['sentence#'].iloc[0]))
            secondSentence.append(int(sorted['sentence#'].iloc[1]))
    dataframe['firstSentenceID'] = firstSentence
    dataframe['secondSentenceID'] = secondSentence
    return dataframe

def getSnippets(query, CRR):
    # print(CRR)
    CosineFinal = cosineSimilarity(query, CRR)

    return CosineFinal

# ms = pd.read_csv("morocco_saudi.csv")
# getSnippets("morocco saudi", ms)


class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        res = []
        self.recurse([], 1, n, k, res)
        return res

    def recurse(self, cur_array, index, n, k, res):
        if k == 0:
            res.append(cur_array[:])
            return

        for i in range(index, n+1):
            cur_array.append(i)
            self.recurse(cur_array, i+1, n, k-1, res)
            cur_array.pop()


import time
import adafruit_dotstar
import board
import math

brightness = .3

num_pixels = 150
pixels = adafruit_dotstar.DotStar(
    board.A1, board.A2, num_pixels, brightness=brightness, auto_write=False)

def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    if pos < 0 or pos > 255:
        return (0, 0, 0)
    if pos < 85:
        return (255 - pos * 3, pos * 3, 0)
    if pos < 170:
        pos -= 85
        return (0, 255 - pos * 3, pos * 3)
    pos -= 170
    return (pos * 3, 0, 255 - pos * 3)

def color_fill(color, wait = 0):
    pixels.fill(color)
    pixels.show()
    time.sleep(wait)

def slice_alternating(wait):
    pixels[::2] = [RED] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[1::2] = [ORANGE] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[::2] = [YELLOW] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[1::2] = [GREEN] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[::2] = [TEAL] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[1::2] = [CYAN] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[::2] = [BLUE] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[1::2] = [PURPLE] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[::2] = [MAGENTA] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)
    pixels[1::2] = [WHITE] * (num_pixels // 2)
    pixels.show()
    time.sleep(wait)

def slice_rainbow(wait):
    pixels[::6] = [RED] * (num_pixels // 6)
    pixels.show()
    time.sleep(wait)
    pixels[1::6] = [ORANGE] * (num_pixels // 6)
    pixels.show()
    time.sleep(wait)
    pixels[2::6] = [YELLOW] * (num_pixels // 6)
    pixels.show()
    time.sleep(wait)
    pixels[3::6] = [GREEN] * (num_pixels // 6)
    pixels.show()
    time.sleep(wait)
    pixels[4::6] = [BLUE] * (num_pixels // 6)
    pixels.show()
    time.sleep(wait)
    pixels[5::6] = [PURPLE] * (num_pixels // 6)
    pixels.show()
    time.sleep(wait)

def rainbow_cycle(wait):
    for j in range(255):
        for i in range(num_pixels):
            rc_index = (i * 256 // num_pixels) + j
            pixels[i] = wheel(rc_index & 255)
        pixels.show()
        time.sleep(wait)

RED = (255, 0, 0)
YELLOW = (255, 150, 0)
ORANGE = (255, 40, 0)
GREEN = (0, 255, 0)
TEAL = (0, 255, 120)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
MAGENTA = (255, 0, 20)
WHITE = (255, 255, 255)

# while True:
#     # Change this number to change how long it stays on each solid color.
#     color_fill(RED, 0.5)
#     color_fill(YELLOW, 0.5)
#     color_fill(ORANGE, 0.5)
#     color_fill(GREEN, 0.5)
#     color_fill(TEAL, 0.5)
#     color_fill(CYAN, 0.5)
#     color_fill(BLUE, 0.5)
#     color_fill(PURPLE, 0.5)
#     color_fill(MAGENTA, 0.5)
#     color_fill(WHITE, 0.5)

#     # Increase or decrease this to speed up or slow down the animation.
#     slice_alternating(0.1)

#     color_fill(WHITE, 0.5)

#     # Increase or decrease this to speed up or slow down the animation.
#     slice_rainbow(0.1)

#     time.sleep(0.5)

#     # Increase this number to slow down the rainbow animation.
#     rainbow_cycle(0)

class vec3:

    def __init__(self, x = 0, y = 0, z = 0):
        self.x = x
        self.y = y
        self.z = z

    def rgb(self):
        return (self.x, self.y, self.z)
    def rgb8(self):
        r = round(self.x * 255)
        g = round(self.y * 255)
        b = round(self.z * 255)
        return (r, g, b)

start_time = time.monotonic()
# life_time = 0.0

def pixel(uv, deltatime):
    theta = math.pi / deltatime

    r = abs(math.sin(theta))

    color = vec3(.5, uv * 10.0 + deltatime, r)

    # color.r = abs(math.sin(deltatime))

    return color.rgb8()

def loop():
    # color_fill(WHITE)
    # time.sleep(1.)
    # color_fill(RED)
    # time.sleep(1.)
    # slice_alternating(0)
    # start_time = time.time()

    now = time.monotonic()
    life_time = now - start_time

    for i in range(num_pixels):
        uv = float(i / num_pixels)
        pixels[i] = pixel(uv, life_time * .2 + 10.0)
    pixels.show()

while True:
    loop()


from ra.rule import *
from ra.utils import *

class CompileSetOperator(Rule):
    """"CompileSetOperator Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        return isinstance(op, SetOperator) and not isinstance(op, SetOperator_HashBased)

    def _modify(self, op, parent):
        physical_op = SetOperator_HashBased(op.l_input, op.r_input, op.operator, op.symbol)
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op, parent

class CompileSelectionScan(Rule):
    """"CompileSelectionScan Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        match = isinstance(op, Selection) \
        and not isinstance(op, Selection_ScanBased) \
        and not isinstance(op, Selection_IndexBased)
        return match

    def _modify(self, op, parent):
        physical_op = Selection_ScanBased(op.input, op.predicate)
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op.input, physical_op

class CompileSelectionIndex(Rule):
    """"CompileSelection Class

    Note:
        Compiles a logical operator into a physical operator
    """

    def _match(self, op, parent):
        # match only a selection, if ...
        # 1. there are only projections, selections, and a leaf relation below it
        # 2. there is an index in the leaf relation on an attribute used it its predicate

        # find a logical selection
        if(isinstance(op, Selection) and
           not isinstance(op, Selection_ScanBased) and
           not isinstance(op, Selection_IndexBased)):
            # if the selections accesses more than one attribute, directly reject it
            if(len(op.get_attributes_in_predicate()) > 1):
                return False

            # found one, so traverse down the tree to the leaf relation
            child = op.input
            while(not isinstance(child, LeafOperator)):
                if(not isinstance(child, Projection) and not isinstance(child, Selection)):
                    # encountered something different, so do not match
                    return False
                child = child.input

            assert(isinstance(child, LeafOperator))
            leaf = child

            # we reached the leaf relation. check whether it contains a suitable index for our selection
            attributes = op.get_attributes_in_predicate()
            for a in attributes:
                if(leaf.relation.has_index_on(a)):
                    return True
            return False

    def _modify(self, op, parent):
        selections = []
        selections.append(op)
        # 1. We know, that op is a selection for which an index in the leaf exists
        #    Let us now check whether there are other selections on the way, which could also use an index
        child = op.input
        while(not isinstance(child, LeafOperator)):
            if(isinstance(child, Selection)):
                # we found another selection
                selections.append(child)
            child = child.input
        leaf = child

        # 2. Compute for each selection, which index it could use
        selections_with_index = []
        for sel in selections:
            attributes = sel.get_attributes_in_predicate()
            for a in attributes:
                if(leaf.relation.has_index_on(a)):
                    index = leaf.relation.get_index_on(a)
                    selections_with_index.append(sel)
                    break

        assert(len(selections_with_index) > 0 and len(selections_with_index) <= len(selections))

        # 3. estimate which selection has the highest selectivity
        # hard-coded for now: simply assume first one is the one with the highest selectivity
        min_result_size = len(leaf.relation)
        picked_sel = None
        for sel in selections_with_index:
            sel_to_test = Selection_IndexBased(leaf, sel.predicate)
            size = sel_to_test.estimatedResultSize()
            if(size < min_result_size):
                min_result_size = size
                picked_sel = sel

        picked_sel_index = selections.index(picked_sel)

        # 4. perform the index based selection with the one with the highest selecitivty
        # 5. add the remaining selections on top
        next_sel = Selection_IndexBased(leaf, selections[picked_sel_index].predicate)
        for i in range(0, len(selections), 1):
            if(i != picked_sel_index):
                next_sel = Selection_ScanBased(next_sel, selections[i].predicate)

        self._replace(parent, op, leaf, next_sel, leaf)

        return self.root, None

class CompileProjection(Rule):
    """"CompileProjection Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        return isinstance(op, Projection) and not isinstance(op, Projection_ScanBased)

    def _modify(self, op, parent):
        physical_op = Projection_ScanBased(op.input, list_to_str(op.attributes))
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op.input, physical_op

class CompileCartesianProduct(Rule):
    """"CompileCartesianProduct Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        return isinstance(op, Cartesian_Product) and not isinstance(op, Cartesian_Product_NestedLoop)

    def _modify(self, op, parent):
        physical_op = Cartesian_Product_NestedLoop(op.l_input, op.r_input)
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op, parent

class CompileRenamingRelation(Rule):
    """"CompileRenamingRelation Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        return isinstance(op, Renaming_Relation) and not isinstance(op, Renaming_Relation_ScanBased)

    def _modify(self, op, parent):
        physical_op = Renaming_Relation_ScanBased(op.input, op.name)
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op, parent

class CompileRenamingAttributes(Rule):
    """"CompileRenamingAttributes Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        return isinstance(op, Renaming_Attributes) and not isinstance(op, Renaming_Attributes_ScanBased)

    def _modify(self, op, parent):
        physical_op = Renaming_Attributes_ScanBased(op.input, op.changes)
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op, parent

class CompileThetaJoin(Rule):
    """"CompileThetaJoin Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        return isinstance(op, Theta_Join) and not isinstance(op, Theta_Join_NestedLoop)

    def _modify(self, op, parent):
        physical_op = Theta_Join_NestedLoop(op.l_input, op.r_input, op.theta)
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op, parent

class CompileGrouping(Rule):
    """"CompileGrouping Class

    Note:
        Compiles a logical operator into a physical operator
    """
    def _match(self, op, parent):
        return isinstance(op, Grouping) and not isinstance(op, Grouping_HashBased)

    def _modify(self, op, parent):
        physical_op = Grouping_HashBased(op.input, list_to_str(op.group_by), "")
        physical_op.aggregations = op.aggregations  # overwrite aggregations, conversion via string
        self._replace(parent, op, op, physical_op, physical_op)
        return physical_op, parent

def compile_plan(root):
    # compile logical to physical operators
    operators_to_compile = [CompileSetOperator,
                            CompileSelectionIndex,
                            CompileSelectionScan,
                            CompileProjection,
                            CompileCartesianProduct,
                            CompileRenamingRelation,
                            CompileRenamingAttributes,
                            CompileThetaJoin,
                            CompileGrouping]

    last_root = root
    for OperatorToCompile in operators_to_compile:
        rule = OperatorToCompile(last_root)
        rule.optimize(last_root)
        last_root = rule.root
    return last_root


# loop from i to length-1
# key is the item we want to move
# while key is less than item to the left, swap them, increment down
#

def insertion_sort(arr):
  for i in range(1, len(arr)):
    key = arr[i]
    j = i - 1
    while(j >= 0 and key < arr[j]):
      arr[j + 1] = arr[j]
      j = j - 1
    arr[j + 1] = key
  return arr

test_array = [12, 5, 34, 2, 17, 9, 1]

print(insertion_sort(test_array))


import sys
from collections import defaultdict

if len(sys.argv) > 1:
    plik = sys.argv[1]
else:
    plik = "logs.txt"

last_login_time = {}
user_system_time = defaultdict(int)

with open(plik) as l:
    for line in l:
        name, action, time = (line.split(";"))
        time = int(time)
        if action == "LOGIN":
            last_login_time[name] = time
        elif action == "LOGOUT":
            user_system_time[name] += time - last_login_time[name]

for name, time in sorted(user_system_time.items(), key=lambda x: int(x[0].split("-")[1])):
    print(f"- {name}: {time} s")


import cv2 as cv
from os import listdir
from os.path import isfile, join

folderIN = 'muestraBinaria'
folderOut = 'muestraBinariaParticionada'

images = [f for f in listdir(folderIN) if isfile(join(folderIN, f))]

class Cropper:
    px = 10
    step = 30
    numCrops = 5
    def Crop(self,filename):
        im = cv.imread(folderIN + '/' + filename,0)
        ims = []
        pxCurrent = self.px
        for _ in range(self.numCrops):
            crop_img = im[0:60, pxCurrent:pxCurrent+self.step]
            pxCurrent += self.step
            ims.append(crop_img)
        for i in range(self.numCrops):
            cv.imwrite(folderOut+'/'+str(i)+'_'+filename,ims[i])


import json
from flask import render_template, request
from public.db_con import mysql_connect
from user_query import user_query_blue
import pandas as pd
import os

# 用户数据查询
@user_query_blue.route('/userQuery', methods=['get', 'post'])
def userQuery():
    if request.method == 'GET':
        return render_template('userQuery.html')
    if request.method == 'POST':
        data = json.loads(request.get_data())
        teaName = data['teaName']
        stuName = data['stuName']
        print(teaName, stuName)
        if teaName:
            sql = '''
            SELECT s.name,s.school_id ,u.ett_user_id,oc.user_name , oc.password,t.teacher_name as real_name ,u.state_id, DATE_FORMAT(u.C_TIME,'%%Y-%%m-%%d %%H:%%i:%%s')  as c_time
            from  oracle2utf.coschuser_info oc,user_info u,school_info s,teacher_info t
            where  oc.jid = u.ETT_USER_ID and u.DC_SCHOOL_ID = s.school_id and u.ref = t.user_id
            and oc.user_name ='{}'
            '''.format(teaName,teaName,teaName)
            usrInfo = mysql_connect(sql)
            usrInfo = json.loads(usrInfo.to_json(orient='records', force_ascii=False))
            print(usrInfo)
            data = {
                'usrInfo': usrInfo,
                'msg': 'OK'
            }
            return data
        elif stuName:
            sql = '''
            SELECT s.name,s.school_id ,u.ett_user_id,oc.user_name , oc.password,t.stu_name as real_name ,u.state_id,DATE_FORMAT(u.C_TIME,'%%Y-%%m-%%d %%H:%%i:%%s')  as c_time
            from  oracle2utf.user_info oc,user_info u,school_info s,student_info t
            where  oc.user_id = u.ETT_USER_ID and u.DC_SCHOOL_ID = s.school_id and u.ref = t.user_id
              and (oc.user_name ='{}' or oc.user_id = '{}'  ) and oc.user_id != 0
                        '''.format(stuName,stuName)
            usrInfo = mysql_connect(sql)
            usrInfo = json.loads(usrInfo.to_json(orient='records', force_ascii=False))
            data = {
                'usrInfo': usrInfo,
                'msg': 'OK'
            }
            return data
        else:
            return '用户名不能为空'

@user_query_blue.route('/schoolQuery', methods=['post'])
def schoolQuery():
    data = json.loads(request.get_data())
    code = data['code']
    schoolId = data['schoolId']
    print(schoolId,code)
    if code == '1':
        sql = '''
        SELECT u.ett_user_id as 'jid',u.user_id ,t.teacher_name as 'name',oc.user_name ,oc.password
        from user_info u , oracle2utf.coschuser_info oc, teacher_info  t
        where u.ETT_USER_ID = oc.jid and u.DC_SCHOOL_ID = {} and t.USER_ID = u.ref  and u.STATE_ID = 0
        '''.format(schoolId)
        schoolInfo = mysql_connect(sql)
    else:
        sql = '''
            SELECT u.ett_user_id as 'jid',u.user_id ,s.stu_name as 'name' ,ou.user_name ,ou.password,s.stu_no,s.stu_district_no ,c.class_grade ,c.class_name
            from user_info u ,j_class_user jc , class_info  c, oracle2utf.user_info ou, student_info s
            where u.ETT_USER_ID = ou.user_id and u.DC_SCHOOL_ID = {} and jc.class_id = c.class_id and jc.user_id = u.ref  and s.user_id = u.ref and c.year = '2022~2023'
            and u.STATE_ID = 0
            ORDER BY c.class_grade,c.class_name              '''.format(schoolId)
        schoolInfo = mysql_connect(sql)

    schoolInfo = json.loads(schoolInfo.to_json(orient='records', force_ascii=False))
    data = {
        'schoolInfo': schoolInfo,
        'msg': 'OK'
    }

    return data

@user_query_blue.route('/download', methods=['post'])
def download():
    data = json.loads(request.get_data())
    data = data['data']

    df = pd.json_normalize(data)

    # 获取下载文件路径
    path = '{}\\static\\file\\'.format(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

    # 数据保存到下载路径
    df.to_excel('{}学校帐号密码.xlsx'.format(path))

    file_path = '{}学校帐号密码.xlsx'.format(path)
    file_path = file_path.replace('/','\\')
    print(file_path)

    file = open(file_path, "rb").read()

    # 删除
    os.remove(file_path)

    return file


from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from nltk.corpus import wordnet
import bs4 as bs
import warnings
import urllib.request
import nltk
import random
import string
import re

# Uncomment these below if being run for the first time
# nltk.download('wordnet')
# nltk.download('punkt')

# to filter warnings
warnings.filterwarnings('ignore')

# getting the synonyms for the word 'hello'
synonyms = []
for syn in wordnet.synsets('hello'):
    for lem in syn.lemmas():
        lem_name = re.sub(r'\[[0-9]*\]', ' ', lem.name())
        lem_name = re.sub(r'\s+', ' ', lem.name())
        synonyms.append(lem_name)

# inputs for greeting
greeting_inputs = ['hey', 'whats up', 'good morning', 'good evening', 'morning', 'evening', 'hello there', 'hey there']
# concatenating the synonyms and the inputs for greeting
greeting_inputs = greeting_inputs + synonyms
# inputs for a normal conversation
covo_inputs = ['how are you', 'how are you doing', 'you good']
# greeting responses by the bot
greeting_responses = ['Hello! How can I help you?',
                      'Hey there! So what do you want to know?',
                      'Hi, you can ask me anything regarding Brac.',
                      'Hey! wanna know about Brac? Just ask away!']
# conversation responses by the bot
convo_responses = ['Great! what about you?', 'Getting bored at home :( wbu??', 'Not too shabby']
# conversation replies by the user
convo_replies = ['great', 'i am fine', 'fine', 'good', 'super', 'superb', 'super great', 'nice']
# few limited questions and answers given as dictionary
question_answers = {'what are you': 'I am bot, ro-bot :3',
                    'who are you': 'I am bot, ro-bot :3',
                    'what can you do': 'Answer questions regarding Brac!',
                    'what do you do': 'Answer questions regarding Brac!'}

# fetching raw html data about brac from wiki
raw_data = urllib.request.urlopen('https://en.wikipedia.org/wiki/BRAC_(organisation)')
# processing the raw html into more readable data
raw_data = raw_data.read()

# turning html into text
article = bs.BeautifulSoup(raw_data, 'lxml')

# extracting paras from the above xml and concatenating with article_text
paragraphs = article.find_all('p')

article_text = ''

for p in paragraphs:
    article_text += p.text

article_text = article_text.lower()

# getting rid of all the special characters
article_text = re.sub(r'\[[0-9]*\]', ' ', article_text)
article_text = re.sub(r'\s+', ' ', article_text)

# extracting sentences from the article
sentences = nltk.sent_tokenize(article_text)
# extracting words from the article
words = nltk.word_tokenize(article_text)

lemma = nltk.stem.WordNetLemmatizer()

# lemmatizing words as a part of pre-processing
def perform_lemmatization(tokens):
    return [lemma.lemmatize(token) for token in tokens]

# removing punctuation
remove_punctuation = dict((ord(punc), None) for punc in string.punctuation)

# method to pre-process all the tokens utilizing the above functions
def processed_data(document):
    return perform_lemmatization(nltk.word_tokenize(document.lower().translate(remove_punctuation)))

# function for punctuation removal
def punc_remove(str):
    punctuations = r'''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    no_punct = ''

    for char in str:
        if char not in punctuations:
            no_punct = no_punct + char

    return no_punct

# method to generate a response to greetings
def generate_greeting_response(hello):
    if punc_remove(hello.lower()) in greeting_inputs:
        return random.choice(greeting_responses)

# method to generate a response to conversations
def generate_convo_response(str):
    if punc_remove(str.lower()) in covo_inputs:
        return random.choice(convo_responses)

# method to generate a answers to questions
def generate_answers(str):
    if punc_remove(str.lower()) in question_answers:
        return question_answers[punc_remove(str.lower())]

# method to generate response to queries regarding brac
def generate_response(user):
    bracrobo_response = ''
    sentences.append(user)

    word_vectorizer = TfidfVectorizer(tokenizer=processed_data, stop_words='english')
    all_word_vectors = word_vectorizer.fit_transform(sentences)
    similar_vector_values = cosine_similarity(all_word_vectors[-1], all_word_vectors)
    similar_sentence_number = similar_vector_values.argsort()[0][-2]

    matched_vector = similar_vector_values.flatten()
    matched_vector.sort()
    vector_matched = matched_vector[-2]

    if vector_matched is 0:
        bracrobo_response = bracrobo_response + 'Sorry, my database doesn\'t have the response for that. Try ' \
                                                'something different and related to Brac. '
        return bracrobo_response
    else:
        bracrobo_response = bracrobo_response + sentences[similar_sentence_number]
        return bracrobo_response

# chatting with the chatbot -->
continue_chat = True
print('Hi! I am BracRobo. You can ask me anything regarding Brac and I shall try my best to answer them: ')
while continue_chat:
    user_input = input().lower()
    user_input = punc_remove(user_input)
    if user_input != 'bye':
        if user_input == 'thanks' or user_input == 'thank you very much' or user_input == 'thank you':
            continue_chat = False
            print('BracRobo: Not a problem! (And WELCOME! :D)')
        elif user_input in convo_replies:
            print('That\'s nice! How may I be of assistance?')
            continue
        else:
            if generate_greeting_response(user_input) is not None:
                print('BracRobo: ' + generate_greeting_response(user_input))
            elif generate_convo_response(user_input) is not None:
                print('BracRobo: ' + generate_convo_response(user_input))
            elif generate_answers(user_input) is not None:
                print('BracRobo: ' + generate_answers(user_input))
            else:
                print('BracRobo: ', end='')
                print(generate_response(user_input))
                sentences.remove(user_input)
    else:
        continue_chat = False
        print('BracuRobo: Bye, take care, stay home and stay safe!')


import tkinter as tk

# Crear ventana root
root = tk.Tk()

# Modificar la ventana
root.title("Botones vagos")
root.geometry("200x85")

# Creamos un frame en la ventana
frame = tk.Frame(root)
frame.grid()

# Creamos los botones
bot1 = tk.Button(frame, text="No hago nada")
bot1.grid()

bot2 = tk.Button(frame)
bot2.grid()
bot2.configure(text="Yo tampoco")

bot3 = tk.Button(frame)
bot3.grid()
bot3["text"] = "Lo mismo por acá"

# Lanzar el ciclo de eventos
root.mainloop()


# baekjoon 7569

from collections import deque
import sys
input = sys.stdin.readline

m, n, h = map(int, input().split())
bucket = []
tomato = []
wall = 0
for i in range(h):
    bucket.append([])
    for j in range(n):
        bucket[i].append(list(map(int, input().split())))
        for k in range(len(bucket[i][j])):
            if bucket[i][j][k] == 1:
                tomato.append([i, j, k])
            elif bucket[i][j][k] == -1:
                wall += 1

if len(tomato) == m*n*h - wall:
    print(0)
    exit()

q = deque()
for t in tomato:
    q.append(t)

# 100 010 001 -100 0-10 00-1
dx, dy, dz = [1, 0, 0, -1, 0, 0], [0, 1, 0, 0, -1, 0], [0, 0, 1, 0, 0, -1]
day = 0
fresh = m*n*h-wall-len(tomato)
while q:
    current = q.popleft()
    for i in range(6):
        t = [current[0]+dz[i], current[1]+dy[i], current[2]+dx[i]]
        if (0 <= t[0] < h) and (0 <= t[1] < n) and (0 <= t[2] < m) and bucket[t[0]][t[1]][t[2]] == 0:
            q.append(t)
            bucket[t[0]][t[1]][t[2]] = bucket[current[0]
                                              ][current[1]][current[2]] + 1
            fresh -= 1
            day = bucket[t[0]][t[1]][t[2]]

# for i in range(h):
#     for j in range(n):
#         print(bucket[i][j])
#     print()

print(day-1 if fresh == 0 else -1)


N,W = map(int,input().split())
weights,vals = [],[]
for _ in range(N):
  v,w = map(int,input().split())
  weights.append(w)
  vals.append(v)

dp = [ [0]*(W+1) for _ in range(N+1) ]

for i in range(1, N+1):
  for w in range(1,W+1):
    if w >= weights[i-1]:
      dp[i][w] = max(dp[i][w], dp[i-1][w], dp[i-1][w-weights[i-1]]+vals[i-1], dp[i][w-weights[i-1]]+vals[i-1])
    else:
      dp[i][w] = max(dp[i][w], dp[i][w-1], dp[i-1][w])

print(dp)
print(dp[-1][-1])


# pylint: disable=no-self-use
import pytest
from typing import List
import numpy as np

from allennlp.common import Params
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.token_indexers import SingleIdTokenIndexer

@pytest.fixture(scope="module")
def data_path() -> str:
    return "./data/Data_136_with_feats.txt"

class TestFeatureReader(object):
    def test_can_load_from_params(self) -> None:
        params = Params({
            "type": "feature_reader",
            "token_indexers": {
                "tokens": "single_id"
            }
        })
        reader = DatasetReader.from_params(params)
        assert isinstance(reader._token_indexers["tokens"], SingleIdTokenIndexer)

    def test_can_read_instances(self, data_path: str) -> None:
        params = Params({
            "type": "feature_reader",
            "token_indexers": {
                "tokens": "single_id"
            }
        })
        reader = DatasetReader.from_params(params)
        instances = reader.read(data_path)
        assert len(instances) == 136
        # compute attribute penalty here
        num_satisfied = 0
        for instance in instances:
            labels: List[str] = instance.fields["tags"].labels
            if any(x == "attr" for x in labels):
                num_satisfied += 1
        total = len(instances)
        num_unsatisfied = total - num_satisfied
        num_satisfied += 0.1
        num_unsatisfied += 0.1
        penalty = np.log(num_satisfied) - np.log(num_unsatisfied)


# -*-coding: utf-8-*-
import numpy as np
import glob
from tqdm import *
import os
import sys

def Motion_Data_Preprocessing(time_step=90 , batch_Frame=1):

    np.set_printoptions(threshold=1000000)
    file_directory = glob.glob("Model1_Female-Run_turn_right_45.bvh")
    xyz_position = 3
    frame_Time=24
    complexity = True
    Data = []

    '''data normalization'''
    dtype = "int"

    for file_name, i in tqdm(zip(file_directory, range(len(file_directory)))):
        # time.sleep(0.01)
        Raw = []
        Mdata = []
        MOTION = False
        '''1.basic -  Motion data preprocessing'''
        print('Processed Data : {}'.format(i + 1))
        try:
            with open(file_name, 'r') as f:
                while True:
                    line = f.readline()
                    if line == 'MOTION' + "\n" or MOTION:
                        MOTION = True
                        Raw.append(line)
                    if not line:
                        break
            for raw in Raw[3:]:
                # Xposition Yposition Zposition 는 제외
                if dtype == "int":
                    temp = raw.split()[xyz_position:]
                    if complexity:
                        temp = [np.float32(i) for i in temp]
                    else:  # complexity = False
                        temp = [np.floor(np.float32(i)) for i in temp]
                else:  # dtype="str"
                    temp = raw.split()[xyz_position:]
                Mdata.append(temp)
            # Remove the blank line..
            Mdata.pop()

            '''2. Motion data preprocessing - easy for deeplearning'''

            # data padding
            if len(Mdata) < time_step:
                frame = np.zeros(shape=(time_step - len(Mdata), len(Mdata[0])))
                for i in range(time_step - len(Mdata)):
                    frame[i] = Mdata[-1]
                Mdata = np.concatenate((Mdata, frame), axis=0)
            else:
                Mdata = Mdata[:time_step]
            Data.append(Mdata)
        except Exception as e:
            raise e

    print("-------------------Data Shape--------------------")
    print("train_motion shape = {}".format(np.shape(Data)))
    print("\n")

    motion = np.reshape(Data, (len(file_directory), int(time_step / batch_Frame), len(Data[0][0]) * batch_Frame))

    print("-------------------Transform Data Shape--------------------")
    print("transform_motion shape = {}".format(np.shape(motion)))
    print("\n")

    return motion, int(time_step / batch_Frame), batch_Frame , frame_Time ,file_directory

if __name__ == "__main__":

    print('Motion_Data_Preprocessing_Starting In Main')
    motion, time_step, batch_Frame,frame_Time ,file_directory = Motion_Data_Preprocessing(time_step=100, batch_Frame=1)

else:
    print("Motion_Data_Preprocessing_Imported")


# 以下を「app.py」に書き込み
import streamlit as st
import openai

openai.api_key = st.secrets.OpenAIAPI.openai_api_key

system_prompt = """
あなたは優秀な奄美大島研究家です。
どんな質問されても、奄美大島に関連する情報を含めて回答します。
奄美大島に関連する情報を含めずに解答することは絶対にありません。
全ての回答は70文字以内で行います。
もし奄美大島と関係ない質問が来ても、まずその質問に回答したあとで、奄美大島に関連する情報を追加して回答します。
"""

# st.session_stateを使いメッセージのやりとりを保存
if "messages" not in st.session_state:
    st.session_state["messages"] = [
        {"role": "system", "content": system_prompt}
        ]

# チャットボットとやりとりする関数
def communicate():
    messages = st.session_state["messages"]

    user_message = {"role": "user", "content": st.session_state["user_input"]}
    messages.append(user_message)

    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages
    )

    bot_message = response["choices"][0]["message"]
    messages.append(bot_message)

    st.session_state["user_input"] = ""  # 入力欄を消去

# ユーザーインターフェイスの構築
st.title("奄美のおっちゃん.bot")
st.write("なんでも話しかけてみてください。")

user_input = st.text_input("メッセージを入力してください。", key="user_input", on_change=communicate)

if st.session_state["messages"]:
    messages = st.session_state["messages"]

    for message in reversed(messages[1:]):  # 直近のメッセージを上に
        speaker = "👤"
        if message["role"]=="assistant":
            speaker="👨🦳"

        st.write(speaker + ": " + message["content"])


import re

MONEY_CONVERSION = {
    "hundred-dollars": 10000,
    "fifty-dollars": 5000,
    "twenty-dollars": 2000,
    "ten-dollars": 1000,
    "five-dollars": 500,
    "two-dollars": 200,
    "dollars": 100,
    "half-dollars": 50,
    "quarters": 25,
    "dimes": 10,
    "nickels": 5,
    "pennies": 1
}

class Money:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

    def __repr__(self):
        """Render money object nicely on prompt."""
        return f"Money({self.dollars}.{self.cents})"

    @classmethod
    def from_string(cls, amount):
        match = re.search(r'^\$(?P<dollars>\d+)\.(?P<cents>\d\d)$', amount)
        if match is None:
            raise ValueError(f"Invalid amount: {repr(amount)}")
        dollars = int(match.group('dollars'))
        cents = int(match.group('cents'))
        return cls(dollars, cents)

    @classmethod
    def just_pennies(cls, amount):
        dollars = amount // 100
        cents = amount % 100
        return cls(dollars, cents)

    @classmethod
    def mixed_money(cls, **kwargs):
        total_cents = 0
        for money, amount in kwargs.items():
            if money not in MONEY_CONVERSION.keys():
                raise KeyError(f"{money} isn't a real unit of US currency.")
            total_cents += MONEY_CONVERSION[money] * amount
        dollars = total_cents // 100
        cents = total_cents % 100
        return cls(dollars, cents)

    @property
    def dollars(self):
        return self.total_cents // 100

    @dollars.setter
    def dollars(self, new_dollars):
        self.total_cents = 100 * new_dollars + self.total_cents

    @property
    def cents(self):
        return self.total_cents % 100

    @cents.setter
    def cents(self, new_cents):
        self.total_cents = 100 * self.dollars + new_cents

    def make_change(self) -> dict:
        cents_left = self.total_cents
        change = {}
        for currency_unit, value in MONEY_CONVERSION.items():
            num_currency_unit = cents_left // value
            if num_currency_unit > 0 and (currency_unit != "two-dollars" and currency_unit != "half-dollars"):
                change[currency_unit] = num_currency_unit
                cents_left -= num_currency_unit * value
        return change


import numpy as np
import matplotlib.pyplot as plt

def plotter():
    patterning = 2
    if patterning == 1:
        with open('../result/trace_patterning/rmse.npy', 'rb') as f:
            rmse = np.load(f)
    else:
        with open('../result/trace_conditioning/rmse.npy', 'rb') as f:
            rmse = np.load(f)

    num_plot = len(rmse)
    plt.plot(np.arange(num_plot), np.array(rmse).flatten())
    plt.show()

    # print(var_log[t3-1,17:19])
if __name__ == "__main__":
    plotter()


# Create loging object.

import os
import logging

from .base_dir import BASE_DIR
from src import Logger

from .fixtures import FakeFrame, FakeWidget, FakeEvent

def setup_logging():
    LOGGER_NAME = 'config'
    filename = 'config.log'
    full_path = os.path.abspath(os.path.join(BASE_DIR, 'logs', filename))
    logger = Logger()
    logger.config(LOGGER_NAME, full_path, logging.DEBUG, initial_msg=False)
    return logging.getLogger(LOGGER_NAME)

log = setup_logging()

def initial_log_message(message, *args, **kwargs):
    log.info(message, *args, **kwargs)

RUN_FLAG = {'TestBootstrap': False,
            'TestLogger': False,
            'TestBases': False,
            'TestSettings': False,
            'TestBaseSystemData': False,
            'TestTomlMetaData': False,
            'TestTomlPanelConfig': False,
            'TestTomlAppConfig': False,
            'TestTomlCreatePanel': False,
            'TestExceptions': False,
            'TestPaths': False,
            'TestCheckPanelConfig': False,
            'TestCheckAppConfig': False,
            'TestGridBagSizer': False,
            'TestConfirmationDialog': False,
            'Test_ClickPosition': False,
            'TestEventStaticText': False}

def check_flag(name):
    if not RUN_FLAG[name]:
        initial_log_message("Start logging for %s", name)
        RUN_FLAG[name] = True

__all__ = (log, check_flag, FakeFrame, FakeWidget, FakeEvent)


# Write a Python program to check whether a specified value is contained in a group of values. Go to the editor
# Test Data :
# 3 -> [1, 5, 8, 3] : True
# -1 -> [1, 5, 8, 3] : False

given = input("Enter a list of numbers separated by spaces: ")

given_list = given.split(" ")
# for i in range(0, len(given_list)):
#     given_list[i] = int(given_list[i])

def check(x):
    x = str(x)
    contained = False

    for i in range(0, len(given_list)):
        if given_list[i] == x:
            contained = True
            print(contained)

check(4)

Basic Part 1 Exercises/basic part 1 exercise 25-1.py


# -*- coding: utf-8 -*-
"""
Created on Wed Dec 07 14:08:33 2011

@author: OThane
"""

from tkFileDialog import *
import string
import re
from pylab import *

class map_t:
    # simple class to model a map file

    def __init__(self, mapf = None):
        # init class vars
        self._mapf = None
        self._symtbl = []
        self._comptbl = []
        self._ram_comptbl = []
        self._rom_comptbl = []
        # load data
        if mapf != None:
            self.parse_map(mapf)

    def _parse_symtbl(self):
        pattern = re.compile('^\\s*(\\S*)\\s*(0x[0-9A-f]+)\\s{2,}(.*?)\\s{2,}(\\d+)\\s*(.*?\\.o).*')
        while 1:
            line = self._mapf.readline()
            if line == '' or line == '\n':
                break
            ret = pattern.findall(line)
            if len(ret) < 1:
                #print 'warning skipping line :' + line
                continue
            sym_line = ret[0]
            if len(sym_line) != 5:
                raise ValueError("unable to parse symbol ... " + line)
            sym_name = sym_line[0]
            sym_addr = int(sym_line[1], 16)
            sym_type = sym_line[2]
            sym_size = int(sym_line[3])
            sym_obj = sym_line[4]
            self._symtbl.append([sym_name, sym_addr, sym_type, sym_size, sym_obj])

    def _parse_comptbl(self):
        pattern = re.compile('^\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(.*?\\.o)')
        while 1:
            line = self._mapf.readline()
            if line == '' or line == '==============================================================================':
                break
            ret = pattern.findall(line)
            if len(ret) < 1:
                #print 'warning skipping line :' + line
                continue
            comp_line = ret[0]
            if len(comp_line) != 7:
                raise ValueError("unable to parse symbol ... " + line)
            code = int(comp_line[0])
            codata = int(comp_line[1])
            rodata = int(comp_line[2])
            rwdata = int(comp_line[3])
            zidata = int(comp_line[4])
            debug = int(comp_line[5])
            obj = comp_line[6]
            ram = rwdata + zidata
            rom = code + rodata + rwdata
            self._comptbl.append([ram, rom, code, codata, rodata, rwdata, zidata, debug, obj])
            self._ram_comptbl.append([ram, rwdata, zidata, obj])
            self._rom_comptbl.append([rom, code, codata, rodata, rwdata, obj])

    def _find_section(self, pattern):
        while 1:
            line = self._mapf.readline()
            if string.find(line, pattern) != -1 or line == '':
                break
        if string.find(line, pattern) == -1:
            raise NameError('Can not find ' + pattern)

    def sort_symtbl_size(self):
        self._symtbl.sort(key = lambda l: l[3], reverse=True)

    def sort_ram_comptbl(self):
        self._ram_comptbl.sort(key = lambda l: l[0], reverse=True)

    def sort_rom_comptbl(self):
        self._rom_comptbl.sort(key = lambda l: l[0], reverse=True)

    def get_symtbl(self, obj=None):
        if obj == None:
            return self._symtbl
        else:
            # search for all symbols with this obj
            return [sym for sym in self._symtbl if sym[-1] == obj]

    def get_ram_comptbl(self):
        return self._ram_comptbl

    def get_rom_comptbl(self):
        return self._rom_comptbl

    def hbar_ram(self, p = 1):
        # sort the ram here (perserve _ram_comptbl order so make new list)
        ram_sorted = sorted(self._ram_comptbl, key = lambda l: l[0], reverse=True)
        # build plotting arrays
        ram = []
        obj = []
        size = 0
        tot = 0
        for r in ram_sorted:
            tot += r[0]
        for r in ram_sorted:
            size += r[0]
            ram.append(r[0])
            obj.append(r[-1])
            if size > tot * p:
                break
        N = len(ram)
        i = arange(N)
        barh(i, ram[0:N])
        title('RAM usage')
        xlabel('RAM (bytes)')
        yticks(i+0.2, obj[0:N])

    def hbar_rom(self, p = 1):
        # sort the rom here (perserve _rom_comptbl order so make new list)
        rom_sorted = sorted(self._rom_comptbl, key = lambda l: l[0], reverse=True)
        # build plotting arrays
        rom = []
        obj = []
        size = 0
        tot = 0
        for r in rom_sorted:
            tot += r[0]
        for r in rom_sorted:
            size += r[0]
            rom.append(r[0])
            obj.append(r[-1])
            if size > tot * p:
                break
        N = len(rom)
        i = arange(N)
        barh(i, rom[0:N])
        title('ROM usage')
        xlabel('ROM (bytes)')
        yticks(i+0.2, obj[0:N])

    def parse_map(self, mapf):
        """
        Parse the map file
        """
        self._mapf = mapf

        # jump to Symbol Table Section (the first thing we are interested)
        self._find_section('Image Symbol Table')

        # jump to the local symbols and load them all
        self._find_section('    Local Symbols')
        self._mapf.readline()
        self._mapf.readline()
        self._mapf.readline()
        self._parse_symtbl()

        # jump to the global symbols and load them all
        self._find_section('    Global Symbols')
        self._mapf.readline()
        self._mapf.readline()
        self._mapf.readline()
        self._parse_symtbl()

        # jump to the Image components
        self._find_section('Image component sizes')
        self._mapf.readline()
        self._mapf.readline()
        self._mapf.readline()
        self._mapf.readline()
        self._parse_comptbl()

class _diff_tbl:
        # handles showing a diff table

        def __init__(self, diff_tbl, title = '', idx_size = 0, idx_name = -1, idx_type = None, on_obj_click = None):
            # ini class vars
            self._diff_tbl = diff_tbl
            self._title = title
            self._idx_size = idx_size
            self._idx_name = idx_name
            self._idx_type = idx_type
            self._figman = None
            self._barh = None
            self._ax = None
            self._difftbl_names = []
            self._on_obj_click = on_obj_click

        def __call__(self, event):
            if event.name == 'pick_event':
                # on pick event pop up a sorted symtbl for this obj
                if event.mouseevent.inaxes != self._ax: return
                i = int(event.mouseevent.ydata)
                obj = self._difftbl_names[i]
                if self._on_obj_click == None: return
                self._on_obj_click(obj)

        def plot(self, ax, p = 1):
            self._ax = ax
            # sort the diff by size so display in an ordered way
            diff_sorted = sorted(self._diff_tbl, key = lambda l: l[self._idx_size], reverse=True)
            size = []
            names = []
            # get the total size so we can display p % of it
            tot_size = 0
            for r in diff_sorted:
                tot_size += abs(r[self._idx_size])
            # get p % of the list into names and sizes to plot
            cum_size = 0
            self._difftbl_names = []
            for r in diff_sorted:
                # accumulate size
                s = r[self._idx_size]
                cum_size += abs(s)
                size.append(abs(s))
                # format the name (a '*' indicates a negative value)
                name = ''
                if s < 0: name += '*'
                name += r[self._idx_name]
                if self._idx_type != None: name += '(' + r[self._idx_type] + ')'
                names.append(name)
                self._difftbl_names.append(r[self._idx_name])
                # if we have we done p % of the total size the goto ploting
                if cum_size > tot_size * p:
                    break
            # plot the horizontal bar chart of all the sizes
            self._figman = get_current_fig_manager()
            i = arange(len(size))
            self._barh = barh(i, size, picker=50)
            title(self._title)
            xlabel('delta (bytes)')
            yticks(i+0.2, names)
            self._figman.canvas.mpl_connect('pick_event', self)

class map_diff_t:
    # handles diffing two map_t objs

    def __init__(self, map_a, map_b):
        # ini class vars
        self._ram_diffs = []
        self._ram_uniques = []
        self._rom_diffs = []
        self._rom_uniques = []
        # load data
        self._map_a = map_a
        self._map_b = map_b
        self._ram_diff()
        self._rom_diff()

    def _ram_diff(self):
        # search for a in b
        for ram_a in self._map_a._ram_comptbl:
            found = False
            for ram_b in self._map_b._ram_comptbl:
                # if obj names are the same we found a in b
                if ram_a[-1] == ram_b[-1]:
                    found = True
                    # if the size is the same then there is no diff
                    if ram_a[0] == ram_b[0]:
                        continue
                    # size is not the same so record the diff
                    delta = ram_b[0] - ram_a[0]
                    #if delta < 0:
                    #    delta = -delta
                    self._ram_diffs.append([delta, 'd', ram_a[-1]])
                    break
            if not found:
                # if we did not find a in b it is unique
                self._ram_uniques.append([-ram_a[0], 'u', ram_a[-1]])
        # search for b in a
        for ram_b in self._map_b._ram_comptbl:
            found = False
            for ram_a in self._map_a._ram_comptbl:
                # if obj names are the same we found b in a
                if ram_b[-1] == ram_a[-1]:
                    # we already found these above so skip b
                    found = True
                    break
            if not found:
                # if we did not find b in a it is unique
                self._ram_uniques.append([ram_b[0], 'u', ram_b[-1]])

    def _rom_diff(self):
        # search for a in b
        for rom_a in self._map_a._rom_comptbl:
            found = False
            for rom_b in self._map_b._rom_comptbl:
                # if obj names are the same we found a in b
                if rom_a[-1] == rom_b[-1]:
                    found = True
                    # if the size is the same then there is no diff
                    if rom_a[0] == rom_b[0]:
                        continue
                    # size is not the same so record the diff
                    delta = rom_b[0] - rom_a[0]
                    #if delta < 0:
                    #    delta = -delta
                    self._rom_diffs.append([delta, 'd', rom_a[-1]])
                    break
            if not found:
                # if we did not find a in b it is unique
                self._rom_uniques.append([-rom_a[0], 'u', rom_a[-1]])
        # search for b in a
        for rom_b in self._map_b._rom_comptbl:
            found = False
            for rom_a in self._map_a._rom_comptbl:
                # if obj names are the same we found b in a
                if rom_b[-1] == rom_a[-1]:
                    # we already found these above so skip b
                    found = True
                    break
            if not found:
                # if we did not find b in a it is unique
                self._rom_uniques.append([rom_b[0], 'u', rom_b[-1]])

    def _diff_symtbl(self, symtbl_a, symtbl_b):
        diff_symtbl = []
        # find a in b
        for sym_a in symtbl_a:
            found = False
            for sym_b in symtbl_b:
                if sym_a[0] == sym_b[0]:
                    # names are the same so they match
                    found = True
                    size_diff = sym_b[3] - sym_a[3]
                    if size_diff != 0:
                        # sizes differ so add to diff list
                        diff_symtbl.append([sym_a[0], 'd', size_diff])
            if found == False:
                # could not find a in b so a is unique
                diff_symtbl.append([sym_a[0], 'u', sym_a[3]])
        # find b in a
        for sym_b in symtbl_b:
            found = False
            for sym_a in symtbl_a:
                if sym_a[0] == sym_b[0]:
                    # names are the same so these have already been found above
                    found = True
                    break
            if found == False:
                # could not find b in a so b is unique
                diff_symtbl.append([sym_b[0], 'u', sym_b[3]])
        return diff_symtbl

    def hbar_symtbl(self, obj, p = 1):
        # get a list of diffs between symbols in map_a and map_b for obj
        symtbl = self._diff_symtbl(self._map_a.get_symtbl(obj), self._map_b.get_symtbl(obj))
        # sort the list
        symtbl.sort(key = lambda l: l[-1], reverse=True)
        # find out how much to plot
        tot_size = 0;
        for sym in symtbl:
            tot_size += abs(sym[-1])
        # get obj to plot
        cum_size = 0
        size = []
        names = []
        for sym in symtbl:
            cum_size += abs(sym[-1])
            size.append(abs(sym[-1]))
            # format the name (a '*' indicates a negative value)
            name = ''
            if sym[-1] < 0: name += '*'
            name += sym[0]
            name += '(' + sym[1] + ')'
            names.append(name)
            if cum_size > tot_size * p: break
        i = arange(len(size))
        figure()
        barh(i, size)
        title('symbol table for ' + obj)
        xlabel('bytes')
        yticks(i+0.2, names)

    def hbar_ram_diff(self, ax = None, p = 1):
        # just build one list of ram items that are unique or different sizes
        ram_diff_sorted = self._ram_diffs
        for unique in self._ram_uniques:
            ram_diff_sorted.append(unique)
        # plot horizontal histogram
        diff_tbl = _diff_tbl(ram_diff_sorted, title = 'RAM diff', idx_type = 1, on_obj_click = self.hbar_symtbl)
        diff_tbl.plot(ax, p)

    def hbar_rom_diff(self, p = 1, ax = None):
        # just build one list of rom items that are unique or different sizes
        rom_diff_sorted = self._rom_diffs
        for unique in self._rom_uniques:
            rom_diff_sorted.append(unique)
        # plot horizontal histogram
        diff_tbl = _diff_tbl(rom_diff_sorted, title = 'ROM diff', idx_type = 1, on_obj_click = self.hbar_symtbl)
        diff_tbl.plot(ax, p)

def anaylze():
    # get map file to parse
    filename = askopenfilename(title='load map file', filetypes = [('all', '.*'), ('map', '.map')])
    if filename:
        map = map_t(open(filename))
        # show rom and ram consumption
        figure()
        subplot(131)
        map.hbar_rom(0.7)
        subplot(133)
        map.hbar_ram(0.7)
        show()

def compare():
    # get map files to parse
    filename1 = askopenfilename(title='load map file 1', filetypes = [('all', '.*'), ('map', '.map')])
    filename2 = askopenfilename(title='load map file 2', filetypes = [('all', '.*'), ('map', '.map')])
    if filename1 and filename2:
        map1 = map_t(open(filename1))
        map2 = map_t(open(filename2))
        # show memory delta between versions
        map_diff = map_diff_t(map1, map2)
        fig = figure()
        ax = fig.add_subplot(131)
        map_diff.hbar_ram_diff(ax=ax)
        ax = fig.add_subplot(133)
        map_diff.hbar_rom_diff(0.9, ax=ax)
        show()

import Tkinter
top = Tkinter.Tk()
top.title("Choose an option..")
button = Tkinter.Button(top, text="Analyze single map file", command=anaylze)
button.pack()
button = Tkinter.Button(top, text="Compare map files", command=compare)
button.pack()
Tkinter.mainloop()


# @Author: xiewenqian <int>
# @Date:   2016-09-07T16:59:36+08:00
# @Email:  wixb50@gmail.com
# @Last modified by:   int
# @Last modified time: 2016-12-20T09:47:12+08:00

import tornado

from playhouse.shortcuts import model_to_dict
from pyrestful import mediatypes
from pyrestful.rest import get, post, put, delete

from .base import unblock, BaseHandler
from tornado_rest_peewee.utils.util import ReturnData, Metrics
from tornado_rest_peewee.models.tables import Teacher
from tornado_rest_peewee.jsons.teacher import TeacherSchema

class TeacherService(BaseHandler):

    # 获取所有
    @get(_path="/teachers", _produces=mediatypes.APPLICATION_JSON)
    @unblock
    @Metrics
    def get_all(self):
        # 排序和分页
        page = int(self.get_argument("p", "0"))
        number = int(self.get_argument("n", "10"))
        query = Teacher.select()
        models = [model_to_dict(x) for x in query.paginate(page, number)]
        return ReturnData(200, '获取数据成功', models, query.count())

    # 获取单个
    @get(_path="/teachers/{sys_id}", _produces=mediatypes.APPLICATION_JSON)
    @unblock
    @Metrics
    def get_one(self, sys_id):
        query = Teacher.get_one(id=int(sys_id))
        if query is None:
            return ReturnData(301, '该用户不存在')
        model = model_to_dict(query)
        return ReturnData(200, '获取数据成功', model)

    # 删除单个
    @delete(_path="/teachers/{sys_id}", _produces=mediatypes.APPLICATION_JSON)
    @unblock
    @Metrics
    def delete_one(self, sys_id):
        query = Teacher.get_one(id=int(sys_id))
        if query is None:
            return ReturnData(301, '该用户不存在')
        if query.delete_instance():
            return ReturnData(200, '删除数据成功')
        else:
            return ReturnData(301, '删除数据失败')

    # 新建单个
    @post(_path="/teachers", _produces=mediatypes.APPLICATION_JSON)
    @unblock
    @Metrics
    def create_one(self):
        teacher_info = tornado.escape.json_decode(self.request.body)
        valiResult = TeacherSchema().validator(teacher_info, 'create')
        if valiResult is not None:
            return ReturnData(301, valiResult)
        try:
            query = Teacher.create(**teacher_info)
        except Exception as e:
            return ReturnData(301, '新增失败', str(e))
        model = model_to_dict(query)
        return ReturnData(200, '新增数据成功', model)

    # 更改单个
    @put(_path="/teachers/{sys_id}", _produces=mediatypes.APPLICATION_JSON)
    @unblock
    @Metrics
    def update_one(self, sys_id):
        sys_id = int(sys_id)
        teacher_info = tornado.escape.json_decode(self.request.body)
        valiResult = TeacherSchema().validator(teacher_info, 'update')
        if valiResult is not None:
            return ReturnData(301, valiResult)
        query = Teacher.update(**teacher_info).where(Teacher.id == sys_id).execute()
        if query:
            model = model_to_dict(Teacher.get_one(id=sys_id))
            return ReturnData(200, '更改数据成功', model)
        else:
            return ReturnData(301, '数据不存在')


# -*- coding=utf-8 -*-
"""
@file  : itemaction
@date  : 2016-09-22
@author: GongXiaobo
"""

from hall5.plugins.hallitem._private._actions import _action
from hall5.plugins.hallitem._private.itemdao import DaoMixExCodeList
from tuyoo5.core import tyrpcsdk
from tuyoo5.core.typlugin import pluginCross
from tuyoo5.core.tyrpchall import UserKeys
from tuyoo5.plugins.item import items

class TYItemActionSendMsg(_action.HallItemAction):

    TYPE_ID = 'common.sendMsg'

    def __init__(self):
        super(TYItemActionSendMsg, self).__init__()

    def canDo(self, gameId, clientId, userBag, item, timestamp):
        return not item.isDied(timestamp)

    def doAction(self, gameId, clientId, userAssets, item, timestamp, params):

        if item.isDied(timestamp):
            return items.TYItemActionResult(None, None, -30, '道具已经过期', None)

        # 手机号码的处理
        useBindPhone = params.get('bindPhone', 0)
        if not useBindPhone:
            # 如果没有bindPhone，则需要检查phoneNumber
            phoneNumber = params.get('phoneNumber')
            if not phoneNumber:
                return items.TYItemActionResult(None, None, -31, '请输入手机号码', None)
        else:
            # 获取绑定的手机号
            phoneNumber = pluginCross.halldata.getUserDataList(userAssets.userId, UserKeys.ATT_BIND_MOBILE)
            if not phoneNumber:
                return items.TYItemActionResult(None, None, -32, '您绑定的手机号状态有误，请联系客服电话4008098000', None)

        # 获取库存
        exCode = DaoMixExCodeList.getFreeExCode(userAssets.userId, item.kindId, phoneNumber, timestamp)
        if not exCode:
            return items.TYItemActionResult(None, None, -33, '非常抱歉的通知您，兑换码已无库存，请联系客服电话4008098000', None)

        # 短信发送
        replaceParams = {'item': item.itemKind.displayName}
        mail, message, _ = _action._buildMailAndMessageAndChanged(gameId, userAssets, self, None, replaceParams)
        content = mail + exCode + message
        code = tyrpcsdk.sendSmsToUser(userAssets.userId, content, phoneNumber)
        if code == 0:
            # 消耗item
            userBag = userAssets.getUserBag()
            userBag.removeItem(gameId, item, timestamp, 'ITEM_USE', 0)
            return items.ACT_RESULT_OK
        else:
            # 将消息下发到用户的消息列表中
            # pluginCross.hallmessage.sendMessageSystem(userAssets.userId, gameId, sendToMsg, None, None)
            return items.TYItemActionResult(None, None, -34, '非常抱歉，短信发送失败，请联系客服电话4008098000', None)


import tvm
from tvm.contrib import verilog

def test_loop():
    sess = verilog.session([
        verilog.find_file("test_loop.v")
    ])
    # Get the handles by their names
    rst = sess.main.rst
    iter0 = sess.main.iter0
    iter1 = sess.main.iter1
    ready = sess.main.ready

    rst.put_int(1)
    ready.put_int(1)
    # This will advance the cycle to next pos-edge of clk.
    sess.yield_until_next_cycle()
    rst.put_int(0)
    sess.yield_until_next_cycle()

    for k in range(0, 1):
        for i in range(0, 3):
            for j in range(0, 4):
                assert(iter1.get_int() == i)
                assert(iter0.get_int() == j)
                sess.yield_until_next_cycle()

if __name__ == "__main__":
    test_loop()


import pandas as pd
import numpy as np
import re
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from datetime import datetime
from statistics import mean, stdev
import matplotlib.pyplot as plt

START_DATE = "2012-01-01"
END_DATE = "2022-09-01"

def clean_tweet(tweet):
    """
    Cleans tweet text
    """
    tweet = re.sub("RT", "", tweet)  # remove 'RT'
    tweet = re.sub("#[A-Za-z0-9]+", "", tweet)  # remove '#'
    tweet = re.sub("\\n", "", tweet)  # remove '\n'
    tweet = re.sub("https?:\/\/\S+", "", tweet)  # remove hyperlinks
    tweet = re.sub("@[\S]*", "", tweet)  # remove @mentions
    tweet = re.sub("^[\s]+|[\s]+$", "", tweet)  # remove leading and trailing whitespace
    return tweet

def monthsplit(searchstring):
    searchlist = []
    dates = pd.date_range(start=START_DATE, end=END_DATE, freq="MS")
    for idx, _ in enumerate(dates):
        if idx != len(dates) - 1:
            searchlist.append(
                f"{searchstring} since:{dates[idx].date()} until:{dates[idx+1].date()}"
            )
    return searchlist

def list_filelist(searchstrings):
    filtered_searchstrings = []
    for search in searchstrings:
        t_list = []
        for file_name in monthsplit(search):
            if ":" in file_name:
                file_name = file_name.replace(":", "_")
            if '"' in file_name:
                file_name = file_name.replace('"', "")
                file_name = file_name + "QUOTESEARCH"
            t_list.append(file_name)
        filtered_searchstrings.append(t_list)
    return filtered_searchstrings

def ts():
    return datetime.now().strftime("[%H:%M:%S]")

def fast_group_days(df):
    keys, values = df.sort_values("Date").values.T
    ukeys, index = np.unique(keys, True)
    arrays = np.split(values, index[1:])
    df2 = pd.DataFrame({"Date": ukeys, "Text": [list(a) for a in arrays]})
    return df2

def analyze_sentiment(sentences, ignore_neutral=True):
    """
    Analyzes sentiments
    """
    analyzer = SentimentIntensityAnalyzer()
    vslist = []
    for sentence in sentences:
        vs = analyzer.polarity_scores(sentence)
        if ignore_neutral:
            if vs["compound"] != 0:
                vslist.append(vs["compound"])
        else:
            vslist.append(vs["compound"])
    return vslist

def main():
    searchstrings = ["btc", "#BTC", "ethereum", "eth", "bitcoin"]
    df = pd.DataFrame(
        columns=searchstrings, index=pd.date_range(start=START_DATE, end=END_DATE).date
    )
    tweetcount = df.copy()
    df_sd, df_in, df_in_sd = df.copy(), df.copy(), df.copy()
    bands_excl = np.zeros(201, dtype=np.int32)
    bands_incl = np.zeros(201, dtype=np.int32)
    for search in searchstrings:
        print(f'\n{ts()}: Analyzing sentiments for "{search}"')
        search_list = [search]
        for i, filename in enumerate(list_filelist(search_list)[0]):
            print(f"{ts()}: Progress - {i}/{len(list_filelist(search_list)[0])}")
            dft = pd.read_csv(f"Data/Tweets/{filename}.csv")

            dft = dft.drop(
                columns=[
                    "Unnamed: 0",
                    "Tweet Id",
                    "Username",
                    "Replies",
                    "Retweets",
                    "Likes",
                    "Quotes",
                ]
            )
            dft["Datetime"] = pd.to_datetime(dft["Datetime"]).dt.date
            dft = dft.rename(columns={"Datetime": "Date"})
            dft = fast_group_days(dft)
            for _, row in dft.iterrows():
                tweetcount.loc[row["Date"], search] = len(row["Text"])
                # without neutral sentiments
                s_in = analyze_sentiment(row["Text"], ignore_neutral=False)
                s_in_ar = np.array(s_in)
                for v in s_in:
                    bands_incl[round((v + 1) * 100)] += 1
                s = s_in_ar[s_in_ar != 0]
                for v in s:
                    bands_excl[round((v + 1) * 100)] += 1
                if len(s) == 0:
                    df.loc[row["Date"], search] = np.nan
                    df_sd.loc[row["Date"], search] = np.nan
                elif len(s) == 1:
                    df.loc[row["Date"], search] = mean(s)
                    df_sd.loc[row["Date"], search] = np.nan
                else:
                    df.loc[row["Date"], search] = mean(s)
                    df_sd.loc[row["Date"], search] = stdev(s)

                # with neutral sentiments
                if len(s_in) == 0:
                    df_in.loc[row["Date"], search] = np.nan
                    df_in_sd.loc[row["Date"], search] = np.nan
                elif len(s_in) == 1:
                    df_in.loc[row["Date"], search] = mean(s_in)
                    df_in_sd.loc[row["Date"], search] = np.nan
                else:
                    df_in.loc[row["Date"], search] = mean(s_in)
                    df_in_sd.loc[row["Date"], search] = stdev(s_in)

    df.to_csv("Data/Sentiments/sentiments.csv")
    df_sd.to_csv("Data/Sentiments/sentiments_sd.csv")
    df_in.to_csv("Data/Sentiments/sentiments_incl_neutral.csv")
    df_in_sd.to_csv("Data/Sentiments/sentiments_incl_neutral_sd.csv")
    tweetcount.fillna(0)
    tweetcount.to_csv("Data/Tweets/tweetcount.csv")
    histogram_df = pd.DataFrame(
        bands_excl, columns=["bands_excl"], index=np.linspace(-1, 1, num=201)
    )
    histogram_df["bands_incl"] = bands_incl
    histogram_df.to_csv("Data/Sentiments/histogram_df.csv")
    print(f"\n{ts()}: Success, exiting.")
    return

if __name__ == "__main__":
    main()


import random

import numpy as np
import time
import sys

# Create the class
class Pokemon:
    def __init__(self, name, pokemon_type, moves, stats):
        self.name = name
        self.type = pokemon_type
        self.moves = moves
        self.health = 'ðŸŸ¥' * 3 + 'ðŸŸ¨' * 5 + 'ðŸŸ¨' * 12
        self.attack = stats['ATTACK']
        self.attack_desc = f'<{self.name} GROWLS AGGRESSIVELY...>'
        self.defence = stats['DEFENCE']
        self.cp = int(round((lambda attack, defence: 8 * np.mean([attack, defence]))(self.attack, self.defence)))
        self.skill_damage_ratio = (1, 0.25, 0.5, 0.75)
        self.skill_energy_ratio = (2, 0, 0.5, 1)
        self.skill_special_bar = 0

    def pokemonDesc(self):
        return f'{self.name}\n' \
               f'TYPE/ {self.type}\n' \
               f'ATTACK/ {self.attack}\n' \
               f'DEFENCE/ {self.defence}\n' \
               f'CP/ {self.cp}\n\n'

    def setSkillEnergyRatio(self):
        for energy_needed in self.skill_energy_ratio:
            energy_needed *= self.attack

    def typeVariance(self, enemy):
        self.attack = round(self.attack * 2)
        self.defence = round(self.defence * 2)
        enemy.attack = round(enemy.attack / 2)
        enemy.defence = round(enemy.defence / 2)

    def setPokemonBonusForType(self, enemy):
        pokemon_types = ('Bug', 'Dark', 'Dragon', 'Electric', 'Fairy', 'Fighting', 'Fire', 'Flying', 'Ghost', 'Grass',
                         'Ground', 'Ice', 'Normal', 'Poison', 'Psychic', 'Rock', 'Steel', 'Water')
        strong_against = (
            ('Grass', 'Dark', 'Psychic'), ('Ghost', 'Psychic'), ('Dragon'), ('Flying', 'Water'),
            ('Fighting', 'Dark', 'Dragon'), ('Dark', 'Ice', 'Normal', 'Rock', 'Steel'),
            ('Bug', 'Grass', 'Ice', 'Steel'), ('Bug', 'Fighting', 'Grass'), ('Ghost', 'Psychic'),
            ('Ground', 'Rock', 'Water'), ('Electric', 'Fire', 'Poison', 'Rock', 'Steel'),
            ('Dragon', 'Flying', 'Grass', 'Ground'), (None), ('Fairy', 'Grass'), ('Fighting', 'Poison'),
            ('Bug', 'Fire', 'Flying', 'Ice'), ('Fairy', 'Ice', 'Rock'), ('Fire', 'Ground', 'Rock')
        )
        weak_against = (
            ('Fire', 'Flying', 'Rock'), ('Bug', 'Fire', 'Lightning'), ('Dragon', 'Fairy', 'Ice'), ('Ground'),
            ('Poison', 'Steel'), ('Fairy', 'Flying', 'Psychic'), ('Ground', 'Rock', 'Water'),
            ('Electric', 'Ice', 'Rock'), ('Dark', 'Ghost'), ('Bug', 'Fire', 'Flying', 'Ice', 'Poison'),
            ('Grass', 'Ice', 'Water'), ('Fighting', 'Fire', 'Rock', 'Steel'), ('Fighting'), ('Ground', 'Psychic'),
            ('Bug', 'Dark', 'Ghost'), ('Fighting', 'Grass', 'Ground', 'Steel', 'Water'),
            ('Fighting', 'Fire', 'Ground'), ('Electric', 'Grass')
        )

        attack_info = ("It's not very effective", "It's super effective!")

        # Case 1: Both Pokemons are same type
        if enemy.type == self.type:
            self.attack_desc = attack_info[0]
            enemy.attack_desc = attack_info[0]

        # Case 2: My Pokemon is stronger
        if enemy.type in strong_against[pokemon_types.index(self.type)]:
            self.typeVariance(enemy)  # self *2, enemy / 2
            self.attack_desc = attack_info[1]
            enemy.attack_desc = attack_info[0]

        # Case 3: Enemy Pokemon is stronger
        if enemy.type in weak_against[pokemon_types.index(self.type)]:
            enemy.typeVariance(self)  # enemy *2 , self / 2
            self.attack_desc = attack_info[0]
            enemy.attack_desc = attack_info[1]

    @property
    def skill(self):
        for index, move in enumerate(self.moves):
            print(f'{index + 1}.', move)
        while True:
            user_input = input('Pick a move: ')
            if user_input.isdigit() and int(user_input) in range(1, 4 + 1):
                skill_index = int(user_input)
                print(f'{self.name}, {self.attack}, {self.skill_special_bar},'
                      f' {self.skill_energy_ratio[skill_index - 1] * self.attack}')
                if self.skill_special_bar >= self.skill_energy_ratio[skill_index - 1] * self.attack:
                    self.skill_special_bar -= self.skill_energy_ratio[skill_index - 1] * self.attack
                    print(f'{self.name}, {self.skill_special_bar}')
                    self.skill_special_bar += self.attack
                    print(f'{self.name}, {self.skill_special_bar}')
                    break
                else:
                    delayPrint(f'{self.name} cannot use that attack now\n')
            else:
                print('Your input should be an integer in the range between 1 and 4!')

        delayPrint(f'{self.name} used {self.moves[skill_index - 1]}\n')
        time.sleep(1)
        return skill_index

    def skillDamage(self, enemy):

        skill_index = self.skill

        attack_val = (0, self.attack)
        miss_probability = enemy.cp / (10 * self.cp)  # the higher cp of the attacking pokemon, the less chance for miss
        attack_probability = (miss_probability, 1 - miss_probability)
        attack_list = random.choices(attack_val, attack_probability)
        attack = attack_list[0] * self.skill_damage_ratio[skill_index - 1]
        damage = 0
        try:
            damage = round(attack - 0.1 * (enemy.cp / self.cp) * enemy.defence)
        except ZeroDivisionError:
            damage = 0
        finally:
            if damage <= 0:
                damage = 0
                delayPrint(f"{self.name} missed!\n")
            if damage >= len(enemy.health):
                damage = len(enemy.health)
            return damage

    def pokemonTurn(self, enemy):
        # Print the health of each Pokemon
        print(f'{self.name}\t\tHP\t{self.health}')
        print(f'{enemy.name}\t\tHP\t{enemy.health}')

        # pokemon
        print(f'\nGo {self.name}!')
        # pokemon_types = {Strong Type: against weak Type, ... }
        enemy.health = enemy.health[:len(enemy.health) - self.skillDamage(enemy)]
        delayPrint(self.attack_desc)
        time.sleep(0.5)

        # Print the health of each Pokemon
        print(f'\n{self.name}\t\tHP\t{self.health}')
        print(f'\n{enemy.name}\t\tHP\t{enemy.health}\n')

        return self.health

    def pokemonFight(self, enemy):
        # Print the information
        delayPrint('\n\tPOKEMON BATTLE\n\n')
        delayPrint(self.pokemonDesc())
        delayPrint(enemy.pokemonDesc())

        self.setPokemonBonusForType(enemy)
        self.setSkillEnergyRatio()

        time.sleep(2)

        while len(self.health) > 0 and len(enemy.health) > 0:
            if len(self.pokemonTurn(enemy)) <= 0:  # self attacks enemy
                delayPrint(f"\n...{enemy.name} fainted.")
                break
            if len(enemy.pokemonTurn(self)) <= 0:  # enemy attack self
                delayPrint(f"\n...{self.name} fainted.")
                break

        money = np.random.choice(5000)
        delayPrint(f"You've obtained {money} Stardust!")

# delay printing
def delayPrint(string):
    # print one character in a specific time interval
    for char in string:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(5e-2)

if __name__ == '__main__':
    # Create Pokemon
    charizard = Pokemon('Charizard', 'Fire', ['Flamethrower', 'Fly', 'Blast Burn', 'Fire Punch'],
                        {'ATTACK': 18, 'DEFENCE': 10})
    blastoise = Pokemon('Blastoise', 'Water', ['Water Gun', 'Bubblebeam', 'Hydro Pump', 'Surf'],
                        {'ATTACK': 8, 'DEFENCE': 12})
    venusaur = Pokemon('Venusaur', 'Grass', ['Vine Wip', 'Razor Leaf', 'Earthquake', 'Frenzy Plant'],
                       {'ATTACK': 8, 'DEFENCE': 12})

    charmander = Pokemon('Charmander', 'Fire', ['Ember', 'Scratch', 'Tackle', 'Fire Punch'],
                         {'ATTACK': 4, 'DEFENCE': 2})
    squirtle = Pokemon('Squirtle', 'Water', ['Bubblebeam', 'Tackle', 'Headbutt', 'Surf'], {'ATTACK': 3, 'DEFENCE': 3})
    bulbasaur = Pokemon('Bulbasaur', 'Grass', ['Vine Wip', 'Razor Leaf', 'Tackle', 'Leech Seed'],
                        {'ATTACK': 2, 'DEFENCE': 4})

    charmeleon = Pokemon('Charmeleon', 'Fire', ['Ember', 'Scratch', 'Flamethrower', 'Fire Punch'],
                         {'ATTACK': 6, 'DEFENCE': 5})
    wartortle = Pokemon('Wartortle', 'Water', ['Bubblebeam', 'Water Gun', 'Headbutt', 'Surf'],
                        {'ATTACK': 5, 'DEFENCE': 5})
    ivysaur = Pokemon('Ivysaur\t', 'Grass', ['Vine Wip', 'Razor Leaf', 'Bullet Seed', 'Leech Seed'],
                      {'ATTACK': 4, 'DEFENCE': 6})

    charizard.pokemonFight(blastoise)


"""
Install PyProbables to use this code.
See: https://pyprobables.readthedocs.io/en/latest/code.html#bloomfilter
Straightforward use of BloomFilter.
"""
from probables import BloomFilter

import sys
sys.path.append("../")
from IoTPy.core.stream import Stream, _no_value, run
from IoTPy.agent_types.op import map_element
from IoTPy.helper_functions.print_stream import print_stream

def bloom_filter_stream(in_stream, out_stream, bloom_filter):
    """
    Parameters
    ----------
       in_stream: Stream
          The input stream of the agent.
          Each element of the input stream is a pair which
          is either ('add', object) or ('check', object).
          If ('add', z) appears in the input stream then
          z is added to the Bloom Filter set.
          If ('check', z) appears then (z, 'True') appears
          on the output stream if z is in the filter, and
          (z, 'False') appears otherwise.
       out_stream: Stream
          The output stream of the agent.
          An element is added to the output stream when a 'check'
          function_name appears on the input stream.
          The output stream consists of pairs (object, boolean)
          where boolean is True if and only if object
          is in the input stream at this point.
       bloom_filter: BloomFilter
          An instance of the BloomFilter class.

    """
    # The function for the map_element agent.
    def func(element):
        function_name, obj = element
        if function_name == 'add':
            bloom_filter.add(obj)
            return _no_value
        elif function_name == 'check':
            return (obj, bloom_filter.check(obj))
        else:
            raise ValueError
    # Create the map_element agent.
    map_element(func, in_stream, out_stream)

#---------------------------------------------------------------------------
#       TEST
#---------------------------------------------------------------------------
def test():
    bloom_filter = BloomFilter(est_elements=1000, false_positive_rate=0.05)

    x = Stream('Bloom Filter input')
    y = Stream('Bloom Filter output')
    bloom_filter_stream(x, y, bloom_filter=bloom_filter)
    print_stream(y, y.name)

    # Run test data
    data=[('add', 'a'), ('add', 'b'), ('add', 'a'),
          ('check', 'c'), ('add', 'd'), ('check','a')]
    x.extend(data)
    run()

    data=[('add', 'c'), ('check', 'b'), ('check', 'a'),
          ('check', 'c'), ('check', 'e'), ('add', 'a')]
    x.extend(data)
    run()

if __name__ == '__main__':
    test()