# Problem [1948] : 날짜 계산기
# 입력 : 월 일로 이루어진 날짜 2개
# 두 번째 날짜가 첫 번째 날짜의 몇칠째 인지 출력
# 두 번째 날짜 > 첫 번쨰 날짜

calendar = {1 : 31, 2 : 28, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, 8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31}

test_cnt = int(input())

for test in range(1,test_cnt+1) :
    result = 0
    calc_date = list(map(int,input().split()))
    month1 = calc_date[0]
    date1 = calc_date[1]
    month2 = calc_date[2]
    date2 = calc_date[3]
    date_sum1 = 0
    date_sum2 = 0
    if month1 == month2:
        result = date2 - date1 + 1
    else :
        for i in range(1,month1) :
            date_sum1 += calendar[i]
        for i in range(1,month2) :
            date_sum2 += calendar[i]
        result = (date_sum2+date2) - (date_sum1 + date1) + 1
    print('#{} {}'.format(test,result))


def strip(word):
    stripped = word.strip()
    for char in ["!", "?", "."]:
        stripped = stripped.strip(char)
    return stripped

def get_answer(question):
    return {
        "как дела": "Отлично",
        "привет": "Привет",
        "как настроение": "Хорошо",
        "как погода": "Ужас!!",
        "какой ответ на самый главный вопрос жизни, вселенной и всего такого": 42,
        "пока": "Пока!"
    }.get(strip(question.lower()), "Спроси еще что-нибудь")

def ask_user():
    while True:
        user_ask = input('Спроси меня о чем нибудь ')
        print(get_answer(user_ask))
        if strip(user_ask.lower()) == "пока":
            break

ask_user()


#!/usr/bin/env python

import math
import rospy
import tf2_ros
import tf2_geometry_msgs
from tf.transformations import euler_from_quaternion
from geometry_msgs.msg import PoseStamped, TransformStamped
from crazyflie_driver.msg import Position
from Astar import Astar
import matplotlib.pyplot as plt
from aruco_msgs.msg import MarkerArray

# Current goal (global state)
# goal = []
# pos = PoseStamped()
state = 0
count_pose = 0

goal=None
def goal_callback(msg):
    global goal
    goal=msg

def transform_marker(data):

    for marker_detect in data.markers:
        marker = PoseStamped()
        marker.header.stamp = rospy.Time.now()
        marker.header.frame_id = 'cf1/camera_link'
        marker.pose = marker_detect.pose.pose

        if not tf_buf.can_transform(marker.header.frame_id, 'map', marker.header.stamp, rospy.Duration(0.5)):
                rospy.logwarn_throttle(5.0, 'No transform from %s to map' % marker.header.frame_id)
                return

        marker_odom = tf_buf.transform(marker, 'map', rospy.Duration(0.5))

        trans = TransformStamped()
        trans.header.stamp = rospy.Time.now()
        trans.child_frame_id = "aruco/detected" + str(marker_detect.id)
        trans.header.frame_id = 'map'
        trans.transform.translation = marker_odom.pose.position
        trans.transform.rotation = marker_odom.pose.orientation

        br.sendTransform(trans)

rospy.init_node("aruco_tranz")

tf_buf   = tf2_ros.Buffer()
tf_lstn  = tf2_ros.TransformListener(tf_buf)
br = tf2_ros.StaticTransformBroadcaster()

sub_det = rospy.Subscriber('/aruco/markers', MarkerArray, goal_callback)

def main():
    rate = rospy.Rate(20)
    while not rospy.is_shutdown():
        if goal:
            transform_marker(goal)
        rate.sleep()

if __name__ == '__main__':
    main()


sec = 2503
if __name__ == '__main__':
	map = { }
	state = { }
	with open('../input.txt', 'r') as fp:
		while True:
			line = fp.readline()
			if line is None or line == '':
				break
			parts = line.split(' ')
			rd = parts[0]
			speed = int(parts[3])
			fly_time = int(parts[6])
			rest_time = int(parts[13])
			map[rd] = (speed, fly_time, rest_time)
			state[rd] = (0, 0)
	#For each second
	while sec > 0:
		sec -= 1
		for rd in map:
			rd_state = state[rd][0]
			rd_dist = state[rd][1]
			#Switch to resting
			if rd_state >= map[rd][1]:
				rd_state = -1 * map[rd][2]
			rd_state += 1
			if rd_state > 0:
				rd_dist = rd_dist + map[rd][0]
			state[rd] = (rd_state, rd_dist)
	#Find winner
	winner = (-1, None)
	for rd in state:
		if state[rd][1] > winner[0]:
			winner = (state[rd][1], rd)
	print("%s: %d" % (winner[1], winner[0]))


from __future__ import (print_function,
                        unicode_literals,
                        division)
from future.builtins import str, open, range, dict

import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import argparse
from spikevo import *
from spikevo.pynn_transforms import PyNNAL
from pprint import pprint

parser = argparse.ArgumentParser()
parser.add_argument('-b', '--backend', help='available %s' % supported_backends,
                    default=GENN)

args = parser.parse_args()
backend = args.backend
pynn = backend_setup(backend)

print(pynn.__name__)

pynnx = PyNNAL(pynn, max_subpop_size=2)

N_NEURONS = 10
w = 0.025
syn_delay = 1.
sim_time = 1000.

neuron_parameters = {
    'v_thresh': -35.0,
    'tau_m': 20.,
    'tau_syn_E': 10.0,
    # 'e_rev_E':     0.,
    'tau_refrac': 0.1,
    'v_reset': -50.0,  # hdbrgs
    'tau_syn_I': 5.,
    'i_offset': 0.0,
    # ESS - BrainScaleS
    'cm': 0.2,
    'v_rest': -50.0,
    # 'e_rev_I':    -100.,
}

pynn.setup(timestep=1.0, min_delay=1.0)

neurons = pynnx.Pop(N_NEURONS, pynn.IF_cond_exp, neuron_parameters,
                    label='neurons')
neurons.record('spikes')

inputs = pynnx.Pop(N_NEURONS, pynn.SpikeSourcePoisson,
                   {'rate': [10.0] * N_NEURONS},
                   label='poisson'
                   )
inputs.record('spikes')

proj = pynnx.Proj(inputs, neurons, pynn.FixedProbabilityConnector,
                  weights=w, delays=syn_delay,
                  conn_params={
                      'p_connect': 0.1,
                      'rng': pynnx.NumpyRNG()})
# proj = pynnx.Proj(inputs, neurons, pynn.AllToAllConnector,
#                   weights=w, delays=syn_delay)
# proj = pynnx.Proj(inputs, neurons, pynn.OneToOneConnector,
#                   weights=w, delays=syn_delay)

graph = pynnx._graph.clone()
pprint(graph)

pynnx.run(sim_time)

out_spikes = pynnx.get_spikes(neurons)
in_spikes = pynnx.get_spikes(inputs)

if backend != GENN:
    weights = pynnx.get_weights(proj)
else:
    weights = np.zeros((N_NEURONS, N_NEURONS))

pynnx.end()

fig = plt.figure(figsize=(10, 5))
ax = plt.subplot(1, 1, 1)
for nid, times in enumerate(in_spikes):
    plt.plot(times, np.ones_like(times) * nid, '+g', markersize=5)
for nid, times in enumerate(out_spikes):
    plt.plot(times, np.ones_like(times) * nid, 'xb', markersize=5)

ax.set_xlim(0, sim_time)
ax.set_ylim(0, N_NEURONS)
ax.set_xlabel('Time [ms]')
ax.set_ylabel('Neuron id')

# ax = plt.subplot(1, 2, 2)
# plt.imshow(weights)
# ax.set_xlabel('Post id')
# ax.set_ylabel('Pre id')

plt.savefig("output.pdf")
plt.show()
#
#
#
#


# pylint:disable=unused-variable
# pylint:disable=unused-argument
# pylint:disable=redefined-outer-name

import sys
from pathlib import Path
from typing import Tuple

import pytest

current_dir = Path(sys.argv[0] if __name__ == "__main__" else __file__).resolve().parent

@pytest.fixture(scope="session")
def project_slug_dir() -> Path:
    raise NotImplementedError("Override fixture 'project_slug_dir' REQUIRED")

@pytest.fixture(scope="session")
def project_name(project_slug_dir) -> str:
    # Override if it does not apply
    return project_slug_dir.name

@pytest.fixture(scope="session")
def src_dir(project_slug_dir: Path) -> Path:
    _src_dir = project_slug_dir / "src"
    assert _src_dir.exists()
    return _src_dir

@pytest.fixture(scope="session")
def tests_dir(project_slug_dir) -> Path:
    _tests_dir = project_slug_dir / "tests"
    assert _tests_dir.exists()
    return _tests_dir

@pytest.fixture(scope="session")
def validation_dir(project_slug_dir: Path) -> Path:
    validation_dir = project_slug_dir / "validation"
    assert validation_dir.exists()
    return validation_dir

@pytest.fixture(scope="session")
def tools_dir(project_slug_dir: Path) -> Path:
    tools_dir = project_slug_dir / "tools"
    assert tools_dir.exists()
    return tools_dir

@pytest.fixture(scope="session")
def docker_dir(project_slug_dir: Path) -> Path:
    docker_dir = project_slug_dir / "docker"
    assert docker_dir.exists()
    return docker_dir

@pytest.fixture(scope="session")
def metadata_file(project_slug_dir: Path) -> Path:
    metadata_file = project_slug_dir / "metadata" / "metadata.yml"
    assert metadata_file.exists()
    return metadata_file

# HELPERS -----------

def get_expected_files(docker_name: str) -> Tuple[str, ...]:
    return (
        ".cookiecutterrc",
        ".dockerignore",
        ".gitignore",
        ".pylintrc",
        "metadata:metadata.yml",
        f"docker/{docker_name}:entrypoint.sh",
        f"docker/{docker_name}:Dockerfile",
        "service.cli:execute.sh",
        "versioning:integration.cfg",
        "versioning:service.cfg",
        "requirements.in",
        "requirements.txt",
        "Makefile",
        "VERSION",
        "VERSION_INTEGRATION",
        "README.md",
        "docker-compose-build.yml",
        "docker-compose-meta.yml",
        "docker-compose.devel.yml",
        "docker-compose.yml",
    )

def assert_path_in_repo(expected_path: str, project_slug_dir: Path):

    if ":" in expected_path:
        folder, glob = expected_path.split(":")
        folder_path = project_slug_dir / folder
        assert folder_path.exists(), f"folder {folder_path} is missing!"
        assert any(folder_path.glob(glob)), f"no {glob} in {folder_path}"
    else:
        assert (
            project_slug_dir / expected_path
        ).exists(), f"{expected_path} is missing from {project_slug_dir}"


import sys
from login_ui import *
from PyQt5.QtWidgets import *

class ventana_login(QWidget):
    def __init__(self, parent=None):
            QtWidgets.QWidget.__init__(self, parent)
            self.ui=Ui_Form()
            self.ui.setupUi(self)

            #falta lo mas importante

if __name__ ==  "__main__":
    login_app = QApplication(sys.argv)
    login = ventana_login()
    login.show()
    sys.exit(login_app.exec_())


import torch
import numpy as np
import torch.nn as nn
from torch.nn import functional as F
import torch.optim as optim
from torch.autograd import Variable
import torchvision
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from torch.utils.data import DataLoader
import skimage.io
import skimage
import os
import time
import pandas as pd
import random
import pickle
import DANN_model_imp
import DANN_Dataset

random.seed(312)
torch.manual_seed(312)

def save_checkpoint(checkpoint_path, model):#, optimizer):
    state = {'state_dict': model.state_dict()}
             #'optimizer' : optimizer.state_dict()}
    torch.save(state, checkpoint_path)
    print('model saved to %s' % checkpoint_path)

