import pandas as pd
import random
import numpy as np
import os
import PIL
import seaborn as sns
import pickle
from PIL import *
import cv2
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications import DenseNet121
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.initializers import glorot_uniform
from tensorflow.keras.utils import plot_model
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint, LearningRateScheduler
from IPython.display import display
from tensorflow.python.keras import *
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import layers, optimizers
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.layers import *
from tensorflow.keras import backend as K
from keras import optimizers
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split

keyfacial_df = pd.read_csv('./../data.csv')
keyfacial_df.info()

# Check if null values exist in the dataframe
keyfacial_df.isnull().sum()

#initially 1D array
keyfacial_df['Image'].shape

#Image are given as space separated string, separate the values using ' ' as separator. 1D->2D
keyfacial_df['Image'] = keyfacial_df['Image'].apply(lambda x: np.fromstring(x, dtype = int, sep = ' ').reshape(96, 96))
keyfacial_df['Image'][0].shape

#particular column details
keyfacial_df['right_eye_center_x'].describe()

#x-coordinates are in even columns like 0,2,4,.. and y-coordinates are in odd columns like 1,3,5,..
i = np.random.randint(1, len(keyfacial_df)) # as o th row is title
plt.imshow(keyfacial_df['Image'][i], cmap = 'gray')
for j in range(1, 31, 2):
        plt.plot(keyfacial_df.loc[i][j-1], keyfacial_df.loc[i][j], 'rx')

# Let's view more images in a grid format
fig = plt.figure(figsize=(20, 20))

for i in range(64):
    ax = fig.add_subplot(8, 8, i + 1)
    x = np.random.randint(1, len(keyfacial_df))
    image = plt.imshow(keyfacial_df['Image'][x],cmap = 'gray')
    for j in range(1,31,2):
        plt.plot(keyfacial_df.loc[x][j-1], keyfacial_df.loc[x][j], 'rx')

#Data Augmentation
# Create a new copy of the dataframe
import copy
keyfacial_df_copy = copy.copy(keyfacial_df)

# Obtain the columns in the dataframe
columns = keyfacial_df_copy.columns[:-1]
columns

# Horizontal flip the images along y axis(1)
keyfacial_df_copy['Image'] = keyfacial_df_copy['Image'].apply(lambda x: np.flip(x, axis = 1))

# horizontal- y coordinate values would be the same
# Only x coordiante values would change( width of the image(96) - x) & only x cordinate only even numbers
for i in range(len(columns)):
    if i%2 == 0:
        keyfacial_df_copy[columns[i]] = keyfacial_df_copy[columns[i]].apply(lambda x: 96. - float(x) )

#  Original image
plt.imshow(keyfacial_df['Image'][9], cmap = 'gray')
for j in range(1, 31, 2):
        plt.plot(keyfacial_df.loc[9][j-1], keyfacial_df.loc[9][j], 'rx')

#  Horizontally flipped image
plt.imshow(keyfacial_df_copy['Image'][9],cmap='gray')
for j in range(1, 31, 2):
        plt.plot(keyfacial_df_copy.loc[9][j-1], keyfacial_df_copy.loc[9][j], 'rx')

# Concatenate  the flipped image
augmented_df = np.concatenate((keyfacial_df, keyfacial_df_copy))
augmented_df.shape

#clip the value between 0 and 255 as intensity <= 255

keyfacial_df_copy = copy.copy(keyfacial_df)
keyfacial_df_copy['Image'] = keyfacial_df_copy['Image'].apply(lambda x:np.clip(random.uniform(1.5, 2)* x, 0.0, 255.0))
augmented_df = np.concatenate((augmented_df, keyfacial_df_copy))
augmented_df.shape

# increased brightness
plt.imshow(keyfacial_df_copy['Image'][9], cmap='gray')
for j in range(1, 31, 2):
        plt.plot(keyfacial_df_copy.loc[9][j-1], keyfacial_df_copy.loc[9][j], 'rx')

# Vertical flip the images along x axis(0)
keyfacial_df_copy = copy.copy(keyfacial_df)
keyfacial_df_copy['Image'] = keyfacial_df_copy['Image'].apply(lambda y: np.flip(y, axis = 0))

for i in range(len(columns)):
    if i%2 != 0:
        keyfacial_df_copy[columns[i]] = keyfacial_df_copy[columns[i]].apply(lambda y: 96. - float(y) )

#  Original image
plt.imshow(keyfacial_df['Image'][9], cmap = 'gray')
for j in range(1, 31, 2):
        plt.plot(keyfacial_df.loc[9][j-1], keyfacial_df.loc[9][j], 'rx')

#  vertically flipped image
plt.imshow(keyfacial_df_copy['Image'][9],cmap='gray')
for j in range(1, 31, 2):
        plt.plot(keyfacial_df_copy.loc[9][j-1], keyfacial_df_copy.loc[9][j], 'rx')

img = augmented_df[:,30]

# Normalize the images
img = img/255.

#  array of shape (x, 96, 96, 1) to feed the model
X = np.empty((len(img), 96, 96, 1))

#  expanding it's dimension from (96, 96) to (96, 96, 1)
for i in range(len(img)):
  X[i,] = np.expand_dims(img[i], axis = 2)

# Convert the array type to float32
X = np.asarray(X).astype(np.float32)
X.shape

# Obtain the value of x & y coordinates which are to used as target.
y = augmented_df[:,:30]
y = np.asarray(y).astype(np.float32)
y.shape

# Split the data into train and test data 20% testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)

X_train.shape
y_test.shape


import pymongo
import pandas as pd
import json

from sensor.config import mongo_client
#client = pymongo.MongoClient("mongodb://localhost:27017/neurolabDB")

database_name = 'aps_database'
collection_name = 'collection_name'
data_file_path = '/config/workspace/aps_failure_training_set1.csv'

if __name__=="__main__":
    df = pd.read_csv(data_file_path)
    print(f'rows and columns: {df.shape}')

    #convert the data frame to the json so that we can dump these records in to the mongo db

    df.reset_index(drop=True, inplace=True) # dropping the index given previously and resetting it
    json_record = list((json.loads(df.T.to_json()).values()))
    print(json_record[0])

    #insert the converted json record in to the mongo db
    mongo_client[database_name][collection_name].insert_many(json_record)


import pytest

from wemake_python_styleguide.violations.best_practices import (
    WrongNamedKeywordViolation,
)
from wemake_python_styleguide.visitors.ast.statements import (
    WrongNamedKeywordVisitor,
)

@pytest.mark.parametrize('code', [
    'print(**{"@": "2"})',
    'print(**{"2ab": "2"})',
    'print(**{"!": "2"})',
    'print(**{"&a": "2"})',
    'print(**{"()": "2"})',
    'print(**{"-b": "2"})',
    'print(**{"+1": "2"})',
    'print(**{"#FFF": "2"})',
    'print(**{"some.value": "2"})',
    'print(**{"Username[FIELD]": "2"})',
    'print(**{"call()": "2"})',
    'print(end="|", **{"2ab": "2"})',
])
def test_wrong_starred_keyword(
    assert_errors,
    parse_ast_tree,
    default_options,
    code,
):
    """Testing that pointless starred expression is detected."""
    tree = parse_ast_tree(code)

    visitor = WrongNamedKeywordVisitor(default_options, tree=tree)
    visitor.run()

    assert_errors(visitor, [WrongNamedKeywordViolation])

@pytest.mark.parametrize('code', [
    '_list = [1, 2]',
    '_dict = {"end": " "}',
    'print(*_list, **_dict)',
    'print(end="1", **{"a": 1})',
    'filter(**{User.USERNAME_FIELD: username})',  # noqa: P103
    'filter(**{"a2": 1, _: 2})',
    'filter(**{"a": 1, b: 2})',
    'filter(**{"_a": 1, b: 2})',
    'filter(**{"a_": 1, b: 2})',
    'filter(**{"a": 1, call(): 2})',
    'filter(**{"a": 1, b.method(): 2})',
    'filter(**{b["a"]: 2})',
])
def test_correct_starred_keyword(
    assert_errors,
    parse_ast_tree,
    default_options,
    code,
):
    """Testing that pointless starred expression is detected."""
    tree = parse_ast_tree(code)

    visitor = WrongNamedKeywordVisitor(default_options, tree=tree)
    visitor.run()

    assert_errors(visitor, [])


import torch
from torch import nn, LongTensor
from torch.autograd import Variable
from torch.nn import functional

USE_GPU = torch.cuda.is_available()

