import torch
import torch.nn as nn
import torch.nn.functional as F

nclasses = 43 # GTSRB as 43 classes

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
        self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
        self.conv2_drop = nn.Dropout2d()
        self.fc1 = nn.Linear(500, 50)
        self.fc2 = nn.Linear(50, nclasses)

    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
        x = x.view(-1, 500)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return F.log_softmax(x)

class ConvBlock(nn.Module):
    def __init__(self, in_ch, k_size, out_ch, st, pad, pool=None, pool_k=None, pool_st=None, bias=True):
        super(ConvBlock, self).__init__()
        self.pool = pool

        self.c1 = nn.Conv2d(in_ch, out_ch, kernel_size=k_size, stride=st, padding=pad, bias=bias)
        self.b1 = nn.BatchNorm2d(out_ch, affine=True)
        self.a1 = nn.ELU(True)
        if self.pool:
            self.p1 = nn.MaxPool2d(pool_k, pool_st)
        self.apply(weights_init)
    def forward(self, x):
        x = self.c1(x)
        x = self.b1(x)
        x = self.a1(x)
        if self.pool:
            x = self.p1(x)
        return x

class Net1(nn.Module):
    def __init__(self):
        super(Net1, self).__init__()
        self.l1 = ConvBlock(3, 3, 32, 1, 1)
        self.l2 = ConvBlock(32, 3, 32, 1, 1, 1, 2, 2)
        self.l3 = ConvBlock(32, 3, 64, 1, 1)
        self.l4 = ConvBlock(64, 3, 64, 1, 1, 1, 2, 2)
        self.l5 = ConvBlock(64, 3, 64, 1, 1, 1, 2, 2)
        self.l6 = ConvBlock(64, 4, 512, 1, 0)
        self.l7 = nn.Dropout2d(0.5)
        self.l8 = ConvBlock(512, 1, 512, 1, 0, bias=False)
        self.l9 = nn.Dropout2d(0.5)
        # Global avg pooling to be used instead of maxpool
        self.l10 = nn.Conv2d(512, nclasses, 1, 1, 0, bias=False)
        self.l11 = nn.AvgPool2d(1, 1)
        self.l12 = nn.BatchNorm2d(nclasses, affine=True)
        self.apply(weights_init_uniform)

    def forward(self, x):
        x = self.l1(x)
        x = self.l2(x)
        x = self.l3(x)
        x = self.l4(x)
        x = self.l5(x)
        x = self.l6(x)
        x = self.l7(x)
        x = self.l8(x)
        x = self.l9(x)
        x = self.l10(x)
        x = self.l11(x)
        x = self.l12(x)
        x = x.view(-1, nclasses)
        return F.log_softmax(x)

class Net2(nn.Module):
    def __init__(self):
        super(Net2, self).__init__()
        layers = []
        layers.append(nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=0))
        layers.append(nn.ELU())

        layers.append(nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=0))
        layers.append(nn.BatchNorm2d(32, affine=True))
        layers.append(nn.ELU())

        layers.append(nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=0))
        layers.append(nn.BatchNorm2d(32, affine=True))
        layers.append(nn.ELU())
        layers.append(nn.MaxPool2d(2))
        layers.append(nn.Dropout(0.2))

        layers.append(nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=0))
        layers.append(nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=0))
        layers.append(nn.BatchNorm2d(64, affine=True))
        layers.append(nn.ELU())
        layers.append(nn.MaxPool2d(2))
        layers.append(nn.Dropout(0.2))
        self.convlayers = nn.Sequential(*layers)

        layers = []
        layers.append(nn.Linear(4096, 512))
        layers.append(nn.ELU())
        layers.append(nn.Dropout(0.5))
        layers.append(nn.Linear(512, nclasses))
        self.flatlayers = nn.Sequential(*layers)

    def forward(self, x):
        x = self.convlayers(x)
        x = x.view(x.size(0), -1)
        x =self.flatlayers(x)
        return F.log_softmax(x)

class Net3(nn.Module):
    def __init__(self):
        super(Net2, self).__init__()
        layers = []
        layers.append(nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=0))
        layers.append(nn.ReLU())

        layers.append(nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=0))
        layers.append(nn.ReLU())

        layers.append(nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=0))
        layers.append(nn.ReLU())
        layers.append(nn.MaxPool2d(2))
        layers.append(nn.Dropout(0.2))

        layers.append(nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=0))
        layers.append(nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=0))
        layers.append(nn.ReLU())
        layers.append(nn.MaxPool2d(2))
        layers.append(nn.Dropout(0.2))
        self.convlayers = nn.Sequential(*layers)

        layers = []
        layers.append(nn.Linear(4096, 512))
        layers.append(nn.ReLU())
        layers.append(nn.Dropout(0.5))
        layers.append(nn.Linear(512, nclasses))
        self.flatlayers = nn.Sequential(*layers)

    def forward(self, x):
        x = self.convlayers(x)
        x = x.view(x.size(0), -1)
        x =self.flatlayers(x)
        return F.log_softmax(x)

def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Linear') != -1:
        m.weight.data.normal_(0.0, 0.01)
    if classname.find('Conv2d') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

def weights_init_uniform(m):
    classname = m.__class__.__name__
    if classname.find('Linear') != -1:
        m.weight.data.uniform_(-0.01, 0.01)
    if classname.find('Conv2d') != -1:
        m.weight.data.uniform_(-0.01, 0.01)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.uniform_(-0.01, 0.01)
        m.bias.data.fill_(0)

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1):
        super(BasicBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)

        self.shortcut = nn.Sequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)
        out = F.relu(out)
        return out

class ResNet(nn.Module):
    def __init__(self, block, num_blocks, num_classes=10):
        super(ResNet, self).__init__()
        self.in_planes = 64

        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
        #self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
        # self.linear = nn.Linear(8192, 4096)
        self.do = nn.Dropout(0.5)
        self.linear2 = nn.Linear(2304, 512)
        self.linear3 = nn.Linear(512, num_classes)

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return nn.Sequential(*layers)

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        #out = self.layer4(out)
        out = F.avg_pool2d(out, 4)
        out = out.view(out.size(0), -1)
        #out = self.do(self.linear(out))

        out = self.do(self.linear2(out))
        out = self.linear3(out)
        return F.log_softmax(out)

class ResBlock(nn.Module):
    def __init__(self, in_ch, out_ch, stride):
        super(ResBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_ch)
        self.conv2 = nn.Conv2d(out_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_ch)
        self.relu_act = nn.ReLU()

        self.shortcut = nn.Sequential()
        if stride != 1 or in_ch != out_ch:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=stride, padding=1, bias=False),
                nn.BatchNorm2d(out_ch)
            )

    def forward(self, x):
        out = self.relu_act(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)
        out = self.relu_act(out)
        return out

class Resnet_Custom(nn.Module):
    def __init__(self, num_classes):
        super(Resnet_Custom, self).__init__()
        self.in_ch = 64
        self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.act = nn.ReLU()
        # Res Layers
        self.res1 = self.make_res_layer(64, 2, 1)
        self.res2 = self.make_res_layer(128, 2, 2)
        self.res3 = self.make_res_layer(256, 2, 2)

        self.pool = nn.AvgPool2d(4, 4)
        self.do = nn.Dropout(0.5)
        self.l1 = nn.Linear(2304, 512)
        self.l2 = nn.Linear(512, num_classes)

    def make_res_layer(self, out_ch, block_size, stride):
        strides = [stride] + [1]*(block_size-1)
        layers = []
        for stride in strides:
            layers.append(ResBlock(self.in_ch, out_ch, stride))
            self.in_ch = out_ch
        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.act(self.bn1(self.conv1(x)))
        x = self.res1(x)
        x = self.res2(x)
        x = self.res3(x)
        x = self.pool(x)
        x = x.view(x.size(0), -1)
        x = self.do(self.l1(x))
        x = self.l2(x)
        return F.log_softmax(x)


"""
This custom database backend inherits from the sqlite3 backend but adds
a few customizations for this application.

"""
from django.db.backends.sqlite3 import base, schema

class DatabaseSchemaEditor(schema.DatabaseSchemaEditor):
    # This adds cascading deletes to foreign key relations. Foreign key
    # fields with on_delete set to DO_NOTHING will still cascade, but SQLite
    # will do the cascading, without Django having to pull all rows into
    # memory. Signals and such aren't run, but for large tables, this is the
    # only way to delete a large number of objects without using a lot of
    # memory.
    sql_create_inline_fk = "REFERENCES %(to_table)s (%(to_column)s) " \
                           "ON DELETE CASCADE " \
                           "DEFERRABLE INITIALLY DEFERRED"

class DatabaseWrapper(base.DatabaseWrapper):
    SchemaEditorClass = DatabaseSchemaEditor

    def __init__(self, *args, **kwargs):
        # This flag is set by a custom context manager to tell us to use BEGIN
        # IMMEDIATE when beginning a transaction
        self.begin_immediate = False
        super().__init__(*args, **kwargs)

    def _start_transaction_under_autocommit(self):
        if self.begin_immediate:
            self.cursor().execute("BEGIN IMMEDIATE")
        else:
            self.cursor().execute("BEGIN")

    def get_new_connection(self, conn_params):
        """Enable some sqlite features that are disabled by the default"""
        conn = super().get_new_connection(conn_params)

        # Set the page size. In SQLite version 3.12.0 this was changed to a
        # default of 4096, but some distros still use older versions of SQLite.
        conn.execute("PRAGMA page_size=4096").close()
        conn.execute("PRAGMA page_cache=-2000").close()

        # The write-ahead-log's main advantage is that it allows readers
        # while another connection is in a write transaction. It also may add
        # some performance improvements, but at the moment, tests show
        # performance is about the same.
        conn.execute("PRAGMA journal_mode=WAL").close()

        # The next two options can help improve performance for some kinds of
        # workloads, but according to some quick tests, performance is about
        # the same for this application. My guess is that performance is
        # limited by other IO and the database is not the main bottleneck.
        # I'm leaving these settings in the code but commented out so it's
        # easy to uncomment them for performance tests in the future.

        # Setting the synchronous mode to NORMAL sacrifices durability for
        # performance. Writes to the WAL are not synced, so writes may be lost
        # on a system crash or power failure, which feels acceptable for this
        # application. Writes to the database are still synced, and the WAL
        # is still synced before checkpoints.
        #conn.execute("PRAGMA synchronous=NORMAL").close()

        # Memory-mapped IO can help performance on read-heavy loads by
        # avoiding a lot of read() system calls, but according to some quick
        # tests it doesn't speed up the code much, despite almost cutting the
        # number of system calls in half during a scan.
        # The only problem with leaving this on is that Linux counts shared
        # memory toward's a process's RSS usage, making this process look
        # like it's using more memory than it actually is. So I keep this off
        # for development so it's easy to see if a routine or query uses
        # more memory than I expect.
        #conn.execute("PRAGMA mmap_size=1073741824;").close()
        return conn


from sklearn import model_selection, preprocessing, linear_model, naive_bayes, metrics, svm
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn import decomposition, ensemble
import pandas as pd, xgboost, numpy as np, textblob, string
import statistics

predicted_vector = []
classes_csv = open('/home/arshad/Documents/FYP99/FYP/UserSpecs2PseudoCode/PC_Interface/pc_corpus/classes.csv').read()
classes = {}

for k, line in enumerate(classes_csv.split("\n")):
    try:
        if line is not '':
            content = line.split(',')
        classes[content[0]] = (content[1])
    except:
        print("Unable to locate classes_csv")

def predict(classifier, feature_vector_train, label, feature_vector_pred, header):
    clf = classifier
    clf.fit(feature_vector_train, label)
    r = clf.predict(feature_vector_pred)
    lbl = encoder.inverse_transform(r)
    # predicted_vector.append(r)
    for lb in lbl:
        intent = classes[lb]
        print(intent)
    predicted_vector.append(str(lbl))
    print("-" * 30)
    print(header + "\n" + str(r) + "-" + str(lbl))
    print("=" * 50)

