# -*- coding: utf-8-*-
import random
import re
import json
import httplib
from datetime import datetime
from dateutil import tz
from client import jasperpath

WORDS = ["OCTO", "EVENTS"]

def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, by telling a joke.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    events = "These are the last 5 Octo Events. "
    JasperKey = "API-get your own key"
    connection = httplib.HTTPConnection("kno2-deploy.cloudapp.net", 80)
    connection.connect()
    connection.request('GET', '/api/events', None, {"X-Octopus-ApiKey": JasperKey})
    result = json.loads(connection.getresponse().read())
    index = 0
    for attribute, value in result.iteritems():
        if attribute == "Items":
            for each_dict in value[:5]:
                friendlydate = datetime.strptime(each_dict.get("Occurred"), "%Y-%m-%dT%H:%M:%S.%f+00:00")
                from_zone = tz.tzutc()
                to_zone = tz.tzlocal()
                friendlydate = friendlydate.replace(tzinfo=from_zone)
                central = friendlydate.astimezone(to_zone)
                events += "Event: " + each_dict.get("Message") + " was performed by " + each_dict.get("Username") + " at " + \
                      central.strftime("%m/%d/%Y at %H:%M Local Time.")

    mic.say(events)

def isValid(text):
    """
        Returns True if the input is related to jokes/humor.

        Arguments:
        text -- user-input, typically transcribed speech
    """
    return bool(re.search(r'\bocto events\b', text, re.IGNORECASE))


import matplotlib.pyplot as plt
import numpy as np
import csv

def adjacent_values(vals, q1, q3):
    upper_adjacent_value = q3 + (q3 - q1) * 1.5
    upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])

    lower_adjacent_value = q1 - (q3 - q1) * 1.5
    lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
    return lower_adjacent_value, upper_adjacent_value

def set_axis_style(ax, labels):
    ax.get_xaxis().set_tick_params(direction='out')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_xticks(np.arange(1, len(labels) + 1))
    ax.set_xticklabels(labels)
    ax.set_xlim(0.25, len(labels) + 0.75)
    ax.set_xlabel('Sample name')

def read_results_csv(file_path, row_id=0):
    dice_values = []
    with open(file_path, 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            dice_values.append(float(row[row_id]))

        return dice_values

# create test data
np.random.seed(19680801)

path_file_1 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
                  '3x3_grayscale_dataset/results/' \
                  'ResUnet_lr_0.001_bs_16_grayscale_16_11_2020_19_37/' \
                  'results_evaluationtest_01_ResUnet_lr_0.001_bs_16_grayscale_16_11_2020_19_37_new.csv'

path_file_2 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
              '3x3_grayscale_dataset/results/' \
              'ResUnet_lr_1e-05_bs_16_grayscale_16_11_2020_19_32/' \
              'results_evaluationtest_01_ResUnet_lr_1e-05_bs_16_grayscale_16_11_2020_19_32_new.csv'

path_file_3 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
              'lumen_data/results/' \
              'ResUnet_lr_0.001_bs_16_hsv_14_11_2020_20_06/' \
              'results_evaluation_test_02_ResUnet_lr_0.001_bs_16_hsv_14_11_2020_20_06_.csv'

path_file_4 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
              'lumen_data/results/' \
              'ResUnet_lr_0.001_bs_16_rgb_06_11_2020_00_51/' \
              'results_evaluation_test_02_ResUnet_lr_0.001_bs_16_rgb_06_11_2020_00_51_.csv'

path_file_5 = '/home/nearlab/Jorge/current_work/lumen_segmentation/' \
              'data/' \
              '3x3_grayscale_dataset/results/MaskRCNN_2/' \
              'results_evaluationtest_02_MaskRCNN_2_new.csv'

path_file_6 = '/home/nearlab/Jorge/current_work/lumen_segmentation/' \
              'data/3x3_grayscale_dataset/' \
              'results/MaskRCNN_2/' \
              'results_evaluationtest_02_MaskRCNN_2_new.csv'

data_experiment_1 = sorted(read_results_csv(path_file_1, 2))
data_experiment_2 = read_results_csv(path_file_2, 2)
data_experiment_3 = read_results_csv(path_file_3, 2)
data_experiment_4 = sorted(read_results_csv(path_file_4, 2))
data_experiment_5 = sorted(read_results_csv(path_file_5, 2))
data_experiment_6 = sorted(read_results_csv(path_file_6, 2))

#data = [data_experiment_1, data_experiment_4, data_experiment_5, data_experiment_6]
#data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)]
data = [data_experiment_1, data_experiment_2,
        data_experiment_3, 0, 0, 0]
data_2 = [0,0,0, data_experiment_4,
        data_experiment_5, data_experiment_6]
print(np.shape(data))

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,
                               figsize=(9, 5), sharey=True)

ax1.set_title('Default violin plot')
ax1.set_ylabel('Observed values')
ax1.violinplot(data)
ax1.violinplot(data_2)

ax2.set_title('Customized violin plot')
parts = ax2.violinplot(
        data, showmeans=True, showmedians=True,
        showextrema=True)
"""
for pc in parts['bodies']:
    pc.set_facecolor('#D43F3A')
    pc.set_edgecolor('black')
    pc.set_alpha(1)

quartile1, medians, quartile3 = np.percentile(data, [25, 50, 100], axis=1)
print(quartile1, medians, quartile3)
whiskers = np.array([
    adjacent_values(sorted_array, q1, q3)
    for sorted_array, q1, q3 in zip(data, quartile1, quartile3)])
whiskers_min, whiskers_max = whiskers[:, 0], whiskers[:, 1]

inds = np.arange(1, len(medians) + 1)
ax2.scatter(inds, medians, marker='o', color='white', s=30, zorder=3)
ax2.vlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5)
ax2.vlines(inds, whiskers_min, whiskers_max, color='k', linestyle='-', lw=1)
"""
# set style for the axes
labels = ['A', 'B', 'C', 'D', 'E', 'F']
for ax in [ax1, ax2]:
    set_axis_style(ax, labels)

plt.subplots_adjust(bottom=0.15, wspace=0.05)
plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov  8 14:06:56 2018

