def crayonColors():
    '''
crayonColors=checks the file with the 1990 crayon colors, removes the ones
listed in the file that were discontinued, and adds the ones listed in
the file that were added to production
@param original=file with the list of colors in 1990
@param removed=file with list of colors discontinued
@param added=file with list of colors added to production
@param final=new file with list of colors in production after 1990's
@param colorList=list holding all the colors from original
@param removeList=list of colors from removed to take from original
note:book says that there is an almond but there is no almond in the file and
the color Apricot was on both the original list and the list of colors added
so I added a bit to remove repeated colors
    '''
    try:
        original=open("Pre1990.txt", 'r')
        removed=open("Retired.txt", 'r')
        added=open("Added.txt", 'r')
        final=open("final.txt", 'w')
        colorList=[line.rstrip() for line in original]
        for line in added:
            if colorList.count(line.rstrip())==0:
                colorList.append(line.rstrip())
        removeList=[line.rstrip() for line in removed]
        for color in colorList:
            for noncolor in removeList:
                if color == noncolor:
                    colorList.remove(color)
        colorList.sort()
        for sep in range(len(colorList)):
            colorList[sep]=colorList[sep] + "\n"
        final.writelines(colorList)
        original.close()
        removed.close()
        added.close()
        final.close()
    except:
        print("Error.")
if __name__ == "__main__":
    def test_crayonColors():
        '''
test_crayonColors()=tests the crayonColors() method
@param cont=boolean that determines if program repeats
        '''
        try:
            cont=True
            while cont==True:
                crayonColors()
                end=input("Continue? y or n ")
                if end.lower()=="n":
                    cont=False
        except:
            print("Error, test.")
    test_crayonColors()


# coding=utf-8
from __future__ import absolute_import
import logging.config
from os.path import join, realpath, abspath, dirname as up

from django.utils.text import slugify

class LoggingSettings(object):
    """
    Drop in replacement of Django's Logging Configuration:
    Sends INFO level or higher to the console AND file (Django defaults to console only)
        File is auto-rotated, and named after CODENAME slugified.
    Sends ERROR and CRITICAL levels to the ADMINS if DEBUG=True (same as Django defaults).

    https://docs.djangoproject.com/en/1.11/topics/logging/#disabling-logging-configuration
    http://www.caktusgroup.com/blog/2015/01/27/Django-Logging-Configuration-logging_config-default-settings-logger
    https://lincolnloop.com/blog/django-logging-right-way/

    Note on settings.ADMINS:
    ========================
    Errors	: only for Staging, Prod confs.; with
    Regular	: thru send_mail() in Staging, Prod confs. fakes to console with Dev conf.
    (cf. `mail_admins` logging handlers)
    """

    @property
    def LOGGING(self):

        # Reset logging first
        self.LOGGING_CONFIG = None
        _LOGGING = {
            'version': 1,
            'disable_existing_loggers': False,
            'formatters': {
                'verbose': {
                    'format': "[%(asctime)s] %(levelname)s [%(pathname)s:%(lineno)s] %(message)s",
                    'datefmt': "%d/%b/%Y %H:%M:%S"
                },
                'simple': {
                    'format': '%(levelname)s %(message)s'
                },
            },
            'filters': {
                'require_debug_true': {
                    '()': 'django.utils.log.RequireDebugTrue',
                },
            },
            'handlers': {
                'file': {
                    'level': 'DEBUG',
                    'class': 'logging.handlers.RotatingFileHandler',
                    'filename': join(str(self.PROJECT_LOGS_ROOT), '%s.log' % slugify(str(self.CODENAME))),
                    'maxBytes': 15728640,  # 1024 * 1024 * 15B = 15MB
                    'backupCount': 10,
                    'formatter': 'verbose',
                },
                'console': {
                    'level': 'DEBUG',
                    'filters': ['require_debug_true'],
                    'class': 'logging.StreamHandler',
                    'formatter': 'verbose'
                },

                'mail_admins': {
                    # send an email to the site admins on every HTTP 500 error.
                    'level': 'ERROR',
                    'filters': ['require_debug_true'],
                    'class': 'django.utils.log.AdminEmailHandler',
                    'include_html': True,
                }
            },

            # If the log level of the message meets or exceeds the log level of the logger itself,
            # the message will undergo further processing. If it doesn’t, the message will be ignored.
            # INFO, DEBUG, WARNING, ERROR, CRITICAL
            'loggers': {
                # root logger
                '': {
                    'handlers': ['console', 'file'],
                    'level': self.DJANGO_LOG_LEVEL,
                    'propagate': True,
                },
                'django.request': {
                    'handlers': ['mail_admins'],
                    'level': 'ERROR',
                    'propagate': True,
                },
            }
        }

        logging.config.dictConfig(_LOGGING)


import tensorflow as tf
import numpy as np
import facenet
import math
import pickle
from scipy import  misc

import sklearn.metrics as ms
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
import matplotlib.pyplot as plt  # 可视化绘图
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)

def prewhiten(x):
    mean = np.mean(x)
    std = np.std(x)
    std_adj = np.maximum(std, 1.0 / np.sqrt(x.size))
    y = np.multiply(np.subtract(x, mean), 1 / std_adj)
    return y