def train_model(classifier, feature_vector_train, label, feature_vector_valid, is_neural_net=False):
    # fit the training dataset on the classifier
    classifier.fit(feature_vector_train, label)

    # predict the labels on validation dataset
    predictions = classifier.predict(feature_vector_valid)

    if is_neural_net:
        predictions = predictions.argmax(axis=-1)

    return metrics.accuracy_score(predictions, valid_y)

# load the dataset
# data = open('pc_corpus/corpus').read()
data = open('pc_corpus/user_entered').read()
labels, texts = [], []

# load the dataset (testing 1by1)
data_testing = open('pc_corpus/pred')
# data_testing = open('pc_corpus/users_entered_lines')
texts_testing = [line for line in data_testing.readlines() if line.strip()]

# load the dataset (filling 1by1)
data_filling = open('pc_corpus/test_filling').read()
labels_filling, texts_filling = [], []

for i, line in enumerate(data.split("\n")):
    content = line.split()
    try:
        labels.append(content[0])
        texts.append(" ".join(content[1:]))
    except:
        print("End of the list")

for i, line in enumerate(data_filling.split("\n")):
    content = line.split()
    try:
        labels_filling.append(content[0])
        texts_filling.append(" ".join(content[1:]))
    except:
        print("End of the list")

# create a dataframe using texts and lables
trainDF = pd.DataFrame()
trainDF['text'] = texts
trainDF['label'] = labels

# create a dataframe using texts and lables (testing 1by1)
trainDF_testing = pd.DataFrame()
trainDF_testing['text'] = texts_testing
print(trainDF_testing['text'])

# create a dataframe using texts and lables (filling)
trainDF_filling = pd.DataFrame()
trainDF_filling['text'] = texts_filling
trainDF_filling['label'] = labels_filling

# split the dataset into training and validation datasets
train_x, valid_x, train_y, valid_y = model_selection.train_test_split(trainDF['text'], trainDF['label'], test_size=0.2)

# combine the filling and corpus
frames_y = [valid_y, trainDF_filling['label']]
frames_x = [valid_x, trainDF_filling['text']]
valid_y_filled = pd.concat(frames_y)
valid_x_filled = pd.concat(frames_x)
# print(valid_x)
print("=" * 50)
# print(valid_x_filled)

f = open("results.txt", "w+")
f.write('*' * 120 + '\n')

# label encode the target variable
encoder = preprocessing.LabelEncoder()
train_y = encoder.fit_transform(train_y)

f.write('=' * 120 + '\n')
valid_y = encoder.fit_transform(valid_y_filled)

for n in range(48):
    x = encoder.inverse_transform(n)
    f.write(str(n) + " : " + str(x) + "\n")

# create a count vectorizer object
count_vect = CountVectorizer(analyzer='word', token_pattern=r'\w{1,}')
count_vect.fit(pd.concat([trainDF['text'], trainDF_testing['text'], trainDF_filling['text']]))

# transform the training and validation data using count vectorizer object
xtrain_count = count_vect.transform(train_x)
xvalid_count = count_vect.transform(valid_x_filled)
xvalid_count_t = count_vect.transform(trainDF_testing['text'])
# print(xvalid_count_t)

# word level tf-idf
tfidf_vect = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', max_features=5000)
tfidf_vect.fit(pd.concat([trainDF['text'], trainDF_testing['text'], trainDF_filling['text']]))
xtrain_tfidf = tfidf_vect.transform(train_x)
xvalid_tfidf = tfidf_vect.transform(valid_x_filled)
xvalid_tfidf_t = tfidf_vect.transform(trainDF_testing['text'])

# ngram level tf-idf
tfidf_vect_ngram = TfidfVectorizer(analyzer='word', token_pattern=r'\w{1,}', ngram_range=(2, 3), max_features=5000)
tfidf_vect_ngram.fit(pd.concat([trainDF['text'], trainDF_testing['text'], trainDF_filling['text']]))
xtrain_tfidf_ngram = tfidf_vect_ngram.transform(train_x)
xvalid_tfidf_ngram = tfidf_vect_ngram.transform(valid_x_filled)
xvalid_tfidf_ngram_t = tfidf_vect_ngram.transform(trainDF_testing['text'])

# characters level tf-idf
tfidf_vect_ngram_chars = TfidfVectorizer(analyzer='char', token_pattern=r'\w{1,}', ngram_range=(2, 3),
                                         max_features=5000)
tfidf_vect_ngram_chars.fit(pd.concat([trainDF['text'], trainDF_testing['text'], trainDF_filling['text']]))
xtrain_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(train_x)
xvalid_tfidf_ngram_chars = tfidf_vect_ngram_chars.transform(valid_x_filled)
xvalid_tfidf_ngram_chars_t = tfidf_vect_ngram_chars.transform(trainDF_testing['text'])

predict(svm.SVC(gamma=0.001, C=100.), xtrain_count, train_y, xvalid_count_t, "SVM, N-Gram Vectors")
predict(naive_bayes.MultinomialNB(), xtrain_count, train_y, xvalid_count_t, "NB, Count Vectors")
predict(naive_bayes.MultinomialNB(), xtrain_tfidf, train_y, xvalid_tfidf_t, "NB, WordLevel TF-IDF")
predict(naive_bayes.MultinomialNB(), xtrain_tfidf_ngram, train_y, xvalid_tfidf_ngram_t, "NB, N-Gram Vectors")
predict(naive_bayes.MultinomialNB(), xtrain_tfidf_ngram_chars, train_y, xvalid_tfidf_ngram_chars_t, "NB, CharLevel "
                                                                                "Vectors")

predict(linear_model.LogisticRegression(), xtrain_count, train_y, xvalid_count_t, "LR, Count Vectors")
predict(linear_model.LogisticRegression(), xtrain_tfidf, train_y, xvalid_tfidf_t, "LR, WordLevel TF-IDF")
predict(linear_model.LogisticRegression(), xtrain_tfidf_ngram, train_y, xvalid_tfidf_ngram_t, "LR, N-Gram Vectors")
predict(linear_model.LogisticRegression(), xtrain_tfidf_ngram_chars, train_y, xvalid_tfidf_ngram_chars_t, "LR, "
                                                                                "CharLevel "
                                                                                "Vectors")
predict(svm.SVC(), xtrain_tfidf_ngram, train_y, xvalid_tfidf_ngram_t, "SVM, N-Gram Vectors")
predict(ensemble.RandomForestClassifier(), xtrain_count, train_y, xvalid_count_t, "RF, Count Vectors")
predict(ensemble.RandomForestClassifier(), xtrain_tfidf, train_y, xvalid_tfidf_t, "RF, WordLevel TF-IDF")

# Naive Bayes on Count Vectors
accuracy = train_model(naive_bayes.MultinomialNB(), xtrain_count, train_y, xvalid_count)
print("NB, Count Vectors: ", accuracy)

# Naive Bayes on Word Level TF IDF Vectors
accuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf, train_y, xvalid_tfidf)
print("NB, WordLevel TF-IDF: ", accuracy)

# Naive Bayes on Ngram Level TF IDF Vectors
accuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf_ngram, train_y, xvalid_tfidf_ngram)
print("NB, N-Gram Vectors: ", accuracy)

# Naive Bayes on Character Level TF IDF Vectors
accuracy = train_model(naive_bayes.MultinomialNB(), xtrain_tfidf_ngram_chars, train_y, xvalid_tfidf_ngram_chars)
print("NB, CharLevel Vectors: ", accuracy)

# Linear Classifier on Count Vectors
accuracy = train_model(linear_model.LogisticRegression(), xtrain_count, train_y, xvalid_count)
print("LR, Count Vectors: ", accuracy)

# Linear Classifier on Word Level TF IDF Vectors
accuracy = train_model(linear_model.LogisticRegression(), xtrain_tfidf, train_y, xvalid_tfidf)
print("LR, WordLevel TF-IDF: ", accuracy)

# Linear Classifier on Ngram Level TF IDF Vectors
accuracy = train_model(linear_model.LogisticRegression(), xtrain_tfidf_ngram, train_y, xvalid_tfidf_ngram)
print("LR, N-Gram Vectors: ", accuracy)

# Linear Classifier on Character Level TF IDF Vectors
accuracy = train_model(linear_model.LogisticRegression(), xtrain_tfidf_ngram_chars, train_y, xvalid_tfidf_ngram_chars)
print("LR, CharLevel Vectors: ", accuracy)

# SVM on Ngram Level TF IDF Vectors
accuracy = train_model(svm.SVC(), xtrain_tfidf_ngram, train_y, xvalid_tfidf_ngram)
print("SVM, N-Gram Vectors: ", accuracy)

# SVM on Ngram Level TF IDF Vectors (param changed)
accuracy = train_model(svm.SVC(gamma=0.001, C=100.), xtrain_count, train_y, xvalid_count)
print("SVM, N-Gram Vectors Mod: ", accuracy)

# RF on Count Vectors
accuracy = train_model(ensemble.RandomForestClassifier(), xtrain_count, train_y, xvalid_count)
print("RF, Count Vectors: ", accuracy)

# RF on Word Level TF IDF Vectors
accuracy = train_model(ensemble.RandomForestClassifier(), xtrain_tfidf, train_y, xvalid_tfidf)
print("RF, WordLevel TF-IDF: ", accuracy)

# print(predicted_vector)

# for i in predicted_vector:
#     print(encoder.inverse_transform())

try:
    res = statistics.mode(predicted_vector)
except statistics.StatisticsError:
    print('equal no of res found')
    res = predicted_vector[6]

# print(res.split())
for result in res.split():
    result = result.replace(']', '').replace('[','').replace('\'', '')
    i = classes[result]
    print(i)


def count_case(string):
    lower_count = 0
    upper_count = 0

    for char in string:
        if char.islower():

            lower_count = lower_count + 1

        elif char.isupper():

            upper_count = upper_count + 1

    return upper_count, lower_count

user_input = input("Enter a string: ")
upper, lower = count_case(user_input)
print("Upper case count: ", upper)
print("Lower case count: ", lower)


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

import unittest

from pybel import BELGraph
from pybel.constants import *
from pybel_tools.mutation import enrich_pubmed_citations
from tests.constants import ManagerMixin

class TestCitations(ManagerMixin):
    def setUp(self):
        super(TestCitations, self).setUp()

        self.pmid = "9611787"

        g = BELGraph()

        g.add_node(1)
        g.add_node(2)

        g.add_edge(1, 2, attr_dict={
            CITATION: {
                CITATION_TYPE: CITATION_TYPE_PUBMED,
                CITATION_REFERENCE: self.pmid
            }
        })

        self.graph = g

    def test_enrich_overwrite(self):
        citation = self.manager.get_or_create_citation(type=CITATION_TYPE_PUBMED, reference=self.pmid)
        self.manager.session.commit()
        self.assertIsNone(citation.date)
        self.assertIsNone(citation.name)

        enrich_pubmed_citations(self.graph, manager=self.manager)

        _, _, d = self.graph.edges(data=True)[0]
        citation_dict = d[CITATION]

        self.assertIn(CITATION_NAME, citation_dict)

        self.assertIn(CITATION_DATE, citation_dict)
        self.assertEqual('1998-05-01', citation_dict[CITATION_DATE])

        self.assertIn(CITATION_AUTHORS, citation_dict)
        self.assertEqual(
            {'Lewell XQ', 'Judd DB', 'Watson SP', 'Hann MM'},
            set(citation_dict[CITATION_AUTHORS])
        )

    def test_enrich_graph(self):
        enrich_pubmed_citations(self.graph, manager=self.manager)

        _, _, d = self.graph.edges(data=True)[0]
        citation_dict = d[CITATION]

        self.assertIn(CITATION_NAME, citation_dict)

        self.assertIn(CITATION_DATE, citation_dict)
        self.assertEqual('1998-05-01', citation_dict[CITATION_DATE])

        self.assertIn(CITATION_AUTHORS, citation_dict)
        self.assertEqual(
            {'Lewell XQ', 'Judd DB', 'Watson SP', 'Hann MM'},
            set(citation_dict[CITATION_AUTHORS])
        )