def main():
    # parameters
    s_train_file_root = "./hw3_data/digits/mnistm/train"
    s_train_csv_root = "./hw3_data/digits/mnistm/train.csv"
    s_test_file_root = "./hw3_data/digits/mnistm/test"
    s_test_csv_root = "./hw3_data/digits/mnistm/test.csv"
    t_train_file_root = "./hw3_data/digits/svhn/train"
    t_train_csv_root = "./hw3_data/digits/svhn/train.csv"
    t_test_file_root = "./hw3_data/digits/svhn/test"
    t_test_csv_root = "./hw3_data/digits/svhn/test.csv"

    learning_rate = 0.01
    num_epochs = 200
    batch_size = 500

    # create the save log file
    print("Create the directory")
    if not os.path.exists("./save"):
        os.makedirs("./save")
    if not os.path.exists("./logfile"):
        os.makedirs("./logfile")
    if not os.path.exists("./logfile/DANN"):
        os.makedirs("./logfile/DANN")
    if not os.path.exists("./save_imgs"):
        os.makedirs("./save_imgs")
    if not os.path.exists("./save_imgs/DANN"):
        os.makedirs("./save_imgs/DANN")

    # load my Dataset
    s_train_dataset = DANN_Dataset.DANN_Dataset(filepath = s_train_file_root ,csvpath = s_train_csv_root)
    s_train_loader = DataLoader(s_train_dataset ,batch_size = batch_size ,shuffle=True ,num_workers=1)
    s_test_dataset = DANN_Dataset.DANN_Dataset(filepath = s_test_file_root ,csvpath = s_test_csv_root)
    s_test_loader = DataLoader(s_test_dataset ,batch_size = batch_size ,shuffle=True ,num_workers=1)
    t_train_dataset = DANN_Dataset.DANN_Dataset(filepath = t_train_file_root ,csvpath = t_train_csv_root)
    t_train_loader = DataLoader(t_train_dataset ,batch_size = batch_size ,shuffle=True ,num_workers=1)
    t_test_dataset = DANN_Dataset.DANN_Dataset(filepath = t_test_file_root ,csvpath = t_test_csv_root)
    t_test_loader = DataLoader(t_test_dataset ,batch_size = batch_size ,shuffle=True ,num_workers=1)

    print('the source dataset has %d size.' % (len(s_train_dataset)))
    print('the target dataset has %d size.' % (len(t_train_dataset)))
    print('the batch_size is %d' % (batch_size))

    # models setting
    feature_extractor = DANN_model_imp.Feature_Extractor()
    label_predictor = DANN_model_imp.Label_Predictor()
    domain_classifier = DANN_model_imp.Domain_classifier()

    # GPU enable
    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")
    print('Device used:', device)
    if torch.cuda.is_available():
        feature_extractor = feature_extractor.to(device)
        label_predictor = label_predictor.to(device)
        domain_classifier = domain_classifier.to(device)

    # setup optimizer
    optimizer = optim.Adam([{'params': feature_extractor.parameters()},
                            {'params': label_predictor.parameters()},
                            {'params': domain_classifier.parameters()}], lr= learning_rate)

    #Lossfunction
    D_criterion = nn.BCELoss()
    L_criterion = nn.NLLLoss()

    D_loss_list = []
    L_loss_list = []
    sum_src_acc_list = []
    sum_trg_acc_list = []
    sum_label_acc_loist = []
    sum_test_acc_list = []
    print("Starting training...")

    for epoch in range(num_epochs):
        feature_extractor.train()
        label_predictor.train()
        domain_classifier.train()

        print("Epoch:", epoch+1)
        len_dataloader = min(len(s_train_loader), len(t_train_loader))

        epoch_D_loss = 0.0
        epoch_L_loss = 0.0
        sum_src_acc = 0.0
        sum_trg_acc = 0.0
        sum_label_acc = 0.0
        sum_test_acc = 0.0

        if (epoch+1) == 11:
            for optimizer_t in optimizer.param_groups:
                optimizer_t['lr'] /= 2
        #    F_optimizer.param_groups[0]['lr'] /= 2
        #    L_optimizer.param_groups[0]['lr'] /= 2
        #    D_optimizer.param_groups[0]['lr'] /= 2

        if (epoch+1) == 50:
            for optimizer_t in optimizer.param_groups:
                optimizer_t['lr'] /= 2
        if (epoch+1) == 80:
            for optimizer_t in optimizer.param_groups:
                optimizer_t['lr'] /= 2
        if (epoch+1) == 150:
            for optimizer_t in optimizer.param_groups:
                optimizer_t['lr'] /= 2
        if (epoch+1) == 250:
            for optimizer_t in optimizer.param_groups:
                optimizer_t['lr'] /= 2
        if (epoch+1) == 400:
            for optimizer_t in optimizer.param_groups:
                optimizer_t['lr'] /= 2
        if (epoch+1) == 500:
            for optimizer_t in optimizer.param_groups:
                optimizer_t['lr'] /= 2
        #    F_optimizer.param_groups[0]['lr'] /= 2
        #    L_optimizer.param_groups[0]['lr'] /= 2
        #    D_optimizer.param_groups[0]['lr'] /= 2

        for i, (source_data, target_data) in enumerate(zip(s_train_loader,t_train_loader)):
            source_img, source_label = source_data
            target_img, target_label = target_data
            batch_size = len(source_img)
            from_source_labels = torch.zeros(batch_size)
            batch_size = len(target_img)
            from_target_labels = torch.ones(batch_size)

            source_img = Variable(source_img).to(device)
            source_label = Variable(source_label).to(device)
            target_img = Variable(target_img).to(device)
            target_label = Variable(target_label).to(device)

            from_source_labels = Variable(from_source_labels).to(device)
            from_target_labels = Variable(from_target_labels).to(device)

            # colculate the lambda_
            p = (i + len_dataloader * epoch)/(len_dataloader * num_epochs)
            lambda_ = 2.0 / (1. + np.exp(-10 * p)) - 1.0

            # train the feature_extractor
            optimizer.zero_grad()

            source_feature = feature_extractor(source_img)
            target_feature = feature_extractor(target_img)

            # Label_Predictor network
            src_label_output = label_predictor(source_feature)
            _, src_pred_arg = torch.max(src_label_output,1)
            src_acc = np.mean(np.array(src_pred_arg.cpu()) == np.array(source_label.cpu()))
            L_loss = L_criterion(src_label_output, source_label)

            # Domain_classifier network with source domain
            src_domain_output = domain_classifier(source_feature,lambda_).view(-1)
            src_domain_acc = np.mean(np.array(src_domain_output.detach().cpu()) >= 0.5)
            D_loss_src = D_criterion(src_domain_output, from_source_labels)

            # Domain_classifier network with target domain
            trg_domain_output = domain_classifier(target_feature,lambda_).view(-1)
            # print("trg_domain_output : ",trg_domain_output)
            trg_domain_acc = np.mean(np.array(trg_domain_output.detach().cpu()) < 0.5)

            D_loss_trg = D_criterion(trg_domain_output, from_target_labels)
            # print("D_loss_src : ",D_loss_src)
            # print("D_loss_trg : ",D_loss_trg)
            D_loss = D_loss_src + D_loss_trg
            loss = L_loss + D_loss

            epoch_D_loss += D_loss.item()
            epoch_L_loss += L_loss.item()
            sum_src_acc += src_domain_acc
            sum_trg_acc += trg_domain_acc
            sum_label_acc += src_acc

            loss.backward()
            optimizer.step()

            if (i % 20 == 0):
                print('Epoch [%d/%d], Iter [%d/%d] D_loss %.4f, L_loss %.4f , LR = %.6f'
                %(epoch, num_epochs, i+1, len_dataloader, D_loss.item(), L_loss.item(), optimizer.param_groups[0]['lr']))
                print("label_acc : %.4f , Domain src_acc : %.4f , Domain trg_acc : %.4f" %(src_acc,src_domain_acc,trg_domain_acc))

        if (epoch) % 200 == 0:
            save_checkpoint('./save/DANN-F-%03i.pth' % (epoch) , feature_extractor)
            save_checkpoint('./save/DANN-L-%03i.pth' % (epoch) , label_predictor)
            save_checkpoint('./save/DANN-D-%03i.pth' % (epoch) , domain_classifier)

        # testing
        """
        for i, (source_data, target_data) in enumerate(zip(s_train_loader,t_train_loader)):
            source_img, source_label = source_data
            target_img, target_label = target_data
            source_img = Variable(source_img).to(device)
            source_label = Variable(source_label).to(device)
            target_img = Variable(target_img).to(device)
            target_label = Variable(target_label).to(device)

            feature_extractor.eval()
            label_predictor.eval()
            domain_classifier.eval()

            target_feature = feature_extractor(target_img)
            trg_label_output = label_predictor(target_feature)
            _, trg_preds = torch.max(trg_label_output,1)
            trg_acc = np.mean(np.array(trg_preds.cpu()) == np.array(target_label.cpu()))

            sum_test_acc += trg_acc

        print("Test avg trg_acc : " %(sum_test_acc/len_dataloader))
        """
        # save loss data
        print("training D Loss:", epoch_D_loss/len_dataloader)
        print("training L Loss:", epoch_L_loss/len_dataloader)
        D_loss_list.append(epoch_D_loss/len_dataloader)
        L_loss_list.append(epoch_L_loss/len_dataloader)
        sum_src_acc_list.append(sum_src_acc/len_dataloader)
        sum_trg_acc_list.append(sum_trg_acc/len_dataloader)
        sum_label_acc_loist.append(sum_label_acc/len_dataloader)
        #sum_test_acc_list.append(sum_test_acc/len_dataloader)

        # epoch done
        print('-'*88)

    with open('./logfile/DANN/D_loss.pkl', 'wb') as f:
        pickle.dump(D_loss_list, f)
    with open('./logfile/DANN/L_loss.pkl', 'wb') as f:
        pickle.dump(L_loss_list, f)
    with open('./logfile/DANN/src_acc.pkl', 'wb') as f:
        pickle.dump(sum_src_acc_list, f)
    with open('./logfile/DANN/trg_acc.pkl', 'wb') as f:
        pickle.dump(sum_trg_acc_list, f)
    with open('./logfile/DANN/label_acc.pkl', 'wb') as f:
        pickle.dump(sum_label_acc_loist, f)
    #with open('./logfile/DANN/test_acc.pkl', 'wb') as f:
    #    pickle.dump(sum_test_acc_list, f)

    # shuffle
if __name__ == '__main__':
    main()


from sqlalchemy import create_engine, Column, Integer, String, Sequence
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import and_, or_
from sqlalchemy.orm import sessionmaker

DB_URI = 'mysql+pymysql://yngwie:yngwie@192.168.1.130:3306/test'
eng = create_engine(DB_URI)
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(20))

    def __repr__(self):
        return "<User(name='%s', id='%d')>" % (self.name, self.id)

Base.metadata.drop_all(bind=eng)
Base.metadata.create_all(bind=eng)

Session = sessionmaker(bind=eng)
session = Session()

session.add_all([User(name=username) for username in ('XiaoMing', 'WangWei','LiLei')])
# session.commit()

def get_result(rs):
    print ('-' * 20)
    for user in rs:
        print(user)

rs = session.query(User).all()
get_result(rs)

# with eng.connect() as conn:
#     conn.execute('create table user(id int primary key auto_increment,name varchar(255))')


def han(n):
    c = 0
    for i in range(100, n+1):
        i = str(i)
        if int(i[1]) * 2 == int(i[0]) + int(i[2]):
            c += 1
    return c

x = int(input())
if x // 100 == 0:
    print(x)
else:
    print(99 + han(x))


#!/usr/bin/env python

import os
import sys
import time
import signal
import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument('--name', '-n', required=True, type=str, help='Name of the cluster.')
parser.add_argument('--port', '-p', default='10000', type=str, help='Local port to use for SSH tunnel to master node.')
parser.add_argument('--zone', '-z', default='us-central1-b', type=str, help='Compute zone for Google cluster.')
args = parser.parse_args()

# check if Google Chrome is installed at default path
#chrome = os.path.abspath(r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
#if not os.path.isfile(chrome):
#    print 'Connection failed - Google Chrome executable not found at "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".'
#    sys.exit()

# if process is currently running on local port designated for SSH tunnel, kill it
try:
    pid = subprocess.check_output(['lsof', '-t', '-i:{}'.format(args.port)]).split()
except subprocess.CalledProcessError:
    pass
else:
    for x in pid:
        os.kill(int(x), signal.SIGTERM)

# open SSH tunnel to master node
cmd = [
    'gcloud compute ssh {}-m'.format(args.name),
    '--zone={}'.format(args.zone),
    '--ssh-flag="-D {} -N -f -n"'.format(args.port),
    '> /dev/null 2>&1 &'
]
subprocess.call(' '.join(cmd), shell=True)

# wait for SSH tunnel to open
time.sleep(2)

# open Chrome with SOCKS proxy configuration
cmd = [
    r'/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome',
    'http://localhost:8123',
    '--proxy-server="socks5://localhost:{}"'.format(args.port),
    '--host-resolver-rules="MAP * 0.0.0.0 , EXCLUDE localhost"',
    '--user-data-dir=/tmp/',
    '> /dev/null 2>&1 &'
]
subprocess.call(' '.join(cmd), shell=True)


# ------------------------
# Sort My Folders Python#
# ------------------------
import os
import shutil

print(os.getcwd())
myPath = r"C:\Users\AUC\Documents\PyProjects\fileTests/"
# print(os.getcwd() + r"\fileTests/" + "1" + ".jpg")

# Create Junk Files
# for n in range(5):
#     open(os.getcwd() + r"\fileTests/" + str(n) + ".mp3", "x")

# My Extentions
texts = ('txt', 'doc', 'docx', 'pdf', 'rtf', 'odt')

imgs = ('jpg', 'jpeg', 'png', 'gif')