def crop(image, random_crop, image_size):
    if image.shape[1] > image_size:
        sz1 = int(image.shape[1] // 2)
        sz2 = int(image_size // 2)
        if random_crop:
            diff = sz1 - sz2
            (h, v) = (np.random.randint(-diff, diff + 1), np.random.randint(-diff, diff + 1))
        else:
            (h, v) = (0, 0)
        image = image[(sz1 - sz2 + v):(sz1 + sz2 + v), (sz1 - sz2 + h):(sz1 + sz2 + h), :]
    return image

def flip(image, random_flip):
    if random_flip and np.random.choice([True, False]):
        image = np.fliplr(image)
    return image

def to_rgb(img):
    w, h = img.shape
    ret = np.empty((w, h, 3), dtype=np.uint8)
    ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img
    return ret

def load_data(image_paths, do_random_crop, do_random_flip, image_size, do_prewhiten=True):
    nrof_samples = len(image_paths)
    #print(nrof_samples)# 90
    images = np.zeros((nrof_samples, image_size, image_size, 3))
    #print(images.shape) #90 160 160 3
    for i in range(nrof_samples):
        img = misc.imread(image_paths[i])
        #print(img.ndim)3
        #print(img.shape) 160 160 3
        if img.ndim == 2:
            img = to_rgb(img)
        if do_prewhiten:
            img = prewhiten(img)
        img = crop(img, do_random_crop, image_size)
        img = flip(img, do_random_flip)
        images[i,:,:,:] = img
        #print(images.shape)# 90 160 160 3
        #print(images[i,:,:,:].shape) 160 160 3
    return images

def split_dataset(dataset, min_nrof_images_per_class, nrof_train_images_per_class):
    train_set = []
    test_set = []
    for cls in dataset:
        paths = cls.image_paths
        #print("进入函数")
        #print(len(paths))
        # Remove classes with less than min_nrof_images_per_class
        if len(paths)>=min_nrof_images_per_class:
            np.random.shuffle(paths)
            #print(cls.name)
            #print(nrof_train_images_per_class)
            nrof_train_images_per_class = int(0.8*len(paths))
            train_set.append(facenet.ImageClass(cls.name, paths[:nrof_train_images_per_class]))
            test_set.append(facenet.ImageClass(cls.name, paths[nrof_train_images_per_class:]))
    return train_set, test_set

def get_image_paths_and_labels(dataset):
    image_paths_flat = []
    labels_flat = []
    #print(dataset)
    #print(len(dataset))
    for i in range(len(dataset)):
        image_paths_flat += dataset[i].image_paths
        #print(dataset[i].image_paths)
        #print(len(dataset[i].image_paths))
        #print(image_paths_flat)
        #print([i])
        labels_flat += [i] * len(dataset[i].image_paths)#复制10个[0],[1],[2],[3]
        #print(labels_flat)
    #print(len(image_paths_flat))
    #print(len(labels_flat))
    return image_paths_flat, labels_flat

# dataset_tmp = facenet.get_dataset("C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\data\\self_data_1601")
# #print(dataset_tmp)
# train_set, test_set = split_dataset(dataset_tmp, 20,10)
# dataset = train_set
# paths, labels = get_image_paths_and_labels(dataset)
# dataset = test_set
# paths, labels = get_image_paths_and_labels(dataset)
def main1(args):
    with tf.Graph().as_default():
        with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
            np.random.seed(seed=666)
            if True:
                dataset_tmp = facenet.get_dataset(args.data_dir)
                train_set, test_set = split_dataset(dataset_tmp, 20,30)
                # if (args.mode == 'TRAIN'):
                #     dataset = train_set
                # elif (args.mode == 'CLASSIFY'):
                #     dataset = test_set
            else:
                dataset = facenet.get_dataset("C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\data\\self_data_160")
            dataset = train_set
            paths, labels = get_image_paths_and_labels(dataset)
            print('Number of classes: %d' % len(dataset))
            print('Number of images: %d' % len(paths))
            # Load the model
            print('Loading feature extraction model')
            facenet.load_model("C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\models\\20180402-114759")

            # Get input and output tensors
            # 输入的图片
            images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
            # 卷积网络最后输出的特征
            embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
            # 现在是不是训练阶段
            phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
            embedding_size = embeddings.get_shape()[1]

            # Run forward pass to calculate embeddings
            print('Calculating features for images')
            nrof_images = len(paths)  # 图片总数目
            # print(nrof_images)
            nrof_batches_per_epoch = int(math.ceil(1.0 * nrof_images / 90))
            # print(nrof_batches_per_epoch)
            emb_array = np.zeros((nrof_images, embedding_size))
            #print(emb_array.shape)

            for i in range(nrof_batches_per_epoch):
                start_index = i * 90
                end_index = min((i + 1) * 90, nrof_images)
                paths_batch = paths[start_index:end_index]
                images = facenet.load_data(paths_batch, False, False, 160)
                # 计算特征
                feed_dict = {images_placeholder: images, phase_train_placeholder: False}
                emb_array[start_index:end_index, :] = sess.run(embeddings, feed_dict=feed_dict)

            classifier_filename_exp = os.path.expanduser(args.classifier_filename)
            #model = SVC(kernel='poly',C=1,gamma=1,degree=3,probability=True)
            #model = SVC(C=100,kernel='linear',probability=True)
            model =SVC(kernel='rbf',C=10,gamma=1,probability=True)
            #model = SVC(kernel='poly', C=10, gamma=1, degree=10, probability=True)
            # model = SVC(kernel='poly',C=1,gamma=1,degree=5,probability=True)
            # model = SVC(kernel='poly',C=1,gamma=1,degree=6,probability=True)
            # model = SVC(kernel='poly',C=1,gamma=1,degree=7,probability=True)

            model.fit(emb_array,labels)
            # param_grid = [#{'kernel': ['linear'], 'C': [0.001,0.01,0.1,1]},
            #               #{'kernel': ['rbf'], 'C': [0.001,0.01,0.1,1], 'gamma': [1, 0.1, 0.01, 0.001]},
            #               {
            #               'degree':[2,3,4,5,6,7,8,9,10]}
            #               ]
            # grid = GridSearchCV(estimator=model, param_grid=param_grid, cv=10,
            #                     scoring='accuracy',n_jobs=4)  # 针对每个参数对进行了10次交叉验证。scoring='accuracy'使用准确率为结果的度量指标。可以添加多个度量指标
            # grid.fit(emb_array, labels)
            print(emb_array.shape)
            #print(type(emb_array))
            #print(emb_array.shape[0])
            # print(emb_array[:,0].shape)
            #print(len(labels))
            #print(type(labels))
            print("_________________")
            # #print('网格搜索-度量记录：', grid.cv_results_)  # 包含每次训练的相关信息
            # print('网格搜索-最佳度量值:', grid.best_score_)  # 获取最佳度量值
            # print('网格搜索-最佳参数：', grid.best_params_)  # 获取最佳度量值时的代定参数的值。是一个字典
            # print('网格搜索-最佳模型：', grid.best_estimator_)  # 获取最佳度量时的分类器模型

            dataset= test_set
            paths1, labels1 = get_image_paths_and_labels(dataset)
            #
            print('Number of classes: %d' % len(dataset))
            print('Number of images: %d' % len(paths1))
            # print(paths)
            # Load the model
            print('Loading feature extraction model')
            facenet.load_model("C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\models\\20180402-114759")

            # Get input and output tensors
            # 输入的图片
            images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
            # 卷积网络最后输出的特征
            embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
            # 现在是不是训练阶段
            phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
            embedding_size = embeddings.get_shape()[1]

            # Run forward pass to calculate embeddings
            print('Calculating features for images')
            nrof_images = len(paths1)  # 图片总数目
            # print(nrof_images)
            nrof_batches_per_epoch = int(math.ceil(1.0 * nrof_images / 1))
            # print(nrof_batches_per_epoch)
            emb_array1 = np.zeros((nrof_images, embedding_size))
            print(emb_array1.shape)

            for i in range(nrof_batches_per_epoch):
                start_index = i * 1
                end_index = min((i + 1) * 1, nrof_images)
                paths_batch = paths1[start_index:end_index]
                images = facenet.load_data(paths_batch, False, False, 160)
                # 计算特征
                feed_dict = {images_placeholder: images, phase_train_placeholder: False}
                emb_array1[start_index:end_index, :] = sess.run(embeddings, feed_dict=feed_dict)

            # 使用获取的最佳参数生成模型，预测数据
            #knn = SVC(n_neighbors=grid.best_params_['n_neighbors'],
            #                           weights=grid.best_params_['weights'])  # 取出最佳参数进行建模
            # model = SVC(kernel='poly',C=1,gamma=1,degree=grid.best_params_['degree'],
            #             probability=True)
            #,gamma=grid.best_params_['gamma'],
            # model = SVC(kernel='linear',probability=True)
            # model.fit(emb_array,labels)
            #print(model.predict(emb_array1))
            predictions = model.predict_proba(emb_array1)
            # #print(predictions)
            # #print(predictions.shape)
            best_class_indices = np.argmax(predictions, axis=1)
            #best_class_probabilities = predictions[np.arange(len(best_class_indices)), best_class_indices]
            # #print(best_class_indices)
            # #print(len(best_class_indices))
            #
            # #print(best_class_probabilities)
            # #print(len(best_class_probabilities))
            accuracy = np.mean(np.equal(best_class_indices, labels1))
            print('Accuracy: %.3f' % accuracy)

def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
                        n_jobs=1, train_sizes=np.linspace(.1, 1.0, 10)):
    plt.figure()
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    plt.xlabel("Number of training samples")
    plt.ylabel("Accuracy")
    train_sizes, train_scores, test_scores = learning_curve(
        estimator, X, y, cv=cv,
        n_jobs=n_jobs, train_sizes=train_sizes,
        scoring='accuracy', verbose=0)
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.grid()

    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training accuracy")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="validation accuracy")

    plt.legend(loc="best")
    return plt

# def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
#                         n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
#     plt.figure()
#     plt.title(title)
#     if ylim is not None:
#         plt.ylim(*ylim)
#     plt.xlabel("Training examples")
#     plt.ylabel("Score")
#     train_sizes, train_scores, test_scores = validation_curve(
#         estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
#     train_scores_mean = np.mean(train_scores, axis=1)
#     train_scores_std = np.std(train_scores, axis=1)
#     test_scores_mean = np.mean(test_scores, axis=1)
#     test_scores_std = np.std(test_scores, axis=1)
#     plt.grid()
#
#     plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
#                      train_scores_mean + train_scores_std, alpha=0.1,
#                      color="r")
#     plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
#                      test_scores_mean + test_scores_std, alpha=0.1, color="g")
#     plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
#              label="Training score")
#     plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
#              label="Cross-validation score")
#
#     plt.legend(loc="best")
#     return plt

def main():
    with tf.Graph().as_default():
        with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:
            np.random.seed(seed=666)

            dataset = facenet.get_dataset("C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\data\\self_data_160_not_aligned")

            paths, labels = get_image_paths_and_labels(dataset)
            #X_train, X_test, y_train, y_test = train_test_split(paths, labels, test_size=0.4, random_state=0)
            # print(X_train)
            # print(X_test)
            # print(y_train)
            # print(y_test)
            #
            # print(len(X_train))
            # print(len(X_test))
            # print(len(y_train))
            # print(len(y_test))

            print('Number of classes: %d' % len(dataset))
            print('Number of images: %d' % len(paths))
            # Load the model
            print('Loading feature extraction model')
            facenet.load_model("C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\models\\20180402-114759")

            # Get input and output tensors
            # 输入的图片
            images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
            # 卷积网络最后输出的特征
            embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
            # 现在是不是训练阶段
            phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")
            embedding_size = embeddings.get_shape()[1]
            #print(embeddings) #Tensor("embeddings:0", shape=(?, 512), dtype=float32)
            #print(embedding_size)#512
            # Run forward pass to calculate embeddings
            print('Calculating features for images')
            nrof_images = len(paths)  # 图片总数目
            #print(nrof_images)
            nrof_batches_per_epoch = int(math.ceil(1.0 * nrof_images / 90))
            #print(nrof_batches_per_epoch)
            emb_array = np.zeros((nrof_images, embedding_size))
            #print(emb_array.shape)
            import os
            for i in range(nrof_batches_per_epoch):
                start_index = i * 90
                end_index = min((i + 1) * 90, nrof_images)
                paths_batch = paths[start_index:end_index]
                images = load_data(paths_batch, False, False, 160)
                # 计算特征
                feed_dict = {images_placeholder: images, phase_train_placeholder: False}
                emb_array[start_index:end_index, :] = sess.run(embeddings, feed_dict=feed_dict)
            classifier_filename_exp = os.path.expanduser("C:/Users/rjx/PycharmProjects/untitled1/facenet-master/models/sd_82a.pkl")
            from sklearn.model_selection import learning_curve
            from sklearn.model_selection import ShuffleSplit
            from sklearn.model_selection import validation_curve

    ################1#############
            model = SVC(C=1,kernel='linear', probability=True)
            model.fit(emb_array, labels)
            ylim = (0.75, 1.05)
            title = r"Learning Curves(SVM) for self data(not aligned)"
            #title = r"Learning Curves(SVM) for not aligned data"
            cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=0)
            plt.figure()
            plt.title(title)
            plt.ylim(*ylim)
            plt.xlabel("Number of training samples")
            plt.ylabel("Accuracy")
            train_sizes, train_scores, test_scores = learning_curve(
                model, emb_array, labels, cv=cv,
                n_jobs=4, train_sizes=np.linspace(.1, 1.0, 10),
                scoring='accuracy', verbose=0)
            train_scores_mean = np.mean(train_scores, axis=1)
            train_scores_std = np.std(train_scores, axis=1)
            test_scores_mean = np.mean(test_scores, axis=1)
            test_scores_std = np.std(test_scores, axis=1)
            plt.grid()

            plt.plot(train_sizes, test_scores_mean, 'o-', color="y",
                     label="SVM Linear(C=1) validation accuracy")

            model = SVC(C=10, kernel='linear', probability=True)
            model.fit(emb_array, labels)

            train_sizes, train_scores, test_scores = learning_curve(
                model, emb_array, labels, cv=cv,
                n_jobs=4, train_sizes=np.linspace(.1, 1.0, 10),
                scoring='accuracy', verbose=0)
            train_scores_mean = np.mean(train_scores, axis=1)
            train_scores_std = np.std(train_scores, axis=1)
            test_scores_mean = np.mean(test_scores, axis=1)
            test_scores_std = np.std(test_scores, axis=1)
            plt.plot(train_sizes, test_scores_mean, 'o-', color="r",
                     label="SVM Linear(C=10) validation accuracy")

            model = SVC(C=10,degree=5, gamma=1,kernel='poly', probability=True)
            model.fit(emb_array, labels)

            train_sizes, train_scores, test_scores = learning_curve(
                model, emb_array, labels, cv=cv,
                n_jobs=4, train_sizes=np.linspace(.1, 1.0, 10),
                scoring='accuracy', verbose=0)
            train_scores_mean = np.mean(train_scores, axis=1)
            train_scores_std = np.std(train_scores, axis=1)
            test_scores_mean = np.mean(test_scores, axis=1)
            test_scores_std = np.std(test_scores, axis=1)
            plt.plot(train_sizes, test_scores_mean, 'o-', color="b",
                     label="SVM Poly(C=10,gamma=1,degree=5) validation accuracy")

            model = SVC(C=10,gamma=2.4, kernel='rbf', probability=True)
            model.fit(emb_array, labels)

            train_sizes, train_scores, test_scores = learning_curve(
                model, emb_array, labels, cv=cv,
                n_jobs=4, train_sizes=np.linspace(.1, 1.0, 10),
                scoring='accuracy', verbose=0)
            train_scores_mean = np.mean(train_scores, axis=1)
            train_scores_std = np.std(train_scores, axis=1)
            test_scores_mean = np.mean(test_scores, axis=1)
            test_scores_std = np.std(test_scores, axis=1)
            # title = r"Learning Curves(SVM) for not aligned data"
            plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
                     label="SVM RBF(C=10,gamma=2.4) validation accuracy")

            # model = SVC(C=10,degree=6, gamma=1, kernel='poly', probability=True)
            # model.fit(emb_array, labels)
            #
            # train_sizes, train_scores, test_scores = learning_curve(
            #     model, emb_array, labels, cv=cv,
            #     n_jobs=4, train_sizes=np.linspace(.1, 1.0, 10),
            #     scoring='accuracy', verbose=0)
            # train_scores_mean = np.mean(train_scores, axis=1)
            # train_scores_std = np.std(train_scores, axis=1)
            # test_scores_mean = np.mean(test_scores, axis=1)
            # test_scores_std = np.std(test_scores, axis=1)
            # plt.plot(train_sizes, test_scores_mean, 'o-', color="y",
            #          label="SVM Poly(C=10,degree=6,gamma=1) validation accuracy")

            # model = SVC(C=10, gamma=1,degree=10, kernel='poly', probability=True)
            # model.fit(emb_array, labels)
            #
            # train_sizes, train_scores, test_scores = learning_curve(
            #     model, emb_array, labels, cv=cv,
            #     n_jobs=4, train_sizes=np.linspace(.1, 1.0, 10),
            #     scoring='accuracy', verbose=0)
            # train_scores_mean = np.mean(train_scores, axis=1)
            # train_scores_std = np.std(train_scores, axis=1)
            # test_scores_mean = np.mean(test_scores, axis=1)
            # test_scores_std = np.std(test_scores, axis=1)
            # # title = r"Learning Curves(SVM) for not aligned data"
            # plt.plot(train_sizes, test_scores_mean, 'o-', color="y",
            #          label="SVM Poly(C=10,degree=10,gamma=1) validation accuracy")

            plt.legend(loc="best")
            plt.show()