@author: chenhx1992
"""

import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
import numpy as np
from itertools import combinations
import itertools

lst = np.arange(0, 256, 5)
# for combo in combinations(lst, 3):  # 2 for pairs, 3 for triplets, etc
#     print(combo)

RGBlist = list(itertools.product(lst, lst, lst))

# RGBlist = [(random.randint(0,255), random.randint(0,255), random.randint(0,255)) for i in range(100)]
paleta=list(zip(*RGBlist))
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter([(x-127)/128. for x in paleta[0]],[(x-127)/128. for x in paleta[1]],[(x-127)/128. for x in paleta[2]], c=[(r[0] / 255., r[1] / 255., r[2] / 255.) for r in RGBlist])
ax.grid(False)
ax.set_title('RGB Color Cube')
ax.set_xlabel('Red',fontsize=12)
ax.set_ylabel('Green',fontsize=12)
ax.set_zlabel('Blue',fontsize=12, rotation=90)
# make the panes transparent
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# make the grid lines transparent
ax.xaxis._axinfo["grid"]['color'] =  (1,1,1,0)
ax.yaxis._axinfo["grid"]['color'] =  (1,1,1,0)
ax.zaxis._axinfo["grid"]['color'] =  (1,1,1,0)
# plt.savefig('blah.png')


import cv2
import numpy as np

img=np.zeros((512,512,3),np.int8)

#Function to draw a circle
def draw_circle(event,x,y,flags,param):
    if(event==cv2.EVENT_LBUTTONDOWN):
        cv2.circle(img,(x,y),100,(255,0,255),-1)

cv2.namedWindow('my_drawing')
cv2.setMouseCallback('my_drawing',draw_circle)

#Display the image
while True:
    cv2.imshow('my_drawing',img)
    if cv2.waitKey(20) & 0xFF==27:
        break
cv2.destroyAllWindows()


# Copyright 2014 by Ethan Fritz. All Rights Reserved.

import data.contestant
import random
import logging

class Heat(object):
    def __init__(self, racers):
        self.run_complete = False
        self.populate_heat(racers)

    def populate_heat(self, racers):
        self.racers = []
        self.times = []
        self.places = []
        for racer in racers:
            self.racers.append(racer)
            self.times.append(None)
            self.places.append(None)

    def set_time_and_place(self, times):
        logging.info("Race finished. Setting time and placement.")
        logging.debug("Setting Times = %s", times)
        logging.debug("Racers = %s", [x.id for x in self.racers])
        assert(all(isinstance(x, (float)) for x in times))
        assert(len(times) == len(self.racers))
        assert(len(times) == len(self.times))
        assert(len(times) == len(self.places))
        self.run_complete = True

        times_indexed = []
        for index, time in enumerate(times):
            self.times[index] = time
            times_indexed.append((time, index))
        times_indexed.sort(reverse=False)

        for placement, (time, index) in enumerate(times_indexed):
            self.places[index] = placement + 1
        logging.debug("Heat's Times = %s", self.times)
        logging.debug("Heat's Places = %s", self.places)

    def winner(self):
        "Return a list of the winner."
        winner = []
        winners_index = self.places.index(1)
        winner.append(self.racers[winners_index])
        return winner

    def losers(self):
        "Return a list of the losers."
        losers = []
        winners_index = self.places.index(1)
        for index, racer in enumerate(self.racers):
            if index != winners_index:
                losers.append(racer)
        return losers

    def number_of_racers(self):
        return len(self.racers)

class DoubleEliminationHeat(Heat):
    "Adds double elimination state to the Heat class."

    def __init__(self, lanes, entries):
        assert(isinstance(lanes, (int)))
        assert(len(entries) >= 2)

        self.first_elimination_phase = True
        self.final_heat = False
        self.win_bracket = []
        self.loss_bracket = []
        self.noloss_bracket = list(entries)
        random.shuffle(self.noloss_bracket)
        racers = []
        for i in range(lanes):
            if len(self.noloss_bracket) > 0:
                racers.append(self.noloss_bracket.pop(0))
            else:
                break
        assert(len(racers) >= 2)
        Heat.__init__(self, racers)


# ！/usr/bin/env python3
# -*-coding: UTF-8 -*-
# Author Frank

import time
import cv2
import numpy
import pytesseract
import pyautogui as auto

from datetime import datetime
from core import selfcv, debug_mode
from logzero import logger

class Adam:

    def __init__(self):
        self.point = None
        self.offset = (None, None)
        # auto.FAILSAFE = False
        # auto.PAUSE = 0.1

    @property
    def point_offset(self):
        x0, y0 = self.offset
        istuple = isinstance(self.point, tuple)
        res = map(lambda x: (x[0] + x0, x[1] + y0), [self.point] if istuple else self.point)
        return next(res) if istuple else list(res)

    def find_object(self, image, templ, *args, match_rate=0.8, return_center=True):
        """ Find object on screen.

        Args:
            image: 图片地址
            templ: 大图
            match_rate: 匹配率
            return_center: 是否返回图片中心坐标，否为返回左上角

        Returns:

        """
        img_sml = cv2.imread(image)
        if isinstance(templ, str):
            img_big = cv2.imread(templ)
        elif callable(templ):
            img_big = templ(*args)
        else:
            img_big = templ

        r = selfcv.single_match_template(img_sml, img_big, match_rate=match_rate, return_center=return_center)
        if debug_mode:
            # logger.debug("{0}:{1}".format(image, r[3]))
            logger.debug("{0}:{1}".format(image, r))
        if r[0]:
            self.point = (r[1], r[2])
            return True
        else:
            self.point = None
            return False

    def count_object(self, image, templ, match_rate=0.8, return_center=True):
        """
        Count the object on screen.
        :param image: image of object.
        :param templ: 大图
        :param match_rate: 匹配率
        :param return_center: 是否返回中心坐标
        :return:
        """
        # Take a ScreenShot, then convert picture to OpenCV format.
        img_sml = cv2.imread(image)
        img_big = templ
        # img_big = auto.screenshot()
        r = selfcv.multi_match_template(img_sml, img_big, match_rate=match_rate, return_center=return_center)
        if not r[0]:
            self.point = None
            return False
        else:
            self.point = r[1]
            return True

    def wait_for_object(self, image, templ, *args, match_rate=0.8, duration=60):
        """
        Find object on the screen within given times.
        :param image:
        :param templ:
        :param match_rate:
        :param duration:->int seconds
        :return:
        """
        start = datetime.utcnow()
        while True:
            delta = datetime.utcnow() - start
            if delta.seconds < duration:
                if isinstance(templ, str):
                    img_big = cv2.imread(templ)
                elif callable(templ):
                    img_big = templ(*args)
                else:
                    img_big = templ
                if self.find_object(image, img_big, match_rate=match_rate):
                    return True
                else:
                    continue
            else:
                raise Exception("Can't find image")

    def touch_object(self, image, templ):
        if self.find_object(image, templ):
            self.click_object()
        else:
            raise Exception("Can't find image.")

    def click_object(self, left=True, times=1):
        self.clickpoint(self.point, left, times)

    def show_screenshot(self, rgb=True):
        mode = cv2.COLOR_RGB2BGR
        if not rgb:
            mode = cv2.COLOR_BGR2GRAY
        img = cv2.cvtColor(numpy.asarray(self.screenshot()), mode)
        img = cv2.resize(img, (1536, 864))
        cv2.imshow('image', img)
        cv2.waitKey(0)

    @classmethod
    def clickpoint(cls, points, left=True, times=1):
        if isinstance(points, tuple):
            if left:
                if times == 1:
                    auto.click(*points)
                elif times == 2:
                    auto.doubleClick(*points)
                elif times == 3:
                    auto.tripleClick(*points)
                else:
                    raise Exception("times must within 1~3.")
                time.sleep(0.2)
            else:
                auto.rightClick(*points)
        elif isinstance(points, list):
            for point in points:
                auto.click(*point)
                time.sleep(0.2)
        auto.dragTo(1920, 1080)

    @classmethod
    def find_text(cls, message):
        img = cls.screenshot()
        """
        waiting for adding image processing.
        """
        text = cls.do_ocr_on_image(img)
        for word in text:
            if message in word:
                return word
        else:
            return False

    @classmethod
    def key_down(cls, key):
        auto.keyDown(key)

    @classmethod
    def key_up(cls, key):
        auto.keyUp(key)

    @classmethod
    def click_key(cls, key, times=1, interval=0):
        auto.press(key, presses=times, interval=interval)

    @classmethod
    def hot_key(cls, *keys):
        auto.hotkey(*keys)

    @classmethod
    def send_text(cls, message, interval=0.1):
        auto.typewrite(message, interval=interval)

    @classmethod
    def do_ocr_on_image(cls, img, data=False):
        image = cv2.imread(img, cv2.IMREAD_GRAYSCALE)
        if data:
            data = pytesseract.image_to_data(image)
            return data
        string = pytesseract.image_to_string(image, lang='eng')
        return string

    @classmethod
    def screenshot(cls):
        """
        Take a screenshot and save it.
        :return:
        """
        temp_pic = auto.screenshot()
        screen = cv2.cvtColor(numpy.asarray(temp_pic), cv2.COLOR_RGB2BGR)
        cv2.imshow('ts', screen)
        cv2.waitKey(0)
        return screen


#!/usr/bin/python

from __future__ import division

import numpy as np
import matplotlib

matplotlib.use('Agg')
import xgboost as xgb
import matplotlib.pyplot as plt
from itertools import cycle
from sklearn.preprocessing import normalize

from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from scipy import interp

def addFea(train_Xn, train_X, num1, num2):
    train_var = tran(train_X[:, 1:], np.var, axis=1)
    train_zero = tran(train_X, np.count_nonzero, axis=1)
    train_zero.shape = 1, -1
    train_zero = map(lambda x: 94 - x, train_zero)
    train_zero = np.transpose(train_zero)
    train_add = np.add(train_X[:, num1], train_X[:, num2])
    train_mul = train_X[:, num1] * train_X[:, num2]
    train_sub = np.subtract(train_X[:, num1], train_X[:, num2])

    with np.errstate(divide='ignore', invalid='ignore'):
        train_div = np.true_divide(train_X[:, 25], train_X[:, 67])
        train_div[train_div == np.inf] = 0
        train_div = np.nan_to_num(train_div)

    train_Xn = np.c_[train_Xn, train_var, train_zero, train_add, train_sub, train_mul, train_div]
    return train_Xn

def tran(array, func, *args, **kwargs):
    res = func(array, *args, **kwargs)
    res.shape = (res.shape[0], 1)
    np.transpose(res)
    return res

def normalizer(lst):
    norm = lst
    for i in range(lst.shape[0]):
        norm[i] = [(float(2 * j) - max(lst[i]) - min(lst[i])) / (max(lst[i]) - min(lst[i])) for j in lst[i]]
        if (i % 500 == 0):
            print(" %.4f done" % (float(i / lst.shape[0])))
    return norm

# label need to be 0 to num_class -1
data = np.loadtxt('../train.csv', skiprows=1, delimiter=',',
                  converters={0: lambda x: int('0'), 94: lambda x: int(x[6:]) - 1})
sz = data.shape

np.random.shuffle(data)
train = data[:int(sz[0] * 0.9), :]
test = data[int(sz[0] * 0.9):, :]

train_X = train[:, :93]
train_Xo = train_X

train_Y = train[:, 94]
train_X = addFea(train_X, train_Xo, 25, 67)
train_X = addFea(train_X, train_Xo, 25, 86)
print(train_X[0, :])

train_X = normalize(train_X, norm='l2')

test_X = test[:, :93]
test_Xo = test_X
test_X = addFea(test_X, test_X, 25, 67)
test_X = addFea(test_X, test_Xo, 25, 86)

test_X = normalize(test_X, norm='l2')

test_Y = test[:, 94]
test_Yb = label_binarize(test_Y, classes=range(0, 9))

xg_train = xgb.DMatrix(train_X, label=train_Y)
xg_test = xgb.DMatrix(test_X, label=test_Y)
# setup parameters for xgboost
param = {}
# use softmax multi-class classification
param['objective'] = 'multi:softmax'
# scale weight of positive examples
param['eta'] = 0.1
# param['max_depth'] = int('6')
param['silent'] = 1
param['nthread'] = 4
param['num_class'] = 9

watchlist = [(xg_train, 'train'), (xg_test, 'test')]
num_round = 5
model = xgb.XGBClassifier(max_depth=10, subsample=0.70, colsample_bytree=0.7, objective='multi:softmax', learning_rate=0.05,
                          gamma=5, silent=0,
                          # n_jobs=40, num_class=9
                          )
model.fit(train_X, train_Y)

# bst = xgb.train(param, xg_train, num_round, watchlist)
# get prediction_cascaded
# pred = bst.predict(xg_test)

res = model.predict(test_X)
pred = model.predict_proba(test_X)

# print(model.booster().get_score(importance_type='weight'))
# print(model.booster().plot_importance(model))

'''
for i in range(test_X.shape[0]):
    if res[i] == test_Y[i]:
        print(pred[i])
        print(test_Y[i])
'''

# pred_b = label_binarize(pred, classes=range(0,9))
def plot(test_Yb, pred, param, filename="otto"):
    fpr = dict()
    tpr = dict()

    roc_auc = dict()

    for i in range(param['num_class']):
        fpr[i], tpr[i], _ = roc_curve(test_Yb[:, i], pred[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])

    fpr["micro"], tpr["micro"], _ = roc_curve(test_Yb.ravel(), pred.ravel())
    roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

    n_classes = param["num_class"]
    # Compute macro-average ROC curve and ROC area

    # First aggregate all false positive rates
    all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))

    # Then interpolate all ROC curves at this points
    mean_tpr = np.zeros_like(all_fpr)
    for i in range(n_classes):
        mean_tpr += interp(all_fpr, fpr[i], tpr[i])

    # Finally average it and compute AUC
    mean_tpr /= n_classes

    fpr["macro"] = all_fpr
    tpr["macro"] = mean_tpr
    roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

    # Plot all ROC curves
    plt.figure()
    plt.plot(fpr["micro"], tpr["micro"],
             label='micro-average ROC curve (area = {0:0.2f})'
                   ''.format(roc_auc["micro"]),
             color='deeppink', linestyle=':', linewidth=4)

    plt.plot(fpr["macro"], tpr["macro"],
             label='macro-average ROC curve (area = {0:0.2f})'
                   ''.format(roc_auc["macro"]),
             color='navy', linestyle=':', linewidth=4)

    colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
    for i, color in zip(range(n_classes), colors):
        plt.plot(fpr[i], tpr[i], color=color, lw=2,
                 label='ROC curve of class {0} (area = {1:0.2f})'
                       ''.format(i, roc_auc[i]))

    plt.plot([0, 1], [0, 1], 'k--', lw=2)
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Some extension of Receiver operating characteristic to multi-class')
    plt.legend(loc="lower right")
    plt.savefig(filename)

error_rate = np.sum(res != test_Y) / test_Y.shape[0]
print('Test error using softmax = {}'.format(error_rate))

plt.figure()
xgb.plot_importance(model, max_num_features=20)

plt.savefig("imp.png")

plot(test_Yb, pred, param, "otto")
'''
# do the same thing again, but output probabilities
param['objective'] = 'multi:softprob'
bst = xgb.train(param, xg_train, num_round, watchlist)
#print(xgb.get_score())
# Note: this convention has been changed since xgboost-unity
# get prediction_cascaded, this is in 1D array, need reshape to (ndata, nclass)
pred_prob = bst.predict(xg_test).reshape(test_Y.shape[0], param['num_class'])
pred_label = np.argmax(pred_prob, axis=1)
print(bst.get_score())
#print(xgb.plot_importance(bst))
#error_rate = np.sum(pred != test_Y) / test_Y.shape[0]
#print('Test error using softprob = {}'.format(error_rate))
'''


# built-in
from ssl import create_default_context

# external
import certifi
from aiohttp import ClientSession, TCPConnector

def aiohttp_session(*, auth=None, **kwargs):
    headers = dict()
    if auth:
        headers['Authorization'] = auth.encode()
    ssl_context = create_default_context(cafile=certifi.where())
    try:
        connector = TCPConnector(ssl=ssl_context)
    except TypeError:
        connector = TCPConnector(ssl_context=ssl_context)
    return ClientSession(headers=headers, connector=connector, **kwargs)


import appex
import clipboard
import console
import requests
import json

class dd:
    def req(self):
        #把第二步中获取到的 timestamp和sign拼接到URL中
        url = ('https://oapi.dingtalk.com/robot/send?access_token=9d35a417fd13301e046c31eb6deb29c47b769531a1e9d5e73b8a37d56dd1f2c1&timestamp=1612263003859&sign=B5Q86Vohcwn5rWKcItthGWGkY4kWudr1CyW0vd7kakk%3D')
        h = {
            'content-type':
            'application/json',
            'User-Agent':
            'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'
        }
        #d里面的at参数是需要at的人参数，只有at的人存在这个参数里面才会@成功
        d = json.dumps({
            "msgtype": "text",
            "text": {
                "content": text
            },
            # "at": {
            #     "atMobiles": ["15207163636"],
            #     "isAtAll": "false"
            # }
        })
        req = requests.post(url, data=d, headers=h)
        data = req.json()
        if data.error_code == 0 and data.errmsg == 'ok':
            print('发送成功,请到客户端查看相关信息')
        print(req.text)

# def main():
#     text = appex.get_text()
#     if curl:
#         url, body, headers, method = parse_curl(curl)
#     else:
#         path = appex.get_file_path()
#         url, body, headers, method = parse(path)
# if __name__ == '__main__':
#     dd().req()

text = appex.get_text()
console.hud_alert('已发送,请查收')

if __name__ == '__main__':
    if appex.is_running_extension():
        dd().req()
    else:
        print('请设置为 Share Extension 脚本后使用。')


""" Keyboard manager """

__author__ = "Peter Bennett"
__copyright__ = "Copyright 2012, Peter A Bennett"
__license__ = "LGPL"
__version__ = "0.1"
__maintainer__ = "Peter Bennett"
__email__ = "pab850@googlemail.com"
__contact__ = "www.bytebash.com"

from pyglet.window import key, mouse
from pyglet import clock

""" Statename strings """

flight = "Flight Mode"
wireframe = "Wireframe Mode"

class Controller(object):
    def __init__(self, window, player, console):
        self.keys = key.KeyStateHandler()
        self.player = player

        # Console
        self.console = console

        # States
        self.states = {}
        self.states[wireframe] = False
        self.states[flight] = False

        # Key Press Events
        self.keyPressEvents = {}

        clock.schedule(self.update)

        window.push_handlers(self.on_key_press)
        window.push_handlers(self.on_key_release)
        window.push_handlers(self.keys)
        window.push_handlers(self.on_mouse_motion)
        window.push_handlers(self.on_mouse_drag)
        window.push_handlers(self.on_mouse_press)
        window.push_handlers(self.on_mouse_release)

    def on_mouse_motion(self, x, y, dx, dy):
        self.player.orient(-dy*0.08, dx*0.08)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        self.player.orient(-dy*0.08, dx*0.08)

    def keyPressed(self, symbol):
        if symbol in self.keyPressEvents:
            return self.keyPressEvents[symbol]
        return False

    def update(self, dt):
        # Handle events that must occur while a key is pressed.
        self.player.update(dt,
                           self.keyPressed(key.W),
                           self.keyPressed(key.S),
                           self.keyPressed(key.A),
                           self.keyPressed(key.D))

    def on_mouse_press(self, x, y, button, modifiers):
        if button == mouse.LEFT:
            if not self.keyPressed(mouse.LEFT):
                self.player.fire()

        if button == mouse.RIGHT:
            if not self.keyPressed(mouse.RIGHT):
                self.player.altFire()

    def on_mouse_release(self, x, y, button, modifiers):
        self.keyPressEvents[button] = False

    def on_key_press(self, symbol, modifiers):
        # Handle events that only require one action per keypress here.

        # Player jump
        if symbol == key.SPACE:
            if not self.keyPressed(key.SPACE):
                self.player.jump()

        # Player jump
        if symbol == key.R:
            if not self.keyPressed(key.R):
                self.player.fire()

        # Enable or disable flight mode.
        if symbol == key.F:
            if not self.keyPressed(key.F):
                self.states[flight] = not self.states[flight]
                self.console.updateConsole(flight + ": " +
                                           str(self.states[flight]))
                self.player.toggleFlightMode(self.states[flight])
        # Enable or disable wireframe mode.
        if symbol == key.T:
            if not self.keyPressed(key.T):
                self.states[wireframe] = not self.states[wireframe]
                self.console.updateConsole(wireframe + ": " +
                                           str(self.states[wireframe]))

        self.keyPressEvents[symbol] = True

    def on_key_release(self, symbol, modifiers):
        self.keyPressEvents[symbol] = False


import numpy as np
import imutils
import pickle
import time
import cv2
import os

# float var to set minimum probability to filter weak face detections
CONFIDENCE = 0.5
# float var to set minimum threshold to filter our weak probabilities
THRESHOLD = 0.65

# face detector and pre-trained model
FACE_DETECTOR_DIR = os.path.sep.join(["faceDetectionModel", "deploy.prototxt"])
MODEL_DIR = os.path.sep.join(["faceDetectionModel", "res10_300x300_ssd_iter_140000.caffemodel"])

detector = cv2.dnn.readNetFromCaffe(FACE_DETECTOR_DIR, MODEL_DIR)

# face embedding model
embedder = cv2.dnn.readNetFromTorch("openface_nn4.small2.v1.t7")

# face recognition model
recognizer = pickle.loads(open("output/recognizer.pickle", "rb").read())

# label encoder
le = pickle.loads(open("output/le.pickle", "rb").read())

def recognizeFace(frame):
    # resize the frame
    frame = imutils.resize(frame, width=600)
    # maintain the aspect ratio and get image dimensions
    (h, w) = frame.shape[:2]

    # construct a blob from the image using mean substraction
    # blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size, mean, swapRB=True)
    imageBlob = cv2.dnn.blobFromImage(
        cv2.resize(frame, (300, 300)), 1.0, (300, 300),
        (104.0, 177.0, 123.0), swapRB=False, crop=False)

    # use OpenCV face detector to find faces in the image
    detector.setInput(imageBlob)
    detections = detector.forward()

    # loop over the detections
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]

        # filter out weak detections
        if confidence > CONFIDENCE:
            # compute x and y coordinates of the detected face
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            # extract the face ROI
            face = frame[startY:endY, startX:endX]
            (fH, fW) = face.shape[:2]

            # checks if spatial dimensions are the right size
            if fW < 20 or fH < 20:
                continue

            # create a blob for face ROI, then pass it through
            # the face embedding model to obtain the 128-d
            # embeddings of the face
            faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255,
				(96, 96), (0, 0, 0), swapRB=True, crop=False)

            embedder.setInput(faceBlob)

            # vector with the embedded face
            vec = embedder.forward()

            # pass vector to the recognizer model, the result will tell
            # who is in the face ROI
            preds = recognizer.predict_proba(vec)[0]
            # take highest probability index  from the predictions
            j = np.argmax(preds)
            # extract the probability
            proba = preds[j]
            # use the label encoder to find the name from the dataset
            name = le.classes_[j]

            # filter out weak recognitions using a threshold
            if proba < THRESHOLD:
                continue

            # draw the bounding box of the face along with the
			# associated probability
            text = "{}: {:.2f}%".format(name, proba * 100)
            y = startY - 10 if startY - 10 > 10 else startY + 10
            cv2.rectangle(frame, (startX, startY), (endX, endY),
                (0, 0, 255), 2)
            cv2.putText(frame, text, (startX, y),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)

    return frame


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 23:54:01 2018

@author: paul
"""