if __name__ == '__main__':
    unittest.main()


import json
import numpy as np

def fitness(res, FACTOR=0.7):
    return res[0] * FACTOR + res[1]

def fitness_2(res):
    return 1 / ((res[0] + res[1]) - 2 * abs(res[0] - res[1]))

init = np.array([
    0.0,
    -1.45799022e-12,
    -2.28980078e-13,
    4.62010753e-11,
    -1.75214813e-10,
    -1.83669770e-15,
    8.52944060e-16,
    2.29423303e-05,
    -2.04721003e-06,
    -1.59792834e-08,
    9.98214034e-10
])

with open("./generations.json") as f:
    results = json.load(f)

results = results["results"]

here = []

for x in results:
    # if x["generation"] != 2:
    #     continue
    y = x["vectors"]
    for z in y:
        here.append(z)

here = sorted(here, key=lambda i: fitness(i["results"]))

bests = []

for i in range(60):
    res = here[i]
    bests.append(res)
    x = np.array(res['vector'])
    dist = np.linalg.norm(x-init)
    print(res["results"][0]/1e11, res["results"][1]/1e11, dist)

with open("new_vectors.json", "w") as f:
    json.dump({"vectors": bests}, f)


#!/usr/bin/env python
# coding: utf-8

# In[1]:

## Problem

#Prédire le prix de vente de lots d'un fruit

## Data

#Un dataset contenat des enregistrements de vente d'un fruit

# In[2]:

#Tout d'abord, lisez le fichier fruit_price.csv
import pandas as pd
import numpy as np
import seaborn as sn
import matplotlib.pyplot as plt
df = pd.read_csv('D2FRecrutement/fruit_price/fruit_price.csv')
#J'ai besoin d'observer la structure de la table.
df
#Ce tableau contient les colonnes suivantes:
#Unnamed: 0 : Il s'agit du numéro d'index des données de chaque région，Je n'en ai pas besoin, je peux donc le supprimer
#Date : Ce sont des données très intéressantes, je peux les utiliser, mais je dois les traiter.
#AveragePrice : C'est sont les prix que j'ai besoin d'analyser et de prédire.
#Total Volume, 4046, 4225, 4770, Total Bags,Small Bags,Large Bags,XLarge Bags: des facteurs qu'on peut utiliser.
#type,region: ces sont des variables qualitatives, je peux utiliser One Hot Encoding
#year: year est déjà incluse dans Date

# In[3]:

df.describe()

# In[4]:

#Date
#"Date" est un facteur très utile, mais je ne peux pas l'utiliser directement.
#Puisque nous avons des données de 2015-2018, j'ai converti "Date" en combien de jours se sont écoulés depuis le nouvel an de cette année.
#Cela transformera "date" en une variable quantitative
from datetime import datetime
def date_diff(date):#Il Peut calculer le nombre de jours écoulés depuis le nouvel an
    first_new_year=str(date[0:4])+"-01-01"
    date = datetime.strptime(date, '%Y-%m-%d')
    first_new_year = datetime.strptime(first_new_year, '%Y-%m-%d')
    return (date-first_new_year).days

df['date_newyear_num']=df["Date"].apply(lambda x : date_diff(x))

# Data Visualisation

# In[5]:

#Tout d'abord, je peux utiliser la visualisation des données pour comprendre la relation entre chaque facteur et le prix.
df.plot.scatter(x="Total Volume",y="AveragePrice")
#Ici, je ne vois pas clairement de relation entre le prix et "Total Volume".

# In[6]:

df.plot.scatter(x="Total Bags",y="AveragePrice")
#Je ne vois pas clairement de relation entre le prix et "Total Bags".

# In[7]:

df.groupby('Date')['AveragePrice'].mean().plot(kind='line')
#Je vois que le prix est lié à la "date".

# In[8]:

df.groupby('date_newyear_num')['AveragePrice'].mean().plot(kind='line')

# In[9]:

df.groupby('type')['AveragePrice'].mean().plot(kind='bar')
#Je vois que le prix peut-être lié à la "type".

# In[10]:

df.groupby('year')['AveragePrice'].mean().plot(kind='bar')
#Je ne vois pas clairement de relation entre le prix et "year".

# In[11]:

df.groupby('region')['AveragePrice'].mean().plot(kind='bar')
#Je ne vois pas clairement de relation entre le prix et "region".

# In[12]:

#Construire Une matrice de corrélation
corrMatt = df.corr()
corrMatt

# In[13]:

mask = np.array(corrMatt)
mask[np.tril_indices_from(mask)] = False
fig,ax= plt.subplots()
fig.set_size_inches(15,8)
sn.heatmap(corrMatt, mask=mask,vmax=.8, square=True,annot=True)
#J'utilise Heat Map pour représenter les relations entre divers facteurs et le prix.
#J'ai trouvé que la plupart des facteurs sont liés à "prix", mais ils ne sont pas très pertinents.
#Évidemment, je dois faire des traitements sur les variables.

# Nettoyage de données

# In[14]:

df.count()
#Utilisez la fonction de count() pour déterminer s'il existe des valeurs manquantes
#les résultats montrent qu'il n'y a pas de valeurs manquantes dans les données.

# In[15]:

df.describe()

# In[16]:

df

# In[17]:

#Il ressemble que volume total = 4046 + 4225 + 4770 + Total Bags. Cependant, je dois le vérifier.
re_Total_Volume = pd.DataFrame((df["4046"]+df["4225"]+df["4770"]+df["Total Bags"])-df["Total Volume"])
#J'ai construit une nouvelle dataframe "re_Total_Volume", qui stocke la différence entre la somme de 4046, 4225, 4770, Total Bags et "Total Volume"
re_Total_Volume.describe()#résultat des statistiques

# In[18]:

#Je peux voir qu'il y a pas mal de différences entre les deux. df["4046"]+df["4225"]+df["4770"]+df["Total Bags"] et df["Total Volume"]
#Mais cela peut également être dû à certaines erreurs après avoir arrondi les données.
#Je me concentre donc uniquement sur combien de valeurs dans "re" dont la valeur absolue est supérieure à 1.
re_Total_Volume[(re_Total_Volume[0]> 1) | (re_Total_Volume[0]<-1)]
#Je vois qu'il y a encore des valeurs dans "re" dont la valeur absolue est supérieure à 1.
#Comme je ne sais pas comment le "Volume total" est calculé, j'ai décidé de le garder.

# In[19]:

#Il ressemble que Total Bags = Small Bags+Large Bags+XLarge Bags. Cependant, je dois le vérifier.
re_Total_Bags = pd.DataFrame((df["Small Bags"]+df["Large Bags"]+df["XLarge Bags"])-df["Total Bags"])
#J'ai construit une nouvelle dataframe "re_Total_Bags"
re_Total_Bags.describe()#résultat des statistiques

# In[20]:

re_Total_Bags[(re_Total_Bags[0]> 1) | (re_Total_Bags[0]<-1)]
#Je vois que la valeur absolue de la différence entre "Total Bags" et "Small Bags + Large Bags + XLarge Bags" est toujours inférieure à 1.
#Je pense que cela montre que "Total Bags" est approximativement égal à "Small Bags + Large Bags + XLarge Bags",
#je pense donc que la colonne "Total Bags" peut être supprimée car les informations qu'elle contient sont bien exprimées dans les trois autres colonnes.

# In[21]:

df

# In[22]:

#Pour les trois variables qualitatives "type", "année" et "région", j'utilise One Hot Encoding pour les traiter.
df=pd.get_dummies(df,columns=['type'])
df=pd.get_dummies(df,columns=['year'])
df=pd.get_dummies(df,columns=['region'])

# In[23]:

#Ensuite, j'ai supprimé 'Unnamed: 0', 'Date',"Total Bags" trois colonnes.
df = df.drop(['Unnamed: 0', 'Date','Total Bags'], axis=1)

# In[24]:

df.columns

# Les Valeurs Aberrantes

# In[25]:

#Puisqu'il n'y a pas de valeurs nulles dans les données, j’ai appliqué la méthode des trois écarts-types pour supprimer les Valeurs Aberrantes (Outliers).
outliers=np.abs(df["AveragePrice"]-df["AveragePrice"].mean()) >(3*df["AveragePrice"].std())
outliers = pd.DataFrame(outliers)
outliers_list = outliers.loc[outliers["AveragePrice"]==True]._stat_axis.values.tolist()

# In[26]:

#131 valeurs aberrantes seront supprimées
len(outliers_list)

# In[27]:

df = df.drop(index=outliers_list)

# Plot Kde

# In[28]:

#Il s'agit d'un problème de régression, donc si la valeur cible suit la loi normale, cela fonctionnera bien pour de nombreux modèles.
df['AveragePrice'].plot(kind = 'kde')
#Ce graphique n'est pas une bonne distribution de la loi normale, il peut donc être difficile d'utiliser certains types de modèle linéaire.

# In[29]:

df.to_csv("fruit_price_new.csv")
df

# Machine Learning

# In[30]:

df = pd.read_csv("fruit_price_new.csv", index_col=0)
df

# In[31]:

#Je commence la partie apprentissage automatique, j'utilise "AveragePrice" comme y et tous les autres facteurs comme X
X_feature = [col for col in df.columns.values if col != "AveragePrice"]
y_feature = ["AveragePrice"]
X = df.loc[:,X_feature]
y = df.loc[:,y_feature]

# In[32]:

#Je divise au hasard le dataset en trainset et testset, le rapport 7: 3
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# In[33]:

#Comme je l'ai mentionné précédemment, il peut être difficile d'utiliser certains types de modèle linéaire.
#Par conséquent, j'ai choisi deux méthodes d'apprentissage automatique: Random Forest Regression et Gradient Boosting Regression

from sklearn.model_selection import GridSearchCV
from sklearn import metrics
from sklearn.ensemble import RandomForestRegressor,  GradientBoostingRegressor
from tqdm import *
from math import sqrt
from sklearn.metrics import mean_squared_error, mean_squared_log_error
from sklearn.externals import joblib

# In[34]:

#J'utilise RMSE(root mean square error) et RMSLE(root mean squared logarithmic error) pour évaluer le modèle

def rmsle(y_test, y_pred):
    return np.sqrt(mean_squared_log_error(y_test, y_pred))

def rmse(y_test, y_pred):
    return np.sqrt(mean_squared_error(y_test,y_pred))

# Random Forest Regressor

# In[35]:

#J'utilise GridSearch pour optimiser les hyperparameters
#(je n'ai pas utilisé beaucoup d'hyperparameters en raison des performances limitées de mon ordinateur!!!)
estimator = RandomForestRegressor()
parameters = {
    'min_samples_leaf': [1, 2, 4],
    'min_samples_split': [2, 5, 10],
    'n_estimators': [100, 1000, 2000],
    'random_state' : [0],
    'n_jobs' : [-1]
}
rmsle_scorer = metrics.make_scorer(rmsle, greater_is_better=False)
grid_RFR = GridSearchCV( estimator,
                          param_grid=parameters,
                          scoring = rmsle_scorer,
                          cv=5)

grid_RFR.fit(X=X_train,y=y_train.to_numpy().ravel())

# In[36]:

#Afficher tous les parameters et RMSLE correspondant pour sélectionner les meilleurs parameters
means = grid_RFR.cv_results_['mean_test_score']
params = grid_RFR.cv_results_['params']
for mean,param in zip(means,params):
    print("%f  with:   %r" % (mean,param))
print(grid_RFR.best_params_)
print(grid_RFR.best_score_)

# In[37]:

pre=grid_RFR.predict(X_test)
print('RMSLE：',rmsle(y_test, pre))

# In[38]:

#J'utilise les meilleurs paramètres pour entraîner le modèle
RFR = RandomForestRegressor(min_samples_leaf = grid_RFR.best_params_["min_samples_leaf"],
                            min_samples_split = grid_RFR.best_params_["min_samples_split"],
                            n_estimators = grid_RFR.best_params_["n_estimators"],
                            random_state=0,
                            n_jobs=-1)
RFR.fit(X=X_train,y=y_train.to_numpy().ravel())

# In[39]:

#J'ai utilisé le modèle pour prédire le testset, puis j'ai exprimé les erreurs en utilisant RMSE et RMSLE.
pre=RFR.predict(X_test)
print("RMSE of Random Forest Regression: ", rmse(y_test, pre))
print("RMSLE of Random Forest Regression: ", rmsle(y_test, pre))

# In[40]:

#RMSE 0.1188 RMSLE 0.0487 D'après la figure suivante, il semble que les résultats du modèle sont assez bons.
x_axix = list(range(100))
plt.figure(figsize=(10,8))
plt.title('Random Forest Regression')
plt.plot(x_axix, pre[0:100], color='green', label='Prediction')
plt.plot(x_axix, y_test[0:100], color='red', label='Reality')
plt.xlabel('Sample index')
plt.ylabel('AveragePrice')
plt.show()

# In[41]:

#Enregistrer le modèle "RFR.pkl"
with open('RFR.pkl', 'wb') as f:
    joblib.dump(RFR, 'RFR.pkl')

# Gradient Boosting Regressor

# In[42]:

#J'utilise GridSearch pour optimiser les hyperparameters
#(je n'ai pas utilisé beaucoup d'hyperparameters en raison des performances limitées de mon ordinateur!!!)
estimator = GradientBoostingRegressor()
parameters = {
    'n_estimators':[100,500,1000],
    'learning_rate': [0.1,0.05,0.02],
    'max_depth':[4,3,2],
    'min_samples_leaf':[1,2,3]
}
rmsle_scorer = metrics.make_scorer(rmsle, greater_is_better=False)
grid_GBR = GridSearchCV( estimator,
                          param_grid=parameters,
                          scoring = rmsle_scorer,
                          cv=5)

grid_GBR.fit(X=X_train,y=y_train.to_numpy().ravel())

# In[43]:

#Afficher tous les parameters et RMSLE correspondant pour sélectionner les meilleurs parameters
means = grid_GBR.cv_results_['mean_test_score']
params = grid_GBR.cv_results_['params']
for mean,param in zip(means,params):
    print("%f  with:   %r" % (mean,param))
print(grid_GBR.best_params_)
print(grid_GBR.best_score_)

# In[44]:

pre=grid_GBR.predict(X_test)
print('RMSLE：',rmsle(y_test, pre))

# In[45]:

#J'utilise les meilleurs paramètres pour entraîner le modèle
GBR = GradientBoostingRegressor(n_estimators = grid_GBR.best_params_["n_estimators"],
                               learning_rate = grid_GBR.best_params_["learning_rate"],
                               max_depth = grid_GBR.best_params_["max_depth"],
                               min_samples_leaf = grid_GBR.best_params_["min_samples_leaf"])
GBR.fit(X=X_train,y=y_train)

# In[46]:

#J'ai utilisé le modèle pour prédire le testset, puis j'ai exprimé les erreurs en utilisant RMSE et RMSLE.
pre=GBR.predict(X_test)
print("RMSE of Gradient Boosting Regression: ", rmse(y_test, pre))
print("RMSLE of Gradient Boosting Regression: ", rmsle(y_test, pre))

# In[49]:

#RMSE 0.1142 RMSLE 0.0463 D'après la figure suivante, il semble que les résultats du modèle sont assez bons.
#Et les résultats de Gradient Boosting Regression(RMSE-0.1142,RMSLE-0.0463) sont meilleurs que les résultats de Random Forest Regression(RMSE-0.1188,RMSLE-0.0487)
#donc le meilleur modèle que j'ai obtenu est Gradient Boosting Regression
x_axix = list(range(100))
plt.figure(figsize=(10,8))
plt.title('Gradient Boosting Regression')
plt.plot(x_axix, pre[0:100], color='green', label='Prediction')
plt.plot(x_axix, y_test[0:100], color='red', label='Reality')
plt.xlabel('Sample index')
plt.ylabel('AveragePrice')
plt.show()

# In[48]:

#Enregistrer le modèle "GBR.pkl"
with open('GBR.pkl', 'wb') as f:
    joblib.dump(GBR, 'GBR.pkl')

# Les facteurs les plus importantes

# In[50]:

#Charger le modèle "GBR.pkl"
GBR = joblib.load("GBR.pkl")

# In[51]:

#le classement de l'influence de divers facteurs sur le prix.
indies = np.argsort(GBR.feature_importances_, kind='heapsort')[::-1]
for index in indies:
    print({X_feature[index]:GBR.feature_importances_[index]})

# In[ ]:


#!/usr/bin/env python3
import os
import sys
sys.path.append('../_optimization_model/_rl_model')
sys.path.append('../../_optimization_model/_rl_model')
from env import *

outfile = "observations-vracer-{}-t-{}.json".format(run, target)
resultdir = "_korali_result_{}-t-{}".format(run, target)

####### Defining Korali Problem

envp = lambda s : env(s,target)

import korali
k = korali.Engine()
e = korali.Experiment()

found = e.loadState(resultdir + '/latest')
if (found == True):
  print('Continuing execution from latest...')

### Defining the Cartpole problem's configuration
e["Problem"]["Type"] = "Reinforcement Learning / Continuous"
e["Problem"]["Environment Function"] = envp
e["Problem"]["Training Reward Threshold"] = 498
e["Problem"]["Policy Testing Episodes"] = 25
e["Problem"]["Testing Frequency"] = 100

e["Variables"][0]["Name"] = "Cart Position"
e["Variables"][0]["Type"] = "State"

e["Variables"][1]["Name"] = "Cart Velocity"
e["Variables"][1]["Type"] = "State"

e["Variables"][2]["Name"] = "Pole Angle"
e["Variables"][2]["Type"] = "State"

e["Variables"][3]["Name"] = "Pole Angular Velocity"
e["Variables"][3]["Type"] = "State"

e["Variables"][4]["Name"] = "Force"
e["Variables"][4]["Type"] = "Action"
e["Variables"][4]["Lower Bound"] = -10.0
e["Variables"][4]["Upper Bound"] = +10.0
e["Variables"][4]["Initial Exploration Noise"] = 1.0

### Defining Agent Configuration

e["Solver"]["Type"] = "Agent / Continuous / VRACER"
e["Solver"]["Mode"] = "Training"
e["Solver"]["Experiences Between Policy Updates"] = 1
e["Solver"]["Episodes Per Generation"] = 1

### Defining the configuration of replay memory

e["Solver"]["Experience Replay"]["Start Size"] =   2048
e["Solver"]["Experience Replay"]["Maximum Size"] = 32768

## Defining Neural Network Configuration for Policy and Critic into Critic Container

e["Solver"]["Discount Factor"] = 0.99
e["Solver"]["Learning Rate"] = 1e-4
e["Solver"]["L2 Regularization"]["Enabled"] = True
e["Solver"]["L2 Regularization"]["Importance"] = 1e-4
e["Solver"]["Mini Batch"]["Size"] = 32

e["Solver"]["State Rescaling"]["Enabled"] = True
e["Solver"]["Reward"]["Rescaling"]["Enabled"] = False
e["Solver"]["Reward"]["Rescaling"]["Frequency"] = 0

### Configuring the neural network and its hidden layers

e["Solver"]["Neural Network"]["Engine"] = "OneDNN"
e["Solver"]["Neural Network"]["Optimizer"] = "Adam"

e["Solver"]["Neural Network"]["Hidden Layers"][0]["Type"] = "Layer/Linear"
e["Solver"]["Neural Network"]["Hidden Layers"][0]["Output Channels"] = 32

e["Solver"]["Neural Network"]["Hidden Layers"][1]["Type"] = "Layer/Activation"
e["Solver"]["Neural Network"]["Hidden Layers"][1]["Function"] = "Elementwise/Tanh"

e["Solver"]["Neural Network"]["Hidden Layers"][2]["Type"] = "Layer/Linear"
e["Solver"]["Neural Network"]["Hidden Layers"][2]["Output Channels"] = 32

e["Solver"]["Neural Network"]["Hidden Layers"][3]["Type"] = "Layer/Activation"
e["Solver"]["Neural Network"]["Hidden Layers"][3]["Function"] = "Elementwise/Tanh"

### Defining Termination Criteria

e["Solver"]["Termination Criteria"]["Testing"]["Target Average Reward"] = 100
e["Solver"]["Termination Criteria"]["Max Generations"] = 5000

### Setting file output configuration

e["File Output"]["Enabled"] = True
e["File Output"]["Frequency"] = 1000
e["File Output"]["Path"] = resultdir

### Running Experiment

e["Problem"]["Custom Settings"]["Record Observations"] = "False"

if found == False:
    k.run(e)

### Recording Observations

print('[Korali] Done training. Now running learned policy to produce observations.')

### Now testing policy, dumping trajectory results

e["Solver"]["Mode"] = "Testing"
e["Solver"]["Testing"]["Sample Ids"] = [i for i in range(10)]
e["Problem"]["Custom Settings"]["Output"] = outfile
e["Problem"]["Custom Settings"]["Record Observations"] = "True"

k.run(e)

print("[Korali] Finished testing.")


#! /usr/bin/env python3
import argparse, sys, os, errno
import logging
from tqdm import tqdm
import time
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] [%(levelname)s] %(name)s: %(message)s')

def progress_bar(length,frequency):
    for i in tqdm(range(length)):
        time.sleep(1/frequency)

#✧(≖ ◡ ≖✿)
def dayspan(args):
    import datetime
    today = datetime.date.today()
    frequency=args.frequency
    if args.dayspan:
        logger.info('calculate day span since love')
        dayspan = daysBetweenDates(2013, 2, 14, today.year, today.month, today.day)
        progress_bar(dayspan,frequency)
        print ('Daidai & Duoduo have been together for: '+str(dayspan)+' Days ^_^~'+'\n'+
        'Congratulations to this affectionate couple!')

        logger.info('calculate day span since first photograph')
        dayspan = daysBetweenDates(2012, 9, 26, today.year, today.month, today.day)
        progress_bar(dayspan,frequency)
        print ('It has been '+str(dayspan)+' Days' +' since Daidai Took the First Picture of Duoduo ⁄(⁄ ⁄•⁄ω⁄•⁄ ⁄)⁄'+'\n'+
        'What a Romantic Man Daidai is.')

        logger.info('calculate day span since first travel')
        dayspan = daysBetweenDates(2014, 6, 10, today.year, today.month, today.day)
        progress_bar(dayspan,frequency)
        print ('It has been '+str(dayspan)+' Days' +' since Daidai Took the First Trip with Duoduo O(∩_∩)O~~'+'\n'+
        'The Journey across China is Beautiful and Remembering.')

        dayspan = daysBetweenDates(2018, 8, 6, today.year, today.month, today.day)
        progress_bar(dayspan,frequency)

#	logger.info('calculate day span since meng meng came to the world as a pig')
 #       dayspan = daysBetweenDates(1996, 8, 6, today.year, today.month, today.day)
  #      progress_bar(dayspan,frequency)
   #     print ('It has been '+str(dayspan)+' Days' +' since Duoduo came to the world O(∩_∩)O~~'+'\n')