import argparse
def parse_arguments(argv):
    parser = argparse.ArgumentParser()

    parser.add_argument('--mode', type=str, choices=['TRAIN', 'CLASSIFY'],
                        help='Indicates if a new classifier should be trained or a classification ' +
                             'model should be used for classification', default="TRAIN")
    parser.add_argument('--data_dir', type=str,
                        help='Path to the data directory containing aligned LFW face patches.', default=
                        "C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\data\\self_data_160_aligned")
    parser.add_argument('--model', type=str,
                        help='Could be either a directory containing the meta_file and ckpt_file or a model protobuf (.pb) file',
                        default="C:\\Users\\rjx\\PycharmProjects\\untitled1\\facenet-master\\models\\20180402-114759")
    parser.add_argument('--classifier_filename',
                        help='Classifier model file name as a pickle (.pkl) file. ' +
                             'For training this is the output and for classification this is an input.',
                        default="C:/Users/rjx/PycharmProjects/untitled1/facenet-master/models/sdd_p_82na.pkl")
    parser.add_argument('--use_split_dataset',
                        help='Indicates that the dataset specified by data_dir should be split into a training and test set. ' +
                             'Otherwise a separate test set can be specified using the test_data_dir option.',
                        action='store_true',
                        default=True)
    parser.add_argument('--test_data_dir', type=str,
                        help='Path to the test data directory containing aligned images used for testing.')
    parser.add_argument('--batch_size', type=int,
                        help='Number of images to process in a batch.', default=90)
    parser.add_argument('--image_size', type=int,
                        help='Image size (height, width) in pixels.', default=160)
    parser.add_argument('--seed', type=int,
                        help='Random seed.', default=666)
    parser.add_argument('--min_nrof_images_per_class', type=int,
                        help='Only include classes with at least this number of images in the dataset', default=20)
    # parser.add_argument('--nrof_train_images_per_class', type=int,
    #     help='Use this number of images from each class for training and the rest for testing', default=50)

    return parser.parse_args(argv)

if __name__ == '__main__':
    main()


import torch.nn as nn
import torch
import torch.nn.functional as F
from src.models.dropblock import DropBlock
from torch.autograd import Variable
import math
import numpy as np
import torch.nn.functional as F
from torch.nn.utils.weight_norm import WeightNorm
from collections import defaultdict

class ConvBlock(nn.Module):
    def __init__(self, in_channels, out_channels, retain_activation=True, activation='ReLU'):
        super(ConvBlock, self).__init__()

        self.block = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(out_channels)
        )

        if retain_activation:
            if activation == 'ReLU':
                self.block.add_module("ReLU", nn.ReLU(inplace=True))
            elif activation == 'LeakyReLU':
                self.block.add_module("LeakyReLU", nn.LeakyReLU(0.1))
            elif activation == 'Softplus':
                self.block.add_module("Softplus", nn.Softplus())
        self.block.add_module("MaxPool2d", nn.MaxPool2d(kernel_size=2, stride=2, padding=0))

    def forward(self, x):
        out = self.block(x)
        return out

def conv_block(in_channels, out_channels):
    bn = nn.BatchNorm2d(out_channels)
    nn.init.uniform_(bn.weight) # for pytorch 1.2 or later
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, 3, padding=1),
        bn,
        nn.ReLU(),
        nn.MaxPool2d(2)
    )

class Convnet(nn.Module):

    def __init__(self, x_dim=3, hid_dim=64, z_dim=64):
        super().__init__()
        self.encoder = nn.Sequential(
            conv_block(x_dim, hid_dim),
            conv_block(hid_dim, hid_dim),
            conv_block(hid_dim, hid_dim),
            conv_block(hid_dim, z_dim),
        )
        self.out_channels = z_dim * 25