import matplotlib.pyplot as plt
import numpy as np
import pickle
from kernel_exp_family.estimators.finite.gaussian import KernelExpFiniteGaussian
from kernel_exp_family.estimators.lite.gaussian import KernelExpLiteGaussian
import seaborn as sns
plt.close('all')
N = 2000
D = 7
f = open('/home/paul/data/eprv01_posteriorsamples.dat')
parnames, samples_kepler = pickle.load(f)
f.close()
Period = samples_kepler[:N,4]
Amplitude = samples_kepler[:N,0]
ecc = samples_kepler[:N,3]**2 + samples_kepler[:N,5]**2
pericenter = np.arctan2(samples_kepler[:N,5], samples_kepler[:N,3])
MeanA = samples_kepler[:N, 6]
sigma_Jitter = samples_kepler[:N,1]
V0 = samples_kepler[:N, 2]

P = (Period - np.mean(Period))/np.std(Period)
K = (Amplitude - np.mean(Amplitude))/np.std(Period)
e = (ecc-np.mean(ecc))/np.std(ecc)
w = (pericenter-np.mean(pericenter))/np.std(pericenter)
M = (MeanA-np.mean(MeanA))/np.std(MeanA)
sigma_J = (sigma_Jitter-np.mean(sigma_Jitter))/np.std(sigma_Jitter)
V = (V0-np.mean(V0))/np.std(V0)

X = np.array([P, K, e, w, M, sigma_J, V]).T
surrogate = KernelExpLiteGaussian(sigma=2., lmbda=0.12, D=D, N=N)

surrogate.fit(X)

gradiente = []

for i in range(N):
        gradiente.append(surrogate.grad(X[i,:]))

g = np.array(gradiente)
Params = ['Periodo', 'Semi-Amplitud', 'Excentricidad', 'Arg. pericentro', 'Anomalia media', 'Sigma_J', 'Offset V' ]

for i in range(1, D):

    fig=plt.figure(i, figsize=(10,4))

    plt.style.use('seaborn-darkgrid')
    plt.subplot(121)
    plt.ylabel('%s' %Params[0])
    plt.xlabel('%s' %Params[i])
    plt.scatter(X[:,i], X[:,0], s=0.5, alpha=0.5)

    plt.subplot(122)
    plt.ylabel('%s' %Params[0])
    plt.xlabel('%s' %Params[i])
    plt.quiver(X[:,i], X[:,0], g[:,i], g[:,0])

    plt.tight_layout()
    fig.savefig('/home/paul/Desktop/quiver_keplerian_static%s.png' %Params[i])


# -*- coding: utf-8 -*-
"""
Created on Fri May 11 10:14:13 2018

@author: George
"""

import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

#raw data
x = [3454, 3433, 3559, 3903, 3970, 4282, 4649, 4901]
y = [12546611, 9481327, 7132256, 3900473, 3287550, 2418038, 2235571, 2105149]

def logistic4(x, A, B, C, D):
    """4PL lgoistic equation."""
    return ((A-D)/(1.0+((x/C)**B))) + D

def residuals(p, y, x):
    """Deviations of data from fitted 4PL curve"""
    A,B,C,D = p
    err = y-logistic4(x, A, B, C, D)
    return err

def peval(x, p):
    """Evaluated value at x with current parameters."""
    A,B,C,D = p
    return logistic4(x, A, B, C, D)

# Initial guess for parameters [min, slope, inflection, max]
p0 = [0.1, 1, 0.2, 1.2]

# Fit equation using least squares optimization
plsq = leastsq(residuals, p0, args=(y, x))

# Plot results
plt.plot(x,peval(x,plsq[0]),x,y,'o',x,y)
plt.title('Least-squares 4PL fit to noisy data')

plt.plot(x,y, '+')


from django.conf.urls import url

from services.user_management.views import student_list, parent_list, student_registration, staff_registration
from .auth_token_manager import CustomAuthToken

urlpatterns = [
    url(r'^students/$', student_list),
    url(r'^parents/$', parent_list),
    url(r'^register/student$', student_registration),
    url(r'^register/staff$', staff_registration),
    url(r'^auth/$', CustomAuthToken.as_view())
]


import sys
from setuptools import setup
main = 'ezrp.py'

if (sys.platform == 'darwin'):
	extra_options = dict(
		setup_requires=["py2app"],
		options=dict(py2app=dict(argv_emulation=True))
	)
elif (sys.platform == 'win32'):
	from cx_Freeze import setup, Executable

	extra_options = dict(
		setup_requires=["cx_Freeze"],
		executables = [Executable(main, base="Win32GUI", shortcutName="ezrp", shortcutDir="ProgramMenuFolder")]
	)
else:
	extra_options = dict(
		scripts=[main]
	)
setup(
	name = "ezrp",
	version = "1.0.0a2",
    app=[main],
	**extra_options
)


'''
Authors
  - C. Selmi: written in 2020

List of contents:

Functions for tower alignment
+++++++++++++++++++++++++++++
- :func:`ott_alignment_calibration`
- :func:`ott_alignment`
- :func:`m4_alignment_calibration`
- :func:`m4_alignment`
- :func:`rotation_and_optical_axis_alignment`

Functions for noise measurements
++++++++++++++++++++++++++++++++
- :func:`opto_mech_disturbances_acquisition`
- :func:`stability_vibrations`
- :func:`spectrumFromData`
- :func:`convection_moise`
- :func:`piston_noise`

PT sensors
++++++++++
- :func:`PT_calibration`
- :func:`analyzer_PT_meas`

'''

import os
import time
import glob
import numpy as np
from astropy.io import fits as pyfits
from matplotlib import pyplot as plt
from m4.configuration import config_folder_names as config
from m4.noise_functions import Noise
from m4.alignment import Alignment
from m4.ground import logger_set_up as lsu
from m4.configuration import start
from m4.utils import req_check
from m4.configuration.ott_parameters import OttParameters, OpcUaParameters

def start_log(logging_level):
    """
    Parameters
    ----------
    logging_level: int
                    Warning = 30, Info = 20, Debug = 10, Notset = 0

    """
    file_path = config.LOG_ROOT_FOLDER
    lsu.set_up_logger(file_path, logging_level)
    return file_path

####### Allineamento Torre ########

ott, interf = start.create_ott()
a = Alignment(ott, interf)

def ott_alignment_calibration(n_frames, commandAmpVector, nPushPull, old_or_new, move):
    '''
    Parameters
    ----------------
            command_amp_vector: numpy array
                                  vector containing the movement values
                                  of the 5 degrees of freedom
            n_push_pull: int
                        number of push pull for each degree of freedom
            move: int
                1 to move the tower
                other to show matrix delta command
            old_or_new: int
                        0 for new (mixed), 1 for old (not mixed)

    Returns
    -------
            tt_tower: string
                    calibration measurement
    '''
    print('PAR + RM calibration')
    if move == 1:
        tt_tower = a.ott_calibration(n_frames, commandAmpVector, nPushPull, old_or_new, 0)
    #mask_index = 3 per il simulatore  e 0 per la mott
        return tt_tower
    else:
        mat, cmdList = a._cal._createCommandMatrix(0, commandAmpVector, old_or_new)
        plt.clf()
        plt.imshow(mat, origin='lower')
        plt.colorbar()
        return mat