def isBigMonth(month):
    bigMonth = [1,3,5,7,8,10,12]
    if (month in bigMonth):
        return True
    else:
        return False
def isLeapYear(year):
    if((year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)):
        return True
    else:
        return False
def validateDate(year1, month1, day1, year2, month2, day2):
    if(year1 < year2):
        return True
    elif(year1 == year2):
        if(month1 < month2):
            return True
        elif(month1 == month2):
            if(day1 < day2):
                return True
    else:
        return False
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    days = 0
    yearCount = year1
    monthCount = month1
    dayCount = day1
    while(validateDate(yearCount, monthCount, dayCount, year2, month2, day2)):
        days += 1
        if(monthCount == 12 and dayCount == 31):
            monthCount = 1
            dayCount = 0
            yearCount += 1
        if(isLeapYear(yearCount) and monthCount == 2):
            if(dayCount == 29):
                dayCount = 1
                monthCount += 1
            else:
                dayCount += 1
        elif(isLeapYear(yearCount) != True and monthCount == 2):
            if(dayCount == 28):
                dayCount = 1
                monthCount += 1
            else:
                dayCount += 1
        elif(monthCount != 2):
            if(isBigMonth(monthCount)):
                if(dayCount == 31):
                    dayCount = 1
                    monthCount += 1
                else:
                    dayCount += 1
            elif(isBigMonth(monthCount) == False):
                if(dayCount == 30):
                    dayCount = 1
                    monthCount += 1
                else:
                    dayCount += 1
    return days

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Love for Duoduo Last Forever Module')

    parser.add_argument('--dayspan', '-d', type=str,default='1',
        help='if print the day span since we fell in love')
    parser.add_argument('--frequency', '-f', type=float, default=5000,
        help='display frequency')
    args = parser.parse_args()

    logger = logging.getLogger('Love for Duoduo Last Forever Module')

    dayspan(args)


# coding:utf-8
import time
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

class Base(object):

    def __init__(self, driver):
        """
        初始函数中的变量类中任何方法都可以调用
        :param driver:
        :return:
        """
        self.driver = driver
        self.url = "http://wf74.uf-tobacco.com/sso-webapp/login"

        self.timeout = 20
        self.frequency = 0.5

        self.login_books_select = (By.ID, "dropdown-select")  # 登录页面账套

        self.open_bill_search = (By.ID, "keywordsearch")  # 首页那个搜一搜元素
        self.open_bill_select = (By.XPATH, "//li[@class='ui-menu-item']/a")  # 搜一搜下拉第一条
        self.new_button = (By.ID, "btn_add")  # 所有单据上的新增按钮，要是有个不是就傻逼了。
        self.bill_product = (By.ID, "pk_product")  # 单据上产品字段

    def findelement(self, locator):
        """
        查找某个特定元素
        :param locator:此处为元祖，第一个为找元素的的方式，如By.ID ,第二个为关键字
        :return:这个元素
        """
        # presence_of_element_located 用来检验这个元素是否存在
        try:
            ele = WebDriverWait(self.driver, self.timeout, self.frequency).until(
                EC.presence_of_element_located(locator))
            return ele
        except:
            return False

    def findelements(self, locator):
        """
        查找一组元素
        :param locator: 此处为元祖，第一个为找元素的的方式，如By.ID ,第二个为关键字
        :return: 这组元素
        """
        ele = WebDriverWait(self.driver, self.timeout, self.frequency).until(lambda x: x.find_elements(*locator))
        return ele

    def openurl(self):
        """
        打开客户反馈平台系统
        :return:
        """
        self.driver.get(self.url)
        self.driver.maximize_window()

    def sendkeys(self, locator, text):
        """
        输入字符串
        :param locator: 此处为元祖，第一个为找元素的的方式，如By.ID ,第二个为关键字
        :param text: 输入的字符
        :return:
        """
        ele = self.findelement(locator)
        ele.send_keys(text)

    def sendkeyss(self, locator, text):
        """
        输入字符串，针对所定位元素为一组中最新的一个
        :param locator: 此处为元祖，第一个为找元素的的方式，如By.ID ,第二个为关键字
        :param text: 输入的字符
        :return:
        """
        ele = self.findelements(locator)[-1]
        ele.send_keys(text)

    def click(self, locator):
        """
        点击某元素
        :param locator: 此处为元祖，第一个为找元素的的方式，如By.ID ,第二个为关键字
        :return:
        """
        ele = self.findelement(locator)
        if ele:
            ele.click()
        else:
            pass

    def clicks(self, locator):
        """
        点击某元素，该元素被定位出一组中最新的那个
        :param locator:
        :return:
        """
        ele = self.findelements(locator)[-1]
        ele.click()

    def select_dropdown(self, locator=(By.ID, "dropdown-select"), value="1001"):
        """

        :param locator: 下拉框元素位置
        :param value: 下拉框所要选中的value值
        :return:
        """
        s = self.findelement(locator)
        Select(s).select_by_value(value)

    def open_bill(self, billword):
        """
        通过搜索打开单据
        :param billword: 单据名字
        :return:
        """
        self.findelement(self.open_bill_search).send_keys(billword)
        self.findelement(self.open_bill_select).click()

    def add_bill(self):
        """
        单据新增操作
        :return:
        """
        self.findelement(self.new_button).click()

    def search_todolist_info(self, search_todo_key):
        """
        首页代办搜索
        :param search_todo_key: 搜索的关键字
        :return:
        """
        keyword_box = (By.XPATH, ".//*[text()='输入关键字搜索	']")
        keyword_input_box = (By.ID, "search-keyword")
        keyword_magnifier = (By.XPATH, ".//*[@onclick='searchByKeyWork(this)']")

        time.sleep(2)
        self.findelement(keyword_box).click()
        self.findelement(keyword_input_box).send_keys(search_todo_key)
        self.findelement(keyword_magnifier).click()
        time.sleep(3)
        self.driver.find_element_by_xpath(".//a[contains(@data-content,'%s')]" % search_todo_key).click()

    def switch_to_listframe(self):
        """
        切换到listfram下
        :return:
        """
        time.sleep(2)
        all_handle = self.driver.window_handles
        self.driver.close()
        self.driver.switch_to_window(all_handle[-1])
        time.sleep(1)
        self.driver.switch_to_frame("iframemain")
        self.driver.switch_to_frame("list")
        time.sleep(2)

    def list_to_cardframe(self):
        self.driver.switch_to.default_content()
        self.driver.switch_to.frame("iframemain")
        self.driver.switch_to.frame("card")

    def switch_to_cardframe(self):
        """
        切换到card frame下
        :return:
        """
        time.sleep(2)
        all_handle = self.driver.window_handles
        self.driver.close()
        self.driver.switch_to_window(all_handle[-1])
        time.sleep(1)
        self.driver.switch_to_frame("iframemain")
        self.driver.switch_to_frame("card")
        time.sleep(2)

    def is_element_exit(self, locator):
        ele = self.findelement(locator)
        if ele:
            return True
        else:
            return False

    def js_ele_scrollview(self, locator):
        """
        通过js让浏览器滚动到该元素可见区域
        :param locator:
        :return:
        """
        target = self.findelement(locator)
        self.driver.execute_script("arguments[0].scrollIntoView();", target)

    def js_click_byclassname(self, eleinfo):
        """
        通过元素classname找到元素进行js点击
        :param eleinfo:
        :return:
        """
        js = "document.getElementsByClassName('%s')[0].click()" % eleinfo
        self.driver.execute_script(js)

    # def js_click_byxpath(self, xpathinfo):
    #     """
    #     js中通过xpth 定位元素，其中document.evaluate返回xpthresult，iterateNext() 方法返回和一个 XPath 查询匹配的下一个节点。
    #     :param xpathinfo: 所定位元素的xpth
    #     :return:
    #     """
    #     js = '''
    #                           var xresult = document.evaluate\
    #                           (%s, document, null, XPathResult.ANY_TYPE, null);
    #                           var xnodes = [];
    #                           var xres;
    #                           while (xres = xresult.iterateNext()) {
    #                               xnodes.push(xres);
    #                           }
    #                           xnodes[0].click();
    #                      ''' % xpathinfo
    #     self.driver.execute_script(js)

    # js_scroll_totop，js_scroll_tobottom 都是针对非内嵌div的。如果是内嵌了div 就要定位到div 然后用scrollTop
    # 例：js = 'document.getElementsByClassName("scroll")[0].scrollTop=10000'

    # 例：js = 'document.getElementsByClassName("scroll")[0].scrollLeft=10000'

    def js_scroll_totop(self):
        """
        通过js移动滚动条到最上面
        :return:
        """
        js = "window.scrollTo(0,0)"
        self.driver.execute_script(js)

    def js_scroll_tobottom(self):
        """
        通过js 移动滚动条到最底部
        :return:
        """
        js = "window.scrollTo(0,document.body.scrollHeight"
        self.driver.execute_script(js)

if __name__ == "__main__":
    from selenium import webdriver

    driver = webdriver.Firefox()
    test_driver = Base(driver)
    test_driver.openurl()
    test_driver.login_sys("linhr", "1")
    test_driver.search_todolist_info("请对产品")
    driver.quit()
    driver = webdriver.Firefox()
    test_driver = Base(driver)
    test_driver.openurl()
    test_driver.login_sys("linhr", "1")
    test_driver.open_bill("项目需求填报单")
    test_driver.switch_to_listframe()
    test_driver.add_bill()
    test_driver.list_to_cardframe()


import gc
import os
import sys

from pytype.pyi import parser
from pytype.pytd import pytd
import six

import unittest

def get_builtins_source(python_version):
  filename = "builtins/%d/__builtin__.pytd" % python_version[0]
  pytd_dir = os.path.dirname(pytd.__file__)
  with open(os.path.join(pytd_dir, filename)) as f:
    return f.read()

class MemoryLeakTest(unittest.TestCase):

  PYTHON_VERSION = (2, 7)

  def check(self, src):
    def parse():
      try:
        parser.parse_string(src, python_version=self.PYTHON_VERSION)
      except parser.ParseError:
        if six.PY2:
          # It is essential to clear the error, otherwise the system exc_info
          # will hold references to lots of stuff hanging off the exception.
          # This happens only in Python2.
          sys.exc_clear()

    # Sometimes parsing has side effects that are long-lived (lazy
    # initialization of shared instances, etc).  In order to prevent these
    # from looking like leaks, parse the source twice, using the gc objects
    # after the first pass as a baseline for the second pass.
    parse()
    gc.collect()
    before = gc.get_objects()
    parse()
    gc.collect()
    after = gc.get_objects()

    # Determine the ids of any leaked objects.
    before_ids = {id(x) for x in before}
    after_map = {id(x): x for x in after}
    leaked_ids = set(after_map) - before_ids
    leaked_ids.discard(id(before))
    if not leaked_ids:
      return

    # Include details about the leaked objects in the failure message.
    lines = ["Detected %d leaked objects" % len(leaked_ids)]
    for i in leaked_ids:
      obj = after_map[i]
      detail = str(obj)
      if len(detail) > 50:
        detail = detail[:50] + "..."
      lines.append("  <%s>  %s" % (type(obj).__name__, detail))
    self.fail("\n".join(lines))

  def test_builtins(self):
    # This has a little of everything.
    self.check(get_builtins_source(self.PYTHON_VERSION))

  def test_error_in_class(self):
    self.check("""\
      class Foo:
        def m(): pass
        an error""")

  def test_error_in_function(self):
    self.check("""\
      def m(): pass
      def n(x: int, y: str) -> ->
      """)

  def test_error_within_if(self):
    self.check("""\
      if sys.version_info == (1, 2, 3):
        x = ...  # type: int
        this is an error
      """)