videos = ('mp4', 'mkv', 'avi', 'mov', 'wmv')

audios = ('mp3', 'wav')

comps = ("rar","zip")

for f in os.listdir(myPath):
    # print(f) if f.endswith(imgs) else "" # Testing
    if f.endswith(imgs):
        os.mkdir(myPath + "Images") if not os.path.exists(myPath + "Images") else ""
        # shutil.move(f, myPath + "/Images")
        shutil.copy(myPath + f, myPath + "Images")
        os.remove(myPath + f)

    if f.endswith(texts):
        os.mkdir(myPath + "Docs") if not os.path.exists(myPath + "Docs") else ""
        # shutil.move(f, myPath + "/Images")
        shutil.copy(myPath + f, myPath + "Docs")
        os.remove(myPath + f)

    if f.endswith(videos):
        os.mkdir(myPath + "Vids") if not os.path.exists(myPath + "Vids") else ""
        # shutil.move(f, myPath + "/Images")
        shutil.copy(myPath + f, myPath + "Vids")
        os.remove(myPath + f)

    if f.endswith(audios):
        os.mkdir(myPath + "Sound") if not os.path.exists(myPath + "Sound") else ""
        # shutil.move(f, myPath + "/Images")
        shutil.copy(myPath + f, myPath + "Sound")
        os.remove(myPath + f)

    if f.endswith(comps):
        os.mkdir(myPath + "Comps") if not os.path.exists(myPath + "Comps") else ""
        # shutil.move(f, myPath + "/Images")
        shutil.copy(myPath + f, myPath + "Comps")
        os.remove(myPath + f)


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

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

import pandas as pd

import random

import sys

np.set_printoptions(linewidth=500)
np.set_printoptions(precision=4, floatmode='fixed')

#大きさを返す
def norm(r):
    return(np.sqrt(np.real(np.dot(r.conjugate(),r))))

#ランダムな複素数を作る
def randC():
    return(complex(random.uniform(-1,1),random.uniform(-1,1)))
#スピン１、スピン２のスピノルを作る（規格化込み）
def spin1(s1,s0,sm1):
    a=np.array([s1,s0,sm1])
    a=a/norm(a)
    return(a)
def spin2(r2,r1,r0,rm1,rm2):
    a=np.array([r2,r1,r0,rm1,rm2])
    a=a/norm(a)
    return(a)
def rands1():
    a=[random.uniform(-1,1) for i in range(6)]
    return(spin1(complex(a[0],a[1]),complex(a[2],a[3]),complex(a[4],a[5])))
def rands2():
    a=[random.uniform(-1,1) for i in range(10)]
    return(spin2(complex(a[0],a[1]),complex(a[2],a[3]),complex(a[4],a[5]),complex(a[6],a[7]),complex(a[8],a[9])))

#スピン演算子
rt2=np.sqrt(2.0)
F3x=np.array([[0.0,rt2,0.0],
              [rt2,0.0,rt2],
              [0.0,rt2,0.0]
             ])/2.0
F3y=np.array([[0.0,rt2,0.0],
              [-rt2,0.0,rt2],
              [0.0,-rt2,0.0]
             ])/2.0j
F3z=np.array([[1.0,0.0,0.0],
              [0.0,0.0,0.0],
              [0.0,0.0,-1.0]
             ])

rt6=np.sqrt(6.0)
F5x=(np.array([[0.0,2.0,0.0,0.0,0.0],
               [2.0,0.0,rt6,0.0,0.0],
               [0.0,rt6,0.0,rt6,0.0],
               [0.0,0.0,rt6,0.0,2.0],
               [0.0,0.0,0.0,2.0,0.0]
              ]))/2.0
F5y=(np.array([[0.0,2.0,0.0,0.0,0.0],
                [-2.0,0.0,rt6,0.0,0.0],
                [0.0,-rt6,0.0,rt6,0.0],
                [0.0,0.0,-rt6,0.0,2.0],
                [0.0,0.0,0.0,-2.0,0.0]
               ]))/2.0j
F5z=np.array([[2.0,0.0,0.0,0.0,0.0],
              [0.0,1.0,0.0,0.0,0.0],
              [0.0,0.0,0.0,0.0,0.0],
              [0.0,0.0,0.0,-1.0,0.0],
              [0.0,0.0,0.0,0.0,-2.0]
             ])

#A_0^2
P02=np.array([[0.0,0.0,0.0,0.0,1.0],
              [0.0,0.0,0.0,-1.0,0.0],
              [0.0,0.0,1.0,0.0,0.0],
              [0.0,-1.0,0.0,0.0,0.0],
              [1.0,0.0,0.0,0.0,0.0]
             ])/np.sqrt(5.0)

def A0(r):
    F=np.dot(r.conjugate(),np.dot(P02,r))
    Fans=np.dot(F.conjugate(),F).real
    return(Fans)

#F_(m)^(f)
def F1(s):
    Fx=np.dot(s.conjugate(),np.dot(F3x,s))
    Fy=np.dot(s.conjugate(),np.dot(F3y,s))
    Fz=np.dot(s.conjugate(),np.dot(F3z,s))
    return(np.array([Fx,Fy,Fz]).real)

def F2(r):
    Fx=np.dot(r.conjugate(),np.dot(F5x,r))
    Fy=np.dot(r.conjugate(),np.dot(F5y,r))
    Fz=np.dot(r.conjugate(),np.dot(F5z,r))
    return(np.array([Fx,Fy,Fz]).real)

def F11(s):
    F=np.dot(F1(s),F1(s))
    return(F)

def F22(r):
    F=np.dot(F2(r),F2(r))
    return(F)

def F12(s,r):
    F=np.dot(F1(s),F2(r))
#    vecplot(F1(s),F2(r))
    return(F)

#回転行列
l3x,P3x=np.linalg.eig(F3x)
l5x,P5x=np.linalg.eig(F5x)
l3y,P3y=np.linalg.eig(F3y)
l5y,P5y=np.linalg.eig(F5y)
l3z,P3z=np.linalg.eig(F3z)
l5z,P5z=np.linalg.eig(F5z)
def R3x(t,s):
    A=np.diag(np.exp(-1.0j*l3x*t))
    R=np.dot(P3x,np.dot(A,np.conjugate(P3x.T)))
    ans=np.dot(R,s)
    return(ans)

def R5x(t,s):
    A=np.diag(np.exp(-1.0j*l5x*t))
    R=np.dot(P5x,np.dot(A,np.conjugate(P5x.T)))
    ans=np.dot(R,s)
    return(ans)

def R3y(t,s):
    A=np.diag(np.exp(-1.0j*l3y*t))
    R=np.dot(P3y,np.dot(A,np.conjugate(P3y.T)))
    ans=np.dot(R,s)
    return(ans)

def R5y(t,s):
    A=np.diag(np.exp(-1.0j*l5y*t))
    R=np.dot(P5y,np.dot(A,np.conjugate(P5y.T)))
    ans=np.dot(R,s)
    return(ans)

def R3z(t,s):
    A=np.diag(np.exp(-1.0j*l3z*t))
    R=np.dot(P3z,np.dot(A,np.conjugate(P3z.T)))
    ans=np.dot(R,s)
    return(ans)

def R5z(t,s):
    A=np.diag(np.exp(-1.0j*l5z*t))
    R=np.dot(P5z,np.dot(A,np.conjugate(P5z.T)))
    ans=np.dot(R,s)
    return(ans)

#逆行列はnp.linalg.inv(A)で出る

#成分を実数にするように位相変換
def tau_0real(s):
    tau=np.arctan(-s[0].imag/s[0].real)
    ans=np.exp(1.0j*tau)*s
    return(ans)
def tau_1real(s):
    tau=np.arctan(-s[1].imag/s[1].real)
    ans=np.exp(1.0j*tau)*s
    return(ans)
def tau_2real(s):
    tau=np.arctan(-s[2].imag/s[2].real)
    ans=np.exp(1.0j*tau)*s
    return(ans)

#P_1^12論文のベタ打ち
r01=np.sqrt(1.0/10.0)
r04=np.sqrt(2.0/5.0)
r03=np.sqrt(3.0/10.0)
r06=np.sqrt(3.0/5.0)
def P112beta(s,r):
    A11=(s[0]*r[2]*r01-s[1]*r[1]*r03+s[2]*r[0]*r06)
    A10=(s[0]*r[3]*r03-s[1]*r[2]*r04+s[2]*r[1]*r03)
    A1m1=(s[0]*r[4]*r06-s[1]*r[3]*r03+s[2]*r[2]*r01)
    ans=np.dot(A11.conjugate(),A11)+np.dot(A10.conjugate(),A10)+np.dot(A1m1.conjugate(),A1m1)
    return(ans.real)

def zrad(s,r):
    S=F1(s)
    Sx,Sy,Sz=F1(s)
    a=np.arctan2(Sy,Sx)
    ans1=R3z(-a,s)
    ans2=R5z(-a,r)
    return(a,ans1,ans2)

def yrad(s,r):
    S=F1(s)
    Sx,Sy,Sz=F1(s)
    a=np.arctan2(Sx,Sz)
    ans=R3y(-a,s)
    ans2=R5y(-a,r)
    return(a,ans,ans2)

def RotFz(s1,s2):
    tau,rs1,rs2=zrad(s1,s2)
    beta,rrs1,rrs2=yrad(rs1,rs2)
    return(rrs1,rrs2)

def Fzsize(s1,s2):
    rs1,rs2=RotFz(s1,s2)
    f1z=np.dot(rs1.conjugate(),np.dot(F3z,rs1)).real
    f2z=np.dot(rs2.conjugate(),np.dot(F5z,rs2)).real
    return(f1z,f2z)

fig = plt.figure()
ax1 = fig.add_subplot(111)
c22=0.76

c11=[]
f1zs=[]
f2zs=[]

data = pd.read_table('data_mixed.txt', header=None, delim_whitespace=True)
print(data)

data_c22_fix = data[data[2]==c22]
print(data_c22_fix)

for i in range(len(data_c22_fix)):
    data_tmp = data_c22_fix.iloc[i]
    c = data_tmp[0:5]  # c = [c1^1,c1^2,c2^2,c1^12,c2^12]
    c11.append(c[0])
    s1 = np.array([complex(data_tmp[k],data_tmp[k+1]) for k in [5,7,9]])
    s2 = np.array([complex(data_tmp[k],data_tmp[k+1]) for k in [11,13,15,17,19]])

    f1z, f2z = Fzsize(s1,s2)
    f1zs.append(f1z)
    f2zs.append(f2z)

fontsize=18
plt.rcParams["font.size"] = fontsize
ln1=ax1.plot(c11,f1zs,"C0",label= '$F_z^{(1)}$')
plt.tick_params(labelsize=fontsize)
ax2=ax1.twinx()
ln2=ax2.plot(c11,f2zs,"C1",label= '$F_z^{(2)}$')
ax1.set_xlabel('$c_1^{(1)},c_1^{(2)}$', fontsize=fontsize)
ax1.set_ylabel(r'$F_z^{(1)}$', fontsize=fontsize)
ax2.set_ylabel(r'$F_z^{(2)}$')

h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc='lower left')

plt.tight_layout()
plt.savefig("Fzc22_076")


import BreakpointGraph, ReadTextPattern, WriteReversalsToFile

P, Q = ReadTextPattern.ReadTextPattern('dataset_288_5.txt')
#P = [[1, -7, 6,-10, 9, -8, 2, -11, -3, 5, 4]]
#Q = [[1, 2,3,4,5,6,7,8,9,10, 11]]
#Solve distance

#Red = BreakpointGraph.ColoredEdges(P)
#print len(Red)
#Blue = BreakpointGraph.ColoredEdges(Q)
'''blocks = len(Red)
c = BreakpointGraph.CycleCount(Red, Blue)
print c'''

#Return reversals
#Red = BreakpointGraph.ColoredEdgesGraph(P)
#Blue = BreakpointGraph.ColoredEdgesGraph(Q)

rev = BreakpointGraph.ShortestRearrangementGraph(P, Q)
WriteReversalsToFile.WriteReversalsToFile(rev)
'''P1 = rev[-1]
Red = BreakpointGraph.ColoredEdges(P1)
Blue = BreakpointGraph.ColoredEdges(Q)
blocks = len(Red)
c = BreakpointGraph.CycleCount(Red, Blue)
print c'''

'''for el in rev:
    print el'''


#!/usr/bin/python3.6.8
# -*- coding:utf-8 -*-
import datetime
from decimal import Decimal

from flask import request, jsonify, g

from application import db, app
from common.libs.Helper import getCurrentDate
from common.libs.MemberService import MemberService
from common.libs.UrlManager import UrlManager
from common.libs.mall.PayService import PayService
from common.libs.mall.WechatService import WeChatService
from common.models.ciwei.BalanceOder import BalanceOrder
from common.models.ciwei.Goods import Good
from common.models.ciwei.Member import Member
from common.models.ciwei.MemberSmsPkg import MemberSmsPkg
from common.models.ciwei.Thanks import Thank
from common.models.ciwei.User import User