def ott_alignment(tt_tower, n_images, move=1, intMatModesVector=None, commandId=None):
    '''
    Parameters
    ----------
    tt_tower: string
            calibration measurement to use for alignment
    n_images: int
            number of interferometers frames
    move: int
        1 to move the tower
        other to show commands
    Other Parameters
    ----------
    intMatModesVecor: numpy array
                    None is equal to np.array([0,1,2,3,4,5])
                    for tip, tilt, fuoco, coma, coma
    commandId: numpy array
            array containing the number of degrees of freedom to be commanded
    '''
    print('Ott alignemnt')
    par_cmd, rm_cmd = a.ott_alignment(n_images, move, intMatModesVector, commandId, tt_tower)
    print('comandi separati')
    print(par_cmd)
    print(rm_cmd)
    #check
#    if move == 1:
#	    for i in range(OttParameters.PARABOLA_DOF.size):
#	        if par_cmd[OttParameters.PARABOLA_DOF[i]] < OttParameters.parab_max_displacement[OttParameters.PARABOLA_DOF[i]]:
#	            print('ok')
#	        else:
#	            raise OSError('Par command to large')
#	    for i in range(OttParameters.RM_DOF.size):
#	        if rm_cmd[OttParameters.RM_DOF[i]] < OttParameters.rm_max_displacement[OttParameters.RM_DOF[i]]:
#	            print('ok')
#	        else:
#	            raise OSError('Rm command to large')

def m4_alignment_calibration(nFrames, commandAmpVector_ForM4Calibration=None,
                     nPushPull_ForM4Calibration=None):
    """
    Other Parameters
    ----------------
            commandAmpVector_ForM4Calibration: numpy array
                                            amplitude to be applied to m4
            nPushPull_ForM4Calibration: int
                                        number of push pull for m4 dof
            nFrames = int
                    frames for 4D

    Returns
    -------
            tt_m4: string
                    calibration measurement
    """
    print('M4 calibration')
    if commandAmpVector_ForM4Calibration is None:
        commandAmpVector_ForM4Calibration = np.array([5.0e-06, 5.0e-06])
    if nPushPull_ForM4Calibration is None:
        nPushPull_ForM4Calibration = 3
    tt_m4, zCoefComa, comaSurface = a.m4_calibration(commandAmpVector_ForM4Calibration,
                                                     nPushPull_ForM4Calibration, 5, nFrames)
    return tt_m4

def m4_alignment(tt_m4):
    '''
    Parameters
    ----------
    tt_m4: string
            calibration measurement to use for alignment
    '''
    print('M4 alignment')
    zCoefComa = a._readZcoef(tt_m4)
    cmd_m4 = a.m4_alignment(zCoefComa, tt_m4)
    print(cmd_m4)
    #check
    #applicare comando
    for i in range(OttParameters.M4_DOF.size):
        if cmd_m4[OttParameters.M4_DOF[i]] < OttParameters.m4_max_displacement[OttParameters.M4_DOF[i]]:
            print('ok')
        else:
            raise OSError('Command to large')
    #a._write_m4(cmd_m4)
    return cmd_m4

def rotation_and_optical_axis_alignment(start_point, end_point, n_points):
    '''
    Parameters
    ----------
            start_point: int
                        value of start angle
            end_point: int
                        value of end angle
            n_points:int
                    number of images desired

    Returns
    -------
        ro: object
            rotation_and_optical_axis_alignment class object
        tt: strig
            tracking number of measurement
    '''
    from m4.utils.rotation_and_optical_axis_alignment import RotOptAlign
    ro = RotOptAlign(ott, interf)

    tt = ro.image_acquisition(start_point, end_point, n_points)

    centro, axs, raggio = ro.data_analyzer(tt)
    print(centro, axs, raggio)
    #le immagini le fa l'analyzer
    return ro, tt

######### Misure di noise ##########
def _path_noise_results(data_file_path, h5_or_fits=None):
    ''' Function to get tt'''
    results_path = os.path.join(config.OUT_FOLDER, 'Noise')
    x = data_file_path.split("/")
    if h5_or_fits is None:
        dove = os.path.join(results_path, x[len(x)-2])
    else:
        dove = os.path.join(results_path, x[len(x)-1])
    if os.path.exists(dove):
        dove = dove
    else:
        os.makedirs(dove)
    return dove

def _createTemplateList(numbers_array):
    '''
    Parameters
    ----------
        numbers_array: numpy array
                    vector containing integers numbers for
                    template creation
    Returns
    -------
        template_list: list
                    list of template to use
    '''
    template_list = []
    vec = np.array([1, -1])
    for i in numbers_array:
        if i % 2 == 0:
            #pari
            k = i-2
            temp = np.tile(vec, np.int(i/2))
        elif i %2 == 1:
            #dispari
            k = i-2
            if k == 1:
                temp_pari = vec
            else:
                temp_pari = np.tile(vec, np.int((i-1)/2))
            temp = np.append(temp_pari, 1)
        template_list.append(temp)
    return template_list

def noise_vibrations(data_file_path, numbers_array, tidy_or_shuffle):
    '''
    Parameters
    ----------
        data_file_path: string
                        measurement data folder
        numbers_array: numpy array
                    vector containing integers numbers for
                    template creation
        tidy_or_shuffle: int
                        0 for tidy, 1 for shuffle
    '''
    print('Noise analysis using template')
    n = Noise()
    dove = _path_noise_results(data_file_path)
    template_list = _createTemplateList(numbers_array)

    tt_list = []
    for temp in template_list:
        tt = n.noise_analysis_from_hdf5_folder(data_file_path, tidy_or_shuffle,
                                               temp)
        time.sleep(1)
        tt_list.append(tt)

    fits_file_name = os.path.join(dove, 'trackingnumbers_%d.txt' %tidy_or_shuffle)
    file = open(fits_file_name, 'w+')
    file.write('Tidy or shuffle = %d \n' %tidy_or_shuffle)
    for tt in tt_list:
        file.write('%s \n' %tt)
    file.close()

    rms_medio, quad_medio, n_temp, ptv_medio = n.different_template_analyzer(tt_list)
    pyfits.writeto(os.path.join(dove, 'rms_vector_%d.fits' %tidy_or_shuffle), rms_medio, overwrite=True)
    pyfits.writeto(os.path.join(dove, 'tiptilt_vector_%d.fits' %tidy_or_shuffle), quad_medio, overwrite=True)
    pyfits.writeto(os.path.join(dove, 'n_temp_vector_%d.fits' %tidy_or_shuffle), n_temp, overwrite=True)
    pyfits.writeto(os.path.join(dove, 'ptv_%d.fits' %tidy_or_shuffle), ptv_medio, overwrite=True)

    tt = data_file_path.split('/')[-2]
    plt.clf()
    #WFE = 2*rms_medio
    plt.plot(n_temp, rms_medio*1e9, '-o')
    plt.xlabel('n_temp')
    plt.ylabel('rms [nm]')
    plt.title('%s' %tt)
    plt.grid()
    name = os.path.join(dove, 'rms_ntemp_%d.png' %tidy_or_shuffle)
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

    plt.figure()
    plt.plot(n_temp, quad_medio*1e9, '-o'); plt.xlabel('n_temp')
    plt.ylabel('TipTilt [nm]')
    plt.title('%s' %tt)
    plt.grid()
    name = os.path.join(dove, 'tiptilt_ntemp_%d.png' %tidy_or_shuffle)
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

    plt.figure()
    plt.plot(n_temp, ptv_medio*1e9, '-o'); plt.xlabel('n_temp')
    plt.ylabel('PtV [nm]')
    plt.title('%s' %tt)
    plt.grid()
    name = os.path.join(dove, 'ptv_ntemp_%d.png' %tidy_or_shuffle)
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)
#     plt.figure()
#     plt.plot(freq, np.absolute(spe), '-o'); plt.xlabel('Freq[HZ]');
#     plt.ylabel('|FFT(sig)|'); plt.title('tip_tilt_%d' %tidy_or_shuffle)
#     plt.savefig(os.path.join(dove, 'tiptilt_spectrum_%d.png' %tidy_or_shuffle))
    return