if __name__ == "__main__":
  unittest.main()


'''
IBEHS 1P10 Mini Milestone 11 Main File

Team Number: 76

Name: Owen Johnstone

Date: Feb. 25, 2020
'''
import matplotlib.patches as patches
import math
import matplotlib.pyplot as plt

""" GIVEN Functions """
## This function creates 6" x 6" graphics window
## The functional workspace is created within this window
def functional_workspace():
    fig, ax = plt.subplots(1,1,figsize=(6,6))
    rect = patches.Rectangle((-15,-15),30,30,angle=0.0,fill = False, ls = '--', color = 'r',linewidth=1.5)
    ax.add_patch(rect)
    plt.xlim((-45,45))
    plt.ylim((-45,45))
    ax.set(title='Forefinger-Thumb Path',
            xlabel = 'X (mm) ',
            ylabel = 'Y (mm) ')

##Student ID: 400242374
def forefinger_position(degree_of_increments):
    forefinger_length= 36
    position_list= []

    for angle in range(0, 91, int(degree_of_increments)):
        xcoordinates= -(forefinger_length*math.cos(math.radians(angle)))
        ycoordinates= 36 - forefinger_length*math.sin(math.radians(angle))
        position_list.append([xcoordinates, ycoordinates])
    return position_list

##Student ID: 400268572
def thumb_position(num_inc):
    thumb_length = 42
    coordinate_list = []

    for angle in range(0,91,int(num_inc)):
        x_coordinate = 42 - thumb_length * math.sin(math.radians(angle))
        y_coordinate = -thumb_length * math.cos(math.radians(angle))
        coordinate_list.append([x_coordinate, y_coordinate])

    return coordinate_list

##Student ID: 400242374
def write_lists(file_name, list1, list2):
    length_of_list1= float(len(list1))
    length_of_list2= float(len(list2))
    if length_of_list1 == length_of_list2:
        with open(file_name, "w") as file:
            for i in range(len(list1)):
                file.write(str(list1[i])+"\t"+str(list2[i])+"\n")
    else:
        print("The lengths of the two lists are not equal.")

##Student ID: 400268572
def append_array(text_file, data_array):
    with open(text_file, 'a') as txt:
        for item in data_array:
            txt.write(str(item[0]) + '\t' + str(item[1]) + '\n')

##Student ID: 400242374
def plot_forefinger():
    number_of_increments=int(input("Enter a value for the number of increments."))
    while 90 % number_of_increments != 0:
        print("The number you enetered is not go into 90 evenly. Try another number.")
        number_of_increments= int(input("Enter a value for the number of increments."))

    functional_workspace()
    data_list= forefinger_position(number_of_increments)
    for element in range(len(data_list)):
        x_cd= data_list[element][0]
        y_cd= data_list[element][1]
        plt.scatter(x_cd,y_cd)
    plt.show()

##Student ID: 400268572
def plot_thumb():
    num_inc = int(input('Enter the number of degrees to increment by: '))

    while 90 % num_inc != 0:
        print('Please enter a number of degrees that evenly divides into 90.')
        num_inc = int(input('Enter the number of degrees to increment by: '))

    functional_workspace()
    data_list = thumb_position(num_inc)

    for i in range(len(data_list)):
        x_cd = data_list[i][0]
        y_cd = data_list[i][1]

        plt.scatter(x_cd, y_cd, c='r')
    plt.show()

##Main Function
def main():
    inc_num = int(input('Please enter the number of degrees to increment by: '))

    while 90 % inc_num != 0:
        print('Please enter a number of degrees that evenly divides into 90.')
        inc_num = int(input('Enter the number of degrees to increment by: '))

    functional_workspace()
    thumb_pos  = thumb_position(inc_num)
    finger_pos = forefinger_position(inc_num)

    thumb_x_list = []
    forefinger_x_list = []

    thumb_y_list = []
    forefinger_y_list = []

    for i in range(len(thumb_pos)):
        thumb_x = thumb_pos[i][0]
        thumb_x_list.append(round(thumb_x, 2))

        thumb_y = thumb_pos[i][1]
        thumb_y_list.append(round(thumb_y, 2))

        finger_x = finger_pos[i][0]
        forefinger_x_list.append(round(finger_x, 2))

        finger_y = finger_pos[i][1]
        forefinger_y_list.append(round(finger_y, 2))

        plt.scatter(thumb_x, thumb_y)
        plt.scatter(finger_x, finger_y)

    plt.show()

    x_coordinates = thumb_x_list + forefinger_x_list
    y_coordinates = thumb_y_list + forefinger_y_list

    write_lists('Objective3.txt', x_coordinates, y_coordinates)
    append_array('Objective4.txt', finger_pos)
    append_array('Objective4.txt', thumb_pos)

main()


from programmingPatterns.webElement import ConcreteWebElementBuilder
from programmingPatterns.director import WebDirector, labelUpdate, buttonClick

if __name__ == "__main__":

    builder = ConcreteWebElementBuilder()
    director = WebDirector(builder)

    director.make_label()
    label = builder.product.printParts()
    assert label == {'text': 'I am <label>', 'visibility': True, 'action': ('updated', labelUpdate)}, "Неправильно создан элемент label"

    director.make_button()
    button = builder.product.printParts()
    assert button == {'height': 30, 'width': 120, 'visibility': True, 'text': 'I am <button>', 'action': ('clicked', buttonClick)}, "Неправильно создан элемент button"

    director.make_link()
    link = builder.product.printParts()
    assert link == {'text': 'I am <a>', 'visibility': True, 'link': 'https://smth.com'}, "Неправильно создан элемент link"

    director.make_radioButton()
    radioButton = builder.product.printParts()
    assert radioButton == {'text': 'I am <radio>', 'connectivity': True, 'mainElement': 'previousElem', 'visibility': True}, "Неправильно создан элемент radioButton"


# -*- coding: utf-8 -*-
#feeds.py
from bottle import run,route,template,request,debug,\
	static_file,default_app,post,get,redirect
from feedsdb import FeedsDb
import feedparser
import helper
import os, sys

config=None #default_app().config.load_config('feeds.conf')

@route('/')
@route('/feeds')
@route('/feeds/')
def index():
	redirect('/feeds/1')

#view a rss site news list
@route('/feeds/<feeds_id:int>')
def feeds_detail(feeds_id):
	db = FeedsDb(config)
	title = db.fetch(feeds_id)
	rows = None
	if title:
		d = feedparser.parse(title[2])
		rows = d.entries

	feed_list=db.fetch_all_feeds()

	#db.addentries(rows)
	return template('index', t_rows = rows, t_feedlist = feed_list, t_feeds_id = feeds_id)

#add a new rss site
@post('/feeds/add')
def add_feeds():
	result = True
	message = ""
	url = request.forms.get('url').strip()
	d = feedparser.parse(url)
	db = FeedsDb(config)
	#check exist?
	if db.fetch_by_url(url) > 0:
		result = False
		message = "Feeds has already added,add another one"
	else:
		result = db.addfeeds(d.feed.title,url)
		if result:
			message = "Feeds is added successfully"
		else:
			message = "Error happended when add Feeds"
	return {'result':result,'message':message}

@post('/feeds/valid')
def valid_url():
	url = request.forms.get('url').strip()
	if helper.check_url(url):
		return {'result':True}
	else:
		return {'result':False}

	d = feedparser.parse(url)

	if ('status' in d ) and d.status == 200:
		return {'result':True}
	else:
		return {'result':False}

@get('/feeds/list')
def get_list():
	db = FeedsDb(config)
	feed_list=db.fetch_all_feeds()
	return template('list', t_feedlist = feed_list)

@post('/feeds/delete')
def delete_feeds():
	feeds_id = request.forms.get('id').strip();

	result = False
	db = FeedsDb(config)
	result = db.delete_feeds(int(feeds_id))
	return {'result':result}

#routing static file like css,js,pic

@route('/static/<filename:path>')
def server_static(filename):
	return static_file(filename,root='./static')

@route('/favicon.ico')
def icon_static():
	return static_file('favicon.ico',root='./static')

#running the app
#debug(True)
run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))


# !/usr/bin/env python
# encoding: utf-8
"""
:copyright (c) 2014 - 2018, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Department of Energy) and contributors.
All rights reserved.  # NOQA
:author
"""

import csv
import datetime

from django.http import JsonResponse, HttpResponse
from quantityfield import ureg
from rest_framework.decorators import list_route
from rest_framework.renderers import JSONRenderer
from rest_framework.viewsets import GenericViewSet

from seed.decorators import ajax_request_class
from seed.lib.superperms.orgs.decorators import has_perm_class
from seed.models import (
    Column,
    PropertyView,
    TaxLotProperty,
    TaxLotView,
)
from seed.serializers.tax_lot_properties import (
    TaxLotPropertySerializer
)
from seed.utils.api import api_endpoint_class

INVENTORY_MODELS = {'properties': PropertyView, 'taxlots': TaxLotView}

class TaxLotPropertyViewSet(GenericViewSet):
    """
    The TaxLotProperty field is used to return the properties and tax lots from the join table.
    This method presently only works with the CSV, but should eventually be extended to be the
    viewset for any tax lot / property join API call.
    """
    renderer_classes = (JSONRenderer,)
    serializer_class = TaxLotPropertySerializer

    @api_endpoint_class
    @ajax_request_class
    @has_perm_class('requires_member')
    @list_route(methods=['POST'])
    def csv(self, request):
        """
        Download a csv of the TaxLot and Properties

        .. code-block::

            {
                    "ids": [1,2,3],
                    "columns": ["tax_jurisdiction_tax_lot_id", "address_line_1", "property_view_id"]
            }

        ---
        parameter_strategy: replace
        parameters:
            - name: cycle
              description: cycle
              required: true
              paramType: query
            - name: inventory_type
              description: properties or taxlots (as defined by the inventory list page)
              required: true
              paramType: query
            - name: ids
              description: list of property ids to export (not property views)
              required: true
              paramType: body
            - name: columns
              description: list of columns to export
              required: true
              paramType: body
            - name: filename
              description: name of the file to create
              required: false
              paramType: body

        """
        cycle_pk = request.query_params.get('cycle_id', None)
        if not cycle_pk:
            return JsonResponse(
                {'status': 'error', 'message': 'Must pass in cycle_id as query parameter'})
        columns = request.data.get('columns', None)
        if columns is None:
            # default the columns for now if no columns are passed
            columns = Column.retrieve_db_fields(request.query_params['organization_id'])

        # get the class to operate on and the relationships
        view_klass_str = request.query_params.get('inventory_type', 'properties')
        view_klass = INVENTORY_MODELS[view_klass_str]

        # Grab all the columns and create a column name lookup
        col_inventory_type = 'property' if view_klass_str == 'properties' else 'taxlot'
        columns_db = Column.retrieve_all(request.query_params['organization_id'], col_inventory_type, False)
        column_lookup = {}
        db_column_name_lookup = {}
        column_related_lookup = {}
        for c in columns_db:
            column_lookup[c['name']] = c['display_name']
            db_column_name_lookup[c['name']] = c['column_name']
            column_related_lookup[c['name']] = c['related']

        # add a couple of other Display Names
        column_lookup['notes_count'] = 'Notes Count'
        column_lookup['id'] = 'ID'

        # make the csv header
        header = []
        for c in columns:
            if c in column_lookup:
                header.append(column_lookup[c])
            else:
                header.append(c)

        select_related = ['state', 'cycle']
        ids = request.data.get('ids', [])
        filter_str = {'cycle': cycle_pk}
        if hasattr(view_klass, 'property'):
            select_related.append('property')
            filter_str = {'property__organization_id': request.query_params['organization_id']}
            if ids:
                filter_str['property__id__in'] = ids
            # always export the labels
            columns += ['property_labels']
            header.append('Property Labels')

        elif hasattr(view_klass, 'taxlot'):
            select_related.append('taxlot')
            filter_str = {'taxlot__organization_id': request.query_params['organization_id']}
            if ids:
                filter_str['taxlot__id__in'] = ids
            # always export the labels
            columns += ['taxlot_labels']
            header.append('Tax Lot Labels')

        model_views = view_klass.objects.select_related(*select_related).filter(**filter_str).order_by('id')

        filename = request.data.get('filename', "ExportedData.csv")
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        writer = csv.writer(response)

        # get the data in a dict which includes the related data
        data = TaxLotProperty.get_related(model_views, db_column_name_lookup.values(), columns_db)

        # force the data into the same order as the IDs
        if ids:
            order_dict = {obj_id: index for index, obj_id in enumerate(ids)}
            data.sort(key=lambda x: order_dict[x['id']])  # x is the property/taxlot object

        # note that the labels are in the property_labels column and are returned by the
        # TaxLotProperty.get_related method.

        # header
        writer.writerow(header)

        # iterate over the results to preserve column order and write row.
        for datum in data:
            row = []
            for column in columns:
                row_result = None

                if column in column_related_lookup and column_related_lookup[column]:
                    # this is a related column, grab out of the related section
                    if datum.get('related'):
                        row_result = datum['related'][0].get(column, None)
                else:
                    row_result = datum.get(column, None)

                # Convert quantities (this is typically handled in the JSON Encoder, but that isn't here).
                if isinstance(row_result, ureg.Quantity):
                    row_result = row_result.magnitude
                elif isinstance(row_result, datetime.datetime):
                    row_result = row_result.strftime("%Y-%m-%d %H:%M:%S")
                elif isinstance(row_result, datetime.date):
                    row_result = row_result.strftime("%Y-%m-%d")
                row.append(row_result)

            writer.writerow(row)

        return response