from web.controllers.api import route_api

@route_api.route("/balance/use/warn", methods=['GET', 'POST'])
def warnUseBalance():
    """
    对使用余额，有二维码，但没有任何短信次数的会员进行余额预警
    :return:
    """
    resp = {'code': 200, 'msg': 'success', 'data': False}
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "请先登录"
        return jsonify(resp)

    if member_info.has_qr_code:
        if member_info.left_notify_times <= 0:
            pkg = MemberSmsPkg.query.filter(MemberSmsPkg.open_id == member_info.openid,
                                            MemberSmsPkg.expired_time < datetime.datetime.now() + datetime.timedelta(
                                                weeks=1),
                                            MemberSmsPkg.left_notify_times > 0).first()
            if not pkg:
                resp['data'] = True
    return jsonify(resp)

@route_api.route("/balance/order", methods=['POST', 'GET'])
def createBalanceOrder():
    """
    🥌余额充值下单
    :return:
    """
    resp = {'code': 200, 'msg': 'success', 'data': {}}
    req = request.values
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "请先登录"
        return jsonify(resp)
    price = req['price'] if 'price' in req else 0
    if not price:
        resp['code'] = -1
        resp['msg'] = "支付失败"
        return jsonify(resp)

    # 数据库下单
    wechat_service = WeChatService(merchant_key=app.config['OPENCS_APP']['mch_key'])
    pay_service = PayService()
    model_order = BalanceOrder()
    model_order.order_sn = pay_service.geneBalanceOrderSn()
    model_order.openid = member_info.openid
    model_order.member_id = member_info.id
    model_order.price = Decimal(price).quantize(Decimal('0.00'))

    # 微信下单
    pay_data = {
        'appid': app.config['OPENCS_APP']['appid'],
        'mch_id': app.config['OPENCS_APP']['mch_id'],
        'nonce_str': wechat_service.get_nonce_str(),
        'body': '闪寻-充值',
        'out_trade_no': model_order.order_sn,
        'total_fee': int(model_order.price * 100),
        'notify_url': app.config['APP']['domain'] + "/api/balance/order/notify",
        'time_expire': (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%Y%m%d%H%M%S"),
        'trade_type': 'JSAPI',
        'openid': member_info.openid
    }
    pay_sign_data = wechat_service.get_pay_info(pay_data=pay_data)
    if not pay_sign_data:
        resp['code'] = -1
        resp['msg'] = "微信服务器繁忙，请稍后重试"
        return jsonify(resp)
    model_order.status = 0
    db.session.add(model_order)
    db.session.commit()
    resp['data'] = pay_sign_data
    return jsonify(resp)

@route_api.route('/balance/order/notify', methods=['GET', 'POST'])
def balanceOrderCallback():
    """
    余额单子支付回调
    :return:
    """
    result_data = {
        'return_code': 'SUCCESS',
        'return_msg': 'OK'
    }
    header = {'Content-Type': 'application/xml'}
    app_config = app.config['OPENCS_APP']
    target_wechat = WeChatService(merchant_key=app_config['mch_key'])
    callback_data = target_wechat.xml_to_dict(request.data)
    app.logger.info(callback_data)

    # 检查签名和订单金额
    sign = callback_data['sign']
    callback_data.pop('sign')
    gene_sign = target_wechat.create_sign(callback_data)
    app.logger.info(gene_sign)
    if sign != gene_sign:
        result_data['return_code'] = result_data['return_msg'] = 'FAIL'
        return target_wechat.dict_to_xml(result_data), header
    if callback_data['result_code'] != 'SUCCESS':
        result_data['return_code'] = result_data['return_msg'] = 'FAIL'
        return target_wechat.dict_to_xml(result_data), header

    order_sn = callback_data['out_trade_no']
    pay_order_info = BalanceOrder.query.filter_by(order_sn=order_sn).first()
    if not pay_order_info:
        result_data['return_code'] = result_data['return_msg'] = 'FAIL'
        return target_wechat.dict_to_xml(result_data), header

    if int(pay_order_info.price * 100) != int(callback_data['total_fee']):
        result_data['return_code'] = result_data['return_msg'] = 'FAIL'
        return target_wechat.dict_to_xml(result_data), header

    # 更新订单的支付状态, 记录日志

    # 订单状态已回调更新过直接返回
    if pay_order_info.status == 1:
        return target_wechat.dict_to_xml(result_data), header
    # 订单状态未回调更新过
    target_pay = PayService()
    target_pay.balanceOrderSuccess(pay_order_id=pay_order_info.id, params={"pay_sn": callback_data['transaction_id'],
                                                                           "paid_time": callback_data['time_end']})
    target_pay.addBalancePayCallbackData(pay_order_id=pay_order_info.id, data=request.data)

    return target_wechat.dict_to_xml(result_data), header

@route_api.route('/member/sms/pkg/add', methods=['GET', 'POST'])
def addSmsPkg():
    """

    :return:
    """
    resp = {'code': 200, 'msg': '', 'data': {}}
    req = request.values
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "请先登录"
        return jsonify(resp)

    pkg = MemberSmsPkg()
    pkg.open_id = member_info.openid
    pkg.left_notify_times = 50
    pkg.expired_time = datetime.datetime.now() + datetime.timedelta(weeks=156)
    db.session.add(pkg)
    db.session.commit()
    return jsonify(resp)

@route_api.route('/member/sms/change', methods=['GET', 'POST'])
def changeSmsTimes():
    """
    用户通知次数
    :return:
    """
    resp = {'code': 200, 'msg': '', 'data': {}}
    req = request.values
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "请先登录"
        return jsonify(resp)

    times = int(req['times']) if 'times' in req else 0
    member_info.left_notify_times += times
    db.session.add(member_info)
    db.session.commit()
    return jsonify(resp)

@route_api.route("/member/balance/change", methods=['GET', 'POST'])
def balanceChange():
    resp = {'code': 200, 'msg': '', 'data': {}}
    req = request.values
    unit = req['unit'] if 'unit' in req else 0
    unit = Decimal(unit).quantize(Decimal("0.00"))

    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "请先登录"
        return jsonify(resp)

    member_info.balance += unit
    MemberService.setMemberBalanceChange(member_info=member_info, unit=unit, note=req['note'] if 'note' in req else '')
    db.session.add(member_info)
    db.session.commit()
    return jsonify(resp)

# TODO：如果可以锁号，那么登陆需要判断用户的status
@route_api.route("/member/login", methods=['GET', 'POST'])
def login():
    """
    会员登陆或注册
    :return: openid#会员id
    """
    resp = {'code': 200, 'msg': 'login successfully(login)', 'data': {}}
    req = request.values

    # 检查参数：code
    code = req['code'] if 'code' in req else ''

    if not code or len(code) < 1:
        resp['code'] = -1
        resp['msg'] = "need code"
        return jsonify(resp)

    # 微信端登陆
    # 没注册：新增openid绑定的会员/查找openid绑定的会员
    # 返回openid#会员id
    openid = MemberService.getWeChatOpenId(code)
    if openid is None:
        resp['code'] = -1
        resp['msg'] = "call wechat error"
        return jsonify(resp)

    nickname = req['nickName'] if 'nickName' in req else ''
    sex = req['gender'] if 'gender' in req else 0
    avatar = req['avatarUrl'] if 'avatarUrl' in req else ''
    mobile = req['mobile'] if 'mobile' in req and req['mobile'] else ''
    '''
    判断是否已经注册过，注册了直接返回一些信息即可
    '''
    member_info = Member.query.filter_by(openid=openid, status=1).first()
    if not member_info:
        model_member = Member()
        model_member.nickname = nickname
        model_member.sex = sex
        model_member.avatar = avatar
        model_member.updated_time = model_member.created_time = getCurrentDate()
        model_member.openid = openid
        model_member.mobile = mobile
        db.session.add(model_member)
        db.session.commit()
        member_info = model_member
    else:
        if not nickname:
            member_info.nickname = nickname
            db.session.add(member_info)
        if not sex:
            member_info.sex = sex
            db.session.add(member_info)
        if not avatar:
            member_info.avatar = avatar
            db.session.add(member_info)
        if not mobile:
            member_info.mobile = mobile
            db.session.add(member_info)
        db.session.commit()

    # 登陆后，前端在 app.globalData 中存有全局变量
    is_adm = False
    is_user = False
    has_qrcode = False
    user_info = User.query.filter_by(member_id=member_info.id).first()
    if user_info:
        if user_info.level == 1:
            is_adm = True
            is_user = True
        elif user_info.level > 1:
            is_user = True

    # 济人济市的openid if openid=="opLxO5fmwgdzntX4gfdKEk5NqLQA":
    # uni-济旦财的openid if openid=="o1w1e5egBOLj5SjvPkNIsA3jpZFI":
    if openid == "opLxO5fmwgdzntX4gfdKEk5NqLQA":
        is_adm = True
        is_user = True

    if member_info.qr_code:
        has_qrcode = True

    token = "%s#%s" % (openid, member_info.id)
    resp['data'] = {
        'token': token,
        'is_adm': is_adm,
        'is_user': is_user,
        'has_qrcode': has_qrcode,
        'member_status': member_info.status,
        'id': member_info.id
    }
    return jsonify(resp)

@route_api.route("/member/check-reg", methods=['GET', 'POST'])
def checkReg():
    """
    角色信息
    :return:用户角色,二维码,token,用户状态
    """
    resp = {'code': 200, 'msg': 'login successfully(check-reg)', 'data': {}}
    req = request.values

    # 检查参数：code

    code = req['code'] if 'code' in req else ''
    if not code:
        resp['code'] = -1
        resp['msg'] = "微信繁忙"
        return jsonify(resp)

    openid, session_key = MemberService.getWeChatOpenId(code, get_session_key=True)
    if not openid:
        resp['code'] = -1
        resp['msg'] = "微信繁忙"
        return jsonify(resp)
    member_info = Member.query.filter_by(openid=openid).first()
    if not member_info:
        resp['code'] = -2
        resp['member_status'] = -2
        resp['data'] = {
            'openid': openid,
            'session_key': session_key
        }
        resp['msg'] = "用户未注册"
        return jsonify(resp)
    is_adm = False
    is_user = False
    has_qrcode = False
    user_info = User.query.filter_by(member_id=member_info.id).first()
    if user_info:
        if user_info.level == 1:
            is_adm = True
            is_user = True
        elif user_info.level > 1:
            is_user = True

    # 济人济市的openid if openid=="opLxO5fmwgdzntX4gfdKEk5NqLQA":
    # uni-济旦财的openid if openid=="o1w1e5egBOLj5SjvPkNIsA3jpZFI":
    if openid == "opLxO5fmwgdzntX4gfdKEk5NqLQA":
        is_adm = True
        is_user = True

    if member_info.qr_code:
        has_qrcode = True

    token = "%s#%s" % (openid, member_info.id)
    resp['data'] = {
        'token': token,
        'is_adm': is_adm,
        'is_user': is_user,
        'has_qrcode': has_qrcode,
        'member_status': member_info.status,
        'id': member_info.id
    }
    return jsonify(resp)

@route_api.route("/member/is-reg", methods=['GET', 'POST'])
def isReg():
    resp = {'code': 200, 'msg': '', 'data': {}}
    req = request.values
    openid = req['openid'] if 'openid' in req else ''
    member_info = Member.query.filter_by(openid=openid).first()
    if not member_info:
        resp['data']['is_reg'] = False
    else:
        resp['data']['is_reg'] = True
    return jsonify(resp)

@route_api.route("/member/info")
def memberInfo():
    """
    用户信息
    :return: id,昵称,头像,积分,二维码
    """
    resp = {'code': 200, 'msg': '', 'data': {}}

    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "没有相关用户信息"
        return jsonify(resp)

    has_qrcode = False
    if member_info.qr_code:
        qr_code_url = UrlManager.buildImageUrl(member_info.qr_code, image_type='QR_CODE')
        has_qrcode = True
    else:
        qr_code_url = ""

    pkgs = MemberSmsPkg.query.filter(MemberSmsPkg.open_id == member_info.openid,
                                    MemberSmsPkg.expired_time >= datetime.datetime.now()).all()

    p_times = 0  # 计算套餐包有效期内总数量
    pkg_data_list = []
    for item in pkgs:
        p_time = item.left_notify_times
        tmp_data = {
            'num': p_time,
            'expire': item.expired_time.strftime(format="%Y-%m-%d")
        }
        p_times += p_time
        pkg_data_list.append(tmp_data)

    m_times = member_info.left_notify_times  # 计算按量购买的数量
    resp['data']['info'] = {
        'nickname': member_info.nickname,
        'avatar': member_info.avatar,
        'qr_code': qr_code_url,
        'member_id': member_info.id,
        "credits": member_info.credits,
        "balance": str(member_info.balance),
        "has_qrcode": has_qrcode,
        "name": member_info.name,
        "mobile": member_info.mobile,
        "m_times": m_times,
        "total_times": p_times + m_times,
        "pkgs": pkg_data_list
    }
    return jsonify(resp)

@route_api.route("/member/balance")
def memberBalance():
    """
    用户信息
    :return: id,昵称,头像,积分,二维码
    """
    resp = {'code': 200, 'msg': '', 'data': {}}

    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "没有相关用户信息"
        return jsonify(resp)

    resp['data'] = {
        "balance": str(member_info.balance)
    }
    return jsonify(resp)

@route_api.route("/member/has-qrcode")
def memberHasQrcode():
    """
    用户信息
    :return: id,昵称,头像,积分,二维码
    """
    resp = {'code': 200, 'msg': '', 'data': {}}

    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "没有相关用户信息"
        return jsonify(resp)

    resp['data'] = {
        "has_qr_code": member_info.has_qr_code
    }
    return jsonify(resp)

# TODO：不需要分页么？
@route_api.route("/member/get-new-recommend")
def getNewRecommend():
    """
    未读答谢和所有的匹配推荐
    :return: 总数, 3类推荐的物品列表
    """
    resp = {'code': 200, 'msg': '', 'data': {}}
    # 检查登陆
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "没有相关用户信息"
        return jsonify(resp)

    # 获取所有会员的recommend_id列表中的物品,按状态：待,预,已分类
    recommend_status_2 = recommend_status_3 = recommend_status_1 = 0
    recommend_new = thanks_new = 0
    if member_info.recommend_id:
        recommend_dict = MemberService.getRecommendDict(member_info.recommend_id, True)
        query = Good.query.filter(Good.id.in_(recommend_dict.keys()))
        recommend_status_1 = len(query.filter_by(status=1).all())
        recommend_status_2 = len(query.filter_by(status=2).all())
        recommend_status_3 = len(query.filter_by(status=3).all())
        recommend_new = len(recommend_dict) if len(recommend_dict) <= 99 else 99

    # 获取会员未读的答谢记录
    thanks_query = Thank.query.filter_by(target_member_id=member_info.id)
    thanks_list = thanks_query.filter_by(status=0).all()
    if thanks_list:
        thanks_new = len(thanks_list) if len(thanks_list) <= 99 else 99

    # 总数量,最多显示99+
    total_new = recommend_new + thanks_new
    total_new = total_new if total_new <= 99 else 99

    resp['data'] = {
        'total_new': total_new,
        'recommend_new': recommend_new,
        'thanks_new': thanks_new,
        'recommend': {
            'wait': recommend_status_1 if recommend_status_1 <= 99 else 99,
            'doing': recommend_status_2 if recommend_status_2 <= 99 else 99,
            'done': recommend_status_3 if recommend_status_3 <= 99 else 99,
        }
    }
    return jsonify(resp)

@route_api.route("/member/block-search", methods=['GET', 'POST'])
def blockMemberSearch():
    """
    :return: 状态为status的用户信息列表
    """

    resp = {'code': 200, 'msg': 'search record successfully(search)', 'data': {}}
    req = request.values

    # 检查登陆
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "用户信息异常"
        return jsonify(resp)

    # 按status筛选用户
    status = int(req['status']) if 'status' in req else "nonono"
    query = Member.query.filter_by(status=status)

    # 分页, 排序
    p = int(req['p']) if ('p' in req and req['p']) else 1
    if p < 1:
        p = 1
    page_size = 10
    offset = (p - 1) * page_size
    member_list = query.order_by(Member.updated_time.desc()).offset(offset).limit(10).all()

    # models -> objects
    # 用户信息列表
    data_member_list = []
    if member_list:
        for item in member_list:
            tmp_data = {
                "id": item.id,
                "created_time": str(item.created_time),
                "updated_time": str(item.updated_time),
                "status": item.status,
                # 用户信息
                "member_id": item.id,
                "auther_name": item.nickname + "#####@id:" + str(item.id),
                "avatar": item.avatar,
            }
            # 如果已经被处理过
            data_member_list.append(tmp_data)

    resp['data']['list'] = data_member_list
    resp['data']['has_more'] = 0 if len(data_member_list) < page_size else 1
    return jsonify(resp)

# 恢复会员
@route_api.route('/member/restore-member')
def restoreMember():
    """
    恢复用户
    :return: 成功
    """
    resp = {'code': 200, 'msg': 'operate successfully(get info)', 'data': {}}
    req = request.values

    # 将用户的status改为1
    select_member_id = int(req['id']) if ('id' in req and req['id']) else 0
    select_member_info = Member.query.filter_by(id=select_member_id).first()
    select_member_info.status = 1
    select_member_info.updated_time = getCurrentDate()
    db.session.add(select_member_info)

    # 将用户发布的物品status从8改为1
    goods_list = Good.query.filter(Good.member_id == select_member_id, Good.status == 8).all()
    for item in goods_list:
        item.status = 1
        item.updated_time = getCurrentDate()
        db.session.add(item)

    db.session.commit()
    return jsonify(resp)

@route_api.route('/member/share')
def memberShare():
    """
    分享
    :return: 成功
    """
    resp = {'code': 200, 'msg': 'operate successfully(get info)', 'data': {}}
    # 检查登陆
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "用户信息异常"
        return jsonify(resp)

    # 会员credits加5
    member_info.credits = member_info.credits + 5
    member_info.updated_time = getCurrentDate()
    db.session.add(member_info)
    db.session.commit()

    return jsonify(resp)

@route_api.route("/member/phone/decrypt", methods=['POST', 'GET'])
def decryptPhone():
    resp = {'code': 200, 'msg': '已获取手机号', 'data': {}}
    from common.libs.mall.WechatService import WXBizDataCrypt
    req = request.get_json()
    app.logger.info(req)
    # 获取加密手机号
    encrypted_data = req['encrypted_data'] if 'encrypted_data' in req and req['encrypted_data'] else ''
    if not encrypted_data:
        resp['code'] = -1
        resp['msg'] = "手机号获取失败"
        return jsonify(resp)
    # 获取加密向量
    iv = req['iv'] if 'iv' in req and req['iv'] else ''
    if not iv:
        resp['code'] = -1
        resp['msg'] = "手机号获取失败"
        return jsonify(resp)
    # 获取session_key
    session_key = req['session_key'] if 'session_key' in req and req['session_key'] else ''
    if not session_key:
        resp['code'] = -1
        resp['msg'] = "手机号获取失败"
        return jsonify(resp)
    appId = app.config['OPENCS_APP']['appid']
    # 解密手机号
    pc = WXBizDataCrypt(appId, session_key)
    try:
        mobile_obj = pc.decrypt(encrypted_data, iv)
    except Exception as e:
        app.logger.warn(e)
        resp['code'] = -1
        resp['msg'] = "手机号获取失败，请确保从后台完全关闭小程序后重试"
        return jsonify(resp)
    mobile = mobile_obj['phoneNumber']
    app.logger.info("手机号是：{}".format(mobile))
    resp['data'] = {
        'mobile': mobile
    }
    return jsonify(resp)

@route_api.route('/member/login/wx', methods=['GET', 'POST'])
def getUserInfo():
    resp = {'code': 200, 'msg': '已获取手机号', 'data': {}}
    req = request.get_json()
    code = req['code'] if 'code' in req and req['code'] else ''
    if not code:
        resp['code'] = -1
        resp['msg'] = "手机号获取失败"
        return jsonify(resp)
    openid, session_key = MemberService.getWeChatOpenId(code, get_session_key=True)
    if openid is None:
        resp['code'] = -1
        resp['msg'] = "手机号获取失败"
        return jsonify(resp)
    resp['data'] = {
        'openid': openid,
        'session_key': session_key
    }
    return jsonify(resp)

@route_api.route('/member/set/name', methods=['GET', 'POST'])
def setName():
    resp = {'code': 200, 'msg': '修改成功', 'data': {}}
    req = request.values
    name = req['name'] if 'name' in req and req['name'] else ''
    member_info = g.member_info
    if not member_info:
        resp['code'] = -1
        resp['msg'] = "请先登录"
        return jsonify(resp)

    member_info.name = name
    member_info.updated_time = getCurrentDate()
    db.session.add(member_info)
    db.session.commit()
    resp['data'] = {'name': member_info.name}
    return jsonify(resp)

@route_api.route('/member/exists', methods=['GET', 'POST'])
def member_exists():
    resp = {'code': 200, 'msg': '用户已注册', 'data': {'exists': True}}
    req = request.values
    openid = req['openid'] if 'openid' in req and req['openid'] else ''
    if not openid:
        resp['code'] = -1
        resp['msg'] = "登陆信息缺失"
        return jsonify(resp)
    member_info = Member.query.filter_by(openid=openid).first()
    if not member_info:
        resp['data'] = {'exists': False}
    return jsonify(resp)


#!/usr/bin/env python3
import math
from string import ascii_lowercase

def main():
  polymer = list(open('05_input.txt', 'r').read().strip())
  print('Answer part 1:', reacted_len(polymer))
  part_two(polymer)

def part_two(polymer):
  min_len = math.inf
  for c in ascii_lowercase:
    tmp_polymer = [unit for unit in polymer]
    tmp_polymer[:] = [unit for unit in tmp_polymer if unit != c and unit != c.upper()]
    min_len = min(min_len, reacted_len(tmp_polymer))
  print('Answer part 2:', min_len)

def reacted_len(polymer):
  stack = [polymer[0]]
  for unit in polymer[1:]:
    if len(stack) == 0:
      stack.append(unit)
      continue
    top = stack[-1]
    if same_but_different_case(top, unit):
      stack.pop()
    else:
      stack.append(unit)
  return len(stack)

def same_but_different_case(a, b):
  if a.lower() == b.lower():
    ascii_code = abs(ord(a) - ord(b))
    return ascii_code == 32
  return False

if __name__ == '__main__':
  main()


from django.urls import path, include
from rest_framework.routers import DefaultRouter

from shop import views

router = DefaultRouter()
router.register('products', views.ProductViewSet)
router.register('basket', views.BasketViewSet)

app_name = 'shop'

urlpatterns = [
    path('', include(router.urls)),
]


#create list of 5char string from a different list
def char_func(my_list):
    new_list=[]
    for i in my_list:
        if len(i)==5:
            new_list.append(i)
        else:
            continue
    return new_list

my_list=['abcde','bb','kkkjk','jjj','hjklo','hjkuytr']
print(char_func(my_list))


# By: Riasat Ullah
# This file tests the tokenizer file.

from utils import logging, tokenizer
import jwt
import unittest

class TestTokenizer(unittest.TestCase):

    def test_verify_token(self):
        logging.info('Testing tokenizer...')
        correct_username = 'testuser_one'
        correct_token = tokenizer.create_token(correct_username)

        logging.info('Test 1 - token verifies')
        self.assertEqual(tokenizer.verify_token(correct_token), correct_username)
        logging.info('Test 2 - token does not verify')
        with self.assertRaises(jwt.InvalidSignatureError):
            tokenizer.verify_token('hskdfsd.sdfas3.fsdf')


#!/usr/bin/env python

import numpy as np
from sympy import atan2, cos, latex, pi, pprint, simplify, sin, sqrt, symbols
from sympy.matrices import Matrix
import tf.transformations as tf

def rot_m(axis, q):
    if axis == 'x':
        R = Matrix([[1, 0, 0, 0],
                    [0, cos(q), -sin(q), 0],
                    [0, sin(q), cos(q), 0],
                    [0, 0, 0, 1]])
    elif axis == 'y':
        R = Matrix([[cos(q), 0, sin(q), 0],
                    [0, 1, 0, 0],
                    [-sin(q), 0, cos(q), 0],
                    [0, 0, 0, 1]])
    elif axis == 'z':
        R = Matrix([[cos(q), -sin(q), 0, 0],
                    [sin(q), cos(q), 0, 0],
                    [0, 0, 1, 0],
                    [0, 0, 0, 1]])
    else:
        # print 'Wrong axis: x,y,z'
        R = None
    return R

def trsl_m(x, y, z):
    T = Matrix([[1, 0, 0, x],
                [0, 1, 0, y],
                [0, 0, 1, z],
                [0, 0, 0, 1]])
    return T

def Tmatrix(alpha, a, d, q):
    T = rot_m('x', alpha) * trsl_m(a, 0, 0) * rot_m('z', q) * trsl_m(0, 0, d)
    T = simplify(T)
    return T

def invT(T):
    R = T[:3, :3]
    D = T[:3, 3]
    bottom_row = Matrix([[0, 0, 0, 1]])
    iR = R.T
    iD = iR * D
    iT = iR.row_join(iD)
    iT = iT.col_join(bottom_row)
    return iT

def getWC(px,py,pz,l,T):
    wc = Matrix([[px],[py],[pz]]) - (l * T[:3,:3])[:,2]
    return (wc[0], wc[1], wc[2])

def rpy_m(roll, pitch, yaw):
    return rot_m('z',yaw) * rot_m('y',pitch) * rot_m('x',roll)

if __name__ == '__main__':

    # Symbolics variables definition
    q1, q2, q3, q4, q5, q6, q7 = symbols('q1:8')
    d1, d2, d3, d4, d5, d6, d7 = symbols('d1:8')
    a0, a1, a2, a3, a4, a5, a6 = symbols('a0:7')
    alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols(
        'alpha0:7')
    # KUKA KR2140 DH parameters
    s = {alpha0: 0, a0: 0, d1: 0.75,
         alpha1: -pi / 2, a1: 0.35, d2: 0, q2: q2 - pi / 2,
         alpha2: 0, a2: 1.25, d3: 0,
         alpha3: -pi / 2, a3: -0.054, d4: 1.50,
         alpha4: pi / 2, a4: 0, d5: 0,
         alpha5: -pi / 2, a5: 0, d6: 0,
         alpha6: 0, a6: 0, d7: 0.303, q7: 0}

    # Homogeneous Transforms
    T0_1 = Tmatrix(alpha0, a0, d1, q1)
    T1_2 = Tmatrix(alpha1, a1, d2, q2)
    T2_3 = Tmatrix(alpha2, a2, d3, q3)
    T3_4 = Tmatrix(alpha3, a3, d4, q4)
    T4_5 = Tmatrix(alpha4, a4, d5, q5)
    T5_6 = Tmatrix(alpha5, a5, d6, q6)
    T6_EE = Tmatrix(alpha6, a6, d7, q7)
    # Subtitution
    T_n = [T0_1, T1_2, T2_3, T3_4, T4_5, T5_6, T6_EE]
    for each in range(len(T_n)):
        T_n[each] = T_n[each].subs(s)

    # Composition of Homogeneous Transforms
    T0_2 = simplify(T_n[0] * T_n[1])  # base to link2
    T0_3 = simplify(T0_2 * T_n[2])  # link2 to link3
    T0_4 = simplify(T0_3 * T_n[3])  # link3 to link4
    T0_5 = simplify(T0_4 * T_n[4])  # link4 to link5
    T0_6 = simplify(T0_5 * T_n[5])  # link5 to link6
    T0_EE = simplify(T0_6 * T_n[6])  # link5 to link6

    # Correction needed to account of correlation between URDF and DH convention
    Rcorr = simplify(rot_m('z', pi) * rot_m('y', -pi / 2))
    T0_G = simplify(T0_EE * Rcorr)

    # joint angles vector
    q_0 = {q1: 0, q2: 0, q3: 0, q4: 0, q5: 0, q6: 0}
    q_1 = {q1: 0, q2: 0, q3: -pi/2, q4: pi/2, q5: pi/3, q6: 0}
    q = {q1: -1.33, q2: 1.22, q3: -2.53, q4: -5.90, q5: -1.26, q6: -1.31}
    # Evaluation for comparing with output of tf_echo!
#    print("T0_1 = ", T_n[0].evalf(2,subs=q))
#    print("T0_2 = ", T0_2.evalf(2,subs=q))
#    print("T0_3 = ", T0_3.evalf(subs=q))
#    print("T0_4 = ", T0_4.evalf(subs=q))
#    print("T0_5 = ", T0_5.evalf(subs=q))
#    print("T0_6 = ", T0_6.evalf(subs=q))
    M =  np.array(T0_G.evalf(5,subs=q_0))
    print("T0_G = ", M)
    print(tf.euler_from_matrix(M))
    T0_G = T0_G.evalf(subs=q_0)
    Rrpy = rpy_m(0,0.379,0) * Rcorr
#    wc_x,wc_y,wc_z = getWC(2.153, 0.000, 1.947,Rrpy) # Home pos


import numpy as np
import torch
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import sklearn
from sklearn.datasets import load_digits
from tqdm import tqdm

def noise(X):
    pct_noise = 50    #10% noise
    print("Noise multiplier (%) is:", pct_noise)

    nX = X * (1 + pct_noise/100.*(np.random.random_sample((X[:,1].size,X[1,:].size)) - 0.5))
    plt.figure()
    plt.title('data w & w/o noise')
    plt.plot(np.transpose(X[1000,:]))
    plt.plot(np.transpose(nX[1000,:]))

    X = nX

    return X

def gauss_data_2():
    hu = np.linspace(1, 10, 200)
    #num_of_gauss = np.random.randint(1, 2)
    num_of_cases = 10000
    num_of_gauss = 10

    X = []
    Y = []
    for cases in range(num_of_cases):
        #Create num_of_cases different fake spectra, each made from a set of (mu, std, amp)
        I = 0.0; mu = 0.0; std = 0.0; amp = 0.0; mc = 0.0;
        mu = np.random.choice(np.linspace(6, 14, 20))
        #std = np.random.choice(np.linspace(0.1, 3.0, 20))
        std = 0.5
        #amp = np.random.choice(np.linspace(0.1, 1.0,20))
        amp = 0.1
        for gauss in range(num_of_gauss):
            mc = mc + 1
            mult = mc * 0.1
            #Add up num_of_gauss different Gaussians, where mu and std are scaled by mult, to make fake spectrum
            I = I + amp * (1.0 - hu/12.0) / (std*np.sqrt(2.*np.pi)) * np.exp(-(hu - mult*mu)**2./(2.*mult*std**2.))
        #Y.append([mu,std,amp])
        Y.append([mu])
        X.append(I)
    Y = np.array(Y)
    print(Y.shape)
    X = np.array(X)
    print(X.shape)

    X = noise(X)

    xtrain, xtest, ytrain, ytest = train_test_split(X, Y)

    print("ytrain shape is:", ytrain.shape)
    print("ytest shape is:", ytest.shape)

    plt.figure()
    plt.title('data')
    plt.plot(hu,np.transpose(xtrain[::50]))

    return hu, xtrain, ytrain, xtest, ytest, X, Y

def gauss_data_bay():
    hu = np.linspace(1, 10, 200)
    num_of_cases = 1000

    X = []
    Y = []
    for cases in range(num_of_cases):
        #Create num_of_cases different fake spectra, each made from a set of (mu, std, amp)
        I = 0.0; mu = 0.0; std = 0.0; amp = 0.0; mc = 0.0; mult = 1.0;
        #mu = np.random.choice(np.linspace(4, 8, 2))
        mu = 5.5
        std = np.random.choice(np.linspace(0.5, 2.0, 2))
        #std = 0.5
#        amp = np.random.choice(np.linspace(0.1, 1.0,20))
        amp = 0.5
        #Add up num_of_gauss different Gaussians, where mu and std are scaled by mult, to make fake spectrum
        I = amp * (1.0) / (std*np.sqrt(2.*np.pi)) * np.exp(-(hu - mu)**2./(2.* std**2.))
        Y.append([std])
        X.append(I)
    Y = np.array(Y)
    print(Y.shape)
#    print(Y)
    X = np.array(X)
    print(X.shape)
#    print(X)

    X = noise(X)

    xtrain, xtest, ytrain, ytest = train_test_split(X, Y)

    print("ytrain shape is:", ytrain.shape)
    print("ytest shape is:", ytest.shape)

    plt.figure()
    plt.title('data')
    plt.plot(hu,np.transpose(xtrain[::50]))

    return hu, xtrain, ytrain, xtest, ytest, X, Y


import pandas as pd
import numpy as np

def pd_interp1(xLabel,df,xnew):
    # Interpolate a panda dataframe based on a set of new value
    nRow,nCol = df.shape
    nRow = len(xnew)
    data = np.zeros((nRow,nCol))
    xref =df[xLabel].values.astype(float)
    for col,i in zip(df.columns.values,range(nCol)):
        yref = df[col].values
        if yref.dtype!=float:
            raise Exception('Wrong type for yref, consider using astype(float)')
        data[:,i] = np.interp(xnew, xref, yref)
    dfi = pd.DataFrame(data=data,columns = df.columns)
    return dfi

def create_dummy_dataframe(size):
    return pd.DataFrame(data={'col1': np.linspace(0,1,size), 'col2': np.random.normal(0,1,size)})


from django.test import TestCase
from django.contrib.auth.models import User
from django.utils.timezone import datetime

from birthday_reminder_api.models import Person

class TestPerson(TestCase):
    def get_user(self, username):
        return User.objects.all().get_or_create(username=username)[0]

    def create_person(self, birthday, name="random_person", reminder=1, username="test"):
        user = self.get_user(username)
        person = Person(user=user, name=name, birthday=birthday, reminder=reminder)
        person.save()
        return person

    def test_get_age(self):
        birthday = datetime(1990, month=12, day=1)
        person = self.create_person(birthday)
        now = datetime(2015, month=1, day=5)
        expected_age = 24
        actual_age = person.age(now=now)
        self.assertEqual(actual_age, expected_age)

    def test_num_days_to_birthday_on_birthday(self):
        birthday = datetime(1990, month=12, day=1)
        person = self.create_person(birthday)
        now = datetime(2015, month=12, day=1)
        expected = 0
        actual = person.num_days_to_birthday(now)
        self.assertEqual(actual, expected)

    def test_num_days_to_birthday_correct_year(self):
        birthday = datetime(1990, month=12, day=10)
        person = self.create_person(birthday)
        now = datetime(2015, month=12, day=1)
        expected = 9
        actual = person.num_days_to_birthday(now)
        self.assertEqual(actual, expected)

    def test_num_days_to_birthday_wrong_year(self):
        birthday = datetime(1990, month=12, day=10)
        person = self.create_person(birthday)
        now = datetime(2015, month=12, day=11)
        expected = (datetime(2016, month=12, day=10) - datetime(2015, month=12, day=11)).days
        actual = person.num_days_to_birthday(now)
        self.assertEqual(actual, expected)

    def test_num_days_to_birthday_on_birthday_now_with_time(self):
        birthday = datetime(1990, month=12, day=10)
        person = self.create_person(birthday)
        now = datetime(2015, month=12, day=10, hour=5, minute=3)
        expected = 0
        actual = person.num_days_to_birthday(now)
        self.assertEqual(actual, expected)


from django.utils.translation import ugettext

from rest_framework import serializers

from olympia import amo
from olympia.addons.models import Addon
from olympia.addons.serializers import AddonSerializer, VersionSerializer
from olympia.amo.templatetags.jinja_helpers import absolutify
from olympia.versions.models import Version

class DiscoveryVersionSerializer(VersionSerializer):
    class Meta:
        fields = ('compatibility', 'files',)
        model = Version

class DiscoveryAddonSerializer(AddonSerializer):
    current_version = DiscoveryVersionSerializer()

    class Meta:
        fields = ('id', 'current_version', 'guid', 'icon_url', 'name',
                  'slug', 'theme_data', 'type', 'url',)
        model = Addon

class DiscoverySerializer(serializers.Serializer):
    heading = serializers.CharField()
    description = serializers.CharField()
    addon = DiscoveryAddonSerializer()
    is_recommendation = serializers.BooleanField()

    def to_representation(self, instance):
        data = super(DiscoverySerializer, self).to_representation(instance)
        authors = u', '.join(
            author.name for author in instance.addon.listed_authors)
        addon_name = unicode(instance.addon_name or instance.addon.name)
        url = absolutify(instance.addon.get_url_path())

        if data['heading'] is None:
            data['heading'] = (
                u'{0} {1} {3}'.format(
                    addon_name, ugettext(u'by'), url, authors))
        else:
            # Note: target and rel attrs are added in addons-frontend.
            addon_link = u'{1} {2} {3}'.format(
                url, addon_name, ugettext(u'by'), authors)

            data['heading'] = data['heading'].replace(
                '{start_sub_heading}', '').replace(
                '{end_sub_heading}', '').replace(
                '{addon_name}', addon_link)

        if data['description'] is None:
            if (instance.addon.type == amo.ADDON_EXTENSION and
                    instance.addon.summary):
                data['description'] = (
                    u'
%s
' % instance.addon.summary)
            elif (instance.addon.type == amo.ADDON_PERSONA and
                    instance.addon.description):
                data['description'] = (
                    u'
%s
' %
                    instance.addon.description)
        return data


#!/usr/bin/env python3
import os
import re

from shutil import copyfile

# create an output directory
output_dir = "latin_texts"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

source_text_path = os.path.join("..", "LatinMarkovJS", "texts")

# get the list of files in the source directory
try:
    files = [
        filename
        for filename in os.listdir(source_text_path)
        if not filename.startswith(".")]
except FileNotFoundError:
    raise FileNotFoundError("Directory {} not found!".format(source_text_path))

# get the files currently contained in latin_texts
current_files = [
    filename
    for filename in os.listdir(output_dir)
    if not filename.startswith(".")]

# find out what files in the source directory are new
new_files = [filename for filename in files if filename not in current_files]

# copy the new texts over
print("Copying texts...")
if new_files:
    for filename in new_files:
        print(filename)
        copyfile(os.path.join(source_text_path, filename), os.path.join(output_dir, filename))
else:
    print("No new files!")

# read in game.html in order to update it with script tags for each of the new files added;
# each new script tag will have the class "training-text"
with open("game.html", "r") as gf:
    game_file = gf.read()

script_tags = "\n        ".join(
    ['<script class="training-text" src="latin_texts/{}"></script>'.format(filename)
     for filename in new_files]) + "\n        "
new_game_file = re.sub('(<script src="helper.js"></script>\n        )', "\\1{}".format(script_tags), game_file)

with open("game.html", "w") as gf:
    gf.write(new_game_file)


import fileinput
import tempfile
import sys
import subprocess
import structure_extract_relax
from pathlib import Path
from pyrosetta import *
from pyrosetta.toolbox import cleanATOM
from pyrosetta.rosetta.protocols.docking import *
import pyrosetta.rosetta.protocols.rigid as rigid_moves

def main(path, pdb, light_chain):

    abdf = structure_extract_relax.main(path, pdb, light_chain)

    init()
    outfile = Path(pdb).stem+'_rand.pdb'
    pose = pose_from_pdb(pdb)
    init_pose = pose.clone()
    setup_foldtree(pose, "LH_A", Vector1([1]))
    print(pose.fold_tree())
    jump_num = 1
    randomize1 = rigid_moves.RigidBodyRandomizeMover(pose, jump_num, rigid_moves.partner_downstream)
    randomize1.apply(pose)
    slide = DockingSlideIntoContact(jump_num)
    slide.apply(pose)
    # docking_pre_prot = DockingPrepackProtocol()
    # docking_pre_prot.apply(pose)
    # docking_pre_prot.apply(init_pose)
    pose.dump_pdb(outfile)
    init_pose.dump_pdb(Path(pdb).stem+'_init.H.pdb')

    readout = open(outfile)
    abfile = open(Path(outfile).stem+'_LH.pdb', "w")
    with tempfile.TemporaryFile(mode='w+t') as temp:
        temp.writelines(readout)
        temp.seek(0)
        p1 = subprocess.Popen(['pdb_selchain', '-L,H'], stdin=temp, stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['pdb_delelem','-H'], stdin=p1.stdout, stdout=abfile)
    abfile.close()
    temp.close()

    readout = open(outfile)
    ligfile = open(Path(outfile).stem+'_A.pdb', "w")
    with tempfile.TemporaryFile(mode='w+t') as temp:
        temp.writelines(readout)
        temp.seek(0)
        p1 = subprocess.Popen(['pdb_selchain', '-A'], stdin=temp, stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['pdb_delelem','-H'], stdin=p1.stdout, stdout=ligfile)
    ligfile.close()
    temp.close()
    readout.close()

    readout = open(Path(pdb).stem+'_init.H.pdb')
    initfile = open(Path(pdb).stem+'_init.pdb', "w")
    with tempfile.TemporaryFile(mode='w+t') as temp:
        temp.writelines(readout)
        temp.seek(0)
        p2 = subprocess.Popen(['pdb_delelem','-H'], stdin=temp, stdout=initfile)
    initfile.close()
    temp.close()

    return(abdf)

if __name__ == '__main__':
    main('/home/drewaight/hdd1/proQ3drewdock_big/4ydl/4ydl_1.pdb')


import tkinter
import tkinter.ttk as ttk
from . import validate, scanlock
from . import locale

class Popup(tkinter.Toplevel):
	"""Popup frame for scanning the RFID card."""
	def __init__(self, parent, root, callback):
		tkinter.Toplevel.__init__(self)
		self.title(locale.SCAN_TITLE)
		scanlock.scanlock(False)

		# widgets
		validator = (self.register(self.validate_id), '%P')
		self.id = tkinter.StringVar()
		self.id_entry = ttk.Entry(self, textvariable=self.id, validate='key', validatecommand=validator, justify='center')
		self.cancel_button = ttk.Button(self, text=locale.SCAN_CANCEL, command=self.cancel, takefocus=False)
		self.confirm_button = ttk.Button(self, text=locale.SCAN_CONFIRM, command=self.confirm, takefocus=False, state='disabled')

		# layout
		ttk.Label(self, text=locale.SCAN_PROMPT).grid(column=0, row=0, columnspan=2)

		self.id_entry.grid(column=0, row=1, columnspan=2, sticky='ew')

		self.cancel_button.grid(column=0, row=2)
		self.confirm_button.grid(column=1, row=2)

		for child in self.children.values():
			child.grid(padx=5, pady=5)

		self.grid_columnconfigure(0, weight=0)
		self.grid_columnconfigure(1, weight=1)
		self.grid_rowconfigure(0, weight=0)
		self.grid_rowconfigure(1, weight=0)
		self.grid_rowconfigure(2, weight=0)

		# position
		self.update_idletasks()
		x = root.winfo_rootx() + root.winfo_width() / 2 - self.winfo_width() / 2
		y = root.winfo_rooty() + root.winfo_height() / 2 - self.winfo_height() / 2
		self.geometry('+%d+%d' % (x, y))

		# callbacks
		self.callback = callback
		for child in self.children.values():
			child.bind("<Escape>", self.cancel)
			child.bind('<Return>', self.confirm)
			child.bind('<KP_Enter>', self.confirm)
		self.protocol("WM_DELETE_WINDOW", self.cancel)

		# focus
		self.grab_set()
		self.id_entry.focus_set()
		self.transient(root)

		print('Scanning card...')

	def validate_id(self, value):
		valid = validate.validate_int(value)
		if len(value) >= 8 and valid:
			self.confirm_button.configure(state='enabled')
		elif len(value) < 8:
			self.confirm_button.configure(state='disabled')
		return valid

	def cancel(self, event=None):
		self.grab_release()
		scanlock.scanlock(True)
		print('Scanning canelled.')
		self.destroy()

	def confirm(self, event=None):
		id = self.id.get()
		if len(id) < 8: return
		self.grab_release()
		scanlock.scanlock(True)
		print('Scanned ID %s' % id)
		self.callback(id)
		self.destroy()


#/usr/bin/python3

from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5 import QtWidgets

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtOpenGL import QGLFormat

from .util import log

import sys

class Canvas(QOpenGLWidget):

    def __init__(self, parent=None, requestedGLVersion=(2,1)):

        self.log = log

        self.debugMembers = False

        self.requestedVersion = requestedGLVersion
        self.log.debug("About to try to initialize parent (abstract) gl widget")
        super(Canvas, self).__init__(parent)
        self.log.debug("Parent (abstract) gl widget should now have been created")
        self.destroyed.connect(self._on_destroyed)

    def _on_destroyed(self, *args):
        self.log.debug("Canvas is about to be destroyed")
        self.makeCurrent()
        self.closeGL()
        self.doneCurrent()

    # Override if necessary
    def minimumSizeHint(self):
        self.log.trace("minimumSizeHint() is not overridden")
        return QSize(400, 400)

    # Override if necessary
    def sizeHint(self):
        self.log.trace("sizeHint() is not overridden")
        return QSize(500, 500)

    def dumpGLLogMessages(self, location = None):

        currentError = self.gl.glGetError()
        while currentError != self.gl.GL_NO_ERROR:
            msg = "UNKNOWN GL ERROR"
            if currentError == self.gl.GL_INVALID_OPERATION:
                msg = "GL_INVALID_OPERATION"
            if currentError == self.gl.GL_INVALID_ENUM:
                msg = "GL_INVALID_ENUM"
            if currentError == self.gl.GL_INVALID_VALUE:
                msg = "GL_INVALID_VALUE"
            if currentError == self.gl.GL_OUT_OF_MEMORY:
                msg = "GL_OUT_OF_MEMORY"
            if currentError == self.gl.GL_INVALID_FRAMEBUFFER_OPERATION:
                msg = "GL_INVALID_FRAMEBUFFER_OPERATION"

            if location is None:
                self.log.debug("\n" + msg + "!\n")
            else:
                self.log.debug("\n" + msg + " at location \"" + location + "\"!\n")

            currentError = self.gl.glGetError()

        if self.glLog is None:
            return

        messages = self.glLog.loggedMessages()
        if not messages is None and len(messages) > 0:
            if location is None:
                self.log.debug("\n--- LOG MESSAGES ---")
            else:
                self.log.debug("\n--- " + location + " ---")
            for message in messages:
                self.log.debug(message.message())

            print("---\n")

    # Do not override this, instead override setupGL
    def initializeGL(self):

        self.log.debug("About to start general GL initialization")

        self.glLog = QOpenGLDebugLogger(self);
        if not self.glLog.initialize():
            self.log.debug("Unable to initialize GL logging")
            self.glLog = None
        else:
            self.glLog.enableMessages(sources = QOpenGLDebugMessage.AnySource, types = QOpenGLDebugMessage.AnyType, severities = QOpenGLDebugMessage.AnySeverity)

        if self.debugMembers:

            print("\n--- MEMBERS IN CANVAS ---")
            for member in dir(self):
                print(member)
            print ("---\n")

            print("\n--- MEMBERS IN CONTEXT ---")
            ctx = self.context()
            for member in dir(ctx):
                print(member)
            print ("---\n")

        self.profile = QOpenGLVersionProfile()
        if self.requestedVersion[0] > 2:
            self.profile.setProfile(QSurfaceFormat.CoreProfile)
        self.profile.setVersion(self.requestedVersion[0],self.requestedVersion[1])

        ctx = None

        log.debug("About to request the GL context from the widget")
        try:
            ctx = self.context()
        except:
            log.debug("The GL layer crashed when trying to read the context object from the widget")

        if ctx is None:
            log.debug("Giving up as we don't have a valid OpenGL context.")
            sys.exit(1)

        self.gl = None
        log.debug("About to request QOpenGLFunctions for OpenGL version " + str(self.requestedVersion))

        try:
            self.gl = ctx.versionFunctions(self.profile)
        except:
            log.debug("A stack trace was thrown when requesting a QOpenGLFunctions object from the GL context. The most likely cause is that we asked for a higher GL version than was available, but it is also possible the GL context as such is faulty.")

        if self.gl is None:
            log.debug("Giving up as we could not get access to a QOpenGLFunctions object for the selected version. We'll do a sys.exit here, in order to avoid cascading error messages, so it is expected that the application closes.")
            sys.exit(1)
            return

        self.gl.initializeOpenGLFunctions()

        # Enable GL capabilities we need
        self.gl.glEnable(self.gl.GL_DEBUG_OUTPUT_SYNCHRONOUS)
        self.gl.glEnable(self.gl.GL_DEPTH_TEST)
        self.gl.glEnable(self.gl.GL_VERTEX_PROGRAM_POINT_SIZE)

        self.log.debug("\nGeneral GL information")
        self.log.debug("--------------------------------")
        self.log.debug("Version profile object",self.profile)
        self.log.debug("GL API compatibility wrapper",str(self.gl) + "  <--  look at instance name to figure out what GL API we work with")

        self.dumpGLLogMessages("initializeGL()")

        glVer = self.gl.glGetString(self.gl.GL_VERSION)
        glLangVer = self.gl.glGetString(self.gl.GL_SHADING_LANGUAGE_VERSION)
        glVendor = self.gl.glGetString(self.gl.GL_VENDOR)
        glRenderer = self.gl.glGetString(self.gl.GL_RENDERER)

        self.log.debug("GL Version used by backend", glVer)
        self.log.debug("Max GLSL version available",glLangVer)
        self.log.debug("GL vendor", glVendor)
        self.log.debug("GL renderer (gfx card)", glRenderer)

        self.log.debug("--------------------------------\n")

        self.setupGL()

    # Override this
    def setupGL(self):
        self.log.trace("setupGL() is not overridden")

    # Override this
    def paintGL(self):
        self.log.trace("paintGL() is not overridden")

    # Override this
    def resizeGL(self, width, height):
        self.log.trace("resizeGL() is not overridden")

    # Override this
    def closeGL(self):
        self.log.trace("resizeGL() is not overridden")


import pytest
from mock import Mock, MagicMock

@pytest.fixture
def isakmpd():
    from ipsec.isakmpd import ISAKMPD
    return ISAKMPD()

def test_remsec(isakmpd, monkeypatch):
    import os
    import ipsec.isakmpd
    exists = Mock()
    monkeypatch.setattr(os.path, 'exists', exists)
    mock_open = MagicMock()
    monkeypatch.setattr(ipsec.isakmpd, 'open', mock_open, raising=False)
    fobj = MagicMock(spec=file)
    mock_open().__enter__.return_value = fobj

    # test that nothing happens when the fifo isn't there
    exists.return_value = False
    assert isakmpd.remove_section("ok") == None
    assert fobj.write.called == False

    # now the fifo is there
    exists.return_value = True
    assert isakmpd.remove_section("ok") == None
    fobj.write.assert_called_with("C rms [ok]\n")

def test_get_pid(isakmpd, monkeypatch):
    import os
    import ipsec.isakmpd
    exists = Mock()
    monkeypatch.setattr(os.path, 'exists', exists)
    mock_open = MagicMock()
    monkeypatch.setattr(ipsec.isakmpd, 'open', mock_open, raising=False)
    fobj = MagicMock(spec=file)
    mock_open().__enter__.return_value = fobj

    # no pidfile = no pid
    exists.return_value = False
    assert isakmpd.get_pid() == None

    # pidfile but bad data
    exists.return_value = True
    fobj.read.return_value = "oh god how did I get here"
    assert isakmpd.get_pid() == None

    # pidfile and actual pid
    fobj.read.return_value = "42"
    assert isakmpd.get_pid() == 42

def test_get_report(isakmpd, monkeypatch):
    import os
    import ipsec.isakmpd
    import time
    sleep = Mock()
    monkeypatch.setattr(time, 'sleep', sleep)
    exists = Mock()
    monkeypatch.setattr(os.path, 'exists', exists)
    kill = Mock()
    monkeypatch.setattr(os, 'kill', kill)
    get_pid = Mock()
    monkeypatch.setattr(isakmpd, 'get_pid', get_pid)
    mock_open = MagicMock()
    monkeypatch.setattr(ipsec.isakmpd, 'open', mock_open, raising=False)
    fobj = MagicMock(spec=file)
    mock_open().__enter__.return_value = fobj

    # okay, test that with no pid, we never get to os.kill
    get_pid.return_value = None
    isakmpd.get_report()
    assert kill.called == False

    # with pid but no repfile, we never try to open it
    get_pid.return_value = 42
    exists.return_value = False
    isakmpd.get_report()
    assert fobj.called == False

    # pid and repfile returns a "proper" report
    exists.return_value = True
    lines = [
                'it little profits that an idle king',
                'by this still hearth, among these barren craigs',
                'matched with an aged wife I mete and dole',
                'unequal laws unto a savage race',
                'that hoard and sleep and feed, and know not me',
                'choo choo dumping running configuration',
                '123456.098765 Report> a\n',
                '123456.098765 Report> b\n'
            ]
    fobj.readlines.return_value = lines
    assert isakmpd.get_report() == ['a', 'b']

def test_parse_report(isakmpd):
    conf = [
            '[conf1]',
            ' this = that',
            'up = down',
            '', '',
            '[conf2]',
            'top =    bottom   ',
            '[conf1]',
            'strange = charm'
        ]
    ans = {
            'conf1': {'this': 'that', 'up': 'down', 'strange': 'charm'},
            'conf2': {'top': 'bottom'}
          }
    assert isakmpd.parse_report(conf) == ans

def test_capture(isakmpd):
    send = Mock()
    isakmpd.send = send
    assert isakmpd.capture("/bad/path") == None
    assert send.called == False
    isakmpd.capture("/var/run/isakmpd.conf")
    assert send.called_with("p on=/var/run/isakmpd.conf")
    isakmpd.capture()
    assert send.called_with("p off")


import os
import re

from citeproc import CitationStylesStyle, CitationStylesBibliography
from citeproc import Citation, CitationItem
from citeproc import formatter
from citeproc.source.json import CiteProcJSON

from website.preprints.model import PreprintService
from website.settings import CITATION_STYLES_PATH, BASE_PATH, CUSTOM_CITATIONS

def clean_up_common_errors(cit):
    cit = re.sub(r"\.+", '.', cit)
    cit = re.sub(r" +", ' ', cit)
    return cit

def display_absolute_url(node):
    url = node.absolute_url
    if url is not None:
        return re.sub(r'https?:', '', url).strip('/')

def preprint_csl(preprint, node):
    csl = node.csl

    csl['id'] = preprint._id
    csl['publisher'] = preprint.provider.name
    csl['URL'] = display_absolute_url(preprint)

    if csl.get('DOI'):
        csl.pop('DOI')

    doi = preprint.article_doi
    if doi:
        csl['DOI'] = doi

    return csl

def render_citation(node, style='apa'):
    """Given a node, return a citation"""
    csl = None
    if isinstance(node, PreprintService):
        csl = preprint_csl(node, node.node)
        data = [csl, ]
    else:
        data = [node.csl, ]

    bib_source = CiteProcJSON(data)

    custom = CUSTOM_CITATIONS.get(style, False)
    path = os.path.join(BASE_PATH, 'static', custom) if custom else os.path.join(CITATION_STYLES_PATH, style)
    bib_style = CitationStylesStyle(path, validate=False)

    bibliography = CitationStylesBibliography(bib_style, bib_source, formatter.plain)

    citation = Citation([CitationItem(node._id)])

    bibliography.register(citation)

    bib = bibliography.bibliography()
    cit = unicode(bib[0] if len(bib) else '')

    title = csl['title'] if csl else node.csl['title']
    if cit.count(title) == 1:
        i = cit.index(title)
        prefix = clean_up_common_errors(cit[0:i])
        suffix = clean_up_common_errors(cit[i + len(title):])
        cit = prefix + title + suffix
    elif cit.count(title) == 0:
        cit = clean_up_common_errors(cit)

    return cit


import cv2
import numpy as np

img= np.zeros((512,512,3),np.uint8)                                            #creating a black image

#img [:]=255,0,0                                                               #changing all the pixels to blue

#cv2.line(img,(0,0),(300,300),(0,255,0),3)                                     #drawing a line from (0,0) to (300,300) in green color and thickness=3
cv2.line(img,(0,0),(img.shape[1], img.shape[0]),(0,255,0),3)                   #diagonal line across the image
cv2.rectangle(img,(128,128),(384,384),(0,0,255),cv2.FILLED)                    #Rectange drawing from (128,128) to (384,384) and filled it with red color
cv2.circle(img,(256,256),70,(255,255,0),cv2.FILLED)                            #Circle as (256,256) as centre and radius=50 and filled
cv2.putText(img," OpenCV ",(180,260),cv2.FONT_HERSHEY_DUPLEX,1,(0,255,255),2)  #add text to the image at position (180,260)

cv2.imshow("Output",img)
cv2.waitKey(0)


#!

__author__ = "E. A. Ramos"
__email__ = "ear@ku.edu"

"""
            Class Necessary for Prefix Data Structure
"""
###########################################################
## Creating Data Struct: Word Node
###########################################################

class WordNode:
    def __init__(self, name, freq):
        self.name = name #String containing name
        self.freq = freq #Frequency of Word (Relative to Last Root)
        self.next = {} #Dictionary of the next available words and their frequencies
        self.nextFive = [] #Ordered tuple of the top 5 next words

        #Flagging the Period
        if self.name == "FULLSTOP":
            self.theend = 1
        else:
            self.theend = 0


import pyecore.ecore as Ecore
from .library import getEClassifier, eClassifiers
from .library import Employee, Library, Writer, Book, BookCategory
from . import library

__all__ = ['Employee', 'Library', 'Writer', 'Book', 'BookCategory']

name = 'library'
nsURI = 'http://emf.wikipedia.org/2011/Library'
nsPrefix = 'lib'

eClass = Ecore.EPackage(name=name, nsURI=nsURI, nsPrefix=nsPrefix)

eSubpackages = []
eSuperPackage = None

# Non opposite EReferences
Library.employees.eType = Employee
Library.writers.eType = Writer
Library.books.eType = Book

# opposite EReferences
Writer.books.eType = Book
Book.authors.eType = Writer
Book.authors.eOpposite = Writer.books

# Manage all other EClassifiers (EEnum, EDatatypes...)
otherClassifiers = [BookCategory]
for classif in otherClassifiers:
    eClassifiers[classif.name] = classif
    classif._container = library

for classif in eClassifiers.values():
    eClass.eClassifiers.append(classif.eClass)

for subpack in eSubpackages:
    eClass.eSubpackages.append(subpack.eClass)


# http://www.cnblogs.com/cv-pr/p/4625122.html

from math import sin, cos, pi, sqrt
import numpy as np
from numpy.linalg import eig, inv
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.patches import Ellipse

import time
from termcolor import colored

def ellipse(t, a, b):
    return a*cos(t), b*sin(t)

def product_ellipse_test_data(a, b, data_count):
    points = [ellipse(t, a, b) for t in np.linspace(0, 2*pi, data_count)]
    x, y = [np.array(v) for v in list(zip(*points))]
    # print(x[1],x[2], y[1], y[2], '#'*10, type(x), type(y))
    noise = np.random.rand(data_count)
    x += noise
    y += noise
    # print('noise->', noise)
    return x, y

def fit_ellipse(x, y):
    x = x[:, np.newaxis]
    y = y[:, np.newaxis]
    # build design matrix
    D =  np.column_stack((x**2, x*y, y**2, x, y, np.ones_like(x)))
    # build scatter matrix
    S = np.dot(D.T, D)
    # build 6x6 constraint matrix
    C = np.zeros([6,6])
    C[0, 2] = 2
    C[2, 0] = 2
    C[1, 1] = -1
    # solve eigensystem
    E, V = eig(np.dot(inv(S), C))
    # find the positive eigenvalue
    n = np.argmax(np.abs(E))

    return V[:, n]

if __name__ == '__main__':
    x, y = product_ellipse_test_data(8, 4, 8)

    # print(x[1],x[2], y[1], y[2],'#'*20)
    tic = time.clock()
    A, B, C, D, E, F = fit_ellipse(x, y)
    K = D**2/(4*A) + E**2/(4*C) - F
    a = sqrt(K/A)
    b = sqrt(K/C)
    print('a:',a, 'b:', b)

    toc = time.clock()
    print(colored('time =>', 'red'), toc - tic, colored('seconds', 'red'))
    # fig = plt.figure()
    # plt.scatter(x, y)
    # plt.show()
    fig = plt.figure()
    # plt.scatter(x, y)
    # plt.show()
    ax = plt.subplot(111, aspect='equal')

    ell = Ellipse(xy=(0,0),
                  width=a*2, height=b*2,
                  edgecolor='r', fc='None', lw=2
                  )
    ell.set_facecolor('none')
    ax.add_artist(ell)

    plt.scatter(x, y)
    plt.show()


"""
# handleget sourcecode -- please see handleget/readme.md
## src/load.py
This file's is a container for the FileHandler object -- which manages all
transactions between handleget and the users files.

To help manage multi-OS setups paths should be loaded safetly using pathlib and
should be thoroughly errorchecked.

Note that all file outputs should be stored here as general python. That means
properly loading and handling any JSON.
"""
import pathlib
import re
import json
import click
import yaml

def get_rootdir():
    # since it's a file path we need to get the second parent
    rootdir = pathlib.Path(__file__).parents[1]
    return rootdir

def load_config(path):
    """
    Load handleget config yml file

    Handled outside of the FileHandler object because any argument can be
    overwritten by this config -- this means it must be loaded before any other
    object has been initalized.
    """
    # Default Configuration, in case config.yml can't be opened or is corrupt
    default_config = """
    override_flags: No
    verbose: Yes
    strip: Yes
    char_pattern: r"([^a-zA-Z0-9_]*)"
    """
    if path == '':
        conf_path = pathlib.Path(str(get_rootdir()), 'data', 'config.yml')
    else:
        conf_path = pathlib.Path(path)

    if conf_path.is_file() == False:
        click.echo('config invalid, using defaults')
        yaml_string = default_config
    else:
        yaml_string = ""
        with conf_path.open() as f:
            yaml_string = f.read()

    config = yaml.load(yaml_string)
    return config

class FileHandler(object):
    """
    This class manages all transactions between handleget and files.
    """
    def __init__(self, error_handler, verbose=False, rootdir=None):
        """
        Initiate the FileHandler object.

        FileHandler(error_handler, strip_illegial_chars, illegial_characters_pattern)

        Arguments and expected types:
        - error_handler: an ErrorHandler class as defiend in src/error.py
        """
        self.error_handler = error_handler
        self.verbose = verbose
        self.rootdir = get_rootdir()

    def _unpack_services(self, services):
        """
        Services are currently passed into the program as a single string,
        with each service split by a comma.
        """
        return services.split(',')

    def load_services(self, services):
        services_wanted = self._unpack_services(services)
        service_path = pathlib.Path(self.rootdir, 'data', 'services')
        services = []
        for child in service_path.iterdir():
            with child.open() as f:
                try:
                    tmp = yaml.load(f.read())
                    if tmp['name'] in services_wanted:
                        services.append(tmp)
                    elif tmp['shortname'] in services_wanted:
                        services.append(tmp)
                except:
                    self.error_handler.catch_invalid_service('', child.name)
        return services