class ShallowConv(nn.Module):
    def __init__(self,
        h_dim,
        z_dim,
        projection,
        classifier_type,
        num_classes,
        x_dim=3,
        x_width=84,
        retain_last_activation=True,
        activation='ReLU',
        learnable_scale=False):

        super(ShallowConv, self).__init__()

        self.encoder = nn.Sequential(
            conv_block(x_dim, h_dim),
            conv_block(h_dim, h_dim),
            conv_block(h_dim, h_dim),
            conv_block(h_dim, z_dim),
        )

        # classifier creation
        self.projection = projection
        print("Unit norm projection is ", self.projection)
        print("Avg pool is always False for Conv64")
        self.final_feat_dim = z_dim * ((x_width // 16) ** 2) # the feat size is z_dim x w X h, where w,h = (original_width // 16) due to 4 stacked Maxpool(2) operators
        self.num_classes = num_classes
        self.no_fc_layer = (classifier_type == "no-classifier")
        self.classifier_type = classifier_type

        if self.no_fc_layer is True:
            self.fc = None
        elif self.classifier_type == 'linear':
            self.fc = nn.Linear(self.final_feat_dim, num_classes)
            self.fc.bias.data.fill_(0)
        else:
            raise ValueError("classifier type not found")

        # initialization
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # init learnable scale
        if learnable_scale:
            self.scale = torch.nn.Parameter(torch.FloatTensor([1.0]))

    def forward(self, x, only_features=False):
        x = self.encoder(x)
        x = x.view(x.size(0), -1)

        # hypersphere projection
        if self.projection:
            x_norm = torch.norm(x, dim=1, keepdim=True)+0.00001
            x = x.div(x_norm)

        # fc
        if (self.fc is not None) and (not only_features):
            x = self.fc.forward(x)

        return x


from typing import List, Tuple

STUDENT_START = -1
STUDENT_END = 1

def get_students_count(events: List[Tuple[int, int, int]], students_count: int) -> Tuple[int, List[int]]:
    """
    Функция которая вычисляет необходимое количество билетов и вариант раздачи билетов.

    :param events: список событий в котором указаны координата студента, тип события, порядковый номер студента
    :type events: List[Tuple[int, int, int]]
    :param students_count: количество студентов
    :type students_count: int

    :return: количество билетов, список с вариантом раздачи билетов
    :rtype: Tuple[int, List[int]]
    """
    max_exam_number = 0
    reused_tickets = []
    exam_tickets = [0] * students_count

    for x, event, original_order in events:
        if event == STUDENT_START:
            if len(reused_tickets) == 0:
                max_exam_number += 1
                next_exam_number = max_exam_number
            else:
                next_exam_number = reused_tickets.pop(0)
            exam_tickets[original_order] = next_exam_number
        elif event == STUDENT_END:
            student_exam_number = exam_tickets[original_order]
            reused_tickets.append(student_exam_number)

    return max_exam_number, exam_tickets

def main():
    """Основная функция для чтения входных данных и вывода результата."""
    n, d = map(int, input().split())
    students = list(map(int, input().split()))

    events = []
    for i, x in enumerate(students):
        events.append((x, STUDENT_START, i))
        events.append((x + d, STUDENT_END, i))

    sorted_events = sorted(events)

    result = get_students_count(sorted_events, n)

    print(result[0])
    print(*result[1])

if __name__ == '__main__':
    main()


from selenium.webdriver.common.action_chains import ActionChains

from pymouse import PyMouse
from pykeyboard import PyKeyboard

from random import choice
import time

from utomarket.skip_util import *

from utomarket.util import *
from utomarket.settings import Settings

def upload_avatar_o(browser):
    upload_btns = browser.find_elements_by_class_name('ant-btn')
    upload_btn = upload_btns[0]
    upload_btn.click()
    upload('20180917154817.JPEG')
    # kk = PyKeyboard()#实例化
    # time.sleep(1)
    # kk.tap_key(kk.shift_key)  # 切换为英文，看实际情况是否需要
    # time.sleep(1)
    # kk.type_string(r'C:\Users\Apple\Desktop\photos')  # 打开文件所在目录，方便多个文件上传
    # time.sleep(1)
    # kk.tap_key(kk.enter_key)
    # time.sleep(1)
    # kk.type_string('20180917154817.JPEG')  # 多文件上传
    # time.sleep(1)
    # kk.tap_key(kk.enter_key)
    popup_o(browser, '修改头像成功')

def get_code(browser, code, btn):
    get_code_btn = browser.find_element_by_xpath("//span[contains(text(),'获取验证码')]/..")
    code_input = browser.find_element_by_xpath("//input[@placeholder='验证码']")
    next_btn = browser.find_element_by_xpath("//span[contains(text(),'%s')]//.." % btn)
    print(next_btn, '-----------------------------')
    get_code_btn.click()
    popup_o(browser, '发送成功')
    code_input.send_keys(code)
    time.sleep(4)
    next_btn.click()

def select_mode(browser, method):
    time.sleep(1)
    method_btns = browser.find_elements_by_class_name('ant-select-dropdown-menu-item')
    for item in method_btns:
        if item.text == method:
            item.click()
            time.sleep(1)
            break

def change_mail_o(browser, email, code):
    change_btn = browser.find_element_by_xpath(
        '//*[@id="root"]/div/div/div/div[2]/div/div[2]/div/div[1]/div[2]/div[2]/ul')
    change_btn.click()
    explicit_wait(browser, 'VOEL', ['getCaptcha___3e6Ch', 'class'])
    get_code(browser, code, '下一步')
    explicit_wait(browser, 'VOEL', ['ant-input', 'class'])
    new_email_input = browser.find_element_by_id('email')
    new_email_input.send_keys(email)
    get_code(browser, code, '下一步')
    popup_o(browser, '操作成功')
    time.sleep(5)

def band_telephone_o(browser, phone, code, country):
    bind_btn = browser.find_element_by_xpath(
        '//*[@id="root"]/div/div/div/div[2]/div/div[2]/div/div[1]/div[2]/div[3]/ul')
    bind_btn.click()
    explicit_wait(browser, 'VOEL', ['ant-modal-title', 'class'])
    country_btn = browser.find_element_by_class_name('ant-select-selection__rendered')
    country_btn.click()
    time.sleep(1)
    select_country(browser, country)
    input_phone = browser.find_element_by_id('telephone')
    input_phone.send_keys(phone)
    get_code(browser, code, '下一步')
    popup_o(browser, '操作成功')

def change_telephone_o(browser, phone, code, country):
    change_btn = browser.find_element_by_xpath(
        '//*[@id="root"]/div/div/div/div[2]/div/div[2]/div/div[1]/div[2]/div[3]/ul')
    change_btn.click()
    explicit_wait(browser, 'VOEL', ['ant-modal-title', 'class'])
    get_code(browser, code, '下一步')
    explicit_wait(browser, 'VOEL', ['ant-select-selection__rendered', 'class'])
    change_country_btn = browser.find_element_by_class_name('ant-select-selection__rendered')
    change_country_btn.click()
    time.sleep(1)
    select_country(browser, country)
    input_phone = browser.find_element_by_id('telephone')
    input_phone.send_keys(phone)
    get_code(browser, code, '下一步')
    popup_o(browser, '操作成功')

def band_google_o(browser, code):
    change_btn = browser.find_element_by_xpath(
        '//*[@id="root"]/div/div/div/div[2]/div/div[2]/div/div[1]/div[2]/div[4]/ul')
    change_btn.click()
    explicit_wait(browser, 'VOEL', ['ant-card-head-title', 'class'])
    copy_btn = browser.find_element_by_class_name('anticon-copy')
    input_code = browser.find_element_by_id('captcha')
    tick = browser.find_element_by_xpath("//input[@type='checkbox']//..")
    start_using_btn = browser.find_element_by_xpath("//button[@type='submit']")
    copy_btn.click()
    popup_o(browser, '复制成功')
    input_code.send_keys(code)
    tick.click()
    time.sleep(3)
    start_using_btn.click()
    popup_o(browser, '操作成功')
    url = get_current_url(browser)
    assert url == 'https://dev.utomarket.com:9094/#/user-center/index'

def stop_google_o(browser, code):
    stop_btn = browser.find_element_by_xpath(
        '//*[@id="root"]/div/div/div/div[2]/div/div[2]/div/div[1]/div[2]/div[4]/ul')
    stop_btn.click()
    explicit_wait(browser, 'VOEL', ['ant-modal-title', 'class'])
    code_input = browser.find_element_by_xpath("//input[@placeholder='谷歌验证码']")
    confirm_btn = browser.find_element_by_xpath("//button[@type='submit']")
    code_input.send_keys(code)
    confirm_btn.click()
    popup_o(browser, '操作成功')

def change_pw_o(browser, code, old_pw, new_pw, method):
    change_btn = browser.find_element_by_xpath(
        '//*[@id="root"]/div/div/div/div[2]/div/div[2]/div/div[1]/div[2]/div[5]/ul')
    change_btn.click()
    explicit_wait(browser, 'VOEL', ['ant-modal-title', 'class'])
    method_btn = browser.find_element_by_xpath("//div[@role='combobox']")
    method_btn.click()
    time.sleep(1)
    options = browser.find_elements_by_class_name('ant-select-dropdown-menu-item')
    for item in options:
        if method in item.text:
            item.click()
            break
    time.sleep(2)
    get_code(browser, code, '确定')
    explicit_wait(browser, 'VOEL', ["//input[@id='old_password']", 'xpath'])
    old_input = browser.find_element_by_xpath("//input[@id='old_password']")
    new_input = browser.find_element_by_xpath("//input[@id='password']")
    confirm_input = browser.find_element_by_xpath("//input[@id='confirm']")
    next_btn = browser.find_element_by_xpath("//span[contains(text(),'下一步')]/..")
    old_input.send_keys(old_pw)
    new_input.send_keys(new_pw)
    confirm_input.send_keys(new_pw)
    next_btn.click()
    popup_o(browser, '操作成功')
    time.sleep(2)

def auth_c1_o(browser, name, id_number):
    certification_btn = browser.find_element_by_xpath("//span[contains(text(),'立即认证')]/..")
    certification_btn.click()
    explicit_wait(browser, 'VOEL', ["//input[@id='name']", 'xpath'])
    assert get_current_url(browser) == 'https://dev.utomarket.com:9094/#/authentication'
    name_input = browser.find_element_by_id('name')
    id_number_input = browser.find_element_by_id('number')
    submit_btn = browser.find_element_by_xpath("//span[contains(text(),'提交审核')]/..")
    name_input.send_keys(name)
    id_number_input.send_keys(id_number)
    submit_btn.click()

def auth_c2_o(browser):
    explicit_wait(browser, 'VOEL', ["anticon-check", 'class'])
    upload_btns = browser.find_elements_by_class_name('ant-form-item-control-wrapper')
    upload_btns[0].click()
    upload('0642.png')
    time.sleep(4)
    upload_btns[1].click()
    upload('160704.PNG')
    time.sleep(4)
    submit_btn = browser.find_element_by_class_name('ant-btn-primary')
    submit_btn.click()
    # explicit_wait(browser, 'VOEL', ["ant-alert-info", 'class'])
    time.sleep(15)
    browser.implicitly_wait(20)
    iframe = browser.find_element_by_tag_name("iframe")
    print(iframe, '---------------------------')
    browser.switch_to_frame(iframe)
    time.sleep(5)
    explicit_wait(browser, 'VOEL', ["jr-qrcode", 'id'])
    QR_code = browser.find_element_by_id('jr-qrcode')
    print(QR_code, '-----------------------')
    assert QR_code != None
    browser.switch_to_default_content()

def payment_alipay_o(browser, method, name, account, receipt_code):  # 支付宝、微信、paytm共用
    add_btn = browser.find_element_by_xpath("//span[contains(text(),'添加新的支付方式')]/..")
    add_btn.click()
    time.sleep(1)
    choose_input = browser.find_element_by_xpath("//div[contains(text(),'请选择支付方式')]/..")
    choose_input.click()
    time.sleep(2)
    select_mode(browser, method)
    explicit_wait(browser, 'VOEL', ['payment_detail.name', 'id'])
    name_input = browser.find_element_by_id('payment_detail.name')
    account_input = browser.find_element_by_id('payment_detail.account')
    code_btn = browser.find_element_by_class_name('ant-upload-drag')
    confirm_btn = browser.find_element_by_xpath("//span[contains(text(),'确定')]/..")
    name_input.send_keys(name)
    account_input.send_keys(account)
    code_btn.click()
    upload(receipt_code)
    time.sleep(4)
    confirm_btn.click()
    popup_o(browser, '操作成功')
    time.sleep(2)

def payment_bank_o(browser, method, name, account, card_number):
    add_btn = browser.find_element_by_xpath("//span[contains(text(),'添加新的支付方式')]/..")
    add_btn.click()
    time.sleep(1)
    choose_input = browser.find_element_by_xpath("//div[contains(text(),'请选择支付方式')]/..")
    choose_input.click()
    time.sleep(2)
    select_mode(browser, method)
    explicit_wait(browser, 'VOEL', ['payment_detail.name', 'id'])
    name_input = browser.find_element_by_id('payment_detail.name')
    account_input = browser.find_element_by_id('payment_detail.bank_name')
    card_number_input = browser.find_element_by_id('payment_detail.bank_account')
    confirm_btn = browser.find_element_by_xpath("//span[contains(text(),'确定')]/..")
    name_input.send_keys(name)
    account_input.send_keys(account)
    card_number_input.send_keys(card_number)
    confirm_btn.click()
    popup_o(browser, '操作成功')
    time.sleep(2)

def payment_western_union_o(browser, method, name, transfer_information):
    add_btn = browser.find_element_by_xpath("//span[contains(text(),'添加新的支付方式')]/..")
    add_btn.click()
    time.sleep(1)
    choose_input = browser.find_element_by_xpath("//div[contains(text(),'请选择支付方式')]/..")
    choose_input.click()
    time.sleep(2)
    select_mode(browser, method)
    explicit_wait(browser, 'VOEL', ['payment_detail.name', 'id'])
    name_input = browser.find_element_by_id('payment_detail.name')
    confirm_btn = browser.find_element_by_xpath("//span[contains(text(),'确定')]/..")
    transfer_information_input = browser.find_element_by_id('payment_detail.account')
    name_input.send_keys(name)
    transfer_information_input.send_keys(transfer_information)
    confirm_btn.click()
    popup_o(browser, '操作成功')
    time.sleep(2)

def delete_payment_o(browser):
    delete_btns = browser.find_elements_by_class_name('text-red')
    choice(delete_btns).click()
    confirm_btn = browser.find_element_by_xpath("//span[contains(text(),'确 定')]/..")
    print(confirm_btn, '-----------------------------')
    time.sleep(1)
    confirm_btn.click()
    popup_o(browser, '操作成功')

def others_information_o(browser):
    name_a = browser.find_elements_by_xpath('//a[contains(@href,"#/personage")]')
    choice(name_a).click()


'''
<문제>
- 도현이 집 n개. 좌표 x1, x2, x3, ...
- 집에 공유기 c개 설치
- 가장 인접한 공유기 사이 거리 최대 -> 최댓값 출력
'''

n,c = map(int,input().split())

house = []
for _ in range(n):
    x = int(input())
    house.append(x)

house.sort()

# 좌표값의 최소값
start = 1
# 가장 높은 좌표와 가장 낮은 좌표의 차이
end = house[-1] - house[0]

result = 0

while (start <= end):
    mid = (start+end)//2 # gap
    old = house[0]
    count = 1

    for i in range(1, len(house)):
        if house[i] >= old+mid: # gap 이상
            count+=1
            old = house[i]

    if count >=c:
        start = mid + 1
        result = mid
    else:
        end = mid - 1

print(result)


#!/usr/bin/env python3
import sys

# Simple script to manage brightness of the display.

# Min brightness (to not turn out monitor completely)
MIN_BRIGHTNESS = 1
# Max brightness supported by the monitor on the target machine
MAX_BRIGHTNESS = 512
# Path to the current brightness file
BRIGHTNESS_FILE_PATH = "/sys/class/backlight/intel_backlight/brightness"

# Expects something like '-16' or '+16'
change = int(sys.argv[1])

cur_brightness = MAX_BRIGHTNESS
with open(BRIGHTNESS_FILE_PATH, mode="r") as f:
    cur_brightness = int(f.read())

with open(BRIGHTNESS_FILE_PATH, mode="w") as f:
    new_val = cur_brightness + change
    new_val = min(new_val, MAX_BRIGHTNESS)
    new_val = max(new_val, MIN_BRIGHTNESS)
    f.write(str(new_val))


from tool_share_app import models, forms
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.shortcuts import render
from tool_share_app.forms.date_form import RequestDate, ReturnDate
from tool_share_app.views import add_context_extra_data
from django.views.decorators.csrf import csrf_exempt

import datetime, calendar

from . import tool_requested, notification_num

# ---------------------
# process tool requests
# ---------------------
@csrf_exempt
def tool_request(request, tool_id, tool_listing_section):
	if not request.session['is_open']:
		return HttpResponseRedirect('/')

	try:
		tool = models.Tool.objects.get(id=tool_id)

	except:
		messages.warning(request, 'Tool requested has been deleted from the system, the transaction could not be completed')

		return HttpResponseRedirect('/user_profile/manage_tools/all_tools/')

	if tool.status == 'Unavailable':
		messages.error(request, 'This tool "'+ tool.name + '" is unavailable! it cannot be requested')

		return HttpResponseRedirect('/user_profile/manage_tools/all_tools/' + tool_listing_section)

	user = models.User.objects.get(email=request.session['user_email'])
	request_date_form = RequestDate(request.POST or None)
	return_date_form = ReturnDate(request.POST or None)
	shed = models.Shed.objects.get(address__zip_code=user.address.zip_code)

	context = {
		'tool_requested_number': tool_requested.tool_requested(user),
		'email': user.email,
		'address': user.address,
		'num_notification': notification_num.notification_num(user),
		'request_date_form': request_date_form,
		'return_date_form': return_date_form,
		'tool_requested': tool,
	}

	context.update(add_context_extra_data.add_context_extra_data(user))

	if request_date_form.is_valid() and return_date_form.is_valid():

		data_statistics = models.DataStatistics()

		if tool.location == shed.address and user.admin == True:
			tool_borrowed = models.CurrentlyBorrowedTools(possesor=user,
														  tool=tool,
													 	  start_time=request_date_form.cleaned_data['start_date'],
														  return_time=return_date_form.cleaned_data['return_date'])
			tool.status = 'Unavailable'

			tool.save()

			tool_borrowed.save()

			data_statistics.tool_requested = tool

			data_statistics.requester = user

			data_statistics.is_accepted =True

			data_statistics.save()

			messages.success(request, 'You have successfully obtained "'+ tool.name + '"')

			return HttpResponseRedirect('/user_profile/manage_tools/all_tools/' + tool_listing_section)

		if tool.location == shed.address:
			tool_borrowed = models.CurrentlyBorrowedTools(possesor=user,
														  tool=tool,
													 	  start_time=request_date_form.cleaned_data['start_date'],
														  return_time=return_date_form.cleaned_data['return_date'])

			# class Notification(models.Model):
    			# notification_request_type = models.CharField(max_length=1)
    			# notification_receiver = models.ForeignKey(User)
    			# notification_sender = models.CharField(max_length=100, default='')
    			# notification_information = models.CharField(max_length=256)
    			# notification_tool = models.ForeignKey(Tool, blank=True, null=True)
    			# notification_timestamp = models.DateTimeField(default=datetime.datetime.now)

			shed_coordinator = models.User.objects.get(address__zip_code=user.address.zip_code, admin=True)

			print(user.first_name)

			notification = models.Notification(notification_request_type='Z',
											   notification_receiver=shed_coordinator,
											   notification_sender=user.first_name + ' ' + user.last_name + \
											   ' (' + user.email + ')',
											   notification_information="'" + tool_borrowed.tool.name + "' borrowed from shed.",
											   notification_tool=tool_borrowed.tool)

			notification.save()

			tool.status = 'Unavailable'

			tool.save()

			tool_borrowed.save()

			data_statistics.tool_requested = tool

			data_statistics.requester = user

			data_statistics.is_accepted =True

			data_statistics.save()

			messages.success(request, 'You have successfully obtained "'+ tool.name + '"')

			return HttpResponseRedirect('/user_profile/manage_tools/all_tools/' + tool_listing_section)

		else:
			tool_being_requested = models.ToolBorrowingRequest(requester=user,
														date_request=request_date_form.cleaned_data['start_date'],
														date_return=return_date_form.cleaned_data['return_date'],
														tool_requested=tool)

			if datetime.date.today() > request_date_form.cleaned_data['start_date']:

				date = str(request_date_form.cleaned_data['start_date'])

				messages.error(request, 'Invalid date start date '+ str(datetime.date(1900, int(date[5:7]), 1).strftime('%B')) + ',' + date[8:] +',' + date[0:4] + '! The date must start from today\'s date')

				return HttpResponseRedirect('/user_profile/manage_tools/all_tools/share_zone_tools/request/'+ tool_id +'/')

			if request_date_form.cleaned_data['start_date'] > return_date_form.cleaned_data['return_date']:

				date = str(return_date_form.cleaned_data['return_date'])

				messages.error(request, 'Invalid date return date '+ str(datetime.date(1900, int(date[5:7]), 1).strftime('%B')) + ',' + date[8:] +',' + date[0:4] + '! The date must start from the start\'s date')

				return HttpResponseRedirect('/user_profile/manage_tools/all_tools/share_zone_tools/request/'+ tool_id +'/')

			tool_being_requested.save()

			data_statistics.tool_requested = tool

			data_statistics.requester = user

			data_statistics.save()

			messages.success(request, 'You have successfully requested "'+ tool.name + '". Your tool requests can be seen under the My requested tools tab.')

			return HttpResponseRedirect('/user_profile/manage_tools/all_tools/' + tool_listing_section)

	return render(request, 'tools_usage_dates.html', context)

# end tool_request function


import time

import pygame
import threading

from opening import screen

# atak = 'first'
from קבועים import rto, xx
atak_1 = [100, 300, True]
atak_2 = [200,200,True]

def bose_atak(atak,a,x,y,live ):

    time = pygame.time.get_ticks()

    if time > 5000 and time < 7000:
        image = pygame.image.load(rto)
        p = pygame.transform.rotate(image, 180)
        p = pygame.transform.scale(p, (100, 100))
        screen.blit(p, (atak_1[0], atak_1[1]))

    if time > 7000 and time < 8000:
        image = pygame.image.load(xx)
        p = pygame.transform.rotate(image, 180)
        p = pygame.transform.scale(p, (100, 100))
        screen.blit(p, (atak_1[0], atak_1[1]))
        if atak_1[0] < x+5 < atak_1[1] + 100 and atak_1[1] < y+5 < atak_1[1] + 100 and atak_1[2]:
            live -= 100
            print(1)
            atak_1[2] = False


from random import randint
import pygame

class Colone:
    def __init__(self):
        self.x = 10
        self.vitesse = 3
        self.trou = randint(1,399)
        self.taille_trou = 100
        self.rectUp = pygame.Rect((round(500*(self.x/10)), 0), (50, self.trou))
        self.rectDown = pygame.Rect((round(500*(self.x/10)), self.trou+self.taille_trou), (50, 500-self.trou-self.taille_trou))


import time

from pyspark.sql import SparkSession
from pyspark.sql import Window
from pyspark.sql.functions import col, to_timestamp, rank, desc

spark = (SparkSession
         .builder
         .appName("SparkEj1")
         .getOrCreate())

csv_trade = "trade_details.csv"

csv_trade_snap = "trade_details_snapshot.csv"

df = (spark.read.format("csv")
      .option("inferSchema", "true")
      .option("header", "true")
      .option("delimiter", ";")
      .load(csv_trade))

df_snap = (spark.read.format("csv")
           .option("inferSchema", "true")
           .option("header", "true")
           .option("delimiter", ";")
           .load(csv_trade_snap))

df.show()

df_snap.show()

df_snap_filtered = (df_snap.select("origin_contract_number", col("maturity").alias("maturity2"))
                    .filter((col("mfamily") == "CURR") | (col("mgroup") == "FXD") | (col("mtype") == "SWLEG")))

df_fxswap = (df.select("mfamily", "mgroup", "mtype", "origin_trade_number", col("origin_contract_number"), to_timestamp("maturity").alias("maturity"))
             .filter((col("mfamily") == "CURR") | (col("mgroup") == "FXD") | (col("mtype") == "SWLEG"))
             .join(df_snap_filtered,
                   ["origin_contract_number"], "left")
             .orderBy(df["origin_contract_number"], col("maturity"), col("maturity2")))

df_fxswap.show(50)
df_fxswap.printSchema()
print(df_fxswap.count())

windowSpec = Window.partitionBy("origin_contract_number").orderBy(desc(col("maturity")), desc(col("maturity2")))

df_semi = (df_fxswap.withColumn("rank", rank().over(windowSpec)))

df_final = (df_semi.distinct()
            .filter(col("rank") == 1)
            .drop(col("rank"))
            .drop(col("maturity2")))

df_semi.show()

df_final.show()


var1 = ""
var2 = ""
while not var1.replace('.', '', 1).isdigit():
  var1 = input('Введите первое число: ')

while not var2.replace('.', '', 1).isdigit():
  var2 = input('Введите второе число: ')

if var1.find('.') != -1:
  var1 = float(var1)
else:
  var1 = int(var1)

if var2.find('.') != -1:
  var2 = float(var2)
else:
  var2 = int(var2)

print(f'Сумма: {var1 + var2}')
print(f'Разность: {var1 - var2}')

print(f'Умножение: {var1 * var2}')

if var2 != 0:
  print(f'Деление: {var1 / var2}')
else:
  print(f'Деление: На 0 делить нельзя')

print(f'Степень: {var1 ** var2}')

if var2 != 0:
  print(f'Деление по модулю: {var1 % var2}')
else:
  print('Деление по модулю: На 0 делить нельзя')

if var2 != 0:
  print(f'Целочисленное деление: {var1 // var2}')
else:
  print('Целочисленное деление: На 0 делить нельзя')


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

import subprocess
import os
import sys
import socket
import logging
import dns.resolver #pip install dnspython

dominio = raw_input(str('Digite o nome do seu dominio: '))

# Path's
amavis_novalistadeverificacao = '/tmp/amavis_novalistadeverificacao'
amavis_novalistadeverificacaoip = '/tmp/amavis_novalistadeverificacaoip'

# Zimbra Path's
if os.path.exists('/opt/zimbra/conf/postfix_blacklist'):
    postfix_blacklistfile = '/opt/zimbra/conf/postfix_blacklist'
else:
    subprocess.call(['touch', '/opt/zimbra/conf/postfix_blacklist'], shell=True)
# Postmap
if os.path.exists('/opt/zimbra/postfix/sbin/postmap'):
    postmap = '/opt/zimbra/postfix/sbin/postmap'
elif os.path.exists('/opt/zimbra/common/sbin/postmap'):
    postmap = '/opt/zimbra/common/sbin/postmap'
else:
    logging.error('postmap nao encontrado...')
    print('caminho para o postmap nao encontrado, o Zimbra esta instalado?')
    sys.exit(1)
# Zmprov
if os.path.exists('/opt/zimbra/bin/zmprov'):
    zmprov = '/opt/zimbra/bin/zmprov'
else:
    logging.error('zmprov nao encontrado...')
    print('caminho para o zmprov nao encontrado, o Zimbra esta instalado?')
    sys.exit(1)

# Commands
cmd_awk2 = "'{print $2}'"
cmd_apagalinhasembranco = "'/^$/d'"

# Logs
logging.basicConfig(filename='/opt/pyAntispam/log/pyaddblacklist.log', format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO)

# 1
def listadeverificacao_tratada():
    try:

        if os.path.exists(amavis_novalistadeverificacao):
            amavis_listadeverificacao = open(amavis_novalistadeverificacao, 'r').read().split('\n')
            amavis_novalista = []
            amavis_listadeverificacao = sorted(amavis_listadeverificacao)
            for item in amavis_listadeverificacao:
                try:
                    for dominio in item.splitlines():
                        k, v = dominio.split("@", 2)
                        amavis_novalista.append(v)
                        logging.info('adicionando item a lista de verificacao: %s' % (v))
                except ValueError as e:
                    logging.error(e)
                    amavis_novalista.append(dominio)
                    logging.info('adicionando item a lista de verificacao: %s' % (dominio))

        lista_unica = []

        for item in amavis_novalista:
            if item not in lista_unica:
                logging.info('removendo itens repetidos na lista: %s' % (item))
                lista_unica.append(item)

        lista_unica = sorted(lista_unica)

    except Exception as e:
        print('definicao listadeverificacao_tratada erro: %s' % (e))
        logging.error('definicao listadeverificacao_tratada erro: %s' % (e))

    return lista_unica
# 2
def amavis_listatual():
    amavis_coletalistatual = 'zmprov gd %s amavisBlacklistSender | grep -v %s | awk %s | sed %s > /tmp/amavis_%s_blacklist' % (dominio, dominio, cmd_awk2, cmd_apagalinhasembranco, dominio)
    subprocess.call(amavis_coletalistatual, shell=True)
    try:
        if os.path.exists('/tmp/amavis_%s_blacklist' % (dominio)):
            amavis_listatual_dominios = ('/tmp/amavis_%s_blacklist' % (dominio))
            amavis_listatual_bruta = open(amavis_listatual_dominios, 'r').read().split('\n')
            amavis_listatual_bruta = sorted(amavis_listatual_bruta)

            amavis_listatual = []

            for item in amavis_listatual_bruta:
                if item != "":
                    amavis_listatual.append(item)
                    logging.info('adicionando item a lista atual: %s' % (item))
        else:
            print('Lista atual não encontrada. Chame o suporte.')
            logging.error('Lista atual não encontrada. Chame o suporte.')
            sys.exit(1)

        amavis_listatual = sorted(amavis_listatual)

        return amavis_listatual

    except Exception as e:
        print('definicao amavis_listatual erro: %s' % (e))
        logging.error('definicao amavis_listatual erro: %s' % (e))
# 3
def comparando_listas(atual, checagem):
    listapara_adesao = []
    try:
        for item in checagem:
            if item not in atual:
                logging.info('adicionando item para lista de adesao: %s' % (item))
                listapara_adesao.append(item)
    except Exception as e:
        print('definicao comparando_listas erro: %s' % (e))
        logging.error('definicao comparando_lista erro: %s' % (e))

    listapara_adesao = sorted(listapara_adesao)

    return listapara_adesao
# 4
def lista_ips(data):
    try:
        lista_ips = []
        lista_mx = []
        lista_unica = []
        for mxs in data:
            for mx in dns.resolver.query(mxs, 'MX'):
                mx = mx.to_text()
                try:
                    for nome_mx in mx.splitlines():
                        k, v = nome_mx.split(" ", 2)
                        lista_mx.append(v)
                        logging.info('MX coletado: %s' % (v))
                except ValueError as e:
                    logging.error(e)

            for ips in lista_mx:
                try:
                    if socket.gethostbyname(ips):
                        ip = socket.gethostbyname(ips)
                        lista_ips.append(ip)
                except Exception as e:
                    logging.warning('nao foi possivel resolver o ip do dominio: %s' % (ips))
                    print('nao foi possivel resolver o ip do dominio: %s' % (ips))
    except Exception as e:
        print('definicao lista_ips erro: %s' % (e))
        logging.error('definicao lista_ips erro: %s' % (e))

    for item in lista_ips:
        if item not in lista_unica:
            logging.info('removendo itens repetidos na lista: %s' % (item))
            lista_unica.append(item)

    lista_ip = sorted(lista_unica)

    return lista_ip
# 5
def postfix_blacklist(data):
# pegar a lista atual
    arquivo_blacklist = 'cat %s > %s' % (postfix_blacklistfile, amavis_novalistadeverificacaoip)
    subprocess.call(arquivo_blacklist, shell=True)
    blacklist_atual = open(amavis_novalistadeverificacaoip, 'r').read().split('\n')
    blacklist_atual = sorted(blacklist_atual)
    del blacklist_atual [0]

    lista_unica = []
    lista_ipatual = []
    lista_ipadesao = []
# O arquivo é alimentado IP REJECT por linha. Exemplo 1.1.1.1 REJECT
    try: # Separa IP REJECT
        for ip in blacklist_atual:
            if ip != '':
                for ip_atual in ip.splitlines():
                    k, v = ip_atual.split(" ", 1)
                    lista_ipatual.append(k)

        for item in lista_ipatual:
            if item not in lista_unica:
                logging.info('removendo itens repetidos caso existam na lista: %s' % (item))
                lista_unica.append(item)

        for ip_novo in data:
            if ip_novo not in lista_unica:
                lista_ipadesao.append(ip_novo)
                logging.info('adicionando ip: %s a lista de adesao.' % (ip_novo))

        if not len(lista_ipadesao) == 0:
            for ip_adesao in lista_ipadesao:
                print('incluindo ip: %s' % (ip_adesao))
                cmd_shell = "echo '%s REJECT' >> %s" % (ip_adesao, postfix_blacklistfile)
                subprocess.call(cmd_shell, shell=True)
                logging.info('incluindo ip: %s' % (ip_adesao))

            cmd_postmap = '%s %s' % (postmap, postfix_blacklistfile)
            subprocess.call(cmd_postmap, shell=True)

        else:
            logging.warning('nao existem novas entradas ips')
            print('nao existem novas entradas ips.')

    except Exception as e:
        print('definicao postfix_blacklist erro: %s' % (e))
        logging.error('definicao postfix_blacklist erro: %s' % (e))
# 6
def amavis_blacklistsender(data):
    try:
        if not len(data) == 0:
            for dominio_adesao in data:
                cmd_zmprov = '%s md %s +amavisBlacklistSender %s' % (zmprov, dominio, dominio_adesao)
                subprocess.call(cmd_zmprov, shell=True)
        else:
            logging.info('nao existem novas entradas dominio.')
            print('nao existem novas entradas dominio.')
    except Exception as e:
        print('definicao amavis_blacklistsender erro: %s' % (e))
        logging.error('definicao amavis_blacklistsender erro: %s' % (e))

lista_ips(comparando_listas(amavis_listatual(), listadeverificacao_tratada()))
postfix_blacklist(lista_ips(comparando_listas(amavis_listatual(), listadeverificacao_tratada())))
amavis_blacklistsender(comparando_listas(amavis_listatual(), listadeverificacao_tratada()))


import sqlite3
from aiocryptopay import AioCryptoPay, Networks
from config import cryptobot_test_net, cryptobot_main_net
from database.db_keys import user_table, k_user_id, k_locate, k_login, k_key, k_addres

cp = AioCryptoPay(token=cryptobot_main_net, network=Networks.MAIN_NET)

sql_create_users_table = f""" CREATE TABLE IF NOT EXISTS {user_table} (
                                        id integer PRIMARY KEY,
                                        {k_user_id} text NOT NULL,
                                        {k_login} text,
                                        {k_locate} text,
                                        {k_key} text,
                                        {k_addres} text,
                                        join_date datetime
                                    ); """

sql_create_record_table = f""" CREATE TABLE IF NOT EXISTS records (
                                        id integer PRIMARY KEY,
                                        {k_user_id} text NOT NULL,
                                        amount text,
                                        operation real
                                    ); """

sql_create_sequence_table = """ CREATE TABLE IF NOT EXISTS sqlite_sequence (
                                        name text NOT NULL,
                                        seq text
                                    ); """
sql_create_trans_table = f""" CREATE TABLE IF NOT EXISTS transactions (
                                        id integer PRIMARY KEY,
                                        {k_user_id} text NOT NULL,
                                        currency text NOT NULL,
                                        amount real
                                    ); """

class db:
    def __init__(self, db_file):
        self.conn = sqlite3.connect(db_file)
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute(sql_create_trans_table)
            # self.cursor.execute(sql_create_sequence_table)
            self.cursor.execute(sql_create_record_table)
            self.cursor.execute(sql_create_users_table)
        except Exception as e:
            print(e)

    def row_exist(self, table, id):
        #Проверяем, есть ли юзер в базе
        result = self.cursor.execute(f"SELECT `id` FROM `{table}` WHERE `{k_user_id}` = ?", (id,))
        return bool(len(result.fetchall()))

    def user_exists(self, user_id):
        #Проверяем, есть ли юзер в базе
        result = self.cursor.execute(f"SELECT `id` FROM `users` WHERE `{k_user_id}` = ?", (user_id,))
        return bool(len(result.fetchall()))

    def cell_exist(self,table,f_id,coll):
        result = self.cursor.execute(f"SELECT `{coll}` FROM `{table}` WHERE `{k_user_id}` = ?", (f_id,))
        f_res = result.fetchone()[0]
        return bool(f_res)

    def get_cell(self,table,coll,id):
        SQL = f"SELECT `{coll}` FROM `{table}` WHERE `{k_user_id}` = {id}"
        result = self.cursor.execute(SQL)
        return result.fetchone()[0]
    def get_row(self,table, id):
        #Достаем id юзера в базе по его user_id
        result = self.cursor.execute(f"SELECT `id` FROM `{table}` WHERE `{k_user_id}` = `{id}`",)
        return result.fetchone()[0]

    def get_user_id(self, user_id):
        #Достаем id юзера в базе по его user_id
        result = self.cursor.execute(f"SELECT `id` FROM `users` WHERE `{k_user_id}` = ?", (user_id,))
        return result.fetchone()[0]

    def get_used_locate(self, user_id):
        result = self.cursor.execute(f"SELECT `{k_locate}` FROM `{user_table}` WHERE `{k_user_id}` = ?", (user_id,))
        return result.fetchone()[0]

    def add_row(self,table,data):
        f_sql = f'INSERT INTO "{table}" ('
        f_values = ''
        for q_key in data.keys():
            f_sql += f'"{q_key}", '
            f_values += f'"{data[q_key]}",'
        f_sql = f_sql.removesuffix(', ')
        f_values = f_values.removesuffix(',')
        f_sql += f") VALUES ({f_values})"
        self.cursor.execute(f_sql)
        return self.conn.commit()

    def add_cell(self,table,f_id,coll,data):
        # data = '0x' + data
        data = data.removeprefix("0x")
        self.cursor.execute(f"UPDATE `{table}` SET `{coll}` = '%s' WHERE `{k_user_id}` = {f_id}" % data)
        return self.conn.commit()

    def add_user(self, user_id,f_key):
        #Добавляем юзера в базу
        self.cursor.execute(f"INSERT INTO `users` (`{k_user_id}`, `{k_locate}`) VALUES (?,?)", (user_id,f_key))
        return self.conn.commit()

    # def add_user(self, user_id):
    #     #Добавляем юзера в базу
    #     self.cursor.execute("INSERT INTO `users` (`user_id`) VALUES (?)", (user_id,))
    #     return self.conn.commit()

    def add_records(self, user_id, operation, amount):
        #Создаем записи о депозитах и выводах
        self.cursor.execute(f"INSERT INTO 'records'('{k_user_id}', 'operation', 'amount') VALUES (?, ?, ?)", (self.get_user_id(user_id),
                                                                                operation,
                                                                                amount))
        return self.conn.commit()

    def get_balance(self, user_id):
        #Счетаем баланс пользователя
        c = self.cursor.execute(f'SELECT COALESCE(SUM(CASE WHEN operation = "+" THEN amount ELSE -amount END), 0) AS balance FROM records WHERE {k_user_id} = ?', (self.get_user_id(user_id),))
        return c.fetchall()

    # def add_record(self, user_id, currency, amount):
    #     #Создаем запись о депозите
    #     self.cursor.execute("INSERT INTO `transactions` (`users_id`,'currency', 'amount') VALUES (?, ?, ?)", (self.get_user_id(user_id),
    #                                                                                currency,
    #                                                                                amount))
    #     return self.conn.commit()
    #
    # async def get_balance(self, user_id):
    #     #Считаем баланс пользователя
    #     c = self.cursor.execute("SELECT currency, SUM(amount) FROM transactions WHERE users_id=? GROUP BY currency", (self.get_user_id(user_id),))
    #     run_equivalent = 0.0
    #     rub_equivalent = 0.0
    #     rates = await cp.get_exchange_rates()
    #     results = c.fetchall()
    #     arr ='\n'
    #     for row in results:
    #         currency, balance = row
    #         match currency:
    #             case ("USDT"):
    #                 run_equivalent += balance * rates[0].rate
    #                 rub_equivalent = balance * rates[0].rate
    #             case ("TON"):
    #                 run_equivalent += balance * rates[18].rate
    #                 rub_equivalent = balance * rates[18].rate
    #             case ("ETH"):
    #                 run_equivalent += balance * rates[54].rate
    #                 rub_equivalent = balance * rates[54].rate
    #             case ("BNB"):
    #                 run_equivalent += balance * rates[72].rate
    #                 rub_equivalent = balance * rates[72].rate
    #             case ("BUSD"):
    #                 run_equivalent += balance * rates[90].rate
    #                 rub_equivalent = balance * rates[90].rate
    #             case ("USDC"):
    #                 run_equivalent += balance * rates[108].rate
    #                 rub_equivalent = balance * rates[108].rate
    #
    #         arr += f"{currency}: {balance}    <=>   {rub_equivalent} руб\n"
    #     arr += f"\n Ваш баланс : {run_equivalent} руб"
    #     return arr
    #
    # async def rub_balance(self, user_id):
    #     #Считаем баланс пользователя в рублях
    #     c = self.cursor.execute("SELECT currency, SUM(amount) FROM transactions WHERE users_id=? GROUP BY currency",
    #                             (self.get_user_id(user_id),))
    #     balance = 0.0
    #     rates = await cp.get_exchange_rates()
    #     results = c.fetchall()
    #     for row in results:
    #         currency, b = row
    #         match currency:
    #             case ("USDT"):
    #                 balance += b * rates[0].rate
    #             case ("TON"):
    #                 balance += b * rates[18].rate
    #             case ("ETH"):
    #                 balance += b * rates[54].rate
    #             case ("BNB"):
    #                 balance += b * rates[72].rate
    #             case ("BUSD"):
    #                 balance += b * rates[90].rate
    #             case ("USDC"):
    #                 balance += b * rates[108].rate
    #     return balance


# -*- coding: utf-8 -*-
"""
    Resources for handball models.

    TODO: Use ApiKeyAuthentication for models that need authentication. Implement custom authorization based on handball graph.
"""

from tastypie.resources import ModelResource, ALL_WITH_RELATIONS, ALL
from tastypie import fields
from handball.models import *
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.authentication import Authentication, ApiKeyAuthentication
from django.http import HttpResponse, HttpResponseBadRequest
from tastypie.http import HttpUnauthorized
from tastypie.serializers import Serializer
from tastypie.utils.mime import determine_format
from auth.api import UserResource
from django.core.mail import send_mail

class UnionResource(ModelResource):
    """
        Resource for Union model
    """
    class Meta:
        queryset = Union.objects.all()
        allowed_methods = ['get']
        authorization = Authorization()
        authentication = Authentication()
        filtering = {
            'name': ('exact')
        }

class DistrictResource(ModelResource):
    """
        Resource for District model
    """
    union = fields.ForeignKey(UnionResource, 'union', full=True)

    class Meta:
        queryset = District.objects.all()
        allowed_methods = ['get']
        authorization = Authorization()
        authentication = Authentication()
        filtering = {
            'union': ALL_WITH_RELATIONS
        }

    def dehydrate(self, bundle):
        """
            Insert 'display_name' field for use in UI
        """
        bundle.data['display_name'] = str(bundle.obj)
        return bundle

class GroupResource(ModelResource):
    """
        Resource for Group model
    """
    union = fields.ForeignKey(UnionResource, 'union', blank=True, null=True, full=True)
    district = fields.ForeignKey(DistrictResource, 'district', blank=True, null=True, full=True)
    level = fields.ForeignKey('handball.api.LeagueLevelResource', 'level', blank=True, null=True, full=True)

    class Meta:
        queryset = Group.objects.all()
        # allowed_methods = ['get', '']
        authentication = Authentication()
        authorization = Authorization()
        filtering = {
            'union': ALL_WITH_RELATIONS,
            'district': ALL_WITH_RELATIONS,
            'kind': ALL,
            'age_group': ALL,
            'gender': ALL
        }

class PersonResource(ModelResource):
    """
        Resource for Person model
    """
    user = fields.OneToOneField(UserResource, 'user', blank=True, null=True, related_name='handball_profile')

    class Meta:
        queryset = Person.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        excludes = ['activation_key', 'key_expires']
        filtering = {
            'user': ALL_WITH_RELATIONS,
            # 'clubs': ALL_WITH_RELATIONS,
            'clubs_managed': ALL_WITH_RELATIONS,
            # 'teams': ALL_WITH_RELATIONS,
            'teams_managed': ALL_WITH_RELATIONS,
            # 'teams_coached': ALL_WITH_RELATIONS,
            'first_name': ['exact'],
            'last_name': ['exact']
        }
        always_return_data = True

    def dehydrate(self, bundle):
        """
            Insert 'display_name' field for use in UI.
            'Manually' add clubs since the ManyToMany field is (for various reasons) not specified in the Resource.
        """
        bundle.data['display_name'] = str(bundle.obj)

        bundle.data['clubs'] = []
        resource = ClubResource()
        for membership in ClubMemberRelation.objects.filter(member=bundle.obj):
            clubBundle = resource.build_bundle(obj=membership.club, request=bundle.request)
            bundle.data['clubs'].append(resource.full_dehydrate(clubBundle))

        return bundle

class ClubResource(ModelResource):
    """
        Resource for the Club model
    """
    district = fields.ForeignKey(DistrictResource, 'district', full=True)
    home_site = fields.ForeignKey('handball.api.SiteResource', 'home_site', full=True, null=True)
    created_by = fields.ForeignKey(PersonResource, 'created_by', null=True)

    class Meta:
        queryset = Club.objects.all()
        allowed_methods = ['get', 'post', 'put']
        authorization = Authorization()
        authentication = Authentication()
        filtering = {
            'district': ALL_WITH_RELATIONS,
            'managers': ALL_WITH_RELATIONS
        }

    def obj_create(self, bundle, request=None, **kwargs):
        """
            Automatically fill created_by field if there is an authenticated user
        """
        bundle = super(TeamResource, self).obj_create(bundle, request)

        if request.user:
            try:
                profile = Person.objects.get(user=request.user)

                # Set created_by field
                bundle.obj.created_by = profile

                bundle.obj.save()
            except Person.DoesNotExist:
                pass

        return bundle

class TeamResource(ModelResource):
    """
        Resource for Team model
    """
    club = fields.ForeignKey(ClubResource, 'club', full=True)
    created_by = fields.ForeignKey(PersonResource, 'created_by', null=True)

    class Meta:
        queryset = Team.objects.all()
        allowed_methods = ['get', 'post', 'put']
        authorization = Authorization()
        authentication = Authentication()
        filtering = {
            'club': ALL_WITH_RELATIONS,
            'managers': ALL_WITH_RELATIONS
        }

    def obj_create(self, bundle, request=None, **kwargs):
        """
            Automatically fill created_by field and instantly validate under certain conditions
        """
        bundle = super(TeamResource, self).obj_create(bundle, request)

        if request.user:
            try:
                profile = Person.objects.get(user=request.user)

                # Set created_by field
                bundle.obj.created_by = profile

                try:
                    # Instantly validate if user is manager of the respective club
                    ClubManagerRelation.objects.get(manager=profile, club=bundle.obj.club, validated=True)
                    bundle.obj.validated = True
                except ClubManagerRelation.DoesNotExist:
                    pass

                bundle.obj.save()
            except Person.DoesNotExist:
                pass

        return bundle

    def dehydrate(self, bundle):
        """
            Insert 'display_name' field for use in UI.
            'Manually' add players since the ManyToMany field is (for various reasons) not specified in the Resource.
        """
        bundle.data['display_name'] = str(bundle.obj)

        bundle.data['players'] = []
        resource = PersonResource()
        for membership in TeamPlayerRelation.objects.filter(player=bundle.obj, validated=True):
            playerBundle = resource.build_bundle(obj=membership.player, request=bundle.request)
            bundle.data['players'].append(resource.full_dehydrate(playerBundle))
        return bundle

class SiteResource(ModelResource):
    """
        Resource for Site model
    """
    class Meta:
        queryset = Site.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True

    def dehydrate(self, bundle):
        """
            Add display_name for user in UI
        """
        bundle.data['display_name'] = str(bundle.obj)
        return bundle

class GameResource(ModelResource):
    """
        Resource for the Game model
    """
    home = fields.ForeignKey(TeamResource, 'home')
    away = fields.ForeignKey(TeamResource, 'away')
    referee = fields.ForeignKey(PersonResource, 'referee')
    timer = fields.ForeignKey(PersonResource, 'timer')
    secretary = fields.ForeignKey(PersonResource, 'secretary')
    supervisor = fields.ForeignKey(PersonResource, 'supervisor')
    winner = fields.ForeignKey(TeamResource, 'winner', null=True)
    group = fields.ForeignKey(GroupResource, 'group')
    site = fields.ForeignKey(SiteResource, 'site')
    events = fields.ToManyField('handball.api.EventResource', 'events', full=True)

    class Meta:
        queryset = Game.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True

    def hydrate_m2m(self, bundle):
        """
            For some reason tastypie does not correctly create ManyToMany relations. This is a simple fix for that.
        """
        for item in bundle.data['events']:
            item[u'game'] = self.get_resource_uri(bundle)
        return super(GameResource, self).hydrate_m2m(bundle)

class EventResource(ModelResource):
    """
        Resource for the Event model
    """
    person = fields.ForeignKey(PersonResource, 'person', full=True)
    game = fields.ForeignKey(GameResource, 'game')
    team = fields.ForeignKey(TeamResource, 'team')

    class Meta:
        queryset = Event.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        include_resource_uri = False

class ClubMemberRelationResource(ModelResource):
    """
        Resource for the ClubMemberRelation model
    """
    club = fields.ForeignKey(ClubResource, 'club', full=True)
    member = fields.ForeignKey(PersonResource, 'member', full=True)

    class Meta:
        queryset = ClubMemberRelation.objects.all()
        authorization = Authorization()
        authentication = ApiKeyAuthentication()
        always_return_data = True
        filtering = {
            'member': ALL_WITH_RELATIONS,
            'club': ALL_WITH_RELATIONS,
            'validated': ALL
        }

    def obj_create(self, bundle, request=None, **kwargs):
        """
            Instantly validate relation under certain condititions
        """
        bundle = super(ClubMemberRelationResource, self).obj_create(bundle, request)

        if request.user:
            try:
                profile = Person.objects.get(user=request.user)

                # Instantly validate if user is a manager or member of the respective club
                managers = ClubManagerRelation.objects.filter(manager=profile, club=bundle.obj.club, validated=True)
                members = ClubMemberRelation.objects.filter(member=profile, club=bundle.obj.club, validated=True)

                if (len(managers) or len(members)):
                    bundle.obj.validated = True
                    bundle.obj.save()
            except Person.DoesNotExist:
                pass

        return bundle

class GamePlayerRelationResource(ModelResource):
    """
        Resource for GamePlayerRelation resource
    """
    game = fields.ForeignKey(GameResource, 'game', full=True)
    player = fields.ForeignKey(PersonResource, 'player', full=True)
    team = fields.ForeignKey(TeamResource, 'team')

    class Meta:
        queryset = GamePlayerRelation.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True

class TeamPlayerRelationResource(ModelResource):
    """
        Resource for TeamPlayerRelation resource
    """
    team = fields.ForeignKey(TeamResource, 'team', full=True)
    player = fields.ForeignKey(PersonResource, 'player', full=True)

    class Meta:
        queryset = TeamPlayerRelation.objects.all()
        authorization = Authorization()
        authentication = ApiKeyAuthentication()
        always_return_data = True
        filtering = {
            'player': ALL_WITH_RELATIONS,
            'team': ALL_WITH_RELATIONS,
            'validated': ALL
        }

    def obj_create(self, bundle, request=None, **kwargs):
        """
            Instantly validate relation under certain conditions
        """
        bundle = super(TeamPlayerRelationResource, self).obj_create(bundle, request)

        if request.user:
            try:
                profile = Person.objects.get(user=request.user)

                club_managers = ClubManagerRelation.objects.filter(manager=profile, club=bundle.obj.team.club, validated=True)
                team_managers = TeamManagerRelation.objects.filter(manager=profile, team=bundle.obj.team, validated=True)
                players = TeamPlayerRelation.objects.filter(player=profile, team=bundle.obj.team, validated=True)
                coaches = TeamCoachRelation.objects.filter(coach=profile, team=bundle.obj.team, validated=True)

                if (len(club_managers) or len(team_managers) or len(players) or len(coaches)):
                    bundle.obj.validated = True
                    bundle.obj.save()
            except Person.DoesNotExist:
                pass

        return bundle

class TeamCoachRelationResource(ModelResource):
    """
        Resource for TeamCoachRelation model
    """
    team = fields.ForeignKey(TeamResource, 'team', full=True)
    coach = fields.ForeignKey(PersonResource, 'coach', full=True)

    class Meta:
        queryset = TeamCoachRelation.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'coach': ALL_WITH_RELATIONS,
            'team': ALL_WITH_RELATIONS,
            'validated': ALL
        }

    def obj_create(self, bundle, request=None, **kwargs):
        """
            Instantly validate relation under certain conditions
        """
        bundle = super(TeamCoachRelationResource, self).obj_create(bundle, request)

        if request.user:
            try:
                profile = Person.objects.get(user=request.user)

                club_managers = ClubManagerRelation.objects.filter(manager=profile, club=bundle.obj.team.club, validated=True)
                managers = TeamManagerRelation.objects.filter(manager=profile, team=bundle.obj.team, validated=True)
                coaches = TeamCoachRelation.objects.filter(coach=profile, team=bundle.obj.team, validated=True)

                if (len(managers) or len(club_managers) or len(coaches)):
                    bundle.obj.validated = True
                    bundle.obj.save()
            except Person.DoesNotExist:
                pass

        return bundle

class ClubManagerRelationResource(ModelResource):
    """
        Resource for ClubManagerRelation model
    """
    club = fields.ForeignKey(ClubResource, 'club', full=True)
    manager = fields.ForeignKey(PersonResource, 'manager', full=True)

    class Meta:
        queryset = ClubManagerRelation.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'club': ALL_WITH_RELATIONS,
            'manager': ALL_WITH_RELATIONS,
            'validated': ALL
        }

    def obj_create(self, bundle, request=None, **kwargs):
        """
            Instantly validate under certain conditions
        """
        bundle = super(ClubManagerRelationResource, self).obj_create(bundle, request)

        if request.user:
            try:
                profile = Person.objects.get(user=request.user)

                # Instantly validate if user is a manager of the respective club
                ClubManagerRelation.objects.get(manager=profile, club=bundle.obj.club, validated=True)
                bundle.obj.validated = True

                bundle.obj.save()
            except (Person.DoesNotExist, ClubManagerRelation.DoesNotExist):
                pass

        return bundle