from datetime import date

MAIN_PAGES = []

def preBuildPage(site, page, context, data):

	if "sitemap.xml" == page.path:
		context['now'] = date.today().strftime("%Y-%m-%d")
		#context['URI'] = "http://www.example.com/"

	return context, data


from dotenv import load_dotenv
load_dotenv()

from ciphers import encrypt_aes, decrypt_aes, decrypt_json
import base64

from db import connect, migrate, connection, insert_key, get_key, delete_key

if connect() is False:
    print('Database failed to connect')
else:
    migrate()

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

@app.route('/', methods=['GET'])
def show_form():
    return render_template("index.html")

@app.route('/key', methods=['GET'])
def create_keys():
    from ciphers import create_rsa_key_pair
    private_key, public_key = create_rsa_key_pair()

    # Store private key
    key_id = insert_key(private_key)

    return jsonify(
        id=key_id,
        public_key=public_key
    )

@app.route('/decrypt', methods=['POST'])
def decrypt_message():
    json = request.get_json()

    # Retrieve private key
    private_key = get_key(json['id'])

    # Decrypt payload
    message = decrypt_json(private_key, json['message'])

    # Delete private key
    delete_key(json['id'])

    return jsonify(
        message=message.decode("utf-8"),
    )

if __name__ == "__main__":
    app.run(debug=True)


# -*- coding: utf-8 -*-
import pandas as pd
import os
import numpy as np
from sklearn.preprocessing import LabelEncoder

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, recall_score, precision_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV

from sklearn.ensemble import BaggingClassifier, AdaBoostClassifier, RandomForestClassifier, VotingClassifier, GradientBoostingClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression

from mlens.ensemble import SuperLearner

# Function responsible for checking our model's performance on the test data
def testSetResultsClassifier(classifier, x_test, y_test, model_name =''):
    predictions = classifier.predict(x_test)

    results = []
    f1 = f1_score(y_test, predictions)
    precision = precision_score(y_test, predictions)
    recall = recall_score(y_test, predictions)
    roc_auc = roc_auc_score(y_test, predictions)
    accuracy = accuracy_score(y_test, predictions)

    results.append(f1)
    results.append(precision)
    results.append(recall)
    results.append(roc_auc)
    results.append(accuracy)

    print("\n\n#---------------- Test set results ({}) ----------------#\n".format(model_name))
    print("F1 score, Precision, Recall, ROC_AUC score, Accuracy:")
    print(results)

    return results

def saveResult(model, X_test, output='results.csv'):
    """
    CHOOSE MODEL AND SAVE RESULTS
    """
    res = (model.predict(X_test)).astype(int)
    pdResult = pd.DataFrame(list(zip(passId, res)), columns=['PassengerId', 'Survived'])

    pdResult.to_csv(output, index=False)
    print("saved {} rows".format(pdResult.shape[0]))

def encodeColumns(df,categorical_cols):
    """
    LABEL ENCODER
    """

    le = LabelEncoder()
    return df[categorical_cols].apply(lambda col: le.fit_transform(col))

def alterColumns(df):
    df = df.drop(['PassengerId', 'Cabin', 'Name', 'Ticket'], axis=1)

    categorical_cols = ['Sex', 'Embarked']

    df[categorical_cols] = encodeColumns(df,categorical_cols)

    """
    FILL NA
    """

    df['Age'].fillna((df['Age'].mean()), inplace=True)
    df['Fare'].fillna((df['Fare'].mean()), inplace=True)

    """
    CREATE NEW COLUMNS
    """
    df['SibsParch'] = df['SibSp'] > 0

    df['ClassBinding'] = df['Pclass'] < 3

    df['FemaleClassBinding'] = df['Sex'] * df['ClassBinding']

    return df

"""
CLEAN DATA
"""
pathTrain = os.path.join('data', 'train.csv')
pathTest = os.path.join('data', 'test.csv')
df = pd.read_csv(pathTrain)
dfTest = pd.read_csv(pathTest)

passId = dfTest.values[:,0]

df = df.dropna()

df = alterColumns(df)
dfTest = alterColumns(dfTest)

"""
STANDARDIZE COLUMNS
"""
sc = StandardScaler()
sc.fit(df['Fare'].values.reshape(-1,1))
dfTest['Fare'] = sc.transform(dfTest['Fare'].values.reshape(-1,1))
df['Fare'] = sc.transform(df['Fare'].values.reshape(-1,1))

"""
MODEL

"""

X = df.loc[:,df.columns != 'Survived']
y = df.loc[:,'Survived']

"""
X['fareq'] = pd.qcut(X['Fare'], q=5).cat.codes
X['Age'] = pd.qcut(X['Age'], q=7).cat.codes

dfTest['fareq'] = pd.qcut(dfTest['Fare'], q=5).cat.codes
dfTest['Age'] = pd.qcut(dfTest['Age'], q=7).cat.codes
"""

X['fareq'] = pd.qcut(X['Fare'], q=10).cat.codes
X['Age'] = pd.qcut(X['Age'], q=7).cat.codes

dfTest['fareq'] = pd.qcut(dfTest['Fare'], q=10).cat.codes
dfTest['Age'] = pd.qcut(dfTest['Age'], q=7).cat.codes

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=1, stratify=y)

"""
EMBEDDING MODELS
"""
if True:

    knn = KNeighborsClassifier(n_neighbors = 9,
                               p=2)

    tree = DecisionTreeClassifier(criterion='entropy',
                                  max_depth=None,
                                  random_state=1)

    bag = BaggingClassifier(base_estimator=tree,
                            n_estimators=100,
                            max_samples=1.0,
                            max_features=1.0,
                            bootstrap=True,
                            bootstrap_features=False,
                            n_jobs=1,
                            random_state=1)

    ada = AdaBoostClassifier(base_estimator=tree,
                             n_estimators=100,
                             learning_rate=0.1,
                             random_state=1)

    rf = RandomForestClassifier(max_depth=None,
                                n_estimators = 30,
                                criterion='entropy')

    lr = LogisticRegression(penalty='l2',
                        dual=False,
                        C=3,
                        class_weight = 'uniform',
                        random_state = 1,
                        solver = 'lbfgs')

    """
    TRAIN, PREDICT AND RESULTS
    """
    tree = tree.fit(X_train, y_train)
    bag = bag.fit(X_train, y_train)
    ada = ada.fit(X_train, y_train)
    rf = rf.fit(X_train, y_train)
    knn = knn.fit(X_train, y_train)
    lr = lr.fit(X_train, y_train)

    sl = SuperLearner()
    sl.add(tree).add(bag).add(ada).add(rf)

    voting = VotingClassifier(estimators=[('tree', tree),
                                          ('bag', bag),
                                          ('ada', ada),
                                          ('rf', rf),
                                          ('knn', knn)],
                              voting='soft')

    gradient = GradientBoostingClassifier(random_state=1)

    testSetResultsClassifier(tree, X_test, y_test, 'tree')
    testSetResultsClassifier(bag, X_test, y_test, 'baggings')
    testSetResultsClassifier(ada, X_test, y_test, 'adaboost')
    testSetResultsClassifier(rf, X_test, y_test, 'random forests')
    testSetResultsClassifier(knn, X_test, y_test, 'knn')
    testSetResultsClassifier(lr, X_test, y_test, 'logistic regression')
    testSetResultsClassifier(sl.fit(X_train, y_train), X_test, y_test, 'super learner')
    testSetResultsClassifier(voting.fit(X_train, y_train), X_test, y_test, 'voting classifier')
    testSetResultsClassifier(gradient.fit(X_train, y_train), X_test, y_test, 'gradient classifier')
    #0.8378378378378378
    #saveResult(sl, dfTest, 'sl.csv')

"""
PCA EXAMPLE
"""
if False:

    tree = DecisionTreeClassifier(criterion='entropy',
                                  max_depth=None,
                                  random_state=1)

    ada = AdaBoostClassifier(base_estimator=tree,
                             n_estimators=100,
                             learning_rate=0.1,
                             random_state=1)

    pipe = Pipeline(steps=[('pca',PCA()), ('ada',ada)])

    # Parameters of pipelines can be set using ‘__’ separated parameter names:
    param_grid = {
        'pca__n_components': [3, 4, 5, 6, 7, 8, 9],
    }
    search = GridSearchCV(pipe, param_grid)
    search.fit(X_train, y_train)
    print("Best parameter (CV score=%0.3f):" % search.best_score_)
    print(search.best_params_)

    pred = search.predict(X_test)
    acc = accuracy_score(y_test, pred)
    print('luliada: ', acc)


import math
planet_area = float(input("Ввести площу= "))
planet_area = planet_area*1000000
gravity_constant = 6.67e-11
sphere_radius = math.sqrt(planet_area/4/3.1415)
sphere_volume = (4/3)*3.1415*pow(sphere_radius,3)
iron_density = 7780
Earth_density = 5500
planet_mass = sphere_volume*Earth_density
planet_acceleration = gravity_constant*planet_mass/pow(sphere_radius,2)
Oleg_mass = 72
print("Маса планети:", planet_mass, "кг")
print("Радіус планети:", sphere_radius, "м")
print("Об'єм планети:", sphere_volume, "м^3")
print("Прискорення вільноо падіння на поверхі:", planet_acceleration, "м/с^2")
print("Вага Олега:", Oleg_mass*planet_acceleration, "Н" )


from HAC import HACClustering
import numpy as np
from arff import Arff

filepath = 'iris.arff'
af = Arff()
af.load_arff(filepath)

alldata = af.data
split = int(.75 * len(alldata))
shuffle = False
if shuffle:
    np.random.shuffle(alldata)
trainingdata = alldata[:split]
testdata = alldata[:,:]
hac = HACClustering(k=2, link_type='single', print_k=[2, 3, 4, 5, 6, 7])
hac.fit(testdata)