def spectrumFromData(data_file_path):
    '''
    Parameters
    ----------
        data_file_path: string
                        measurement data folder
    '''
    print('Spectrum analysis')
    n = Noise()
    dove = _path_noise_results(data_file_path)

    tip, tilt = n._spectrumAllData(data_file_path)
    spe_tip, freq_tip = n._fft(tip)
    spe_tilt, freq_tilt = n._fft(tilt)

    plt.clf()
    plt.plot(freq_tip, np.absolute(spe_tip), 'o'); plt.xlabel('Freq[HZ]')
    plt.ylabel('|FFT(sig)|'); plt.title('tip_spectrum')
    name = os.path.join(dove, 'tip_spectrum.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)
    plt.figure()
    plt.plot(freq_tilt, np.absolute(spe_tilt), 'o'); plt.xlabel('Freq[HZ]')
    plt.ylabel('|FFT(sig)|'); plt.title('tilt_spectrum')
    name = os.path.join(dove, 'tilt_spectrum.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

def convection_noise(data_file_path, tau_vector):
    '''
    Parameters
    ----------
        data_file_path: string
                        measurement data folder
        tau_vector: numpy array
                    vector of tau to use

    Other Parameters
    ----------------
        h5_or_fits: if it is none the h5 data analysis is performed
    '''
    last_name = data_file_path.split('/')[-1]
    if last_name == 'hdf5':
        h5_or_fits = None
    else:
        h5_or_fits = 7

    print('Noise analysis using tau vector')
    n = Noise()
    dove = _path_noise_results(data_file_path, h5_or_fits)

    rms, quad, n_meas = n.analysis_whit_structure_function(data_file_path,
                                                           tau_vector,
                                                           h5_or_fits)
    pyfits.writeto(os.path.join(dove, 'rms_vector_conv.fits'), rms,
                   overwrite=True)
    pyfits.writeto(os.path.join(dove, 'tiptilt_vector_conv.fits'), quad,
                   overwrite=True)
    pyfits.writeto(os.path.join(dove, 'tau_vector.fits'), tau_vector,
                   overwrite=True)

    rms_nm = rms*1e9
    if h5_or_fits is None:
        x = tau_vector * (1/27.58)
        param = [5, 0.5, 32]
        try:

            pp,fit = _curvFit(param, x, rms_nm)
            decorr_time = 1/pp[0]+pp[1]
        except:
            pp = np.array([0,0,rms[-1]*1e9])
            decorr_time = -1
            fit=rms_nm.copy()*0
        plt.clf()
        plt.plot(x, rms * 1e9, '-o', label='meas')
        plt.xlabel('time [s]')
        plt.ylabel('rms [nm]')
        plt.plot(x, fit, '-', label='fit')
        plt.grid()
        plt.plot([x[0], x[-1]], [pp[2], pp[2]], '--r', linewidth=3,
                 label='%.2f [nm]' %pp[2])
#         plt.plot(decorr_time, _funFit(decorr_time,*pp), 'og',
#                  label='Dec time = %d [s]' %np.round(decorr_time))
        plt.legend()
        tt = dove.split('/')[-1]
        plt.title('%s' %tt)
        name = os.path.join(dove, 'rms_tau.png')
        if os.path.isfile(name):
            os.remove(name)
        plt.savefig(name)
        return pp[2], decorr_time
    else:
        time_diff = timeForPlot(data_file_path)
        x = tau_vector*time_diff
        plt.clf()
        plt.plot(x, rms * 1e9, '-o', label='time_diff = %d' %time_diff)
        plt.xlabel('time [s]')
        plt.ylabel('rms [nm]')
        plt.grid()
        plt.legend()
        tt = dove.split('/')[-1]
        plt.title('%s' %tt)
        name = os.path.join(dove, 'rms_tau.png')
        if os.path.isfile(name):
            os.remove(name)
        plt.savefig(name)
    #stimare tc dal grafico e usare 2*tau_c = epsilon_c / np.sqrt(n) n = 4000
#     tau_c = 30 * (1/27.58)
#     epsilon_c = 2 * tau_c * np.sqrt(n_meas)
#     fits_file_name = os.path.join(dove, 'epsilon_c.txt')
#     file = open(fits_file_name, 'w+')
#     file.write('Epsilon_c = %e' %epsilon_c)
#     file.close()

def timeForPlot(stab_path):
    listtot = glob.glob(os.path.join(stab_path, '*.fits'))
    listtot.sort()
    aa = listtot[0].split('/')
    t0 = aa[-1].split('_')[1].split('.')[0]
    bb = listtot[1].split('/')
    t1 = bb[-1].split('_')[1].split('.')[0]

    hs = float(t0[0: 2])*3600
    ms = float(t0[2: 4])*60
    s = float( t0[4::])
    t0s = hs + ms + s
    hs = float(t1[0: 2])*3600
    ms = float(t1[2: 4])*60
    s = float( t1[4::])
    t1s = hs + ms + s

    time_diff = t1s-t0s
    return time_diff
def _funFit(x, a, b, c):
    fun = -np.exp(-a*(x-b)) + c
    return fun
def _curvFit(param, x, rms_nm):
    from scipy.optimize import curve_fit
    pp, pcov = curve_fit(_funFit, x, rms_nm, param)
    fit = _funFit(x, *pp)
    return pp, fit

def piston_noise(data_file_path):
    '''
    Parameters
    ----------
        data_file_path: string
                        measurement data folder
    '''
    n = Noise()
    dove = _path_noise_results(data_file_path)

    mean, time = n.piston_noise(data_file_path)
    spe, freq = n._fft(mean)
    pyfits.writeto(os.path.join(dove, 'piston_vector.fits'), mean)
    pyfits.writeto(os.path.join(dove, 'time_vector.fits'), time)

    plt.clf()
    plt.plot(time, mean); plt.xlabel('time[s]'); plt.ylabel('mean_image')
    plt.savefig(os.path.join(dove, 'piston_noise.png'))
    plt.figure()
    plt.plot(freq, np.absolute(spe), 'o'); plt.xlabel('Freq[HZ]');
    plt.ylabel('|FFT(sig)|'); plt.title('piston_power_spectrum')
    plt.savefig(os.path.join(dove, 'piston_spectrum.png'))

def analysis_req(data_file_path, zernike_vector_to_subtract, step=None, offset=None):
    ''' Simultaneous analysis of noise requirements for a tn

    Parameters
    ----------
    path: string
        total path for data analysis

    Other Parameters
    ----------------
    offset: if it is None data analysis is made by split n_images in two
    '''
    last_name = data_file_path.split('/')[-1]
    if last_name == 'hdf5':
        tt = data_file_path.split('/')[-2]
    else:
        tt = data_file_path.split('/')[-1]

    results_path = os.path.join(config.OUT_FOLDER, 'Req')
    dove = os.path.join(results_path, tt)
    if os.path.exists(dove):
        dove = dove
    else:
        os.makedirs(dove)
    fits_file_name = os.path.join(dove, 'info.txt')
    file = open(fits_file_name, 'w+')
    if offset is None:
        file.write('Data produced without offset optic image')
    else:
        file.write('Data produced with offset optic image')
    file.close()

    print('Creating cube 50')
    image50 = req_check.robustImageFromDataSet(50, data_file_path, zernike_vector_to_subtract, offset)
    print('Creating cube 100')
    image100 = req_check.robustImageFromDataSet(100, data_file_path, zernike_vector_to_subtract, offset)
    print('Creating cube 300')
    image300 = req_check.robustImageFromDataSet(300, data_file_path, zernike_vector_to_subtract, offset)
#     print('Creating cube 600')
#     image600 = req_check.robustImageFromDataSet(600, data_file_path, offset)

    image_list = [image50, image100, image300]#, image600]
    slop_list = []
    diff_piston_list = []
    roc_list = []
    rms31 = []
    rms500 = []
    for image in image_list:
        print('Producing slope')
        slop_list.append(req_check.test242(image))
        print('Producing differential piston')
        diff_piston_list.append(req_check.diffPiston(image))
        print('Producing roc')
        roc_list.append(req_check.test283(image))
        print('Producing rms31')
        rms31.append(req_check.test243(image, 0.015, step, n_patches=None))
        print('Producing rms51')
        rms500.append(req_check.test243(image, 0.1, step, n_patches=None))

    x = np.array([50,100,300])#,600])
    #GRAFICO STD IMAGES
    y = np.array([image50.std(),image100.std(),image300.std()])#,image600.std()])
    plt.figure(figsize=(10,6))
    plt.plot(np.sqrt(x), y, '-o')
    plt.ylabel('rms_image [m]')
    plt.xlabel('sqrt(n_frames)')
    plt.title('%s' %tt)
    name = os.path.join(dove, 'std.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

    #GRAFICO SLOPE
    y = np.array(slop_list)
    plt.figure(figsize=(10,6))
    plt.plot(np.sqrt(x), y, '-o')
    plt.ylabel('rms_slope [arcsec]')
    plt.xlabel('sqrt(n_frames)')
    plt.title('%s' %tt)
    name = os.path.join(dove, 'slope.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

    #GRAFICO DIFF PISTON
    y = np.array(diff_piston_list)
    plt.figure(figsize=(10,6))
    plt.plot(np.sqrt(x), y, '-o')
    plt.ylabel('diff_piston [m]')
    plt.xlabel('sqrt(n_frames)')
    plt.title('%s' %tt)
    name = os.path.join(dove, 'diff_piston.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

    #GRAFICO ROC
    y = np.array(roc_list)
    plt.figure(figsize=(10,6))
    plt.plot(np.sqrt(x), y, '-o')
    plt.ylabel('roc [m]')
    plt.xlabel('sqrt(n_frames)')
    plt.title('%s' %tt)
    name = os.path.join(dove, 'roc.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

    #GRAFICO RMS 31 MM
    y = np.array(rms31)
    plt.figure(figsize=(10,6))
    plt.plot(np.sqrt(x), y, '-o')
    plt.ylabel('rms_31mm [m]')
    plt.xlabel('sqrt(n_frames)')
    plt.title('%s' %tt)
    name = os.path.join(dove, 'rms_31mm.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

    #GRAFICO RMS 500 MM
    y = np.array(rms500)
    plt.figure(figsize=(10,6))
    plt.plot(np.sqrt(x), y, '-o')
    plt.ylabel('rms_500mm [m]')
    plt.xlabel('sqrt(n_frames)')
    plt.title('%s' %tt)
    name = os.path.join(dove, 'rms_500mm.png')
    if os.path.isfile(name):
        os.remove(name)
    plt.savefig(name)

######## Sensori PT #######

def PT_calibration(n_meas):
    '''
    Parameters
    ----------
        n_meas: int
            number of measurement to store

    Returns
    -------
        dove: string
            data file path of measurement
    '''
    from m4.ground import tracking_number_folder
    from opcua import Client
    server = OpcUaParameters.server
    client = Client(url=server)
    client.connect()

    folder = config.PT_ROOT_FOLDER
    dove, tt = tracking_number_folder.createFolderToStoreMeasurements(folder)

    for i in range(n_meas):
        time.sleep(2)
        temp = client.get_node("ns=7;s=MAIN.i_Temperature_Sensor")
        temp_list = temp.get_value()
        temp_vector = np.array(temp_list.get_value())

        fits_file_name = os.path.join(dove, 'temperature_%04.fits' %i)
        pyfits.writeto(fits_file_name, temp_vector)

        print('Misura %04d' %i)
    return dove

def analyzer_PT_meas(tt):
    '''
    Parameters
    ----------
    tt: string
        tracking number folder
    '''
    #tt = '20200911_142702'
    from m4.ground import smooth_function

    folder = config.PT_ROOT_FOLDER
    name = os.path.join(folder, tt)
    list = os.listdir(name)
    list.sort()

    matrix = np.zeros((len(list), OpcUaParameters.num_PT_sensor))
    matrix_s = np.zeros((len(list), OpcUaParameters.num_PT_sensor))

    i = 0
    for t in list:
        hduList = pyfits.open(os.path.join(name, t))
        temp = hduList[0].data
        matrix[i,:] = temp
        i = i+1

    matrixDiff = matrix - matrix[0,:]
    i=0
    for i in range(OpcUaParameters.num_PT_sensor):
        ss = smooth_function.smooth(matrixDiff[:,i],9)
        matrix_s[:,i] = ss
        i=i+1

    t = np.arange(0,2*len(list),2)
    plt.plot(t, matrix_s/100)
    plt.xlabel('Time [s]'); plt.ylabel('Temperature [C]');
    plt.title('PT Calibration')


# -*- coding: utf-8 -*-
import gi
gi.require_version('Gedit', '3.0')
from gi.repository import GObject, Gio, Gdk, Gedit
import re
try:
    import gettext
    gettext.bindtextdomain('gedit-plugins')
    gettext.textdomain('gedit-plugins')
    _ = gettext.gettext
except:
    _ = lambda s: s

#Code based on https://github.com/theawless/Clear-Doc
class IndentConverterPluginAppActivatable(GObject.Object, Gedit.AppActivatable):
    app = GObject.property(type=Gedit.App)
    __gtype_name__ = "IndentConverterPluginAppActivatable"

    def __init__(self):
        GObject.Object.__init__(self)
        self.menu_ext = None
        self.menu_item = None

    def do_activate(self):
        self._build_menu()

    def _build_menu(self):
        # Get the extension from tools menu
        self.menu_ext = self.extend_menu("tools-section")

        # This is the submenu which is added to a menu item and then inserted in tools menu.
        sub_menu = Gio.Menu()
        sub_menu_item_spaces = Gio.MenuItem.new(_("_Spaces to tabs"), 'win.spaces_to_tabs')
        sub_menu.append_item(sub_menu_item_spaces)
        sub_menu_item_tabs = Gio.MenuItem.new(_("_Tabs to Spaces"), 'win.tabs_to_spaces')
        sub_menu.append_item(sub_menu_item_tabs)
        self.menu_item = Gio.MenuItem.new_submenu(_("_Indent Converter"), sub_menu)
        self.menu_ext.append_menu_item(self.menu_item)

        # Setting accelerators, first action is called when Ctrl+Alt+e is pressed. (PS: for some reason, using S and T do not work)
        self.app.set_accels_for_action("win.spaces_to_tabs", ("<Primary><Alt>E", None))
        self.app.set_accels_for_action("win.tabs_to_spaces", ("<Primary><Alt>A", None))

    def do_deactivate(self):
        self._remove_menu()

    def _remove_menu(self):
        # removing accelerators and destroying menu items
        self.app.set_accels_for_action("win.spaces_to_tabs", ())
        self.app.set_accels_for_action("win.tabs_to_spaces", ())
        self.menu_ext = None
        self.menu_item = None

class IndentConverterPluginWindowActivatable(GObject.Object, Gedit.WindowActivatable):

    __gtype_name__ = "IndentConverterPluginWindowActivatable"

    window = GObject.property(type=Gedit.Window)

    def __init__(self):
        GObject.Object.__init__(self)

    def do_activate(self):
        self._connect_menu()

    def do_deactivate(self):
        pass

    def do_update_state(self):
        view = self.window.get_active_view()

        #Enable if view exists and document is editable
        enabled = False
        enabled = view and view.get_editable()
        self.window.lookup_action('spaces_to_tabs').set_enabled(enabled)
        self.window.lookup_action('tabs_to_spaces').set_enabled(enabled)

    def _connect_menu(self):
        action_spaces = Gio.SimpleAction(name='spaces_to_tabs')
        action_spaces.connect('activate', self.do_spaces_to_tabs)
        self.window.add_action(action_spaces)
        action_tabs = Gio.SimpleAction(name='tabs_to_spaces')
        action_tabs.connect('activate', self.do_tabs_to_spaces)
        self.window.add_action(action_tabs)

    def remove_menu(self):
        pass

    def tab_size(self):
        settings = Gio.Settings.new('org.gnome.gedit.preferences.editor')
        tab_size = settings.get_uint('tabs-size')
        return tab_size

    def guess_tab_size(self, text):
        def gcd(a, b):
            return a if b == 0 else gcd(b, a % b);

        r = re.compile('^ +', re.MULTILINE)
        matches = r.findall(text)
        freq = {}

        # `key` - length of leading spaces, `value` - it's frequency
        for spaces in matches:
            spaces = len(spaces)
            if spaces in freq:
                freq[spaces] += 1
            else:
                freq[spaces] = 1

        # sort frequencies by value:
        items = [ [i[1], i[0]] for i in list(freq.items()) ]
        items.sort()
        items.reverse()
        items = [i[1] for i in items]

        if len(items) == 0:
            return 0
        elif len(items) == 1:
            return items[0]
        else:
            return gcd(items[0], items[1])

    def do_spaces_to_tabs(self, action, data):

        #TODO Code using view works?
        #view = self.window.get_active_view()
        #doc = view.get_buffer()

        #Return if document is empty
        doc = self.window.get_active_document()
        if doc is None:
            return

        #TODO Use selection if any, otherwise the whole document
        #try:
        #    start, end = doc.get_selection_bounds()
        #except ValueError:

        start, end = doc.get_bounds()
        text = doc.get_text(start, end, True)

        tab_size = self.guess_tab_size(text)
        if (tab_size < 2):
            tab_size = self.tab_size()
        r = re.compile('^(?:' +  (' ' * tab_size) + ')+', re.MULTILINE)

        def replacer(match):
            return '\t' * int(len(match.group(0)) / tab_size)

        text = r.sub(replacer, text)

        doc.begin_user_action()
        doc.set_text(text)
        doc.end_user_action()

    def do_tabs_to_spaces(self, action, data):
        doc = self.window.get_active_document()
        if doc is None:
            return

        start, end = doc.get_bounds()
        text = doc.get_text(start, end, True)
        text = text.expandtabs(self.tab_size())

        doc.begin_user_action()
        doc.set_text(text)
        doc.end_user_action()


import coax
import jax
import jax.numpy as jnp
import gym
import haiku as hk
import optax

# the MDP
env = gym.make('FrozenLakeNonSlippery-v0')
env = coax.wrappers.TrainMonitor(env)

def func_v(S, is_training):
    value = hk.Sequential((hk.Linear(1, w_init=jnp.zeros), jnp.ravel))
    return value(S)

def func_pi(S, is_training):
    logits = hk.Linear(env.action_space.n, w_init=jnp.zeros)
    return {'logits': logits(S)}

# function approximators
pi = coax.Policy(func_pi, env)
v = coax.V(func_v, env)

# create copies
pi_old = pi.copy()  # behavior policy
v_targ = v.copy()   # target network

# experience tracer
tracer = coax.reward_tracing.NStep(n=1, gamma=0.9)

# updaters
simple_td = coax.td_learning.SimpleTD(v, v_targ, optimizer=optax.adam(0.02))
ppo_clip = coax.policy_objectives.PPOClip(pi, optimizer=optax.adam(0.01))

# train
for ep in range(500):
    s = env.reset()

    for t in range(env.spec.max_episode_steps):
        a, logp = pi_old(s, return_logp=True)
        s_next, r, done, info = env.step(a)

        # small incentive to keep moving
        if jnp.array_equal(s_next, s):
            r = -0.01

        # update
        tracer.add(s, a, r, done, logp)
        while tracer:
            transition_batch = tracer.pop()
            _, td_error = simple_td.update(transition_batch, return_td_error=True)
            ppo_clip.update(transition_batch, td_error)

            # sync target networks
            v_targ.soft_update(v, tau=0.01)
            pi_old.soft_update(pi, tau=0.01)

        if done:
            break

        s = s_next

    # early stopping
    if env.avg_G > env.spec.reward_threshold:
        break

# run env one more time to render
s = env.reset()
env.render()

for t in range(env.spec.max_episode_steps):

    # estimated state value
    print("  v(s) = {:.3f}".format(v(s)))

    # print individual action probabilities
    params = pi.dist_params(s)
    propensities = jax.nn.softmax(params['logits'])
    for i, p in enumerate(propensities):
        print("  π({:s}|s) = {:.3f}".format('LDRU'[i], p))

    a = pi.mode(s)
    s, r, done, info = env.step(a)

    env.render()

    if done:
        break

if env.avg_G < env.spec.reward_threshold:
    name = globals().get('__file__', 'this script')
    raise RuntimeError(f"{name} failed to reach env.spec.reward_threshold")


import json
import time
from datetime import datetime
from sensors import sensor

unknown_config_topic = "homeassistant/binary_sensor/tydom/{id}/config"
unknown_values_topic = "unknown/tydom/{id}/state_topic"

#temperature = current_temperature_topic
#setpoint= temperature_command_topic
#temperature_unit=C
#"modes": ["STOP", "ANTI-FROST","ECO", "COMFORT"],
#####################################
#setpoint (seulement si thermostat)
#temperature (intérieure, seulement si thermostat)
#anticipCoeff 30 (seulement si thermostat)

#thermicLevel STOP ECO ...
#auhorisation HEATING
#hvacMode NORMAL None (si off)
#timeDelay : 0
#tempoOn : False
#antifrost True False
#openingdetected False
#presenceDetected False
#absence False
#LoadSheddingOn False

#outTemperature float
##################################

# climate_json_attributes_topic = "climate/tydom/{id}/state"
# State topic can be the same as the original device attributes topic !
class Unknown:

    def __init__(self, tydom_attributes, tydom_client=None, mqtt=None):

        self.attributes = tydom_attributes
        self.device_id = self.attributes['device_id']
        self.endpoint_id = self.attributes['endpoint_id']
        self.id = self.attributes['id']
        self.name = self.attributes['name']
        self.mqtt = mqtt
        self.tydom_client = tydom_client

    async def setup(self):
        self.device = {}
        self.config = {}
        self.device['manufacturer'] = 'Delta Dore'
        self.device['name'] = self.name
        self.device['identifiers'] = self.id

        self.config['name'] = self.name
        #self.device['model'] = 'sensor'

        self.config_topic = unknown_config_topic.format(id=self.id)

        self.config['state_topic'] = unknown_values_topic.format(id=self.id)
        self.config['payload_on'] = True
        self.config['payload_off'] = False
        self.config['device_class'] = 'hvac'

        self.config['value_template'] =  "{{ value_json.intrusionDetect }}"
        self.config['unique_id'] = self.id

        if (self.mqtt != None):
            self.mqtt.mqtt_client.publish(self.config_topic, json.dumps(self.config), qos=0)

    async def update(self):
        await self.setup()

        # Chic Debug

        if (self.mqtt != None):
            self.mqtt.mqtt_client.publish(self.config['state_topic'],json.dumps(self.attributes), qos=0)


#!/usr/bin/env python

import numpy
import scipy
from scipy import signal
from scipy.spatial.distance import squareform
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import fcluster
from scm.plams import Molecule, DCDTrajectoryFile, dihedral

"""
The goal is to find out for each bond if all three torsion angles are represented
"""

def define_rotatable_torsions (mol) :
        """
        Return the atoms of the torsion angles for the rotatable bonds
        """
        torsions = []
        for bond in mol.bonds :
                indices = [ind-1 for ind in mol.index(bond)]
                terminal = False
                identical = False
                for i,at in enumerate(bond) :
                        neighbors = at.neighbors()
                        if len(neighbors)<4 :
                                terminal = True
                                continue
                        labels = set([at.IDname for at in neighbors if not at in bond])
                        if len(labels) == 1 :
                                identical = True
                if terminal or identical :
                        continue
                # Define the torsion
                one_four = []
                for at in bond :
                        one_four += [mol.index(n)-1 for n in at.neighbors() if n.symbol=='C' and not n in bond]
                torsion = [one_four[0]] + indices + [one_four[1]]
                torsions.append(torsion)

        return torsions

def get_diffvec (phi,psi) :
        """
        Compute the shift
        """
        diff = phi-psi
        diff = diff - (numpy.round(diff/360)*360)
        return diff

def get_distance (phi,psi) :
        """
        Computes the difference between two dihedral angles
        """
        return abs(get_diffvec (phi,psi))

def get_average_torsion (phis) :
        """
        Get the average torsion angle, taking periodicity into account
        """
        shift = phis[0]
        phis_shifted = get_diffvec(phis,shift)
        avg_shifted = phis_shifted.sum()/len(phis)
        average = avg_shifted + shift
        return average

def check_clusters (centers, threshold=30.) :
        """
        Check that the clusters are approximately 120 degrees apart
        """
        ones = numpy.ones(nclusters)
        distances = get_distance(ones*centers.reshape((nclusters,1)), ones*centers.reshape((1,nclusters)))
        distances = distances[numpy.triu(distances)!=0]
        return (abs(distances-120)).max() <= threshold

mol = Molecule('mol.xyz')
mol.guess_bonds()
mol.label(keep_labels=True)
nats = len(mol)

dcd = DCDTrajectoryFile('RDKit.dcd')

# Define the torsion angles
torsions = define_rotatable_torsions(mol)
for tor in torsions: print(tor)

# Get all the values for the torsion angles
coords = mol.as_array()
torsion_angles = {}
for iconf,(crd,cell) in enumerate(dcd) :
        if iconf%100==0 : print (iconf)
        coords[:] = crd
        for itors,atoms in enumerate(torsions) :
                phi = dihedral(*coords[atoms],unit='degree')
                if not itors in torsion_angles :
                        torsion_angles[itors] = []
                torsion_angles[itors].append(phi)
for itors,atoms in enumerate(torsion_angles) :
        torsion_angles[itors] = numpy.array(torsion_angles[itors])

# Now we need to cluster them somehow (for a function over the histogram and find maxima?
confnum = 6 # The conformation I want to compare
ntorsions = len(torsions)
size_list = []
dists_to_conf = []
for itors in range(ntorsions) :
        phis = torsion_angles[itors]
        #print ('phis: ',phis)

        # Compute a distance matrix
        nconfs = len(phis)
        ones = numpy.ones((nconfs,nconfs))
        matrix = get_distance(ones * phis.reshape((nconfs,1)), ones*phis.reshape((1,nconfs)) )

        # Get the minimum distance conformer for each conformer
        print ('Matrix ',itors)
        print (matrix[confnum,:10])
        matrix[range(nconfs),range(nconfs)] = 1000.
        dists_to_conf.append(matrix[confnum])

dists_to_conf = numpy.array(dists_to_conf)

# Now find the conformers that is overall the most similar
dist_to_conf = dists_to_conf.sum(axis=0) / ntorsions
indices = dist_to_conf.argsort()
mindist = dist_to_conf.min()
print ()
print ('The nearest conformer: ',indices[:5], mindist)


import requests
from time import sleep

def config_params(params, param, payload):

    """
    takes as input a list of params, a param under consideration and payload to be inserted,
    creates a dict in which param under consideration is set to payload
    and sets all other params to "example".
    return dict request_params
    """

    request_params = {}

    for parameter in params:

            if parameter == param:

                request_params[parameter] = payload

            else:

                request_params[parameter] = "test"

    return request_params

def make_fuzz_request(url, params, param, payload):
    """
    takes target url, list of params, present param and payload as inputs,
    configures parameters and makes request,
    returns response and, if WAF and dropping suspicious requests, returns break_loop as True
    """
    break_loop = False

    request_params = config_params(params, param, payload)

    # tries to make request
    try:

        response = requests.post(url, data=request_params)

    # if request is dropped, tries again in 60 seconds
    except:

        print("WAF is dropping suspiscious requests")
        print("Payload: " + payload)
        sleep(60)

        try:

            response = requests.post(url, data=request_params)

        # if dropped again sets break_loop to True
        except:

            print("WAF is blocking this IP address")

            break_loop = True

    return response, break_loop


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  7 16:26:21 2017
爬取信息
@author: lovephysics
"""

from bs4 import BeautifulSoup
import urllib.request as request
import pandas as pd

url = 'http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-recent30-0-0-1-'

shuming = []
value = []

for num in range(1,26):

    urlopen = request.urlopen(url+str(num))
    content = urlopen.read()
    content=content.decode('gbk')
    soup = BeautifulSoup(content,'lxml')

    tem1 = soup.select('body div div div.bang_list_box ul li div.name a')
    #title
    tem2 = soup.select('body div.bang_wrapper div.bang_content div ul li div.price p span.price_n')
    #now price
    tem3 = soup.select('body div.bang_wrapper div.bang_content div ul li div.price p span.price_r')
    #before price
    tem9 = soup.select('body div.bang_wrapper div.bang_content div ul li div.price p span.price_s')
    #zekou
    tem = soup.select('body div.bang_wrapper div.bang_content div.bang_list_box ul li div.publisher_info a')
    tem4 = []  #author
    tem5 = []  #public
    for i,each in enumerate(tem):
        if(i%2==0):
            tem4.append(each)
        else:tem5.append(each)

    tem6 = soup.select('body div.bang_wrapper div.bang_content div.bang_list_box ul li div.star span.tuijian')
    #tuijian
    tem7 = soup.select('body div.bang_wrapper div.bang_content div.bang_list_box ul li div.star a')
    #pinglunshu
    tem8 = soup.select('body div.bang_wrapper div.bang_content div.bang_list_box ul li div.publisher_info span')
    #shijian

    for t1,t2,t3,t4,t5,t6,t7,t8,t9 in zip(tem1,tem2,tem3,tem4,tem5,tem6,tem7,tem8,tem9):
        v1 = t1.get_text()
        v2 = t2.get_text()
        v3 = t3.get_text()
        v4 = t4.get_text()
        v5 = t5.get_text()
        v6 = t6.get_text()
        v7 = t7.get_text()
        v8 = t8.get_text()
        v9 = t9.get_text()

        shuming.append(v1)
        value.append([v2,v3,v6,v7,v8,v9])

columns =  ['现价','原价','推荐','评论','时间','折扣']
df = pd.DataFrame(value,index = shuming,columns=columns)
df.to_csv('dangdang_xiaoshuo.csv')


import numpy as np
import subprocess
import sys
from collections import defaultdict
from tqdm import tqdm
import os
import pickle

np.random.seed(42)

class RNN:
    def __init__(self, H, epoch=1):
        self.H = H
        self.epoch = epoch
        self.x_ids = defaultdict(lambda: len(self.x_ids))
        self.y_ids = defaultdict(lambda: len(self.y_ids))
        self.x_len = 0
        self.y_len = 0

    def init_net(self):
        # w_rx = np.random.rand(self.x_len, self.H) / 5 - 0.1
        w_rx = np.random.rand(self.H, self.x_len) / 5 - 0.1
        w_rh = np.random.rand(self.H, self.H) / 5 - 0.1
        b_r = np.random.rand(self.H, 1) / 5 - 0.1
        # w_oh = np.random.rand(self.H, self.y_len) / 5 - 0.1
        w_oh = np.random.rand(self.y_len, self.H) / 5 - 0.1
        b_o = np.random.rand(self.y_len, 1) / 5 - 0.1
        self.net = [w_rx, w_rh, b_r, w_oh, b_o]

    def softmax(self, x):
        """ #08 p9 """
        r = np.exp(x)
        return r / r.sum()

    def find_best(self, p):
        """ #8 10 """
        return np.argmax(p)
        y = 0
        for i in range(1, len(p)):
            if p[i] > p[y]:
                y = i
        return y

    def create_one_hot(self, id_, size):
        """ #8 p12 """
        vec = np.zeros((size, 1))
        if id_ is not None:
            vec[id_] = 1
        return vec

    def forward(self, x):
        """ #8 p16 """
        w_rx, w_rh, b_r, w_oh, b_o = self.net
        x_len = len(x)
        h = [None for _ in range(x_len)]  # 隠れ層の値 (各時間tにおいて)
        p = [None for _ in range(x_len)]  # 出力の確率分布の値 (各時間tにおいて)
        y = [None for _ in range(x_len)]  # 出力の確率分布の値 (各時間tにおいて)
        for t in range(x_len):
            if t > 0:
                h[t] = np.tanh(np.dot(w_rx, x[t]) + np.dot(w_rh, h[t - 1]) + b_r)   # w_rx → w_rx.T
            else:
                h[t] = np.tanh(np.dot(w_rx, x[t]) + b_r)    # w_rx → w_rx.T
            p[t] = self.softmax(np.dot(w_oh, h[t]) + b_o)        # w_oh → w_oh.T
            y[t] = self.find_best(p[t])
        return h, p, y

    def gradient(self, x, h, p, y_):
        """ #8 p30 """
        w_rx, w_rh, b_r, w_oh, b_o = self.net
        Δw_rx, Δw_rh, Δb_r, Δw_oh, Δb_o = [np.zeros_like(x) for x in self.net]

        δ_r_ = np.zeros((len(b_r), 1))   # 次の時間から伝搬するエラー
        for t in range(len(x) - 1, -1, -1):
            δ_o_ = y_[t] - p[t]                                # 出力層エラー              # 出力層重み勾配
            Δw_oh += np.outer(δ_o_, h[t])                  # 出力層重み勾配
            Δb_o += δ_o_                                   # 出力層重み勾配
            # δ_r = np.dot(δ_r_, w_rh) + np.dot(w_oh, δ_o_)   # 逆伝搬    np.dot(δ_o_, w_oh) → np.dot(w_oh, δ_o_)
            δ_r = np.dot(w_rh, δ_r_) + np.dot(w_oh.T, δ_o_)   # 逆伝搬    np.dot(δ_o_, w_oh) → np.dot(w_oh, δ_o_)
            δ_r_ = δ_r * (1 - h[t] ** 2)                    # tanh の勾配
            # Δw_rx += np.outer(x[t], δ_r_)                   # 隠れ層重み勾配
            Δw_rx += np.outer(δ_r_, x[t])                   # 隠れ層重み勾配
            Δb_r += δ_r_                                    # 隠れ層重み勾配
            if t != 0:
                Δw_rh += np.outer(δ_r_, h[t - 1])
                # Δw_rh += np.outer(h[t - 1], δ_r_)
        Δ = [Δw_rx, Δw_rh, Δb_r, Δw_oh, Δb_o]
        return Δ

    def update_weights(self, Δ, λ=0.01):
        w_rx, w_rh, b_r, w_oh, b_o = self.net
        Δw_rx, Δw_rh, Δb_r, Δw_oh, Δb_o = Δ
        w_rx += λ * Δw_rx
        w_rh += λ * Δw_rh
        b_r += λ * Δb_r
        w_oh += λ * Δw_oh
        b_o += λ * Δb_o
        self.net = w_rx, w_rh, b_r, w_oh, b_o

    def dump(self, data, file_name):
        os.makedirs('pickles_naoto', exist_ok=True)
        with open(f"pickles_naoto/{file_name}.pkl", 'wb') as f_out:
            pickle.dump(data, f_out)

    def train(self, train_path):
        """ #8 p32 """
        X, Y_corrrect = [], []
        for line in map(lambda x: x.rstrip(), open(train_path)):
            words, tags = map(list, zip(*map(lambda x: x.split('_'), line.split())))
            X.append([])
            Y_corrrect.append([])
            for word, tag in zip(words, tags):
                X[-1].append(self.x_ids[word])
                Y_corrrect[-1].append(self.y_ids[tag])
        self.x_ids = dict(self.x_ids)
        self.y_ids = dict(self.y_ids)
        self.x_len = len(self.x_ids)
        self.y_len = len(self.y_ids)
        self.init_net()

        x_onehot_list = []
        y_onehot_list = []
        for x, y_correct in zip(X, Y_corrrect):
            x_onehot_list.append([])
            y_onehot_list.append([])
            for i in range(len(x)):
                x_onehot_list[-1].append(self.create_one_hot(x[i], self.x_len))
            for i in range(len(y_correct)):
                y_onehot_list[-1].append(
                    self.create_one_hot(y_correct[i], self.y_len))
        for _ in tqdm(range(self.epoch)):
            for x_onehot, y_onehot in zip(x_onehot_list, y_onehot_list):
                h, p, y_predict = self.forward(x_onehot)
                Δ = self.gradient(x_onehot, h, p, y_onehot)
                self.update_weights(Δ)
        self.dump(self.net, 'rnn_net')
        self.dump(self.x_ids, 'x_ids')
        self.dump(self.y_ids, 'y_ids')

    def test(self, test_path, out_path):
        self.y_ids_recover = {value: key for key, value in self.y_ids.items()}
        with open(out_path, 'w') as f:
            x_onehot_list = []
            for line in map(lambda x: x.rstrip(), open(test_path)):
                words = line.split(' ')
                x_onehot_list.append([])
                for word in words:
                    if word in self.x_ids:
                        x_onehot_list[-1].append(self.create_one_hot(
                            self.x_ids[word], self.x_len))
                    else:
                        x_onehot_list[-1].append(self.create_one_hot(
                            None, self.x_len))
            for x_onehot in x_onehot_list:
                h, p, y = self.forward(x_onehot)
                predict_list = []
                for predict_num in y:
                    predict = self.y_ids_recover[predict_num]
                    predict_list.append(predict)
                print(' '.join(predict_list), file=f)

if __name__ == '__main__':
    if sys.argv[1:] == ['test']:
        train_path = '../../../nlptutorial/test/05-train-input.txt'
        test_path = '../../../nlptutorial/test/05-test-input.txt'
        ans_path = '../../../nlptutorial/test/05-test-answer.txt'
    else:
        train_path = '../../../nlptutorial/data/wiki-en-train.norm_pos'
        test_path = '../../../nlptutorial/data/wiki-en-test.norm'
        ans_path = '../../../nlptutorial/data/wiki-en-test.pos'
    out_path = 'out.txt'
    script_path = '../../../nlptutorial/script/gradepos.pl'

    rnn = RNN(5, 20)
    rnn.train(train_path)
    rnn.test(test_path, out_path)
    subprocess.run(f'perl {script_path} {ans_path} {out_path}'.split())


import random
import numpy as np
import tkinter as tk
from tkinter import ttk
import time  # Time is needed to slow down the agent and to see how he runs
from PIL import Image, ImageTk  # For adding images into the canvas widget
from path import Environment
from agent import QLearningTable
from configure import episodeAmount,env_height,env_width,randomPixelRatio,startPageTitle,startPageResolation,XCBOptions,YCBOptions

class HomePage(tk.Tk, object):
    def __init__(self):
        super(HomePage, self).__init__()
        #self.configure(bg="white")
        self.startPosition = [tk.StringVar(value=0),tk.StringVar(value=0)]
        self.endPosition = [tk.StringVar(value=0),tk.StringVar(value=0)]
        self.title(startPageTitle)
        self.geometry(startPageResolation)
        self.create_widgets()

    def create_widgets(self):
        self.startButton =  tk.Button(self,text="baslat",command=self.startQLearning)
        self.startButton.place(x = 190,y = 130)
        self.startPositionLabel= tk.Label(self,text = "Başlangıç konumu :").place(x = 40,y = 60)
        self.endPositionLabel = tk.Label(self,text="Bitiş Konumu          :").place(x=40,y=100)
        self.startPositionComboBoxX = ttk.Combobox(self,values=XCBOptions,textvariable=self.startPosition[0],width=5)
        self.startPositionComboBoxX.place(x=150,y=60)
        self.startPositionComboBoxX.current(0)
        self.startPositionComboBoxY = ttk.Combobox(self,values=YCBOptions,textvariable=self.startPosition[1],width=5)
        self.startPositionComboBoxY.place(x=210,y=60)
        self.startPositionComboBoxY.current(0)
        # hedef konum labirentin sonuna yaikin olmasi acisindan degerler ters donduruluyor.
        self.endPositionComboBoxX = ttk.Combobox(self,values=XCBOptions[::-1],textvariable=self.endPosition[0],width=5)
        self.endPositionComboBoxX.place(x=150,y=100)
        self.endPositionComboBoxX.current(0)
        self.endPositionComboBoxY = ttk.Combobox(self,values=YCBOptions[::-1],textvariable=self.endPosition[1],width=5)
        self.endPositionComboBoxY.place(x=210,y=100)
        self.endPositionComboBoxY.current(0)
    def startQLearning(self):
        self.destroy()
        startPixel = [int(self.startPosition[0].get()),int(self.startPosition[1].get())]
        finishPixel = [int(self.endPosition[0].get()),int(self.endPosition[1].get())]
        print(finishPixel)
        # random Obstacle coordinat list ex:5x5 [0,3]
        obstacleCoordinats = self.generateRandomObstacleCoordinats(finishPixel,startPixel)
        self.env = Environment(startPixel ,finishPixel,obstacleCoordinats)
        # Calling for the main algorithm
        self.RL = QLearningTable(actions=list(range(self.env.n_actions)))
        # Running the main loop with Episodes by calling the function update()
        self.env.after(100, self.update)  # Or just update()
        self.env.mainloop()

    def update(self):
        # Resulted list for the plotting Episodes via Steps
        steps = []

    # Summed costs for all episodes in resulted list
        all_costs = []

        for episode in range(episodeAmount):
        # Initial Observation
            print(episode)
            observation = self.env.reset()
        # Updating number of Steps for each Episode
            i = 0

        # Updating the cost for each episode
            cost = 0

            while True:
            # Refreshing environment
                # self.env.render()

            # RL chooses action based on observation
                action = self.RL.choose_action(str(observation))

            # RL takes an action and get the next observation and reward
                observation_, reward, done = self.env.step(action)

            # RL learns from this transition and calculating the cost
                cost += self.RL.learn(str(observation), action, reward, str(observation_))

            # Swapping the observations - current and next
                observation = observation_

            # Calculating number of Steps in the current Episode
                i += 1

            # Break while loop when it is the end of current Episode
            # When agent reached the goal or obstacle
                if done:
                    steps += [i]
                    all_costs += [cost]
                    break

    # Showing the final route
        self.env.final()

    # Showing the Q-table with values for each action
        self.RL.print_q_table()

    # Plotting the results
        self.RL.plot_results(steps, all_costs)

    def generateRandomObstacleCoordinats(self,finishPixel,startPixel):

        obstacleAmount = int(env_height*env_width*randomPixelRatio)
        xList = np.random.randint(env_width,size=obstacleAmount)
        yList =  np.random.randint(env_height,size=obstacleAmount)
        obstacleCoordinats = []
        f = open("./entities/engel.txt", "w")
        try:
            for i in range(obstacleAmount):
                if not(xList[i]==finishPixel[0] and yList[i]==finishPixel[1]) and not(xList[i]==startPixel[0] and yList[i]==startPixel[1]):
                    newObstacle = [xList[i] ,yList[i]]
                    obstacleCoordinats.append(newObstacle)
                    f.write("({}, {}, K)\n".format(xList[i], yList[i]))
            #print(obstacleCoordinats)
            #test icin
            for i in range(obstacleAmount):
                if(xList[i]==finishPixel[0] and yList[i]==finishPixel[1]) or (xList[i]==startPixel[0] and yList[i]==startPixel[1]):
                    print("cakisiyor......")
        except(e):
            print("Dosyaya yazarken veyahut random atama yapilirken bir hata olustu!")
        finally:
            f.close();
            return obstacleCoordinats

# sadece bu dosya calistirilmak
if __name__ == '__main__':
    env = HomePage()
    env.mainloop()


# Python 3
#invite cool guys to the party
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# boundaries
xlim=[0, 30]
ylim=[0, 20]

# set up initial configuration of plot
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=xlim, ylim=ylim)
plt.xticks([])
plt.yticks([])
ln, = plt.plot([], [], 'ro', animated=True)

# global parameters
g = 9.8 # gravity
ag = np.array([0.0, -g]) # gravity vector
delta_t = 0.05
cor = 0.95 # damping factor at each accident with walls or other balls
friction_coeff = 0.97 # coefficient of friction at bottom edge along x direction
balls = []

class Ball():
    def __init__(self, radius, center, velocity):
        self.radius = 0.5 # it is different than that the argument "radius"
        self.position = center
        self.velocity = velocity
        self.scatter, = ax.plot([], [], 'o', markersize=radius)
        balls.append(self)
        self.ball_number = len(balls)

    def update(self):
        self.velocity += ag*delta_t
        self.position += self.velocity*delta_t

        if self.position[1] < ylim[0]: # hit bottom edge
            self.velocity[1] = - cor * self.velocity[1]
        if self.position[1] > ylim[1]: # hit top edge
            self.velocity[1] = - cor * self.velocity[1]
        if self.position[0] > xlim[1]: # hit right edge
            self.velocity[0] = - cor * self.velocity[0]
        if self.position[0] < xlim[0]: # hit left edge
            self.velocity[0] = - cor * self.velocity[0]

        # if ball is stuck at bottom edge apply friction
        if (self.position[1] < 0.2) and (self.velocity[1] < 1):
            self.velocity[0] = friction_coeff * self.velocity[0]

        # check if balls hit each other
        for ball in balls:
            if (ball.ball_number != self.ball_number)and (np.sqrt((ball.position[0]-self.position[0])**2 + (ball.position[1]-self.position[1])**2) < (ball.radius + self.radius)):
                self.velocity[0] = - cor * self.velocity[0]

        # clip position to make sure ball is within the boundaries
        self.position[0] = np.clip(self.position[0], xlim[0], xlim[1])
        self.position[1] = np.clip(self.position[1], ylim[0], ylim[1])

        self.scatter.set_data(self.position)

b1 = Ball(15.0, np.array([3., 18.]), np.array([1., 0.]))
b2 = Ball(9., np.array([28., 15.]), np.array([1.5, -20.]))
b3 = Ball(12., [5., 5.], [5., 5.])
b4 = Ball(14., [5., 15.], [5., -5.])

def init():
    return []

def animate(t):
    for ball in balls:
        ball.update()
    return [ball.scatter for ball in balls]

ani = animation.FuncAnimation(fig, animate, np.arange(0,100,delta_t), init_func=init, interval=10, blit=True)

plt.show()


import cv2
from matplotlib import pyplot as plt
import numpy as np

imgL = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_L.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
imgR = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_R.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
imgL_colour = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_L.jpg', 1)
imgL_colour = cv2.cvtColor(imgL_colour, cv2.COLOR_BGR2RGB)
imgL_green = imgL_colour[:, :, 1]
imgL_green = np.bitwise_not(imgL_green)
imgL_red = imgL_colour[:, :, 0]
imgL_blue = imgL_colour[:, :, 2]
# imgR_colour = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_R.jpg', 1)
# imgR_colour = cv2.cvtColor(imgR_colour, cv2.COLOR_BGR2RGB)
# rows = imgL.shape[0]
# cols = imgR.shape[1]
# stereo = cv2.StereoBM(cv2.STEREO_BM_BASIC_PRESET, ndisparities=0, SADWindowSize=27)
# disparity = stereo.compute(imgL, imgR)
# # diff = cv2.add(imgL, imgR)
# threshL = cv2.adaptiveThreshold(imgL, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 433, 0)
# threshR = cv2.adaptiveThreshold(imgR, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 433, 0)
# contoursL, hierarchy = cv2.findContours(threshL, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# contoursR, hierarchy2 = cv2.findContours(threshR, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(imgL_colour, contoursL, -1, (255, 255, 255), 1)
# cv2.drawContours(imgL_colour, contoursR, -1, (255, 255, 255), 1)

# pixelShift_y = abs(np.argmax(imgL) // cols - np.argmax(imgR) // cols)  # rows shifted
# pixelShift_x = abs(np.argmax(imgL) % cols - np.argmax(imgR) % cols)  # columns shifted
# 120, 1695
# 891, 916

plt.figure()
plt.title('Red')
plt.imshow(imgL_red)
plt.figure()
plt.title('Green')
plt.imshow(imgL_green, 'Greens')
plt.figure()
plt.title('Blue')
plt.imshow(imgL_blue)
plt.show()
'''
commonPix = []
for i in range(0, rows):
    trueIndex = np.where(indices[i] == True)
    for item in trueIndex[0]:
        commonPix.append([i, item+1])
commonPix = np.array(commonPix)

for item in commonPix:
    diff[item[0], item[1]] = 255
'''


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

import webapp2
import logging
import os
import jinja2
from datetime import date
from google.appengine.ext import ndb

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True
)

class UserData(ndb.Model):
    name = ndb.StringProperty()
    age = ndb.IntegerProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)

class BaseHandler(webapp2.RequestHandler):
    def render(self,html,values={}):
        template = JINJA_ENVIRONMENT.get_template(html)
        self.response.write(template.render(values))

class MainHandler(BaseHandler):
    def get(self):
        users = UserData.query().order(-UserData.date).fetch(10)
        values = {'users': users}
        self.render('main.html', values)

    def post(self):
        name = self.request.get('name')
        age_str = self.request.get('age')
        if name is None or age_str is None:
            self.redirect('/')

        user = UserData()
        user.name = name
        user.age = int(age_str)
        user.put()
        self.redirect('/')

class SayHandler(webapp2.RequestHandler):
    def get(self):
        logging.info("============= /say ==============")
        self.response.write('Say hello')

class Message(ndb.Model):
    name = ndb.StringProperty()
    email = ndb.StringProperty()
    msg = ndb.StringProperty()
    postedon = ndb.DateTimeProperty(auto_now_add=True)

class MyPage(BaseHandler):
    def get(self):
        messages = ndb.gql("SELECT * FROM Message ORDER BY postedon DESC")
        values = {'messages': messages}
        self.render('bbs.html', values)

    def post(self):
        message = Message()
        message.name = self.request.get('name')
        message.msg = self.request.get('msg')
        message.email = self.request.get('email')
        message.put()

        self.redirect('/bbs')

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/say', SayHandler),
    ('/bbs', MyPage)
], debug=True)


import uuid
from datetime import datetime

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mysql+mysqldb://root:111111@localhost/arale-7moor?charset=utf8')
Base = declarative_base()

def generate_uuid():
    return uuid.uuid4().hex

class Record(Base):
    __tablename__ = 'records'

    id = Column(String(32), primary_key=True, default=generate_uuid)
    botid = Column(String(100), nullable=False)
    sessionid = Column(String(100))
    usertype = Column(String(100))
    msgcontent = Column(String(1024))
    msgtype = Column(String(100))
    msgtime = Column(String(100), default=datetime.now)
    flag = Column(Integer, default=0)

if __name__ == '__main__':
    Base.metadata.create_all(engine)


"""Add config_settings

Revision ID: 34bb537756b5
Revises:
Create Date: 2021-08-19 15:02:11.396558

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '34bb537756b5'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('config_settings',
    sa.Column('namespace', sa.String(length=64), nullable=False),
    sa.Column('group', sa.String(length=64), nullable=False),
    sa.Column('key', sa.String(length=255), nullable=False),
    sa.Column('type', sa.String(length=24), nullable=False),
    sa.Column('value', sa.LargeBinary(), nullable=False),
    sa.PrimaryKeyConstraint('namespace', 'group', 'key')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('config_settings')
    # ### end Alembic commands ###


from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=chrome_options)

# open the url
driver.get('https://www.amazon.com')
sleep(2)
search_button = driver.find_element(By.XPATH, "//div[@id='nav-signin-tooltip']//a[@class='nav-action-button'][@data-nav-role='signin']")
search_button.click()

# Amazon logo
search_logo = driver.find_element(By.XPATH, "//div[@id='a-page']//i[@class='a-icon a-icon-logo'][@role='img']")

# Email field
search_email = driver.find_element(By.XPATH, "//div[@class='a-row a-spacing-base']//input[@type='email']")

# Continue button
search_continue_button = driver.find_element(By.XPATH, "//input[@id='continue']")

# Need help link
search_need_h_link = driver.find_element(By.XPATH, "//div[@class='a-section']//span[@class='a-expander-prompt']")

# Forgot your password link
# Other issues with sign-in link
# "Create your Amazon account" button
search_create_account = driver.find_element(By.XPATH, "//a[@id='createAccountSubmit']")

# Conditions of use link
search_conditions_of_use = driver.find_element(By.XPATH, "//div[@id='legalTextRow']//a[text()='Conditions of Use']")

# Privace notice link
search_privace_notice = driver.find_element(By.XPATH, "//div[@id='legalTextRow']//a[@href='/gp/help/customer/display.html/ref=ap_signin_notification_privacy_notice?ie=UTF8&nodeId=468496']")

driver.quit()


# Proyecto creado por Eva María Hoyo de la Cruz, TongTong Xu y Antonio Francisco Roldan Martín
import glob
import cv2
import p1procesadoImagen
import numpy as np

class alternativa:

    def Alternativa(strinentradaimg):
        imagen = cv2.imread(strinentradaimg)
        contrast_img = cv2.addWeighted(imagen, 2.5, np.zeros(imagen.shape, imagen.dtype), 0, 0)
        imagenhsv = cv2.cvtColor(contrast_img, cv2.COLOR_BGR2HSV)
        (cannybordes, cerradoimagen) = p1procesadoImagen.filtradorojoDifuminarNucleoCerradoCanny(imagenhsv)
        contornos, hierarchy = cv2.findContours(cerradoimagen.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        if len(contornos) > 0:
            p1procesadoImagen.recorteCorrelarSignals(contornos, imagen.copy(), imagen, "Alternativa", strinentradaimg)
        # cv2.waitKey(0)

        return ()