class TeamManagerRelationResource(ModelResource):
    """
        Resource for TeamManagerRelation resource
    """
    team = fields.ForeignKey(TeamResource, 'team', full=True)
    manager = fields.ForeignKey(PersonResource, 'manager', full=True)

    class Meta:
        queryset = TeamManagerRelation.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'team': ALL_WITH_RELATIONS,
            'manager': ALL_WITH_RELATIONS,
            'validated': ALL
        }

    def obj_create(self, bundle, request=None, **kwargs):
        """
            Instantly validate relation under certain conditions
        """
        bundle = super(TeamManagerRelationResource, self).obj_create(bundle, request)

        if request.user:
            try:
                profile = Person.objects.get(user=request.user)

                # Instantly validate if user is a manager of the respective team
                TeamManagerRelation.objects.get(manager=profile, team=bundle.obj.team, validated=True)
                bundle.obj.validated = True

                bundle.obj.save()
            except (Person.DoesNotExist, TeamManagerRelation.DoesNotExist):
                pass

        return bundle

class LeagueLevelResource(ModelResource):
    """
        Resource for LeagueLevel model
    """
    class Meta:
        queryset = LeagueLevel.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        allowed_methods = ['get']

class GroupTeamRelationResource(ModelResource):
    """
        Resource for GroupTeamRelation resource
    """
    team = fields.ForeignKey(TeamResource, 'team', full=True)
    group = fields.ForeignKey(GroupResource, 'group', full=True)

    class Meta:
        queryset = GroupTeamRelation.objects.all()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'group': ALL_WITH_RELATIONS,
            'team': ALL_WITH_RELATIONS,
            'validated': ALL
        }