class MTL(nn.Module):
    def __init__(self, n_job, n_geek, emb_dim = 36):
        super(MTL, self).__init__()
        self.shape = (n_job, n_geek)
        self.job_emb = nn.Embedding(n_job, emb_dim)
        self.geek_emb = nn.Embedding(n_geek, emb_dim)
        dim = emb_dim * 2
        self.dim = dim
        self.hiden1 = nn.Sequential(
            nn.Linear(dim, dim // 2, bias=False),
            nn.ReLU(),
        )
        self.hiden21 = nn.Sequential(
            nn.Linear(dim // 3, dim // 6, bias=False),
            nn.ReLU(),
            nn.Linear(dim // 6, 1, bias=False),
            nn.Sigmoid()
        )
        self.hiden22 = nn.Sequential(
            nn.Linear(dim // 3, dim // 6, bias=False),
            nn.ReLU(),
            nn.Linear(dim // 6, 1, bias=False),
            nn.Sigmoid()
        )
        self.hiden23 = nn.Sequential(
            nn.Linear(dim // 2, dim // 6, bias=False),
            nn.ReLU(),
            nn.Linear(dim // 6, 1, bias=False),
            nn.Sigmoid()
        )
        self.criterion = nn.MSELoss()

    def forward(self, *input):
        jd, resume, position = input
        jd_emb = self.jd_emb(jd)
        resume_emb = self.resume_emb(resume)
        if self.norm:
            jd_wc = self.word_count(jd)
            resume_wc = self.word_count(resume)
            jd_emb = jd_emb / jd_wc
            resume_emb = resume_emb / resume_wc
        if self.weight:
            position_emb = self.position_emb(position)
            jd_emb = self.weighted(jd_emb, position_emb)
            resume_emb = self.weighted(resume_emb, position_emb)

        jd_emb = torch.sum(jd_emb, dim=1)
        resume_emb = torch.sum(resume_emb, dim=1)

        x = torch.cat((jd_emb, resume_emb), dim=-1).squeeze(dim=1)
        x = self.hiden1(x)
        x1 = self.hiden21(x[:, :self.dim // 3])
        x2 = self.hiden22(x[:, self.dim // 6:])
        x3 = self.hiden23(x)
        x = torch.cat((x1, x2, x3), dim=-1)
        return x

    def predict(self, test_data, profile):
        n_job, n_geek = self.shape
        predictions = []
        # with torch.no_grad():
        for sample in test_data:
            job = sample[0]
            if job >= n_job:
                continue
            geeks = [x for x in sample[1:] if x < n_geek]
            job_tensor_tmp = Variable(LongTensor([job] * len(geeks)))
            geeks_tensor = Variable(LongTensor(geeks))
            position = profile['position'][job_tensor_tmp]
            job_tensor = profile['job'][job_tensor_tmp]
            geeks_tensor = profile['geek'][geeks_tensor]
            if USE_GPU:
                job_tensor = job_tensor.cuda()
                geeks_tensor = geeks_tensor.cuda()
            # print(job_tensor.shape)
            scores = self.forward(job_tensor, geeks_tensor)
            # print(scores)
            scores = scores.cpu()
            scores = scores.detach().numpy()[:, -1]
            predictions.append(scores)
        return predictions

    @staticmethod
    def batch_fit(model, optimizer, sample, profile=False):
        job = sample[:, 0]
        geek = sample[:, 1]
        label = sample[:, 2:]
        job = Variable(LongTensor(job))
        geek = Variable(LongTensor(geek))
        label = label.float()
        position = profile['position'][job]
        job = profile['job'][job]
        geek = profile['geek'][geek]
        label = label.view(label.shape[0], 1)
        if USE_GPU:
            job = job.cuda()
            geek = geek.cuda()
            position = position.cuda()
            label = label.cuda()
        # 前向传播计算损失
        out = model(job, geek, position)
        loss = model.criterion(out, label)
        # 后向传播计算梯度
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        return loss.item() * label.size(0)


import cherrypy
import click
from intercom.roots import IntercomRoot
from cherrypy.process.plugins import Daemonizer, PIDFile

def run_server(
        global_config_filename,
        app_config_filename,
        daemon_pid_filename=None):
    if daemon_pid_filename is not None:
        Daemonizer(cherrypy.engine).subscribe()
        PIDFile(cherrypy.engine, daemon_pid_filename).subscribe()

    cherrypy.config.update(global_config_filename)
    cherrypy.quickstart(root=IntercomRoot(), config=app_config_filename)

@click.command()
@click.argument('global-config', type=click.Path(exists=True, dir_okay=False))
@click.argument('app-config', type=click.Path(exists=True, dir_okay=False))
@click.option('--daemon-pid-file', type=click.Path(dir_okay=False))
def main(global_config, app_config, daemon_pid_file):
    run_server(global_config, app_config, daemon_pid_file)

if __name__ == '__main__':
    main()


import speech_recognition as sr
from gtts import gTTS
import os
import playsound
import warnings
warnings.filterwarnings("ignore")

#import the model class and the tokenizer
from transformers import BlenderbotTokenizer, BlenderbotForConditionalGeneration

# Download and setup the model and tokenizer
tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
model = BlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
playsound.playsound("Zobi.mp3")
while True:
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
        utterance = ""

        try:
            utterance = r.recognize_google(audio)
            print(utterance)
        except Exception as e:
            print("Exception: " + str(e)[3:])
    if "goodbye" in utterance:
        break
    else:
        # Tokenize the utterance
        inputs = tokenizer(utterance, return_tensors="pt")

        # Passing throuth the utterances to Blenderbot model
        res = model.generate(**inputs)

        #Decoding the model output
        respond = tokenizer.decode(res[0])[3:-4]
        print(respond)
        #sending respond to gTTS
        tts = gTTS(respond, lang='en')
        filename = 'voice1.mp3'
        tts.save(filename)
        playsound.playsound(filename)
        os.remove(filename)


# -*- coding: utf-8 -*-
"""
Created on Wed Apr  8 09:45:04 2020

@author: pang
"""

import numpy as np
from PIL import ImageGrab
import cv2
import time
import grep_sreen
import os

def self_blood_number(self_gray):
    self_blood = 0
    range_set = True
    # print(self_gray[0])
    # print(self_gray, self_gray.shape)
    for self_bd_num in self_gray[0]:
        # 大于215判定为一格血量,范围取值，血量面具为高亮
        # print(self_bd_num)
        if self_bd_num > 216 and range_set:
            self_blood += 1
            range_set = False
        elif self_bd_num < 100:
            range_set = True
    print(self_blood)
    return self_blood

main_window = (60, 99, 1219, 610)
blood_window = (222, 95, 530, 120)

last_time = time.time()
while(True):

    #printscreen = np.array(ImageGrab.grab(bbox=(window_size)))
    #printscreen_numpy = np.array(printscreen_pil.getdata(),dtype='uint8')\
    #.reshape((printscreen_pil.size[1],printscreen_pil.size[0],3))
    #pil格式耗时太长

    screen_gray = cv2.cvtColor(grep_sreen.grab_screen(main_window), cv2.COLOR_BGR2GRAY)#灰度图像收集
    # screen_reshape = cv2.resize(screen_gray,(96,86))
    self_blood = self_blood_number(screen_gray)
    print(screen_gray.shape)
    screen_gray = cv2.resize(screen_gray, (290, 128))
    print(screen_gray.shape)

    cv2.imshow('window_blood', screen_gray)
    cv2.moveWindow("window_blood", 1200, 100)
    #cv2.imshow('window3',printscreen)
    #cv2.imshow('window2',screen_reshape)

    #测试时间用
    print('loop took {} seconds'.format(time.time()-last_time))
    last_time = time.time()

    if cv2.waitKey(5) & 0xFF == ord('q'):
        break
cv2.waitKey()# 视频结束后，按任意键退出
cv2.destroyAllWindows()


import torch

import pandas as pd
from PIL import Image

from torch.utils.data import Dataset
from torchvision import transforms

import os
from os.path import join as PJ
import numpy as np
import yaml
import random

def ConceptSets(state, concepts):

    split_list = state['split_list'] + ['general']
    data_dir = PJ('./dataset', state['dataset'], 'list')
    concept_file = pd.read_csv(PJ(data_dir, 'concepts', 'concepts_' + concepts + '.txt'))
    val_times = None if state['mode'] == 'train_test' else state['val_times']

    def _concept_split():
        if state['mode'] == "train_val":
            return yaml.load(open(PJ(data_dir, 'train_val', 'id_split' + str(val_times) + '.txt')))

        else:
            return yaml.load(open(PJ(data_dir, "train_test", 'id_split' + '.txt')))

    def _concept(split_mode, concept_split):

        if split_mode in ['train', 'trainval', 'test_seen']:
            concept_label = concept_split['train_id']

        elif split_mode in ['val', 'test', 'test_unseen']:
            concept_label = concept_split['test_id']

        elif split_mode in ['general']:
            concept_label = list(range(concept_file.shape[1]))
        else:
            assert "Split Mode Error"

        concept_vector = [torch.cuda.FloatTensor(concept_file.iloc[:, i].values) for i in concept_label]

        return {'label': concept_label, 'vector': torch.stack(concept_vector)}

    concept_split = _concept_split()
    return {s: _concept(s, concept_split) for s in split_list}

def ClassDatasets(state):

    split_list = state['split_list']

    class ClassDataset(Dataset):

        def __init__(self, split_mode, state):

            self.dataset = state['dataset']

            self.split_mode = split_mode
            self.root = PJ('./dataset', state['dataset'])

            self.file_name = str(state['val_times']) + '.txt' if state.get('val_times') else '.txt'
            self.csv_file = PJ(self.root, 'list', state['mode'], self.split_mode.strip("_g") + self.file_name)
            self.data = pd.read_csv(self.csv_file, header=None)

            self.img_transform = self.img_transform()

        def __len__(self):
            return len(self.data)

        def __getitem__(self, idx):

            image = Image.open(PJ(self.root, 'img', self.data.iloc[idx, 0])).convert('RGB')
            label = torch.FloatTensor(self.data.iloc[idx, 1:].tolist())
            sample = {'image': self.img_transform(image), 'label': label}
            return sample

        def img_transform(self):

            if self.split_mode.find("train") != -1:
                img_transform = transforms.Compose([
                    transforms.RandomResizedCrop(size=256, scale=(0.8, 1.0)),
                    transforms.RandomRotation(15),
                    transforms.RandomHorizontalFlip(),
                    transforms.CenterCrop(224),
                    transforms.ToTensor()])
            else:
                img_transform = transforms.Compose([
                    transforms.Resize(256),
                    transforms.CenterCrop(224),
                    transforms.ToTensor()])

            return img_transform

    return {s: ClassDataset(s, state) for s in split_list}


# -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 09:08:03 2020

@author: Administrateur
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns #for plotting

df = pd.read_csv("heart.csv")

#Renommer les noms de colonnes
df.columns = ['age', 'sex', 'chest_pain_type', 'resting_blood_pressure', 'cholesterol',
              'fasting_blood_sugar', 'rest_ecg', 'max_heart_rate_achieved',
              'exercise_induced_angina', 'st_depression', 'st_slope',
              'num_major_vessels', 'thalassemia', 'target']

#Types des variables
df.dtypes

#Définir les types appropriés : les variables numériques discrètes deviennent de type object car elles ne sont pas continues
df['sex'] = df['sex'].astype('object')
df['chest_pain_type'] = df['chest_pain_type'].astype('object')
df['fasting_blood_sugar'] = df['fasting_blood_sugar'].astype('object')
df['rest_ecg'] = df['rest_ecg'].astype('object')
df['exercise_induced_angina'] = df['exercise_induced_angina'].astype('object')
df['st_slope'] = df['st_slope'].astype('object')
df['thalassemia'] = df['thalassemia'].astype('object')

#Vérification des nouveaux types
df.dtypes

df.describe()

#Analyse des moyennes des variables discrétisées par la variable cible target (deux modalitéS 0 ou 1, sain ou malade respectivement)
df.groupby('target').mean()
#Elle sera effectuée uniquement sur les variables quantitatives

"""Analyse univariable de la variable cible"""

#Nombre d'individus discrétisés par la variable cible
df.target.value_counts()

plt.figure(figsize=(40,20))
#Variable cible
plt.subplot(3,4,1)
sns.countplot(x="target", data=df)
plt.title('Distribution des patients non atteint et atteint de maladie cardiovasculaire')
plt.xlabel("Cible")

"""Analyse univariable du sexe"""

plt.subplot(3,4,2)
sns.countplot(x='sex', data=df)
plt.xlabel("Sexe (0 = Femme, 1 = Homme)")
plt.title("Distribution des patients par leur sexe")

#Tableau croisé
ax = plt.subplot(3,4,3)
#pd.crosstab(df["sex"], df["target"])

#pd.crosstab(df.sex,df.target).plot(kind="bar",figsize=(15,6))
pd.crosstab(df.sex,df.target).plot(kind="bar", ax=ax)
plt.title('Distibution des patients en fonction du sexe et discrétisé par la variable cible')
plt.xlabel('Sexe (0 = Femme, 1 = Homme)')
plt.xticks(rotation=0)
plt.legend(["Sain", "Malade"])
plt.ylabel('Freq')
#plt.show()

ax = plt.subplot(3,4,4)
#pd.crosstab(df.age,df.target).plot(kind="bar",figsize=(20,6))
pd.crosstab(df.age,df.target).plot(kind="bar", ax=ax)
plt.title('Distibution des patients en fonction de l âge et discrétisé par la variable cible')
plt.xlabel('Age')
plt.ylabel('Freq')
#plt.show()

#plt.savefig('heartDiseaseAndAges.png')

## Analyse univariable de la tension artérielle au repos

#Variable resting_blood_pressure

plt.subplot(3,4,5)

bx = plt.boxplot(df['resting_blood_pressure'])
plt.ylabel('Tension artérielle au repos [mm Hg]')
plt.title('Distribution de la tension artérielle au repos')

plt.subplot(3,4,6)

#Récupérer les outliers
#whiskers = terme pour dire . en dehors des boite à moustache
seuil = bx['whiskers'][1]._yorig[1]
outliers = df[df["resting_blood_pressure"]> seuil]
print(len(outliers))

#Figure
sns.countplot(x='target', data=outliers)
plt.title('Distribution des outliers de la tension artérielle au repos')

#Figure distribution des tension artérielles au repos discrétisé par variable cible
#plt.figure(figsize=(10,5))
plt.subplot(3,4,7)
plt.boxplot(df[df['target']==0]['resting_blood_pressure'])
plt.ylim([90,210])
plt.ylabel('Tension artérielle au repos [mm Hg]')
plt.title('Patients sains')

plt.subplot(3,4,8)
plt.boxplot(df[df['target']==1]['resting_blood_pressure'])
plt.ylim([90,210])
plt.ylabel('Tension artérielle au repos [mm Hg]')
plt.title('Patients malades')

plt.subplot(3,4,9)
plt.scatter(x=df.age[df.target==1], y=df.max_heart_rate_achieved[(df.target==1)], c="red")
plt.scatter(x=df.age[df.target==0], y=df.max_heart_rate_achieved[(df.target==0)])
plt.legend(["Malade", "Sain"])
plt.xlabel("Age")
plt.ylabel("Fréquence cardiaque maximale atteinte")
plt.show()

ax = plt.subplot(3,4,10)
#Equivalent
#df.groupby('target').boxplot(column='resting_blood_pressure', figsize=(15,6))
#df.groupby('target').boxplot(column='resting_blood_pressure')
#plt.show()

plt.subplot(3,4,11)
plt.scatter(x=df.age[df.target==1], y=df.max_heart_rate_achieved[(df.target==1)], c="red")
plt.scatter(x=df.age[df.target==0], y=df.max_heart_rate_achieved[(df.target==0)])
plt.legend(["Malade", "Sain"])
plt.xlabel("Age")
plt.ylabel("Fréquence cardiaque maximale atteinte")
plt.show()

ax = plt.subplot(3,4,12)
pd.crosstab(df.fasting_blood_sugar, df.target).plot(kind="bar", ax=ax)
plt.title('Distribution des patients discrétisés par la glycémie à jeun')
plt.xlabel('Glycémie à jeun - (Fasting Blood Sugar > 120 mg/dl) (1 = true; 0 = false)')
plt.xticks(rotation = 0)
plt.legend(["Sain", "Malade"])
plt.ylabel('Fréquence des patients malades ou non')
#plt.show()

df

#Boites à moustaches
df.boxplot()


from django.urls import path
from . import views

urlpatterns = [
    path('puskesmas/', views.PuskesmasView.as_view(), name='puskesmas-index'),
    path('puskesmas/<str:id_puskesmas>', views.PuskesmasDetailView.as_view(), name='puskesmas-detail'),
    path('user/', views.UserView.as_view(), name='user-index'),
    path('user/<str:id_user>', views.UserDetailView.as_view(), name='user-detail'),
    path('user/<str:id_user>/prescription/', views.PrescriptionFilterUserView.as_view(), name='prescription-user-index'),
    path('user/<str:id_user>/treatment/', views.TreatmentFilterUserView.as_view(), name='treatment-user-index'),
    path('hospital/', views.HospitalView.as_view(), name='hospital-index'),
    path('hospital/<str:id_hospital>', views.HospitalDetailView.as_view(), name='hospital-detail'),
    path('treatment/', views.TreatmentView.as_view(), name='treatment-index'),
    path('treatment/<str:id_treatment>', views.TreatmentDetailView.as_view(), name='treatment-detail'),
    path('covid-data/', views.CovidDataView.as_view(), name='covidData-index'),
    path('prescription/', views.PrescriptionView.as_view(), name='prescription-index'),
    path('prescription/<str:id_prescription>', views.PrescriptionDetailView.as_view(), name='prescription-detail'),
    path('banner/', views.BannerHeaderView.as_view(), name='banner-index'),
    path('article/', views.ArticleView.as_view(), name='article-index'),
    path('article/<str:id_article>', views.ArticleDetailView.as_view(), name='article-detail'),
]


# -*- coding: utf-8 -*-
# @File : code.py
# @Author : HK560
# @Time : 2021/11/11 17:58:45
# @LastUpdate :2021/11/18 19:14:21

from matplotlib import colors
from matplotlib.text import Annotation
from numpy.lib.shape_base import apply_along_axis, column_stack
import pandas as pd
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
from math import sqrt
import operator
from functools import reduce
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error

# 读取数据,预处理
data = pd.read_csv('housing.csv')
#去掉含有nan的行
data=data.dropna(axis=0,how='any')
#独热编码
OneHot_data=pd.get_dummies(data[['ocean_proximity']])
data=data.join(OneHot_data)
data=data.drop(['ocean_proximity'],axis=1)

#归一化
data=data/data.max(axis=0)
#print(data)

#划分训练集和测试集
train_data=data.sample(frac=0.7, random_state=0,axis=0)
test_data=data[~data.index.isin(train_data.index)]
#导出测试数据训练数据的csv文件
train_data.to_csv("train_data.csv",index=False)
test_data.to_csv("test_data.csv",index=False)
#取出X和Y
# data_org_Y=data_org[['median_house_value']]
# data_org_X=data_org.drop(['median_house_value'],axis=1)
test_data_Y=test_data[['median_house_value']]
test_data_X=test_data.drop(['median_house_value'],axis=1)
train_data_Y=train_data[['median_house_value']]#取出Y
train_data_X=train_data.drop(['median_house_value'],axis=1)

# test_data_Y_max=test_data_Y.max(axis=0)
# test_data_X_max=test_data_X.max(axis=0)
# train_data_Y_max=train_data_Y.max(axis=0)
# train_data_X_max=train_data_X.max(axis=0)
#
# test_data_Y=test_data_Y/test_data_Y_max
# test_data_X=test_data_X/test_data_X_max
# train_data_Y=train_data_Y/train_data_Y_max
# train_data_X=train_data_X/train_data_X_max

#导出训练集的X和Y
train_data_X.to_csv("train_data_X.csv",index=False)
train_data_Y.to_csv("train_data_Y.csv",index=False)

# Y_org=data_org_Y.values
# X_org=data_org_X.values

X_test=test_data_X.values
Y_test=test_data_Y.values
X=train_data_X.values
Y=train_data_Y.values
print(X.shape)
print (Y.shape)
#梯度下降
W=np.zeros(shape=[1,X.shape[1]])
b=0
#设置学习速率
alpha= 0.001
#学习次数
learning_count =100000
for i in range(learning_count):
    #y_h 是预测的y值
    y_h=np.dot(X,W.T) + b
    #求出损失
    lost=y_h-Y
    W=W - alpha*(1/len(X))*np.dot(lost.T,X)
    #给欧米噶（其实就是theta）做梯度下降
    b=b-alpha*(1/len(X))* lost.sum()
    #代价
    cost = (lost**2)/(len(X))
    if i%10000==0:
        print ('梯度下降中...')

#求出闭合式的theta
theta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y)

def R2(y_true, y_predict):
    return 1 - mean_squared_error(y_true, y_predict)/np.var(y_true)

print('测试集Y值:')
print(Y_test)

print ('——————线性回归梯度下降——————')
print('theta系数:')
print(W)
print('b值：')
print (b)
y_pre= np.dot(X_test,W.T)+b
print('测试集预测值：')
print(y_pre)

mse_test = np.sum((y_pre - Y_test) ** 2) / len(Y_test)
print('MSE:%e'%mse_test)
rmse_test = sqrt(mse_test)
print('RMSE:%e'%rmse_test)
mae_test = np.sum(np.absolute(y_pre - Y_test)) / len(Y_test)
print('MAE:%e'%mae_test)
r2_s=R2(Y_test,y_pre)
print('R2:%e'%r2_s)

print ('——————线性回归闭式解——————')
print('theta系数:')
print(theta)
y_predict = X_test.dot(theta)
print('测试集预测值：')
print(y_predict)

mse_test = np.sum((y_predict - Y_test) ** 2) / len(Y_test)
print('MSE:%e'%mse_test)
rmse_test = sqrt(mse_test)
print('RMSE:%e'%rmse_test)
mae_test = np.sum(np.absolute(y_predict - Y_test)) / len(Y_test)
print('MAE:%e'%mae_test)
r2_s=R2(Y_test,y_predict)
print('R2:%e'%r2_s)

plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

plt.figure(1)
plt.title("longitude")
pic_X=test_data_X[['longitude']]
#pic_pred_Y=reduce(operator.add, y_predict)
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(2)
plt.title("latitude")
pic_X=test_data_X[['latitude']]
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(3)
plt.title("housing_median_age")
pic_X=test_data_X[['housing_median_age']]
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(4)
plt.title("total_rooms")
pic_X=test_data_X[['total_rooms']]
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(5)
plt.title("total_bedrooms")
pic_X=test_data_X[['total_bedrooms']]
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(6)
plt.title("population")
pic_X=test_data_X[['population']]
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(7)
plt.title("households")
pic_X=test_data_X[['households']]
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(8)
plt.title("median_income")
pic_X=test_data_X[['households']]
plt.scatter(pic_X,Y_test,color='blue')
plt.scatter(pic_X,y_predict,color='red')

plt.figure(9)
plt.title("闭式解预测房价")
plt.scatter(Y_test,y_predict,color='red')
plt.plot(Y_test,Y_test,color='blue')

plt.figure(10)
plt.title("梯度下降预测房价")
plt.scatter(Y_test,y_pre,color='red')
plt.plot(Y_test,Y_test,color='blue')

# plt.figure(11)
# plt.title("org")
# plt.scatter(Y_test*train_data_Y_max,y_pre*train_data_Y_max,color='red')
# plt.plot(Y_test*train_data_Y_max,Y_test*train_data_Y_max,color='blue')

plt.grid()
plt.show()


import os
import pandas as pd
import matplotlib.pyplot as plt
path = '2020-2021/先进集体和先进个人/附件4.长安大学2020-2021学年度本科生课程优秀奖获奖学生名单'
files = os.listdir(path)
pdList = []
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
for i in files:
    pdList.append(pd.read_excel(path+'/' + i, sheet_name=0, skiprows=1, header=0).set_index('序号'))
# print(pdList[0].iloc[:, -1])
for i in range(len(pdList)):
    print(pdList[i]['分数'].value_counts().sort_values(ascending=True).index)
    x = pdList[i]['分数'].value_counts().sort_values(ascending=True).index
    y = pdList[i]['分数'].value_counts().sort_values(ascending=True).values
    plt.pie(y, labels=x)
    plt.title(files[i])
    plt.show()


LABBER_PATH = '/Program Files (x86)/Labber/Script/'
LABBER_SERVER = 'localhost'

VOLTAGE_SOURCE = 'Stanford Research SIM 960 PID Controller'
V_QUANT = 'Manual Output'
V_GAIN = 2

HEAT_SWITCH = 'HPD Heat Switch'

MAG_CYCLE_RELAY = 'Mag Cycle Relay'

SAFE_RAMP_RATE = 5.6e-3 #Amps/second

# LABBER_PATH should be added to PYTHON_PATH already. If not, uncomment the next two lines
# import sys
# sys.path.append(LABBER_PATH)

import threading
import time
import datetime
import Labber as lab
import InstrumentDriver

def get_safe_ramp_rate_V(magtime, target, resistance):
    """magtime in seconds, target is delta in amps"""

    safe_rate = SAFE_RAMP_RATE*resistance #A/second * R = V/s
    target_V = target*resistance
    ask_rate = target_V/magtime

    if safe_rate > ask_rate:
        safe_rate = ask_rate

    #This is in volts/seconds
    return safe_rate/V_GAIN

class Driver(InstrumentDriver.InstrumentWorker):

    def check_if_sweeping(self):
        val1 = self.source.getValue(V_QUANT)
        self.wait(0.5)
        val2 = self.source.getValue(V_QUANT)

        val1 = int(val1*1000)
        val2 = int(val2*1000)

        if val1 == val2:
            isSweeping = False
        else:
            isSweeping = True

        return isSweeping

    def startMag(self):

        if self.resistance is None:
            self.resistance = float(self.getCmdStringFromValue('Resistor'))
        target_I = self.getValue('Mag Current')
        target_V = target_I*self.resistance / V_GAIN

        #Set this for easy access later
        self.ramp_target = target_I

        magTime = self.getValue('Mag Time')*60
        ramprate = get_safe_ramp_rate_V(magTime, target_I, self.resistance)

        waitTime = max(target_V/ramprate, magTime)

        self.setValue('Status', 'Magging up!')

        return (target_V, ramprate, waitTime)

    def startDemag(self):

        if self.resistance is None:
            self.resistance = float(self.getCmdStringFromValue('Resistor'))

        current_V = self.source.getValue(V_QUANT)
        current_I = current_V*V_GAIN/self.resistance
        target_V = 0

        self.ramp_target = 0

        magTime = self.getValue('Demag Time')*60
        ramprate = get_safe_ramp_rate_V(magTime, current_I, self.resistance)

        waitTime = max(current_V/ramprate, magTime)

        self.setValue('Status', 'Magging down!')

        return (target_V, ramprate, waitTime)

    def finishMessage(self):
        self.resistance = None
        self.ramp_target = None
        self.setValue('Status', 'Mag Cycle finished at %s'%str(datetime.datetime.now()))

    def rampMag(self, waitTime=0, isFirstCall=True, precallback=None, postcallback=None):
        if isFirstCall:
            #Figure out the ramp rate and start going

            assert precallback is not None, "Must pass precallback for first call!"
            target_V, ramprate, waitTime = precallback()

            self.source.setValue(V_QUANT, target_V, rate=ramprate, wait_for_sweep=False)

        if waitTime - 10 > 0:
            check_start = time.time()
            current_value = self.source.getValue(V_QUANT)*V_GAIN/self.resistance
            message = 'Ramping mag to %f A. Now at: %f A. Time left: %f minutes.'%(self.ramp_target, current_value, waitTime/60)
            self.setValue('Status', message)

            waitTime-=10
            delay = time.time()-check_start

            self.timer = threading.Timer(10-delay, self.rampMag, args = [waitTime, False, None, postcallback])
            self.timer.start()

        else:
            self.wait(abs(waitTime))
            while self.check_if_sweeping():
                self.setValue('Status', 'Almost done ramping. < 1 minute.')

            if postcallback is not None:
                postcallback()

    def startSoak(self, waitTime=0, isFirstCall=True):
        check_start = time.time()
        if isFirstCall:
            waitTime = self.getValue('Soak Time')*60*60
            if self.getValue('Heat Switch Start Position') == 'Closed':
                hs_cycle_start = time.time()
                self.setValue('Status', 'Cycling heat switch before soak')
                self.heatSwitch.setValue('Heat Switch', 'Open')
                self.heatSwitch.setValue('Heat Switch', 'Closed')
                waitTime -= (time.time() - hs_cycle_start)

        if waitTime - 10 >= 0:
            self.setValue('Status', 'Soaking: %f hours remaining'%(waitTime/3600))
            waitTime -= 10
            delay = time.time()-check_start
            self.timer = threading.Timer(10-delay, self.startSoak, args = [waitTime, False])
            self.timer.start()
        else:
            self.setValue('Status', 'Opening heat switch')
            self.heatSwitch.setValue('Heat Switch', 'Open')
            self.rampMag(precallback=self.startDemag, postcallback=self.finishMessage)

    def performOpen(self, options={}):
        """Try to connect to the instruments. Start it up if necessary."""

        self.client = lab.connectToServer(LABBER_SERVER)
        instruments = self.client.getListOfInstruments()

        for hardware, config in instruments:
            if hardware == VOLTAGE_SOURCE:
                self.source = self.client.connectToInstrument(VOLTAGE_SOURCE, dict(name=config['name']))
            elif hardware == HEAT_SWITCH:
                self.heatSwitch = self.client.connectToInstrument(HEAT_SWITCH, dict(name=config['name']))
            elif hardware == MAG_CYCLE_RELAY:
                self.relay = self.client.connectToInstrument(MAG_CYCLE_RELAY, dict(name=config['name']))

        instruments = [self.source, self.heatSwitch, self.relay]

        for inst in instruments:
            assert inst is not None, "ERROR: Could not find instrument!"

            if not inst.isRunning():
                inst.startInstrument()

            assert inst.isRunning() == True, "ERROR: Cannot start instrument"

        self.timer = None
        self.ramp_target = None
        self.resistance = None

        self.setValue('Status', 'Ready to Cycle')

    def performClose(self, options = {}):
        self.setValue('Status', 'Shutting down driver and killing ramps')
        #Kill off the timer
        if self.timer is not None:
            self.timer.cancel()

        #Stop any sweeps that are currently happening
        self.source.abortCurrentOperation()

    def performSetValue(self, quant, value, sweepRate=0.0, options={}):
        if quant.name == 'Run Cycle':

            #Check for a few necessary starting conditions
            run_conditions = ((self.timer is None or self.timer.is_alive() == False), #Cycle not already running
                              self.source.getValue(V_QUANT) == 0.0, #Start fresh from zero every time
                             )

            run_error_messages = ("Mag cycle is already running!",
                                  "Must start mag cycle at zero current!")

            #Build up a list of errors preventing cycle from starting
            active_errors = []
            for condition, message in zip(run_conditions, run_error_messages):
                if condition == False:
                    active_errors.append(message)

            #Nofify user of why cycle is not starting
            if len(active_errors) > 0:
                self.setValue('Status', ', '.join(active_errors))

            #Check that all pre-conditions are satisfied
            if all(run_conditions):
                #Check to make sure the relay switch is in the desired position
                relay_position = self.relay.getValue('Relay Position')
                resistor = self.getValue('Resistor')
                if resistor == 'Mag Cycle (0.99)':
                    assert (relay_position == 'Mag Cycle'), "Set relay properly before running"
                else:
                    assert( relay_position == 'Regulate'), "Set relay properly before running"
                    message = 'Verify manual switches are set to: %s! Enter 1 to Abort: ' % resistor
                    abort = self.getValueFromUserDialog(value=0, text=message, title='Warning!')

                    if abort:
                        return value

                #Set this now for the duration of the cycle
                self.resistance = float(self.getCmdStringFromValue('Resistor'))

                self.setValue('Status', 'Setting heat switch')
                self.heatSwitch.setValue('Heat Switch', self.getValue('Heat Switch Start Position'))

                start_delay_secs = self.getValue('Start Delay Time')*60*60
                self.timer = threading.Timer(start_delay_secs, self.rampMag,
                                                kwargs = dict(precallback=self.startMag, postcallback=self.startSoak))
                self.timer.start()
                self.setValue('Status', 'Mag Cycle scheduled for %f seconds from now'%start_delay_secs)

        elif quant.name == 'Abort Cycle':
            self.setValue('Status', 'Aborting Cycle')
            if self.timer is not None:
                if self.timer.is_alive():
                    self.timer.cancel()
                    self.timer = None
                    self.setValue('Status', 'Cycle Aborted, mag sweep stopped at %s'%str(datetime.datetime.now()))

            if self.check_if_sweeping():
                self.source.abortCurrentOperation()

            self.resistance = None
            self.ramp_target = None

        return value


import webapp2
import json
import os
import logging
import facebook
import hmac
from google.appengine.api import memcache
from google.appengine.ext import ndb
from google.appengine.api import channel

class User(ndb.Model):
    #Email might be useful if Google+ will be implemented one day.
    fb_user_id = ndb.StringProperty(required=True)
    stickers = ndb.IntegerProperty(repeated=True)
    doubles = ndb.IntegerProperty(repeated=True)
    email = ndb.StringProperty(required=True)

class BaseHandler(webapp2.RequestHandler):
    """Some useful little functions that are needed in multiple Handlers."""

    WORKING_ON_FRONTEND = False
    AUTH_SECRET = "SECRET"
    FACEBOOK_APP_ID = "SECRET"
    FACEBOOK_APP_SECRET = "SECRET"

    def user_is_authorized(self, token=''):
        "Get token and check if user is authorized."
        if not token: token = self.request.get('at')
        return self.check_token(token)

    def hash_for_auth_token(self, s):
        "Return hash sum for given string s."
        return hmac.new(self.AUTH_SECRET, s).hexdigest()

    def check_token(self, s):
        "Check if string s is a valid auth token."
        if s:
            unencrypted_val, encrypted_val = s.split("-")[0], s.split("-")[-1]
            if hmac.new(self.AUTH_SECRET, unencrypted_val).hexdigest() == encrypted_val:
                return True
        return False

    def serve_static(self, relative_path, allowed_files = ['html', 'js', 'css', 'map']):
        """Given a relative path this function trys to load a file from cache.
           If file isn't in cache, it loads it from disk and adds it to it. Optional param
           mime is used for Content-Type http header. If you are developing on the front end
           make sure to change line
            file_text = memchache.get(relative_path)
                into
            file_text = ''
           otherwise you might not see the things you changed."""

        file_extension = relative_path.split('.')[-1]
        if not file_extension or file_extension not in allowed_files and '..' not in relative_path:
            self.error(404)
            return

        file_text = memcache.get(relative_path) if not self.WORKING_ON_FRONTEND else ""
        if not file_text:
            absolute_path = os.path.join(os.path.dirname(__file__), 'interface/', relative_path)
            try:
                with open (absolute_path, "r") as myfile:
                    logging.warning('Read file %s from disk' % relative_path)
                    file_text = myfile.read()
                    memcache.add(relative_path, file_text)
            except EnvironmentError: # file not found
                logging.error('Could not find %s' % absolute_path)
                self.error(404)
                return

        self.response.headers['Content-Type'] = self.mime_type(relative_path)
        self.response.out.write(file_text)
        return

    def mime_type(self, path):
        "Return Mime type for given path. If mime is unknown, returns the empty string."
        mime_map = {"html": "text/html",
                    "css": "text/css",
                    "js": "application/javascript",
                    "json": "application/json"}
        extension = path.split('.')[-1]
        if extension in mime_map:
            return mime_map[extension]
        return ""

    def print_json(self, d):
        "Given a dict returns JSON to client with correct MIME"
        self.response.headers['Content-Type'] = "application/json"
        self.response.out.write(json.dumps(d))

    def print_user_stickers(self, user_object, friends = []):
        """Given a user_object from the database, the function prints user stickers
        in JSON format. If arg friends is given (a list of user ids), each sticker in the printed json
        also contains a field called possibleSwappers that contains all user_ids of the friends list
        that have the sticker in their doubles."""
        all_stickers = {"status": "OK",
                        "stickers": []}
        if not friends:
            for sticker_nr in range(640):
                all_stickers["stickers"].append({"name": '',
                                                 "stickerNr": sticker_nr,
                                                 "collected": user_object and sticker_nr in user_object.stickers,
                                                 "isDouble": sticker_nr in user_object.doubles})
            self.print_json(all_stickers)

        else:
            friends_from_db = User.query(User.fb_user_id.IN(friends)).fetch()

            for sticker_nr in range(640):
                s = {"name": '',
                     "stickerNr": sticker_nr,
                     "collected": user_object and sticker_nr in user_object.stickers,
                     "isDouble": user_object and sticker_nr in user_object.doubles}

                if not s["collected"]:
                    s["possibleSwappers"] = [f.fb_user_id for f in friends_from_db
                                             if sticker_nr in f.doubles]
                all_stickers["stickers"].append(s)

            self.print_json(all_stickers)

class AllStickersHandler(BaseHandler):
    """Handler for /users/[uid]/stickers/all."""

    def delete(self, uid):
        "Resets all stickers and doubles."
        if self.user_is_authorized():
            auth_token = self.request.get('at')
            if auth_token.split('-')[0] == uid:
                user = ndb.Key('User', uid).get()
                user.doubles = []
                user.stickers = []
                user.put()
                self.print_json({"status": "OK"})
                return
        self.print_json({"status": "error",
                         "msg": "Authorization error."})

    def get(self, uid):
        """Prints all stickers to user. If friends HTTP arg is given,
        possible Facebook Friend swappers are returned as well."""
        if self.user_is_authorized():
            friends = self.request.get("friends").split(',')
            user = ndb.Key('User', uid).get()
            if not friends:
                self.print_user_stickers(user)
            else:
                self.print_user_stickers(user, friends)

class GetAuthToken(BaseHandler):
    "Handler for /token"
    def get(self):
        """Given a cookie with FB Auth token (From the JS SDK) this
        returns an auth-Token and stores the user into the DB if he's
        not in there already"""

        return_dict = {"status":"OK",
                       "newUser": False}

        cookie = facebook.get_user_from_cookie(self.request.cookies,
                                               self.FACEBOOK_APP_ID,
                                               self.FACEBOOK_APP_SECRET)
        if cookie:
            graph = facebook.GraphAPI(cookie["access_token"])
            profile = graph.get_object("me")
            user_from_db = ndb.Key('User', profile['id']).get()

            if not user_from_db:
                return_dict["newUser"] = True
                user_from_db = User(key=ndb.Key('User', profile["id"]),
                                    fb_user_id=profile["id"],
                                    email = "")
                user_from_db.put()

            return_dict["authToken"] = "%s-%s" % (profile["id"],
                                                  self.hash_for_auth_token(profile["id"]))
        else:
            return_dict.update({"status": "error", "msg": "Couldn't fetch Facebook data"})

        self.print_json(return_dict)

class CollectedHandler(BaseHandler):
    '''Handler for /users/[uid]/stickers/[sticker Nr.]'''

    @ndb.transactional(retries=15)
    def post(self, uid, sticker_nr):
        "Adds a given Sticker to the users collected stickers."

        form_data = json.loads(self.request.body)
        if self.user_is_authorized(token=form_data['at']):
            if form_data['at'].split('-')[0] == uid:
                #User is posting sticker in his own album
                user_from_db = ndb.Key('User', uid).get()
                if int(sticker_nr) not in user_from_db.stickers:
                    user_from_db.stickers.append(int(sticker_nr))
                    user_from_db.put()
                self.print_user_stickers(user_from_db)

    @ndb.transactional(retries=15)
    def delete(self, uid, sticker_nr):
        "Deletes a given Sticker from the users collected stickers."

        if self.user_is_authorized():
            if self.request.get('at').split('-')[0] == uid:
                user_from_db = ndb.Key('User', uid).get()
                user_from_db.stickers = filter(lambda x: x != int(sticker_nr),
                                               user_from_db.stickers)
                if int(sticker_nr) in user_from_db.doubles:
                    user_from_db.doubles = filter(lambda x: x != int(sticker_nr),
                                                  user_from_db.doubles)
                user_from_db.put()
                self.print_user_stickers(user_from_db)

class DoublesHandler(BaseHandler):

    @ndb.transactional(retries=15)
    def post(self, uid, sticker_nr):
        "Adds a given Sticker to the users double stickers."
        form_data = json.loads(self.request.body)
        if self.user_is_authorized(token=form_data['at']):
            if form_data['at'].split('-')[0] == uid:
                #User is posting sticker in his own album
                user_from_db = ndb.Key('User', uid).get()
                if int(sticker_nr) not in user_from_db.doubles:
                    user_from_db.doubles.append(int(sticker_nr))
                    if int(sticker_nr) not in user_from_db.stickers:
                        user_from_db.stickers.append(int(sticker_nr))
                    user_from_db.put()
                self.print_user_stickers(user_from_db)

    @ndb.transactional(retries=15)
    def delete(self, uid, sticker_nr):
        "Deletes a given Sticker from the users double stickers."
        if self.user_is_authorized():
            if self.request.get('at').split('-')[0] == uid:
                user_from_db = ndb.Key('User', uid).get()
                user_from_db.doubles = filter(lambda x: x != int(sticker_nr),
                                              user_from_db.doubles)
                user_from_db.put()
                self.print_user_stickers(user_from_db)

class FriendsWithCertainSticker(BaseHandler):
    "Handler for /stickers"

    def get(self):
        """Looks for two HTTP get arguments: friends and haveSticker. Friends is a
        comma seperated list of user_ids and haveSticker is an integer for which sticker
        the information is requested. You can read the request as
            'Get me all possible swaps with [friends (http arg)]. that have the sticker [haveSticker].'
        """
        if self.user_is_authorized():
            possible_swappers = []
            user_id = self.request.get('at').split('-')[0]
            user = ndb.Key('User', user_id).get()
            fb_friends = self.request.get("friends").split(',')
            sticker_nr = self.request.get('haveSticker')

            if not sticker_nr:
                self.print_json({"status": "error", "msg": "You need to send a sticker nr. as haveSticker param"})
                return
            if not fb_friends:
                self.print_json({"status": "OK", "possibleSwappers": []})
                return

            swappers = User.query(ndb.AND(User.fb_user_id.IN(fb_friends)),
                                  ndb.AND(User.doubles == int(sticker_nr))).fetch()
            for person in swappers:
                p = {"userId": person.fb_user_id}
                p["needsFromYou"] = [x for x in range(640)
                                     if x in user.doubles and x not in person.stickers]
                possible_swappers.append(p)

            self.print_json({"status": "OK",
                             "stickerNr": sticker_nr,
                             "possibleSwappers": possible_swappers})

class PossibleSwapsByFriend(BaseHandler):
    """Handler for '/users/[user_id]/possibleSwaps"""

    def get(self, user_id):
        """Get possible swaps for friend with user_id given in HTTP arg friend"""
        if self.user_is_authorized():
            user = ndb.Key('User', user_id).get()
            friend_fb_id = self.request.get('friend')
            friend = ndb.Key('User', friend_fb_id).get()

            if not friend:
                self.print_json({"status": "error", "msg": "Friend not found"})
                return

            needs_from_you = [x for x in range(640)
                              if x not in friend.stickers and x in user.doubles]
            you_need_from_him = [x for x in range(640)
                                 if x in friend.doubles and x not in user.stickers]
            self.print_json({"status": "OK",
                             "needsFromYou": needs_from_you,
                             "needFromHim": you_need_from_him})

class SingleUserHandler(BaseHandler):
    "Handler for /users/[user_id]"
    def delete(self, uid):
        "Deletes user given with uid. Facebook App disconnect should be handled on the front end"
        auth_token = self.request.get('at')
        if self.user_is_authorized():
            if auth_token.split('-')[0] == uid:
                #user is deleting himself
                ndb.Key('User', uid).delete()
                self.print_json({"status": "OK"})
                return
        self.print_json({"status": "error",
                         "msg": "Authorization error. Users can only delete themselves."})

class ServeFile(BaseHandler):
    """Handler for static files including the front page (index.html)."""
    def get(self, path):
        "Serves front page if path is /, else trys to serve the requested static file."
        if not path or path == '/':
            self.serve_static('index.html')
        else:
            self.serve_static(path)

class SwapRoomTokenHandler(BaseHandler):
    "Handler for /swapRooms/token"
    def get(self):
        "Opens a new channel and returns a new token"
        if True:#self.user_is_authorized:
            uid = "123456789"#self.request.get('at').split('-')[0]
            token = channel.create_channel(uid)
            self.print_json({"status": "OK",
                             "token": token})
            return
        self.print_json({"status": "error",
                         "msg": "Auth error."})

app = webapp2.WSGIApplication([('/users/([0-9]+)/stickers/all\/?', AllStickersHandler),
                               ('/users/([0-9]+)/stickers/([0-9]+)\/?', CollectedHandler),
                               ('/users/([0-9]+)/stickers/doubles/([0-9]+)\/?', DoublesHandler),
                               ('/users/([0-9]+)/possibleSwaps\/?', PossibleSwapsByFriend),
                               ('/users/([0-9]+)\/?', SingleUserHandler),
                               ('/swapRooms/token', SwapRoomTokenHandler),
                               ('/users', FriendsWithCertainSticker),
                               ('/token', GetAuthToken),
                               ('/stickers', AllStickersHandler),
                               ('/(.*)', ServeFile)
                               ], debug=True)


import gym
from gym import spaces
import numpy as np
import torch

class TorchWrapper(gym.Wrapper):
    """
    OpenAI Environment Wrapper that changes output types of `env.reset()` and
    `env.step()` to `torch.Tensor`.
    """
    def __init__(self, env):
        gym.Wrapper.__init__(self, env)

    def reset(self):
        ob = self.env.reset()
        ob = torch.FloatTensor([ob])
        return ob

    def step(self, action):
        ob, reward, done, info = self.env.step(action)
        ob = torch.FloatTensor([ob])
        reward = torch.FloatTensor([reward])
        done = torch.FloatTensor([done])
        return ob, reward, done, info

class AtariPermuteWrapper(gym.ObservationWrapper):
    """
    OpenAI Atari Environment Wrapper that changes output types of `env.reset()`
    and `env.step()` to `torch.Tensor`.
    """
    def __init__(self, env):
        gym.ObservationWrapper.__init__(self, env)
        shp = env.observation_space.shape
        self.observation_space = spaces.Box(
            low=0,
            high=1,
            shape=(shp[2], shp[0], shp[1]),
            dtype=np.float32)

    def observation(self, observation):
        return observation.permute(0, 3, 1, 2)


from django.urls import path

from api.apis import (DressDetail, DressList, DressLoanDetail, DressLoanList,
                      UserDetail, UserList)

urlpatterns = [
    path('dress/<uuid:id>', DressDetail.as_view(), name='dress-detail'),
    path('dress/', DressList.as_view(), name='dress-list'),
    path('loan/<uuid:id>', DressLoanDetail.as_view(), name='dressloan-detail'),
    path('loan/', DressLoanList.as_view(), name='dressloan-list'),
    path('user/', UserList.as_view(), name='user-list'),
    path('user/<int:id>', UserDetail.as_view(), name='user-detail')
]


from torchaudio.datasets import LIBRISPEECH
import pyroomacoustics as pra
import numpy as np
from typing import Tuple
from torch import Tensor
import torch
import random
from librosa.effects import split

def remove_silence(signal, top_db=20, frame_length=2048, hop_length=512):
    '''
    Remove silence from speech signal
    '''
    signal = signal.squeeze()
    clips = split(signal, top_db=top_db,
                  frame_length=frame_length, hop_length=hop_length)
    output = []
    for ii in clips:
        start, end = ii
        output.append(signal[start:end])

    return torch.cat(output)

class LibriSpeechLocations(LIBRISPEECH):
    '''
    Class of LibriSpeech recordings. Each recording is annotated with a speaker location.
    '''

    def __init__(self, source_locs, split):
        super().__init__("./", url=split, download=True)

        self.source_locs = source_locs

    def __getitem__(self, n: int) -> Tuple[Tensor, int, str, int, int, int, int, float, int]:

        source_loc = self.source_locs[n]
        seed = n
        waveform, sample_rate, transcript, speaker_id, chapter_id, utterance_number = super().__getitem__(n)
        return (waveform, sample_rate, transcript, speaker_id, utterance_number), source_loc, seed

def one_random_delay(room_dim, fs, t60, mic_locs, signal, xyz_min, xyz_max, snr, anechoic=False):
    '''
    Simulate signal propagation using pyroomacoustics using random source location.
    '''

    if anechoic:
        e_absorption = 1.0
        max_order = 0
    else:
        e_absorption, max_order = pra.inverse_sabine(t60, room_dim)

    room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(
        e_absorption), max_order=max_order)

    source_loc = np.random.uniform(low=xyz_min, high=xyz_max, size=(3))
    room.add_source(source_loc, signal=signal.squeeze())
    room.add_microphone(mic_locs)
    c = room.c
    d = np.sqrt(np.sum((mic_locs[:, 0] - source_loc)**2)) - \
        np.sqrt(np.sum((mic_locs[:, 1] - source_loc)**2))
    delay = d * fs / c
    room.simulate(reference_mic=0, snr=snr)
    x1 = room.mic_array.signals[0, :]
    x2 = room.mic_array.signals[1, :]

    return x1, x2, delay, room

def one_delay(room_dim, fs, t60, mic_locs, signal, source_loc, snr=1000, anechoic=False):
    '''
    Simulate signal propagation using pyroomacoustics for a given source location.
    '''

    if anechoic:
        e_absorption = 1.0
        max_order = 0
    else:
        e_absorption, max_order = pra.inverse_sabine(t60, room_dim)

    room = pra.ShoeBox(room_dim, fs=fs, materials=pra.Material(
        e_absorption), max_order=max_order)

    room.add_source(source_loc, signal=signal.squeeze())
    room.add_microphone(mic_locs)
    c = room.c
    d = np.sqrt(np.sum((mic_locs[:, 0] - source_loc)**2)) - \
        np.sqrt(np.sum((mic_locs[:, 1] - source_loc)**2))
    delay = d * fs / c
    room.simulate(reference_mic=0, snr=snr)
    x1 = room.mic_array.signals[0, :]
    x2 = room.mic_array.signals[1, :]

    return x1, x2, delay, room

def pad_sequence(batch):
    # Make all tensor in a batch the same length by padding with zeros
    batch = [item.t() for item in batch]
    batch = torch.nn.utils.rnn.pad_sequence(
        batch, batch_first=True, padding_value=0.)
    return batch

class DelaySimulator(object):
    '''
    Given a batch of LibrispeechLocation samples, simulate signal
    propagation from source to the microphone locations.
    '''

    def __init__(self, room_dim, fs, N, t60, mic_locs, max_tau, anechoic, train=True, snr=1000, lower_bound=16000, upper_bound=48000):

        self.room_dim = room_dim
        self.fs = fs
        self.N = N
        self.mic_locs = mic_locs
        self.max_tau = max_tau
        self.snr = snr
        self.t60 = t60
        self.anechoic = anechoic
        self.train = train

        self.lower_bound = lower_bound
        self.upper_bound = upper_bound

    def __call__(self, batch):
        # A data tuple has the form:
        # waveform, sample_rate, label, speaker_id, utterance_number

        tensors1, tensors2, targets = [], [], []

        # Gather in lists, and encode labels as indices
        with torch.no_grad():
            for (waveform, sample_rate,  _, _, _), source_loc, seed in batch:

                waveform = waveform.squeeze()
                signal = remove_silence(waveform, frame_length=self.N)

                # use random seed for training, fixed for val/test
                # this controls the randomness in sound propagation when simulating the room
                if not self.train:
                    torch.manual_seed(seed)
                    random.seed(seed)
                    np.random.seed(seed)

                # sample random reverberation time and SNR
                this_t60 = np.random.uniform(low=self.t60[0], high=self.t60[1])
                this_snr = np.random.uniform(low=self.snr[0], high=self.snr[1])

                x1, x2, delay, _ = one_delay(room_dim=self.room_dim, fs=self.fs, t60=this_t60,
                                             mic_locs=self.mic_locs, signal=signal,
                                             source_loc=source_loc, snr=this_snr,
                                             anechoic=self.anechoic)

                if self.train:
                    start_idx = torch.randint(
                        self.lower_bound, self.upper_bound - self.N - 1, (1,))
                else:
                    start_idx = self.lower_bound

                end_idx = start_idx + self.N
                x1 = x1[start_idx:end_idx]
                x2 = x2[start_idx:end_idx]

                tensors1 += [torch.as_tensor(x1, dtype=torch.float)]
                tensors2 += [torch.as_tensor(x2, dtype=torch.float)]
                targets += [delay+self.max_tau]

        # Group the list of tensors into a batched tensor
        tensors1 = pad_sequence(tensors1).unsqueeze(1)
        tensors2 = pad_sequence(tensors2).unsqueeze(1)
        targets = torch.Tensor(targets)

        return tensors1, tensors2, targets


import requests

import json

API_KEY = ""

id_ciudad = "2519239"

r = requests.get("http://api.openweathermap.org/data/2.5/weather?id=2519239&lang=es&units=metric&appid=")

respuesta = json.loads(r.text)

print(respuesta)

tiempo = respuesta['weather'][0]['description']

temp_actual = respuesta['main']['temp']

sensacion_termica = respuesta['main']['feels_like']

temp_min = respuesta['main']['temp_min']

temp_max = respuesta['main']['temp_max']

humedad = str(respuesta['main']['humidity'])+"%"

print("El timepo hoy sera", tiempo, "Temperatura: ",temp_actual,"T min:",temp_min,"T max:",temp_max,"Sensacion termica:",sensacion_termica,"Humedad:",humedad)
##print(respuesta.text)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""The setup script."""

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    'Flask==2.1.2',
    'Flask-Dropzone==1.6.0',
    'Flask-WTF==1.0.1',
    'Flask-Limiter==2.4.5.1',
    'sh==1.14.2',
]

setup_requirements = [
    'pytest-runner',
]

test_requirements = [
    'pytest',
    'coverage',
]

setup(
    author='Moritz Maehr',
    author_email='moritz.maehr@gmail.com',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
    ],
    description='Typademic turns distraction '
    'freely written markdown files into beautiful',
    install_requires=requirements,
    license='MIT license',
    long_description=readme + '\n\n' + history,
    include_package_data=True,
    keywords='typademic',
    name='typademic',
    packages=find_packages(include=['typademic']),
    setup_requires=setup_requirements,
    test_suite='tests',
    tests_require=test_requirements,
    url='https://github.com/maehr/typademic',
    version='1.2.4',
    zip_safe=False,
)


#!/usr/bin/env python

import unittest2
import logging
import time
import base64
import yaml
import subprocess
import os
import sys
import cStringIO
import tarfile
from magi.util.calls import MethodCall, CallException, dispatchCall, doMessageAction
from magi.daemon.daemon import Daemon
from magi.messaging.api import MAGIMessage
from magi.tests.util import SimpleMessaging
import magi.tests
import magi.modules
from magi.util import database

class DaemonTest(unittest2.TestCase):
	"""
		Testing of daemon and some of its components
	"""

	def setUp(self):
		database.setDBStatus(False)
		subprocess.call("rm -rf %s" % (magi.modules.__path__[0] + '/testhttp*'), shell=True)
		trans = [ {'address': '127.0.0.1', 'class': 'TCPTransport', 'port': 51232} ]
		# trans = [ {'address': '239.255.1.2', 'class':' MulticastTransport', 'localaddr': '127.0.0.1', 'port': '18808'} ]
		self.d = Daemon('mynode', trans)
		self.d.daemon = True # Helps us exit easier
		self.q = SimpleMessaging()
		self.d.messaging = self.q
		self.d.extAgentsThread.messaging = self.q
		self.d.start()

	def tearDown(self):
		logging.disable(50)
		self.d.stop()
		self.d.join(5.0)
		logging.disable(0)
		subprocess.call("rm -rf %s" % (magi.modules.__path__[0] + '/testhttp*'), shell=True)

	def test_MethodCall(self):
		""" Test MethodCall code """
		class tester(object):
			def __init__(self, ut):
				self.ut = ut
			def kwargs(self, msg, **kwargs):
				self.ut.assertEquals(kwargs['name1'], 'name1')
				self.ut.assertEquals(kwargs['name2'], 'name2')
				self.ut.assert_('name3' not in kwargs)
				self.ut.assertEquals(kwargs['ignoreme'], 'extra')
			def nameddefaults(self, msg, name1=None, name2=None, name3=None):
				self.ut.assertEquals(name1, 'name1')
				self.ut.assertEquals(name2, 'name2')
				self.ut.assertEquals(name3, None)
			def partdefaults(self, msg, name1, name2, name3=None):
				self.ut.assertEquals(name1, 'name1')
				self.ut.assertEquals(name2, 'name2')
				self.ut.assertEquals(name3, None)

		# decoding
		self.assertRaises(CallException, MethodCall, request={'version':2.0, 'method':'ping'})
		m = MethodCall(request={'version':1.0, 'method':'ping'})

		# call types
		call = {
			'version': 1.0,
			'method': 'kwargs',
			'args': { 'name1':'name1', 'name2':'name2', 'ignoreme':'extra' }
		}
		testobj = tester(self)
		testobj.name = 'testobj'
		msg=yaml.safe_dump(call)
		dispatchCall(testobj, msg, call)
		call['method'] = 'nameddefaults'
		msg = MAGIMessage(data=yaml.safe_dump(call))
		dispatchCall(testobj, msg, call)
		call['method'] = 'partdefaults'
		msg = MAGIMessage(data=yaml.safe_dump(call))
		dispatchCall(testobj, msg, call)
		del call['args']['name2']  # missing required argument
		msg = MAGIMessage(data=yaml.safe_dump(call))
		logging.disable(40)
		self.assertRaises(CallException, dispatchCall, testobj, msg, call)
		logging.disable(0)

		call['method'] = 'kwargs'
		call['args']['name2'] = 'name2'
		msg = MAGIMessage(data=yaml.safe_dump(call))
		doMessageAction(testobj, msg)

		call['trigger'] = 'MyAwesomeTrigger'
		msg = MAGIMessage(data=yaml.safe_dump(call))
		doMessageAction(testobj, msg, self.d.messaging)

	def test_Joiner(self):
		""" Test of join and leave requests """
		request = {
			'version': 1.0,
			'method': 'joinGroup',
			'args': {
				'group': 'supergroup',
				'nodes': ['mynode', 'n1', 'n2']
			}
		}

		self.q.inject(MAGIMessage(docks='daemon', data=yaml.safe_dump(request)))
		time.sleep(0.1)
		self.assert_(self.q.checkMembership('supergroup'))

		request['method'] = 'leaveGroup'
		self.q.inject(MAGIMessage(docks='daemon', data=yaml.safe_dump(request)))
		time.sleep(0.1)
		self.assert_(not self.q.checkMembership('supergroup'))

	def test_Alive(self):
		""" Test of alive ping request """
		self.q.inject(MAGIMessage(src='othernode', docks='daemon', data=yaml.safe_dump({'version':1.0, 'method':'ping'})))
		self.assertEquals('pong', self.q.extract(True, 2).msg.dstdocks.pop())
		time.sleep(0.2)

	def test_ExecThread(self):
		""" Test execing of agent in thread """
		request = {
			'version': 1.0,
			'method': 'loadAgent',
			'args': { 'name': 'tht', 'code': 'testhttpthread', 'dock': 'HTTPT', 'execargs': {'arg1':1, 'arg2':2} }
		}
		self.doMessages(request, 'testThread', True)

	def test_ExecPipe(self):
		""" Test execing of agent in a separate process that connects over pipes """
		if 'ygwin' in sys.platform and sys.version_info[1] < 5:
			raise unittest2.SkipTest("Older cygwin can't do pipes")
		request = {
			'version': 1.0,
			'method': 'loadAgent',
			'args': { 'name': 'thp', 'code': 'testhttppipe', 'dock': 'HTTPP', 'execargs': {'arg1':1, 'arg2':2} }
		}
		self.doMessages(request, 'testPipe', True)

	def test_ExecSocket(self):
		""" Test execing of agent in a separate process that connects over a socket """
		request = {
			'version': 1.0,
			'method': 'loadAgent',
			'args': { 'name': 'ths', 'code': 'testhttpsocket', 'dock': 'HTTPC', 'execargs': {'arg1':1, 'arg2':2} }
		}
		self.doMessages(request, 'testSocket', True)

	def _waitForListen(self, dock, wait=5):
		""" Waits until a particular dock has a listening agent, i.e. wait for process to start, hacks into daemon parts """
		stopat = time.time() + wait
		while time.time() < stopat:
			for tAgent in self.d.threadAgents:
				if dock in tAgent.docklist:
					return
			if self.d.extAgentsThread.wantsDock(dock):
					return
			time.sleep(0.1)

		self.assert_(False, "Failed to listen for dock within %d seconds" % wait)

	def doMessages(self, request, dirname, needTrigger):
		store = cStringIO.StringIO()
		tar = tarfile.open(fileobj=store, mode='w')
		dirpath = os.path.join(magi.tests.__path__[0], dirname)
		os.chdir(dirpath)
		tar.add('.', recursive=True)
		tar.close()
		# store now has tar data

		listeningDock = request['args']['dock']

		# First attempt has no file and should fail, have to go direct so we can catch exception
		call = MethodCall(request=request)
		self.assertRaises(EnvironmentError, self.d.loadAgent, None, **call.args)

		# Second attempt has pathname and will run
		request['args']['path'] = dirpath
		self.doOneRequest(request, listeningDock, needTrigger)

		# Third attempt has tardata and will run
		del request['args']['path']
		request['args']['dock'] += '1'
		listeningDock += '1'
		request['args']['tardata'] = base64.encodestring(store.getvalue())
		subprocess.call("rm -rf %s" % (magi.modules.__path__[0] + '/testhttp*'), shell=True)
		self.doOneRequest(request, listeningDock, needTrigger)

		# Fourth attempt has no file but is cached and will run
		del request['args']['tardata']
		request['args']['dock'] += '2'
		listeningDock += '2'
		self.doOneRequest(request, listeningDock, needTrigger)

	def doOneRequest(self, request, listeningDock, needTrigger):
		# load agent request
		self.q.inject(MAGIMessage(docks='daemon', data=yaml.safe_dump(request)))
		self._waitForListen(listeningDock)

		if needTrigger:
			transmitted = self.q.extract(True, 2)
			self.assertIn('control', transmitted.msg.dstdocks)
			self.assertIn('control', transmitted.msg.dstgroups)

		# single test message
		self.q.inject(MAGIMessage(docks=listeningDock, data='testdata'))
		transmitted = self.q.extract(True, 2)
		self.assertEquals('hello', transmitted.msg.dstdocks.pop())
		self.assertEquals(True, transmitted.args['acknowledgement'])
		self.assertEquals(98765, transmitted.args['timestamp'])

if __name__ == '__main__':
	import signal
	signal.signal(signal.SIGINT, signal.SIG_DFL)
	hdlr = logging.StreamHandler()
	hdlr.setFormatter(logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s', '%m-%d %H:%M:%S'))
	root = logging.getLogger()
	root.handlers = []
	root.addHandler(hdlr)
	root.setLevel(logging.ERROR)
	unittest2.main(verbosity=2)


#!/usr/bin/env python
from sympy import *
import matplotlib.pyplot as plt
import numpy as np
import copyright

def xsinx(x):
    y = x * np.sin(x)
    return y

def genTaylor(time):
    x = symbols('x')
    y = 0
    for n in range(0, time):
        y += x ** (2 *(n + 1)) * (-1) ** n / np.math.factorial(2 * n + 1)
    print('gen')
    y.sort_key('rev-lex')
    print(y)
    print('check')
    e = x * sin(x)
    print(e.series(x, 0, 2 *(n + 1) + 1))
    return y

def plotBoth(f2, title, xy):
    x = np.linspace(-np.pi, np.pi, 100)
    y1 = xsinx(x)
    y2 = f2(x)
    plt.plot (x, y1, '-', x, y2, '--')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('x*sin(x) & {}'.format(title))
    plt.text(xy[0], xy[1], copyright.copyright)
    plt.show()

# a

# b
def taylorB(x):
    f = lambdify(symbols('x'), genTaylor(2), 'numpy')
    return f(x)

plotBoth(taylorB, 'x**2 - x**4/6', (-3, -6))

# c
def taylorC(x):
    f = lambdify(symbols('x'), genTaylor(3), 'numpy')
    return f(x)

plotBoth(taylorC, 'x**2 - x**4/6 + x**6/120', (-3, 0))

# d
def taylorD(x):
    f = lambdify(symbols('x'), genTaylor(4), 'numpy')
    return f(x)

plotBoth(taylorD, 'x**2 - x**4/6 + x**6/120 - x**8/5040', (-3, 0))


from PIL import Image
import os
import random
import cv2
import numpy as np

# imgs_root = 'datasets/fer2013_norm/val'
#
# save_root = 'datasets/fer2013_enhanceimgs/'
# train_enhance_savedir = os.path.join(save_root, 'train')
# validation_enhance_savedir = os.path.join(save_root, 'val')

imgs_root = 'datasets/CK+_renew/CK+_reenhance/train/tail_R1'

save_root = 'datasets/CK+_renew/CK+_re_overfit_enhance/'
train_enhance_savedir = os.path.join(save_root, 'train')
validation_enhance_savedir = os.path.join(save_root, 'val')

def enhance_imgs(imgs_root, save_dir):
    landmarks_tail_dirs = os.listdir(imgs_root)
    print(landmarks_tail_dirs)
    for landmarks_tail_dir in landmarks_tail_dirs:
        if landmarks_tail_dir is not None:
            landmarks_tail_path = os.path.join('%s/%s' % (imgs_root, landmarks_tail_dir))
            print(landmarks_tail_path)
            experssion_dirs = os.listdir(landmarks_tail_path)
            print(experssion_dirs)
            for expression in experssion_dirs:
                if expression == 'surprise':
                    print(expression)
                    imgs_path = os.path.join('%s/%s' % (landmarks_tail_path, expression))
                    print(imgs_path)
                        # m=0
                    for img in os.listdir(imgs_path):
                        img_path = os.path.join('%s/%s' % (imgs_path, img))
                        print(img_path)

                        # img_s = addsalt_pepper(img_path, 0.8)

                        # img_s = PepperandSalt(img_path, 0.8)
                        # gnoises = gasuss_noise(img_path)
                        try:
                            # clahes = claheimg(img_path)
                            # lights_dark = lightness(0.87, img_path)
                            # lights_bright = lightness(1.07, img_path)
                            # rorates = rotate(random.randint(-20,20), img_path)
                            # tranposes = transpose(img_path)
                            # crops = crop(img_path)
                            mblurs = midainblur(img_path)
                            # gnoises = gasuss_noise(img_path)
                            # img_s = addsalt_pepper(img_path, 0.8)
                            # img_s = PepperandSalt(img_path, 0.8)

                        except Exception as e:
                            print(e)

                        # light_dark_img, light_dark_operate = lights_dark
                        # light_bright_img, light_bright_operate = lights_bright
                        # rorate_img, rorate_operate = rorates
                        # tranpose_img, tranpose_operate = tranposes
                        # crop_img, crop_operate = crops
                        # crop_lu_img, crop_ld_img, crop_ru_img, crop_rd_img, \
                        # crop_lu_operate, crop_ld_operate, crop_ru_operate, crop_rd_operate = crops
                        # cll_img, cll_operate = clahes
                        # light_dark_img.show()
                        blur_img, blur_operate = mblurs
                        # gnois_img, gnoise_operate = gnoises
                        # img_salt, salt_operate = img_s

                        # print(img_salt.shape)
                        # print(type(img_salt))
                        # print(type(gnois_img))
                        # print(gnois_img.dtype)
                        # img_salt = img_salt.transpose(2, 1, 0)
                        # cv2.imshow('PepperandSalt', img_salt)
                        # cv2.waitKey(0)
                        # print(img_salt.shape)
                        # print(gnois_img.shape)
                        # print(img_s.cvtColor)
                        # img_salt = cv2.cvtColor(img_salt, cv2.COLOR_BGR2GRAY)
                        # img_salt = Image.fromarray(img_salt)
                        # print(img_salt.shape)
                        # print(img_salt.dtype)
                        # for operate in [light_dark_operate, light_bright_operate, rorate_operate, tranpose_operate, crop_operate]:
                        #     save_path = os.path.join(save_dir, landmarks_tail_dir, operate, expression)
                        #     if not os.path.exists(save_path):
                        #         os.makedirs(save_path)
                        for operate in [blur_operate]:
                            save_path = os.path.join(save_dir, operate, expression)
                            if not os.path.exists(save_path):
                                os.makedirs(save_path)

                        # light_dark_img.save(save_dir + '/' + landmarks_tail_dir + '/' + light_dark_operate + '/' + expression + '/' + img)
                        # light_bright_img.save(save_dir + '/' + landmarks_tail_dir + '/' + light_bright_operate + '/' + expression + '/' + img)
                        # rorate_img.save(save_dir + '/' + landmarks_tail_dir + '/' + rorate_operate + '/' + expression + '/' + img)
                        # tranpose_img.save(save_dir + '/' + landmarks_tail_dir + '/' + tranpose_operate + '/' + expression + '/' + img)
                        # crop_img.save(save_dir + '/' + landmarks_tail_dir + '/' + crop_operate + '/' + expression + '/' + img)
                        # crop_ld_img.save(save_dir + '/' + crop_lu_operate + '/' + expression + '/' + 'crop_lu' + img)
                        # crop_ld_img.save(save_dir + '/' + crop_ld_operate + '/' + expression + '/' + 'crop_ld' + img)
                        # crop_ru_img.save(save_dir + '/' + crop_ru_operate + '/' + expression + '/' + 'crop_ru' + img)
                        # crop_ru_img.save(save_dir + '/' + crop_rd_operate + '/' + expression + '/' + 'crop_rd' + img)
                        # cv2.imwrite(save_dir + '/' + 'clahe' + '/' + expression + '/' + 'clahe' + img, cll_img)
                        # cv2.imwrite(save_dir + '/' + 'gnoise' + '/' + expression + '/' + 'gnoise' + img, gnois_img)
                        cv2.imwrite(save_dir + '/' + blur_operate + '/' + expression + '/' + 'mblur' + img, blur_img)
                        # cv2.imwrite(save_dir + '/' + 'salt_noise' + '/' + expression + '/' + 'salt_noise' + img, img_salt)
                        # img_salt.save(save_dir + '/' + salt_operate + '/' + expression + '/' + 'salt_noise' + img)

def lightness(light, img_path):
    """改变图像亮度.
    推荐值：
        0.87，1.07
    明亮程度
        darker < 1.0 <lighter
    """
    try:
        operate = 'lightness_' + str(light)

        with Image.open(img_path) as image:
            # 图像左右翻转
            light_img = image.point(lambda p: p * light)

        # 日志
        # logger.info(operate)
    except Exception as e:
        print('ERROR %s', operate)
        print(e)
    return light_img, operate

def rotate(angle, img_path):
    """图像旋转15度、30度."""
    try:
        operate = 'rotate'

        with Image.open(img_path) as image:
            # 图像左右翻转
            rorate_img = image.rotate(angle)

        # 日志
        print(operate)
    except Exception as e:
        print('ERROR %s', operate)
        print(e)
    return rorate_img, operate

def transpose(img_path):
    """图像左右翻转操作."""
    try:
        operate = 'transpose'

        with Image.open(img_path) as image:
            # 图像左右翻转
            tranpose_img = image.transpose(Image.FLIP_LEFT_RIGHT)
        # 日志
        print(operate)
    except Exception as e:
        print('ERROR %s', operate)
        print(e)
    return tranpose_img, operate

def deform(img_path):
    """图像拉伸."""
    try:
        operate = 'deform'

        with Image.open(img_path) as image:
            w, h = image.size
            w = int(w)
            h = int(h)
            # 拉伸成宽为w的正方形
            deform_ww = image.resize((int(w), int(w)))

            # 拉伸成宽为h的正方形
            deform_ww = image.resize((int(h), int(h)))

    except Exception as e:
        print('ERROR %s', operate)
        print(e)
    return deform_ww, operate

def crop(img_path):
    """提取四个角落和中心区域."""
    try:
        operate_ld = 'crop_ld'
        operate_ru = 'crop_ru'
        operate_lu = 'crop_lu'
        operate_rd = 'crop_rd'
        # crop_operate = 'crop_c'

        with Image.open(img_path) as image:
            w, h = image.size
            # 切割后尺寸
            scale = 0.875
            # 切割后长宽
            ww = int(w * scale)
            hh = int(h * scale)
            # 图像起点，左上角坐标
            x = y = 0

            # 切割左上角
            x_lu = x
            y_lu = y
            out_lu = image.crop((x_lu, y_lu, ww, hh))
            # savename = self.get_savename(operate + '_lu')
            # out_lu.save(savename, quality=100)
            # print(operate + '_lu')

            # 切割左下角
            x_ld = int(x)
            y_ld = int(y + (h - hh))
            out_ld = image.crop((x_ld, y_ld, ww, hh))
            # savename = self.get_savename(operate + '_ld')
            # out_ld.save(savename, quality=100)
            # print(operate + '_ld')

            # 切割右上角
            x_ru = int(x + (w - ww))
            y_ru = int(y)
            out_ru = image.crop((x_ru, y_ru, w, hh))
            # savename = self.get_savename(operate + '_ru')
            # out_ru.save(savename, quality=100)
            # print(operate + '_ru')

            # # 切割右下角
            x_rd = int(x + (w - ww))
            y_rd = int(y + (h - hh))
            out_rd = image.crop((x_rd, y_rd, w, h))
            # savename = self.get_savename(operate + '_rd')
            # out_rd.save(savename, quality=100)
            # print(operate + '_rd')

            # 切割中心
            x_c = int(x + (w - ww) / 2)
            y_c = int(y + (h - hh) / 2)
            crop_c = image.crop((x_c, y_c, ww, hh))
            # print('提取中心')
    except Exception as e:
        print('ERROR %s', crop_c)
        print(e)
    return out_lu, out_ld, out_ru, out_rd, operate_lu, operate_ld, operate_ru, operate_rd

# 自适应直方图均衡化数据增强
def claheimg(img_path):
    try:
        clahe_operate = 'clahe'

        image = cv2.imread(img_path, 0)
        # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        clahe = cv2.createCLAHE(clipLimit=2, tileGridSize=(10, 10))
        clahe_img = clahe.apply(image)

    except Exception as e:
        print('ERROR %s', clahe_operate)
        print(e)
    return clahe_img, clahe_operate

# 中值滤波
def midainblur(img_path):
    try:
        blur_operate = 'mblur'

        image = cv2.imread(img_path, 0)
        # image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        blur_img = cv2.medianBlur(image, 1)

    except Exception as e:
        print('ERROR %s', blur_operate)
        print(e)
    return blur_img, blur_operate

# 添加高斯噪声
def gasuss_noise(img_path, mean=0, var=0.001):
    '''
        添加高斯噪声
        mean : 均值
        var : 方差
    '''
    try:
        gnoise_operate = 'gnoise'
        image = cv2.imread(img_path, 0)
        image = np.array(image/255, dtype=float)
        noise = np.random.normal(mean, var ** 0.5, image.shape)
        out = image + noise
        if out.min() < 0:
            low_clip = -1.
        else:
            low_clip = 0.
        out = np.clip(out, low_clip, 1.0)
        out = np.uint8(out*255)
        #cv.imshow("gasuss", out)
    except Exception as e:
           print('Error %s', gnoise_operate)
    return out, gnoise_operate

# 椒盐噪声
def addsalt_pepper(imgpath, SNR):
    """
    添加椒盐噪声
    :param img:
    :param SNR:
    :return:
    """
    try:
        salt_operate = 'salt_pepper'
        img = cv2.imread(imgpath)
        # img_ = img.copy()
        img_ = img.transpose(2, 1, 0)
        c, h, w = img_.shape
        mask = np.random.choice((0, 1, 2), size=(1, h, w), p=[SNR, (1 - SNR) / 2., (1 - SNR) / 2.])
        mask = np.repeat(mask, c, axis=0)     # 按channel 复制到 与img具有相同的shape
        img_[mask == 1] = 255    # 盐噪声
        img_[mask == 2] = 0      # 椒噪声
    except Exception as e:
        print('Error %s', salt_operate)
    return img_, salt_operate

def PepperandSalt(imgpath, percetage):
    try:
        salt_operate = 'salt_pepper'
        src = cv2.imread(imgpath, 0)
        NoiseImg=src
        NoiseNum=int(percetage*src.shape[0]*src.shape[1])
        for i in range(NoiseNum):
            randX=random.randint(0, src.shape[0]-1)
            randY=random.randint(0, src.shape[1]-1)
            if random.randint(0,1)<=0.5:
                NoiseImg[randX, randY]=0
            else:
                NoiseImg[randX, randY]=255
    except Exception as e:
        print('Error %s', salt_operate)
    return NoiseImg, salt_operate

if __name__ == '__main__':
    # import datetime
    #
    # print('start...')
    # # 计时
    # start_time = datetime.datetime.now()
    #
    # test()
    #
    # end_time = datetime.datetime.now()
    # time_consume = (end_time - start_time).microseconds / 1000000
    enhance_imgs(imgs_root, train_enhance_savedir)
    # img_path = 'datasets/fer2013_landmarks_tail/train/global_tail/0/00000.jpg'
    # img = cv2.imread(img_path, 0)
    # rorate_img = rotate(img, 15)
    # cv2.imshow('rorate_img', rorate_img)
    # cv2.waitKey(0)
    # cv2.imwrite()