"""
------------------------------------------------------------------------------------------------------------------------
Name: John Ixcoy  |  Unit: 2  |  Assignment: Unit 3 Project
Due Date: 10 / 27/ 2021
Description:
This is a runner game made using the pygame module. It has a player that can dodge obstacles by jumping trying to get
the highest score they can.

Also. This code sucks. It's my first python project with pygame. But I was going for a 'If it works, it works' approach.
So sorry if this hurts your eyes :)

Input: Keys SPACE and 1
Output: Jump (SPACE) and Start Game (1)
------------------------------------------------------------------------------------------------------------------------
"""
import pygame, random
from classes import Player
from classes import Pole
from classes import Coin

'#Background scroll variables'
game_speed = 0
bg_x_pos = 0
bg_y_pos = 0

'#Jump Variables'
dog_mass = 1
jump_vel = 7
isjump = False

'#Sets background speed'
def background():
    speed = 10
    return speed

'#Blits the current score, which gets added by 1 every time a while loop iteration has run'
def score():
    global points
    points += 1
    score_text = SCORE_FONT.render(f'Score: {points}', False, BLACK)
    score_text_font = score_text.get_rect(center=(WIDTH / 2, 10))
    canvas.blit(score_text, score_text_font)

def draw_instr():
    INSTR = instr_font.render('PRESS THE SPACE BAR TO JUMP', False, BLACK)
    INSTR_rect = INSTR.get_rect(center=(WIDTH / 2, HEIGHT / 3 + 120))
    canvas.blit(INSTR, INSTR_rect)

'#-----------------------------Set Up-----------------------------'
'#Pygame and pygame.font initialization'
pygame.init()
pygame.font.init()

'#Font instances for text'
FONT = pygame.font.SysFont('Ariel', 100)
SUB_FONT = pygame.font.SysFont('Ariel', 50)
instr_font = pygame.font.SysFont('Ariel', 25)
SCORE_FONT = pygame.font.SysFont('Ariel', 25)

'#Base setup variables'
WIDTH, HEIGHT = 543, 257
FPS = 60
BLACK = (0, 0, 0)

'#Background and Text setup variables'
canvas = pygame.Surface((WIDTH, HEIGHT))
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

TITLE = FONT.render('DOG RUN', False, BLACK)
TITLE_rect = TITLE.get_rect(center=(WIDTH/2, HEIGHT/3))

SUB_TITLE = SUB_FONT.render('PRESS 1 TO START', False, BLACK)
SUB_TITLE_rect = SUB_TITLE.get_rect(center=(WIDTH/2, HEIGHT/3 + 50))

DEATH_TEXT = FONT.render('YOU DIED', False, BLACK)
DEATH_TEXT_rect = DEATH_TEXT.get_rect(center=(WIDTH/2, HEIGHT/3))

LIE = SUB_FONT.render('THE COIN IS A LIE', False, BLACK)
LIE_rect = LIE.get_rect(center=(WIDTH/2, HEIGHT/3 + 100))

BACKGROUND = pygame.image.load('Assets/scrolling_background.jpg').convert_alpha()
pygame.display.set_caption('Dog Run')

'#Clock instance to set fps'
clock = pygame.time.Clock()

'#Load Player, Coin, and Pole instance'
pole = Pole()
coin = Coin()
dog = Player(pole.pole_rect, coin)

'#-----------------------------Game Loop-----------------------------'
points = 0
run = True
while run:
    '#Background, Title, and Sub Title Scroll Logic'
    bg_x_pos -= game_speed
    TITLE_rect.x -= game_speed
    SUB_TITLE_rect.x -= game_speed

    if bg_x_pos <= -WIDTH:
        bg_x_pos += WIDTH

    if TITLE_rect.x <= -WIDTH:
        TITLE_rect.x = -WIDTH

    if SUB_TITLE_rect.x <= -WIDTH:
        SUB_TITLE_rect.x = -WIDTH

    '#Pole Spawn and Scroll Logic'
    pole.pole_rect.x -= game_speed
    if pole.pole_rect.x <= -WIDTH:
        pole.pole_rect.x += pole.X_POS

    coin.coin_rect.x -= game_speed
    random_multiplier = random.randint(1, 4)
    if coin.coin_rect.x <= -WIDTH:
        coin.coin_rect.x += pole.X_POS * random_multiplier

    '#Draws the Canvas, Title, and Subtitle'
    canvas.blit(BACKGROUND, (bg_x_pos, bg_y_pos))
    canvas.blit(TITLE, TITLE_rect)
    canvas.blit(SUB_TITLE, SUB_TITLE_rect)

    '#Event Detection'
    for event in pygame.event.get():

        '#Exit Window'
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:

            '#If key 1 is pressed, start game'
            if event.key == pygame.K_1:
                dog.dog_rect.y = 140
                dog.START_KEY = True
                game_speed = background()

            '#Starts Jump Logic and Updates Dog to Jump img'
            if event.key == pygame.K_SPACE and not dog.update() == 'Death':
                dog.SPACE_KEY = True
                isjump = True

        '#Resets the dog animation to its running state'
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                dog.SPACE_KEY = False

    '#Jump Logic'
    if isjump:
        force = (1/2) * dog_mass * (jump_vel**2)
        dog.dog_rect.y -= force
        jump_vel = jump_vel - 0.5

        if jump_vel < 0:
            dog_mass = -1

        if jump_vel == -6:
            isjump = False
            jump_vel = 7
            dog_mass = 1

            dog.dog_rect.y = 140

    '#Draws score if the dog is not idle and not dead'
    if not dog.idle_state and not dog.update() == 'Death' and not dog.update() == 'coin':
        draw_instr()
        score()
        FINAL_SCORE = SUB_FONT.render(f'FINAL SCORE: {points}', False, BLACK)
        FINAL_SCORE_rect = FINAL_SCORE.get_rect(center=(WIDTH / 2, HEIGHT / 3 + 50))

    '#Draws Death Screen where Final score is displayed'
    if dog.update() == 'Death':
        game_speed = 0
        canvas.blit(DEATH_TEXT, DEATH_TEXT_rect)
        canvas.blit(FINAL_SCORE, FINAL_SCORE_rect)

    if dog.update() == 'coin':
        game_speed = 0
        canvas.blit(DEATH_TEXT, DEATH_TEXT_rect)
        canvas.blit(FINAL_SCORE, FINAL_SCORE_rect)
        canvas.blit(LIE, LIE_rect)

    '#Updates the dog and draws both the dog and the pole on the canvas'
    dog.update()
    dog.draw(canvas)
    pole.draw(canvas)
    coin.draw(canvas)

    '#Draws the canvas, updates the fps to 60 and then updates the display'
    WIN.blit(canvas, (0, 0))
    clock.tick(FPS)
    pygame.display.update()


""" Initialize PEMFC model.

    For now, we hard-code all inputs.  Eventually, we may move them to a 'pemfc_inputs.py' file.

    Read in user inputs, then construct initial solution vector SV_0.  Create a class for all other needed parameters, called 'params.'
"""
import numpy as np

""" BEGIN USER INPUTS """

i_ext = 20

t_final = 100

T = 298   # Simulation temperature, K
P_an_0 = 101325 #Pa
X_k_an_0 = np.array([0.97, 0.03])

" Electric potentials"
phi_an_0 = 0
phi_elyte_0 = 0.6
phi_ca_0 = 1.1

C_dl_an = 1e2 # F/m2
C_dl_ca = 1e2 # F/m2

i_o_an = 2.5
i_o_ca = 1
n_an = 2
n_ca = 4

F = 96485
R = 8.3145

beta_ca = 0.5
beta_an = 0.5

delta_Phi_eq_an = 0.61
delta_Phi_eq_ca = 0.55
""" END USER INPUTS """

"============ INITIALIZE SOLUTION VECTOR ============"
C_k_an_CL_0 = P_an_0*X_k_an_0/R/T

# Construct initial solution vector
SV_0 = np.hstack((np.array([phi_elyte_0 - phi_an_0]), C_k_an_CL_0,
    np.array([phi_ca_0 - phi_elyte_0])))

# Construct class containing all parameters.  Mostly we are just copying the
#   variable names from the user inputs into the class structure:
class pars:
    time_span = np.array([0,t_final])

    T = T

    i_ext = i_ext

    # Anode
    delta_Phi_eq_an = delta_Phi_eq_an
    i_o_an = i_o_an
    n_an = n_an
    beta_an = beta_an

    C_dl_an = C_dl_an

    # Cathode
    delta_Phi_eq_ca = delta_Phi_eq_ca
    i_o_ca = i_o_ca
    n_ca = n_ca
    beta_ca = beta_ca

    C_dl_ca = C_dl_ca

# Create a 'pointer' class that specifies where in SV certain variables are
#    stored:
class ptr:
    phi_dl_an = 0

    # C_k in anode CL: starts just after phi_dl, is same size as X_k_an:
    C_k_an_CL = np.array([phi_dl_an+1, phi_dl_an+X_k_an_0.shape[0]])

    # phi_dl_ca: starts just after C_k_an_CL:
    phi_dl_ca = C_k_an_CL[-1] + 1


class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if prices is None or len(prices) < 2:
            return 0
        profit = 0
        minV = prices[0]
        for p in prices:
            if p > minV: # 只要有利润
                profit += p - minV # 则不断累加利润差值
                minV = p # 同时更新当前的最低买入价
            elif p < minV: # 如果遇到更低价格
                minV = p # 则以更低价格买入
        return profit


""" Looper versions of NGS project models. """

from . import models

__author__ = "Vince Reuter"
__email__ = "vreuter@virginia.edu"

class Project(models.Project):
    """
    Looper-specific NGS Project.

    :param config_file: path to configuration file with data from
        which Project is to be built
    :type config_file: str
    :param subproject: name indicating subproject to use, optional
    :type subproject: str
    :param default_compute: path to default compute environment
        configuration data, optional
    :type default_compute: str

    """
    def __init__(self, config_file, subproject=None, **kwargs):
        super(Project, self).__init__(
                config_file, subproject=subproject,
                no_environment_exception=RuntimeError,
                no_compute_exception=RuntimeError, **kwargs)

    @property
    def required_metadata(self):
        """ Which metadata attributes are required. """
        return ["output_dir"]

    @property
    def project_folders(self):
        """ Keys for paths to folders to ensure exist. """
        return ["output_dir", "results_subdir", "submission_subdir"]

    @staticmethod
    def infer_name(path_config_file):
        """
        Infer project name from config file path.

        The assumption is that the config file lives in a 'metadata' subfolder
        within a folder with a name representative of the project.

        :param str path_config_file: path to the project's config file.
        :return str: inferred name for project.
        """
        import os
        metadata_folder_path = os.path.dirname(path_config_file)
        proj_root_path, _ = os.path.split(metadata_folder_path)
        _, proj_root_name = os.path.split(proj_root_path)
        return proj_root_name


"""
Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados
da área a ser pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados
e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades
de latas de tinta a serem compradas e o preço total.
"""

LITROS_LATA = 18
PRECO_LATA = 80.0
LITRO_PINTA_AREA_M2 = 3
TOTAL_AREA_M2_UMA_LATA_PINTA = LITROS_LATA * LITRO_PINTA_AREA_M2

quantidade_de_latas_para_pintura = 1
total_preco = PRECO_LATA

tamanho_de_area_pintada = float(input('Tamanho em m2:'))

if TOTAL_AREA_M2_UMA_LATA_PINTA < tamanho_de_area_pintada:
    quantidade_de_latas_para_pintura = tamanho_de_area_pintada // TOTAL_AREA_M2_UMA_LATA_PINTA
    if tamanho_de_area_pintada % TOTAL_AREA_M2_UMA_LATA_PINTA > 0:
        quantidade_de_latas_para_pintura += 1
    total_preco = quantidade_de_latas_para_pintura * PRECO_LATA

print("""
QTDE de Latas: {}\n
Preço R$: {}
""".format(quantidade_de_latas_para_pintura, total_preco))