"""
Non-resource api endpoints
"""

def is_unique(request):
    """
        Check if pass number already exists
    """
    data = {}

    if 'pass_number' in request.GET:
        pass_number = request.GET['pass_number']

        try:
            Person.objects.get(pass_number=pass_number)
            unique = False
        except Person.DoesNotExist:
            unique = True
        except Person.MultipleObjectsReturned:
            unique = False

        data['pass_number'] = unique

    serializer = Serializer()

    format = determine_format(request, serializer, default_format='application/json')

    return HttpResponse(serializer.serialize(data, format, {}))

def send_invitation(request):
    """
        Send an invitation to another person via email. NOT TESTED YET
    """
    if request.user.is_authenticated() and request.user.is_active:
        if 'email' in request.POST:
            email = request.POST['email']
        else:
            return HttpResponseBadRequest('Mandatory email parameter not provided.')

        if 'message' in request.POST:
            message = request.POST['message']
        else:
            message = 'Tritt score.it bei und sehe deine Handballergebnisse online!'

        profile = None
        if 'profile' in request.POST:
            serializer = Serializer()
            profile = serializer.deserialize(request.POST['profile'])

        subject = '{0} {1} lädt dich zu Score.it ein!'.format(request.user.first_name, request.user.last_name)

        if profile:
            profile_link = 'http://score-it.de/?a=invite&p={0}'.format(profile.id)
            body = '{0} {1} hat ein Spielerprofil bei Score.it für dich erstellt. Melde dich jetzt bei Score.it an, um deine Handballergebnisse online abzurufen! Zum anmelden, klicke einfach folgenden Link: {3}'.format(request.user.first_name, request.user.last_name, profile_link)
        else:
            body = '{0} {1} hat dir eine Einladung zu der Sportplatform Score.it geschickt:<br>{2}Um dich anzumelden, besuche einfach http://score-it.de/!'.format(request.user.first_name, request.user.last_name, message)

        sender = 'noreply@score-it.de'
        recipients = [email]
        send_mail(subject, body, sender, recipients)
        return HttpResponse('')
    else:
        return HttpUnauthorized('Authentication through active user required.')