import torch
import torchvision
from operation import apply_augment
from torch.utils.data import SubsetRandomSampler, Sampler, Subset, ConcatDataset
from sklearn.model_selection import StratifiedShuffleSplit
from primitives import sub_policies
import torch.nn.functional as F
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from torchvision import transforms
from PIL import Image
from imagenet import ImageNet
from operation import Lighting
import os
import numpy as np

class CutoutDefault(object):
    """
    Reference : https://github.com/quark0/darts/blob/master/cnn/utils.py
    """
    def __init__(self, length):
        self.length = length

    def __call__(self, img):
        h, w = img.size(1), img.size(2)
        mask = np.ones((h, w), np.float32)
        y = np.random.randint(h)
        x = np.random.randint(w)

        y1 = np.clip(y - self.length // 2, 0, h)
        y2 = np.clip(y + self.length // 2, 0, h)
        x1 = np.clip(x - self.length // 2, 0, w)
        x2 = np.clip(x + self.length // 2, 0, w)

        mask[y1: y2, x1: x2] = 0.
        mask = torch.from_numpy(mask)
        mask = mask.expand_as(img)
        img *= mask
        return img

class SubsetSampler(Sampler):
    r"""Samples elements from a given list of indices, without replacement.

    Arguments:
        indices (sequence): a sequence of indices
    """

    def __init__(self, indices):
        self.indices = indices

    def __iter__(self):
        return (i for i in self.indices)

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

class AugmentDataset(torch.utils.data.Dataset):
    def __init__(self, dataset, pre_transforms, after_transforms, valid_transforms, ops_names, search, magnitudes):
        super(AugmentDataset, self).__init__()
        self.dataset = dataset
        self.pre_transforms = pre_transforms
        self.after_transforms = after_transforms
        self.valid_transforms = valid_transforms
        self.ops_names = ops_names
        self.search = search
        self.magnitudes = magnitudes

    def __getitem__(self, index):
        if self.search:
            # start_time = time.time()
            img, target = self.dataset.__getitem__(index)
            img = self.pre_transforms(img)
            magnitude = self.magnitudes.clamp(0, 1)[self.weights_index.item()]
            sub_policy = self.ops_names[self.weights_index.item()]
            probability_index = self.probabilities_index[self.weights_index.item()]
            image = img
            for i, ops_name in enumerate(sub_policy):
                if probability_index[i].item() == 1:
                    image = apply_augment(image, ops_name, magnitude[i])
            image = self.after_transforms(image)
            # print(self.magnitudes)
            # print(self.weights_index)
            # end_time = time.time()
            # print("%f" % (end_time - start_time))
            return image, target
        else:
            img, target = self.dataset.__getitem__(index)
            if self.valid_transforms is not None:
                img = self.valid_transforms(img)
            return img, target

    def __len__(self):
        return self.dataset.__len__()

_IMAGENET_PCA = {
    'eigval': [0.2175, 0.0188, 0.0045],
    'eigvec': [
        [-0.5675,  0.7192,  0.4009],
        [-0.5808, -0.0045, -0.8140],
        [-0.5836, -0.6948,  0.4203],
    ]
}
_CIFAR_MEAN, _CIFAR_STD = (0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)

def num_class(dataset):
    return {
        'cifar10': 10,
        'reduced_cifar10': 10,
        'cifar10.1': 10,
        'cifar100': 100,
        'reduced_cifar100': 100,
        'svhn': 10,
        'reduced_svhn': 10,
        'imagenet': 1000,
        'reduced_imagenet': 120,
    }[dataset]

def get_dataloaders(dataset, batch, num_workers, dataroot, ops_names, magnitudes, cutout, cutout_length, split=0.5, split_idx=0, target_lb=-1):
    if 'cifar' in dataset or 'svhn' in dataset:
        transform_train_pre = transforms.Compose([
            transforms.RandomCrop(32, padding=4),
            transforms.RandomHorizontalFlip(),
        ])
        transform_train_after = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize(_CIFAR_MEAN, _CIFAR_STD),
        ])
        transform_test = transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize(_CIFAR_MEAN, _CIFAR_STD),
        ])
    elif 'imagenet' in dataset:
        transform_train_pre = transforms.Compose([
            transforms.RandomResizedCrop(224, scale=(0.08, 1.0), interpolation=Image.BICUBIC),
            transforms.RandomHorizontalFlip(),
            transforms.ColorJitter(
                brightness=0.4,
                contrast=0.4,
                saturation=0.4,
            ),
        ])
        transform_train_after = transforms.Compose([
            transforms.ToTensor(),
            Lighting(0.1, _IMAGENET_PCA['eigval'], _IMAGENET_PCA['eigvec']),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])
        transform_test = transforms.Compose([
            transforms.Resize(256, interpolation=Image.BICUBIC),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])
    else:
        raise ValueError('dataset=%s' % dataset)

    if cutout and cutout_length != 0:
        transform_train_after.transforms.append(CutoutDefault(cutout_length))

    if dataset == 'cifar10':
        total_trainset = torchvision.datasets.CIFAR10(root=dataroot, train=True, download=True, transform=None)
        # testset = torchvision.datasets.CIFAR10(root=dataroot, train=False, download=True, transform=None)
    elif dataset == 'reduced_cifar10':
        total_trainset = torchvision.datasets.CIFAR10(root=dataroot, train=True, download=True, transform=None)
        sss = StratifiedShuffleSplit(n_splits=1, test_size=46000, random_state=0)   # 4000 trainset
        sss = sss.split(list(range(len(total_trainset))), total_trainset.targets)
        train_idx, valid_idx = next(sss)
        targets = [total_trainset.targets[idx] for idx in train_idx]
        total_trainset = Subset(total_trainset, train_idx)
        total_trainset.targets = targets

        # testset = torchvision.datasets.CIFAR10(root=dataroot, train=False, download=True, transform=None)
    elif dataset == 'cifar100':
        total_trainset = torchvision.datasets.CIFAR100(root=dataroot, train=True, download=True, transform=None)
        # testset = torchvision.datasets.CIFAR100(root=dataroot, train=False, download=True, transform=transform_test)
    elif dataset == 'reduced_cifar100':
        total_trainset = torchvision.datasets.CIFAR100(root=dataroot, train=True, download=True, transform=None)
        sss = StratifiedShuffleSplit(n_splits=1, test_size=46000, random_state=0)   # 4000 trainset
        sss = sss.split(list(range(len(total_trainset))), total_trainset.targets)
        train_idx, valid_idx = next(sss)
        targets = [total_trainset.targets[idx] for idx in train_idx]
        total_trainset = Subset(total_trainset, train_idx)
        total_trainset.targets = targets

        # testset = torchvision.datasets.CIFAR10(root=dataroot, train=False, download=True, transform=None)
    elif dataset == 'svhn':
        trainset = torchvision.datasets.SVHN(root=dataroot, split='train', download=True, transform=None)
        extraset = torchvision.datasets.SVHN(root=dataroot, split='extra', download=True, transform=None)
        total_trainset = ConcatDataset([trainset, extraset])
        # testset = torchvision.datasets.SVHN(root=dataroot, split='test', download=True, transform=transform_test)
    elif dataset == 'reduced_svhn':
        total_trainset = torchvision.datasets.SVHN(root=dataroot, split='train', download=True, transform=None)
        sss = StratifiedShuffleSplit(n_splits=1, test_size=73257-1000, random_state=0)  # 1000 trainset
        # sss = sss.split(list(range(len(total_trainset))), total_trainset.targets)
        sss = sss.split(list(range(len(total_trainset))), total_trainset.labels)
        train_idx, valid_idx = next(sss)
        # targets = [total_trainset.targets[idx] for idx in train_idx]
        targets = [total_trainset.labels[idx] for idx in train_idx]
        total_trainset = Subset(total_trainset, train_idx)
        # total_trainset.targets = targets
        total_trainset.labels = targets
        total_trainset.targets = targets

        # testset = torchvision.datasets.SVHN(root=dataroot, split='test', download=True, transform=transform_test)
    elif dataset == 'imagenet':
        total_trainset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'), transform=None)
        # testset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'), split='val', transform=transform_test)

        # compatibility
        total_trainset.targets = [lb for _, lb in total_trainset.samples]
    elif dataset == 'reduced_imagenet':
        # randomly chosen indices
        idx120 = [904, 385, 759, 884, 784, 844, 132, 214, 990, 786, 979, 582, 104, 288, 697, 480, 66, 943, 308, 282, 118, 926, 882, 478, 133, 884, 570, 964, 825, 656, 661, 289, 385, 448, 705, 609, 955, 5, 703, 713, 695, 811, 958, 147, 6, 3, 59, 354, 315, 514, 741, 525, 685, 673, 657, 267, 575, 501, 30, 455, 905, 860, 355, 911, 24, 708, 346, 195, 660, 528, 330, 511, 439, 150, 988, 940, 236, 803, 741, 295, 111, 520, 856, 248, 203, 147, 625, 589, 708, 201, 712, 630, 630, 367, 273, 931, 960, 274, 112, 239, 463, 355, 955, 525, 404, 59, 981, 725, 90, 782, 604, 323, 418, 35, 95, 97, 193, 690, 869, 172]
        total_trainset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'), transform=None)
        # testset = ImageNet(root=os.path.join(dataroot, 'imagenet-pytorch'), split='val', transform=transform_test)

        # compatibility
        total_trainset.targets = [lb for _, lb in total_trainset.samples]

        # sss = StratifiedShuffleSplit(n_splits=1, test_size=len(total_trainset) - 6000, random_state=0)  # 4000 trainset
        # sss = StratifiedShuffleSplit(n_splits=1, test_size=0, random_state=0)  # 4000 trainset
        # sss = sss.split(list(range(len(total_trainset))), total_trainset.targets)
        # train_idx, valid_idx = next(sss)
        # print(len(train_idx), len(valid_idx))

        # filter out
        # train_idx = list(filter(lambda x: total_trainset.labels[x] in idx120, train_idx))
        # valid_idx = list(filter(lambda x: total_trainset.labels[x] in idx120, valid_idx))
        # # test_idx = list(filter(lambda x: testset.samples[x][1] in idx120, range(len(testset))))
        train_idx = list(range(len(total_trainset)))

        filter_train_idx = list(filter(lambda x: total_trainset.targets[x] in idx120, train_idx))
        # valid_idx = list(filter(lambda x: total_trainset.targets[x] in idx120, valid_idx))
        # test_idx = list(filter(lambda x: testset.samples[x][1] in idx120, range(len(testset))))
        # print(len(filter_train_idx))

        targets = [idx120.index(total_trainset.targets[idx]) for idx in filter_train_idx]
        sss = StratifiedShuffleSplit(n_splits=1, test_size=len(filter_train_idx) - 6000, random_state=0)  # 4000 trainset
        sss = sss.split(list(range(len(filter_train_idx))), targets)
        train_idx, valid_idx = next(sss)
        train_idx = [filter_train_idx[x] for x in train_idx]
        valid_idx = [filter_train_idx[x] for x in valid_idx]

        targets = [idx120.index(total_trainset.targets[idx]) for idx in train_idx]
        for idx in range(len(total_trainset.samples)):
            if total_trainset.samples[idx][1] not in idx120:
                continue
            total_trainset.samples[idx] = (total_trainset.samples[idx][0], idx120.index(total_trainset.samples[idx][1]))
        total_trainset = Subset(total_trainset, train_idx)
        total_trainset.targets = targets

        # for idx in range(len(testset.samples)):
        #     if testset.samples[idx][1] not in idx120:
        #         continue
        #     testset.samples[idx] = (testset.samples[idx][0], idx120.index(testset.samples[idx][1]))
        # testset = Subset(testset, test_idx)
        print('reduced_imagenet train=', len(total_trainset))
    else:
        raise ValueError('invalid dataset name=%s' % dataset)

    train_sampler = None
    if split > 0.0:
        sss = StratifiedShuffleSplit(n_splits=5, test_size=split, random_state=0)
        sss = sss.split(list(range(len(total_trainset))), total_trainset.targets)
        for _ in range(split_idx + 1):
            train_idx, valid_idx = next(sss)

        if target_lb >= 0:
            train_idx = [i for i in train_idx if total_trainset.targets[i] == target_lb]
            valid_idx = [i for i in valid_idx if total_trainset.targets[i] == target_lb]

        train_sampler = SubsetRandomSampler(train_idx)
        valid_sampler = SubsetSampler(valid_idx)

        # if horovod:
        #     import horovod.torch as hvd
        #     train_sampler = torch.utils.data.distributed.DistributedSampler(train_sampler, num_replicas=hvd.size(), rank=hvd.rank())
    else:
        valid_sampler = SubsetSampler([])

        # if horovod:
        #     import horovod.torch as hvd
        #     train_sampler = torch.utils.data.distributed.DistributedSampler(valid_sampler, num_replicas=hvd.size(), rank=hvd.rank())
    train_data = AugmentDataset(total_trainset, transform_train_pre, transform_train_after, transform_test, ops_names, True, magnitudes)
    valid_data = AugmentDataset(total_trainset, transform_train_pre, transform_train_after, transform_test, ops_names, False, magnitudes)

    trainloader = torch.utils.data.DataLoader(
        train_data, batch_size=batch, shuffle=False,
        sampler=train_sampler, drop_last=False,
        pin_memory=True, num_workers=num_workers)

    validloader = torch.utils.data.DataLoader(
        valid_data, batch_size=batch,
        # sampler=torch.utils.data.sampler.SubsetRandomSampler(indices[split:num_train]),
        sampler=valid_sampler, drop_last=False,
        pin_memory=True, num_workers=num_workers)

    # trainloader = torch.utils.data.DataLoader(
    #     total_trainset, batch_size=batch, shuffle=True if train_sampler is None else False, num_workers=32, pin_memory=True,
    #     sampler=train_sampler, drop_last=True)
    # validloader = torch.utils.data.DataLoader(
    #     total_trainset, batch_size=batch, shuffle=False, num_workers=16, pin_memory=True,
    #     sampler=valid_sampler, drop_last=False)

    # testloader = torch.utils.data.DataLoader(
    #     testset, batch_size=batch, shuffle=False, num_workers=32, pin_memory=True,
    #     drop_last=False
    # )
    print(len(train_data))
    return trainloader, validloader


#_author: Administrator
#date:
"呦，又在写bug呐！！！"

import socket

sk=socket.socket()

sk.connect(("127.0.0.1",9004))

while True:
	inp=input(">>".strip())
	sk.send(inp.encode("utf8"))
	data=sk.recv(1024)
	print(data.decode("utf8"))


from django.contrib import admin
from django.urls import path,include
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)
from django.conf import settings
from django.conf.urls.static import static
from rest_framework.documentation import include_docs_urls
from rest_framework.schemas import get_schema_view
schema_view = get_schema_view(title="Example API")

urlpatterns = [
    path('admin/', admin.site.urls),

    path('api/account/',include("apps.account.urls")),
    path('api/',include("apps.social.urls")),
    path('api/user/',include("apps.userprofile.urls")),

    # token
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),

    path('schema', schema_view),
    path('', include_docs_urls(
        title="Social Media Project",
        description="API for social media platform",
    ), name="mumble-docs")

]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
from io import StringIO
matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'

s = StringIO(""" dist acc fscore prot appb appw buffb buffw
PV-AB 37.68 0.83 0.80 0.44 0.059 0.092 0.019 0.004
PV-A 36.62 0.78 0.76 0.41 0.018 0.030 NaN NaN
PV 56.30 0.82 0.80 0.39 NaN NaN NaN NaN
PV-B 57.60 0.86 0.82 0.42 NaN NaN 0.078 0.120
BL 55.80 0.86 0.82 0.38 NaN NaN NaN NaN""")

df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True)
df = df.astype(float)

fig = plt.figure(figsize=(7, 4), dpi=80)   # Create matplotlib figure

ax = fig.add_subplot(111)  # Create matplotlib axes
ax.set_ylim(0, 80)
ax2 = ax.twinx()
ax2.set_ylim(0, 1)
ax3 = ax.twinx()
ax3.set_ylim(0, 0.12)

# right, left, top, bottom
ax3.spines['right'].set_position(('outward', 60))

# no x-ticks
ax3.xaxis.set_ticks([])

width = 0.15

df.dist.plot(kind='bar', color='#0084a3', ax=ax, width=width, position=3, rot=0)
df.acc.plot(kind='bar', color='#f9c768', ax=ax2, width=width, position=2, rot=0)
df.fscore.plot(kind='bar', color='#70507a', ax=ax2, width=width, position=1, rot=0)
df.prot.plot(kind='bar', color='#9bd670', ax=ax2, width=width, position=0, rot=0)
df.appb.plot(kind='bar', color='#cf4931', ax=ax3, width=width, position=-1, rot=0)
df.appw.plot(kind='bar', color='#ffa05c', ax=ax3, width=width, position=-2, rot=0)
ax.set_xticks([0, 1, 2, 3, 4])
ax.set_xticklabels(["PV-AB", "PV-A", "PV", "PV-B", "$\\it{BL}$"])

# ask matplotlib for the plotted objects and their labels
lines, _ = ax.get_legend_handles_labels()
lines2, _ = ax2.get_legend_handles_labels()
lines3, _ = ax3.get_legend_handles_labels()
ax.legend(lines + lines2 + lines3, ["Dist. (x100)", "Acc.", "$F_1$", "Prot.", "App.$\\uparrow$",
                                    "App.$\\downarrow$"], ncol=3, loc=(0.001, 1.0))

ax.set_ylabel('Dist.')
ax2.set_ylabel('Acc. / $F_1$ / Prot.')
ax3.set_ylabel('App.$\\uparrow$ / App.$\\downarrow$')
plt.xlim(-0.65, 4.6)
fig.savefig('o295w_bl.png', bbox_inches='tight', facecolor=fig.get_facecolor(), transparent=True)

plt.show()


import asyncio

async def ticker(delay, to):
    for i in range(to):
        yield i
        await asyncio.sleep(delay)

async def main():
    resutls = [
        (i, j)
        async for i in ticker(1, 5)
        async for j in ticker(1, 5)
        if not i % 2 and j % 2
    ]

    print(resutls)

asyncio.run(main())


import sys
import pygame
from character import Character
def show():
    pygame.init()
    screen = pygame.display.set_mode((1200, 600))
    pygame.display.set_caption("Character")
    bg_color = (25, 25, 255)
    character = Character(screen)
    while True:
        screen.fill(bg_color)
        pygame.display.flip()
        character.blitme()

show()


"""
The canonical example of a function that cannot be
learnt with a simple linear model is XOR
"""

from yoannet.train import train
from yoannet.nn import NeuralNet
from yoannet.layers import Linear, Tanh
import numpy as np

inputs = np.array([
    [0, 0],
    [1, 0],
    [0, 1],
    [1, 1]
])

targets = np.array([
    [1, 0],
    [0, 1],
    [0, 1],
    [1, 0]
])

net = NeuralNet([
    Linear(input_size=2, output_size=2),
    Tanh(),
    Linear(input_size=2, output_size=2)
])

train(net, inputs, targets)

for x, y in zip(inputs, targets):
    predicted = net.forward(x)
    print(x, predicted, y)


# -*- coding: utf-8 -*-
'''
Created on 2016-4-19

@author: wubo
'''

import requests

from utils import path_util
from cloud.cloud_qiniu import DownloadURL, BucketUtil
from user.user_cache import WxUserCache
from wx_pub import wx_wechat_util
from utils import timeout_util

def download_wx_headimg(open_id, avatar_url):
    if not avatar_url:
        return 'no_url'

    f_name = path_util.avatar_temp_exists(open_id)
    if f_name:
        return 'exists'

    f_name = path_util.make_avatar_temp_path(open_id)

    try:
        pic_resp = requests.get(avatar_url, stream=True)
        if pic_resp.ok:
            with open(f_name, 'wb') as f:
                f.write(pic_resp.content)
    finally:
        pass
    return 'ok'

def download_picture_from_qiniu(picture_key):
    uri = path_util.picture_temp_exists(picture_key)
    if not uri:
        url = DownloadURL().get_pub(picture_key)
        f_name = path_util.make_pic_temp_path(picture_key)
        try:
            pic_resp = requests.get(url, stream=True)
            if pic_resp.ok:
                with open(f_name, 'wb') as f:
                    f.write(pic_resp.content)
            # f.close()
        except:
            pass

def download_watermark_picture_from_qiniu(picture_key):
    uri = path_util.watermark_temp_exists(picture_key)
    if not uri:
        watermark_key = path_util.make_watermark_temp_base_name(picture_key)
        url = DownloadURL().get_jjt_pub(watermark_key)
        f_name = path_util.make_pic_watermark_temp_path(picture_key)
        try:
            pic_resp = requests.get(url, stream=True)
            if pic_resp.ok:
                with open(f_name, 'wb') as f:
                    f.write(pic_resp.content)
            # f.close()
        except:
            pass

def fetch_user_wx_info(open_id):
    user_id = WxUserCache.get_user_local_id(open_id)
    if not user_id:
        return 'missing_id'

    user_info = WxUserCache.get_user_info(user_id)
    if user_info:
        return 'ok'

    u_info = get_user_wx_info(open_id)
    if not isinstance(u_info, (dict, )):
        return 'dl_error'

    if u_info and u_info['subscribe'] != 0:
        WxUserCache.set_user_info(open_id=u_info['openid'],
                                  user_id=user_id,
                                  nickname=u_info.get('nickname', u' '),
                                  sex=u_info.get('sex', 0),
                                  city=u_info['city'],
                                  avatar=u_info['headimgurl'],
                                  union_id=u_info.get('unionid'))

        WxUserCache.add_pending_write_id(user_id)

        download_wx_headimg(open_id, u_info['headimgurl'])
    return 'ok'

def get_user_wx_info(open_id):
    """
    :param open_id: weixin open id
    """
    cli = wx_wechat_util.get_wechat_client()
    try:
        resp_ = cli.user.get(open_id)
    except:
        resp_ = {}
    return resp_

@timeout_util.timeout(seconds=3.5, use_signals=True)
def fetch_picture_from_wx(picture_url):
    try:
        fetch_rst = BucketUtil().fetch_file(picture_url)
    except:
        fetch_rst = 'fetch_failed'
    return fetch_rst


import json
import os
import random

import config

import helpers

def change_title():
    titles_path = os.path.join(helpers.folder_path(), config.titles_path[0], config.titles_path[1])
    with open(titles_path) as f:
        titles = json.load(f)

    if not config.testing:
        reddit = helpers.initialize_reddit()
        reddit.subreddit(config.target_subreddit).mod.update(title=random.choice(titles))
    else:
        print('Testing: updated title ("{}")'.format(random.choice(titles)))

def update_sidebar(user_list):
    path_1 = os.path.join(helpers.folder_path(), config.sidebar_text_paths[0][0], config.sidebar_text_paths[0][1])
    path_2 = os.path.join(helpers.folder_path(), config.sidebar_text_paths[1][0], config.sidebar_text_paths[1][1])
    with open(path_1, 'r') as f:
        sidebar_1 = f.read()
    with open(path_2, 'r') as f:
        sidebar_2 = f.read()

    sidebar_rows = [sidebar_1, '\n']
    sidebar_rows.append('Number | User\n---|---')
    for i, user in enumerate(user_list):
        sidebar_rows.append('{} | /u/{}'.format(i + 1, user))
    sidebar_rows.append(sidebar_2)

    sidebar = '\n'.join(sidebar_rows)

    if not config.testing:
        reddit = helpers.initialize_reddit()
        reddit.subreddit(config.target_subreddit).mod.update(description=sidebar)
    else:
        print('Testing: description updated:\n')
        print(sidebar)

if __name__ == '__main__':
    choice = input('Update what? T for title or S for sidebar [T/S]: ')

    if choice.lower() == 't':
        change_title()
    elif choice.lower() == 's':
        update_sidebar(helpers.load_data('user_list'))
    else:
        print('Invalid choice. Exiting.')


from functools import wraps

from django.template.defaultfilters import slugify

from concordia.models import Campaign, MediaType

def ensure_slug(original_function):
    @wraps(original_function)
    def inner(*args, **kwargs):
        title = kwargs.get("title")
        slug = kwargs.get("slug")
        if title and slug is None:
            kwargs["slug"] = slugify(title)

        return original_function(*args, **kwargs)

    return inner

@ensure_slug
def create_campaign(
    *,
    title="Test Campaign",
    slug="test-campaign",
    short_description="Short Description",
    description="Test Description",
    published=True,
    **kwargs,
):
    campaign = Campaign(
        title=title, slug=slug, description=description, published=published, **kwargs
    )
    campaign.full_clean()
    campaign.save()
    return campaign

@ensure_slug
def create_project(
    *,
    campaign=None,
    title="Test Project",
    slug="test-project",
    description="Test Description",
    published=True,
    **kwargs,
):
    if campaign is None:
        campaign = create_campaign()

    project = campaign.project_set.create(
        title=title, slug=slug, published=True, **kwargs
    )
    project.full_clean()
    project.save()
    return project

def create_item(
    *,
    project=None,
    title="Test Item",
    item_id="testitem0123456789",
    item_url="http://example.com/item/testitem0123456789/",
    published=True,
    **kwargs,
):
    if project is None:
        project = create_project()

    item = project.item_set.create(
        title=title, item_id=item_id, item_url=item_url, published=True, **kwargs
    )
    item.full_clean()
    item.save()
    return item

@ensure_slug
def create_asset(
    *,
    item=None,
    title="Test Asset",
    slug="test-asset",
    media_type=MediaType.IMAGE,
    media_url="1.jpg",
    published=True,
    **kwargs,
):
    if item is None:
        item = create_item()
    asset = item.asset_set.create(
        title=title,
        slug=slug,
        media_type=media_type,
        published=published,
        media_url=media_url,
        **kwargs,
    )
    asset.full_clean()
    asset.save()
    return asset


import unittest

def partition_search(input_numbers, key):
    """
    Search an unsorted array by partitioning sections of it.

    :param input_numbers: An array of numbers
    :param key: The value to find
    :return: Whether the array contains the key or not
    """
    lower_bound = 0
    upper_bound = len(input_numbers)-1

    # Copy the array to prevent mutation on original while partitioning
    numbers = input_numbers[:]

    while upper_bound >= lower_bound:
        pivot_index = three_way_partition(numbers, lower_bound, upper_bound)

        if numbers[pivot_index] > key:
            upper_bound = pivot_index - 1

        elif numbers[pivot_index] < key:
            lower_bound = pivot_index + 1

        else:
            return True

    return False

def three_way_partition(input_list, lower, upper):
    """
    Partition the array such that all elements < A[0] is to the left and all elements > A[0] are to the right.

    :param input_list: The array to mutate
    :param lower: Lower index to partition
    :param upper: Upper index to partition
    :return: The index of the first element with a value of A[0] (there could be duplicate keys)
    """
    lower_bound = lower
    upper_bound = upper

    pivot = input_list[lower_bound]

    i = lower

    while i <= upper_bound:
        current_number = input_list[i]
        if current_number < pivot:
            swap(input_list, i, lower_bound)
            i += 1
            lower_bound += 1

        elif current_number > pivot:
            swap(input_list, i, upper_bound)
            upper_bound -= 1

        else:
            i += 1

    return lower_bound

def swap(input_list, a, b):
    """
    Swaps two element inside a collection
    """
    temp = input_list[a]
    input_list[a] = input_list[b]
    input_list[b] = temp

class TestPartitionSearch(unittest.TestCase):

    def setUp(self):
        self.x = [-32, 40, 2, 59, 40, -32, 50, -24, 9, -290]
        self.y = [1, 2, 3, 4, 5, 6, 7]

    def test_exist(self):

        for i in self.x:
            self.assertEquals(partition_search(self.x, i), True)

        for j in self.y:
            self.assertEqual(partition_search(self.y, j), True)

    def test_nonexist(self):
        self.assertEqual(partition_search(self.x, 20), False)

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


'''
Author @ Subhamoy Karmakar

This is the Module where the log generating statements are selected.

Input:

Output:
'''
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import logging
import configuration as cfg
from LogMessageResource import *
import sqlOperations
import LogsDBOperations as dbop

class policySelectLogStatements(QWidget):
    def __init__(self):
        super(policySelectLogStatements, self).__init__()
        logging.basicConfig(
            filename=cfg.FILE_LOG_APPLICATION,
            level=logging.INFO,
            filemode='a',
            format='%(asctime)s %(levelname)s %(filename)s %(funcName)s %(message)s',
            datefmt='%Y-%m-%d %I:%M:%S %p'
        )
        # contents
        self.policyID = QComboBox()
        self.policyTitle = QLineEdit()
        self.policyTitle.setReadOnly(True)
        self.policiesList = QTableWidget()
        self.policiesList.setColumnCount(2)
        self.policiesList.setHorizontalHeaderLabels(['Policies', 'Log Generating'])
        self.policiesList.horizontalHeader().setResizeMode(0, QHeaderView.Stretch)
        self.policiesList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        saveButton = QPushButton('Save')
        saveButton.setCursor(Qt.PointingHandCursor)
        resetButton = QPushButton('Reset')
        resetButton.setCursor(Qt.PointingHandCursor)

        # listeners
        self.policyID.currentIndexChanged.connect(self.updatePoliciesList)
        resetButton.clicked.connect(self.resetButtonClick)
        saveButton.clicked.connect(self.saveButtonOnClick)

        # layout
        mainVLayout = QVBoxLayout()
        policyIDHLayout = QHBoxLayout()
        policyIDHLayout.addWidget(QLabel('Policy ID'))
        policyIDHLayout.addWidget(self.policyID)
        policyIDHLayout.addWidget(QLabel('Policy Title'))
        policyIDHLayout.addWidget(self.policyTitle)
        saveButtonHLayout = QHBoxLayout()
        saveButtonHLayout.addStretch(1)
        saveButtonHLayout.addWidget(resetButton)
        saveButtonHLayout.addWidget(saveButton)
        mainVLayout.addLayout(policyIDHLayout)
        mainVLayout.addWidget(self.policiesList)
        mainVLayout.addLayout(saveButtonHLayout)
        self.setLayout(mainVLayout)

    def resetButtonClick(self):
        string = str(self.policyID.currentText())
        if (string == ''):
            self.policyTitle.clear()
            self.policiesList.setRowCount(0)
            return
        id = int(string)
        (_, policies) = sqlOperations.viewPolicy(id)
        for i in range(len(policies)):
            logGen = policies[i][1]
            if (logGen):
                self.policiesList.item(i, 1).setCheckState(Qt.Checked)
            else:
                self.policiesList.item(i, 1).setCheckState(Qt.Unchecked)

    def saveButtonOnClick(self):
        strPolicyId = str(self.policyID.currentText())
        policyStmtFlag = {}
        if strPolicyId == '':
            self.policyTitle.clear()
            self.policiesList.setRowCount(0)
            return
        for i in range(0, self.policiesList.rowCount()):
            if self.policiesList.item(i, 1).checkState():
                policyStmtFlag[str(self.policiesList.item(i, 0).text())] = 1
            else:
                policyStmtFlag[str(self.policiesList.item(i, 0).text())] = 0

        status = sqlOperations.setLogGenStmtFlag(strPolicyId, policyStmtFlag)
        if status:
            msgBox = QMessageBox()
            msgBox.setText('Log generating statements successfully saved. Do you wish to change the log location details?')
            msgBox.setWindowTitle('Successful')
            logging.info(MESSAGE['0024'])
            msgBox.setIcon(QMessageBox.Information)
            msgBox.addButton(QMessageBox.Yes)
            msgBox.addButton(QMessageBox.No)
            reply = msgBox.exec_()
            if reply == QMessageBox.Yes:
                self.editLogLocation()
        else:
            msgBox = QMessageBox()
            msgBox.setText('Failed')
            msgBox.setInformativeText('Error while saving the log generating statements')
            msgBox.setWindowTitle('Error')
            logging.error(MESSAGE['0025'])
            msgBox.setIcon(QMessageBox.Critical)
            msgBox.exec_()

    def updatePolicyID(self):
        self.policyID.clear()
        # Get unique policy ID from Database
        ids = sqlOperations.getPolicyIDs()
        for ID in ids:
            self.policyID.addItem(str(ID))
        self.updatePoliciesList()

    def updatePoliciesList(self):
        string = str(self.policyID.currentText())
        if (string == ''):
            self.policyTitle.clear()
            self.policiesList.setRowCount(0)
            return
        id = int(string)
        (title, policies) = sqlOperations.viewPolicy(id)
        self.policyTitle.setText(title)
        self.policiesList.setRowCount(0)
        for policy, logGen in policies:
            self.policiesList.insertRow(self.policiesList.rowCount())
            self.policiesList.setItem(self.policiesList.rowCount() - 1, 0, QTableWidgetItem(policy))
            chkBoxItem = QTableWidgetItem()
            chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if (logGen):
                chkBoxItem.setCheckState(Qt.Checked)
            else:
                chkBoxItem.setCheckState(Qt.Unchecked)
            self.policiesList.setItem(self.policiesList.rowCount() - 1, 1, chkBoxItem)
        self.policiesList.resizeRowsToContents()

    def refreshContent(self):
        self.updatePolicyID()

    def editLogLocation(self):
        locations = dbop.getAllLogLocationDetails()
        self.locDialog = QDialog()
        btnEdit = QPushButton('Edit')
        self.logLocLineEdit = QLineEdit()
        # Listeners
        btnEdit.clicked.connect(self.savePolicyLogLocation)

        self.locDialog.resize(700, 500)
        self.locDialog.setWindowTitle('Log Locations')
        gLayout = QGridLayout()
        self.loctable = QTableWidget()
        self.loctable.insertColumn(0)
        self.loctable.insertColumn(1)
        self.loctable.insertColumn(2)
        self.loctable.setHorizontalHeaderLabels(['PolicyId', 'Platform', 'Location'])
        self.loctable.horizontalHeader().setStretchLastSection(True)
        self.loctable.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.loctable.setRowCount(len(locations))
        cnt = 0
        for data in locations:
            self.loctable.setItem(cnt, 0, QTableWidgetItem(data[0]))
            self.loctable.setItem(cnt, 1, QTableWidgetItem(data[1]))
            self.loctable.setItem(cnt, 2, QTableWidgetItem(data[2]))
            cnt = cnt + 1

        # gLayout.addWidget(self.logLocLineEdit, 0, 0, 1, 2)
        gLayout.addWidget(self.loctable, 1, 0, 2, 1)
        gLayout.addWidget(btnEdit, 1, 1)
        self.locDialog.setLayout(gLayout)
        self.locDialog.exec_()

    def savePolicyLogLocation(self):
        row = self.loctable.currentRow()
        col = self.loctable.currentColumn()
        if row != "0" and col != "0":
            msg = QMessageBox()
            msg.setWindowTitle('Question')
            msg.setText('Are you sure you want to change the log location information?')
            msg.addButton(QMessageBox.Yes)
            msg.addButton(QMessageBox.No)
            reply = msg.exec_()
            if reply == QMessageBox.Yes:
                self.tmpdialog = QDialog()
                saveBTN = QPushButton('Save')
                saveBTN.clicked.connect(self.finalLocSave)
                self.lineEditPID = QLineEdit()
                self.lineEditPLATFORM= QLineEdit()
                self.lineEditLocation = QLineEdit()

                pID = self.loctable.item(row, 0).text()
                platform = self.loctable.item(row, 1).text()
                location = self.loctable.item(row, 2).text()

                self.lineEditPID.setText(str(pID))
                self.lineEditPID.setReadOnly(True)
                self.lineEditPLATFORM.setText(str(platform))
                self.lineEditPLATFORM.setReadOnly(True)
                self.lineEditLocation.setText(str(location))

                gridLL = QGridLayout()
                gridLL.addWidget(self.lineEditPID, 0, 0)
                gridLL.addWidget(self.lineEditPLATFORM, 1, 0)
                gridLL.addWidget(self.lineEditLocation, 2 ,0)
                gridLL.addWidget(saveBTN)
                self.tmpdialog.setLayout(gridLL)

                self.tmpdialog.exec_()
        else:
            msg = QMessageBox()
            msg.setWindowTitle('Error')
            msg.setText('Please select a row to continue!')
            msg.setIcon(QMessageBox.Critical)
            msg.exec_()

    def finalLocSave(self):
        if dbop.updateLogLocation(
            str(self.lineEditPID.text()),
                str(self.lineEditPLATFORM.text()),
                str(self.lineEditLocation.text())):
            msg = QMessageBox()
            msg.setWindowTitle('Saved')
            msg.setText('Changes has been saved.')
            msg.setIcon(QMessageBox.Information)
            msg.exec_()
            self.tmpdialog.close()
            self.locDialog.close()


from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status, permissions, generics, viewsets
from .models import CustomUser, MentorProfile, OrgProfile
from .serializers import CustomUserSerializer, MentorProfileSerializer, OrgProfileSerializer, ChangePasswordSerializer
from django.shortcuts import get_object_or_404
from django.core.exceptions import PermissionDenied
from .permissions import IsOwnerOrReadOnly, IsProfileUserOrReadOnly, IsNotAuthenticated
from rest_framework.permissions import IsAuthenticated, IsAdminUser

class CustomUserCreate(generics.CreateAPIView):
    """
    View for registering new account.
    """
    permission_classes = [IsNotAuthenticated, ]
    queryset = CustomUser.objects.all()
    serializer_class = CustomUserSerializer

    def check_permissions(self, request):
        if request.user.is_authenticated:
            self.permission_denied(request)

class ChangePasswordView(generics.UpdateAPIView):
    serializer_class = ChangePasswordSerializer
    model = CustomUser
    permission_classes = [IsAuthenticated, ]

    def get_object(self, queryset=None):
        obj = self.request.user
        return obj

    def update(self, request, *args, **kwargs):
        self.object = self.get_object()
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            if not self.object.check_password(serializer.data.get("old_password")):
                return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST)
            self.object.set_password(serializer.data.get("new_password"))
            self.object.save()
            response = {
                'status': 'success',
                'code': status.HTTP_200_OK,
                'message': 'Password updated successfully',
                'data': []
            }

            return Response(response)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class CustomUserList(APIView):
    permission_classes = [IsAdminUser, ]

    def get(self, request):
        users = CustomUser.objects.all()
        serializer = CustomUserSerializer(users, many=True)
        return Response(serializer.data)

class CustomUserDetail(APIView):
    permission_classes = [IsOwnerOrReadOnly, ]
    lookup_field = 'username'

    def get_object(self, username):
        try:
            return CustomUser.objects.get(username=username)
        except CustomUser.DoesNotExist:
            raise Http404

    def get(self, request, username):
        user = self.get_object(username)
        serializer = CustomUserSerializer(user)
        return Response(serializer.data)

    def put(self, request, username):
        user = self.get_object(username)
        self.check_object_permissions(request, user)
        data = request.data
        serializer = CustomUserSerializer(
            instance=user,
            data=data,
            partial=True
        )
        if serializer.is_valid():
            serializer.save()
            return Response(
                serializer.data,
                status=status.HTTP_200_OK
            )
        return Response(
            serializer.errors,
            status=status.HTTP_400_BAD_REQUEST
        )

    def delete(self, request, username):
        user = self.get_object(username)
        self.check_object_permissions(request, user)

        try:
            user.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except CustomUser.DoesNotExist:
            raise Http404

class MentorProfileDetail(APIView):
    permission_classes = [IsProfileUserOrReadOnly, ]
    serializer_class = MentorProfileSerializer

    def get_object(self, username):
        try:
            profile = MentorProfile.objects.get(user__username=username)
            self.check_object_permissions(self.request, profile)
            return profile
        except MentorProfile.DoesNotExist:
            raise Http404

    def get(self, request, username):
        profile = self.get_object(username)
        serializer = MentorProfileSerializer(profile)
        return Response(serializer.data)

    def put(self, request, username):
        profile = self.get_object(username)
        self.check_object_permissions(request, profile)
        serializer = MentorProfileSerializer(
            instance=profile, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save(user=request.user)
            return Response(
                serializer.data,
                status.HTTP_200_OK
            )
        return Response(
            serializer.errors,
            status.HTTP_400_BAD_REQUEST
        )

class OrgProfileDetail(APIView):
    permission_classes = [IsProfileUserOrReadOnly, ]
    serializer_class = OrgProfileSerializer

    def get_object(self, username):
        try:
            org_profile = OrgProfile.objects.select_related(
                'user').get(user__username=username)
            self.check_object_permissions(self.request, org_profile)
            return org_profile
        except org_profile.DoesNotExist:
            raise Http404

    def get(self, request, username):
        org_profile = self.get_object(username=username)
        serializer = OrgProfileSerializer(org_profile)
        return Response(serializer.data)

    def put(self, request, username):
        org_profile = self.get_object(username=username)
        serializer = OrgProfileSerializer(
            org_profile, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save(user=request.user)
            return Response(
                serializer.data,
                status.HTTP_200_OK
            )
        return Response(
            serializer.errors,
            status.HTTP_400_BAD_REQUEST
        )


# Script to read video from a camera and try to recognise some body parts
# Only for TEST purposes

import cv2 as cv
import numpy as np

# ------------- SETUP variables  ----------------------
CAMERA_ID = 0  # Index of the camera. Start with 0 and use higher if more camera devices available

# ------------- CODE ----------------------------------
# Create a VideoCapture object, the interface to communicate with the camera
cap = cv.VideoCapture(CAMERA_ID)
print("Reading Video from camera ", CAMERA_ID)
print("Frame width:", cap.get(cv.CAP_PROP_FRAME_WIDTH))
print("Frame height:", cap.get(cv.CAP_PROP_FRAME_HEIGHT))

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    cv.imshow('Video', frame)
    # When q pressed, quit the video stream from the camera
    if cv.waitKey(1) == ord('q'):
        break
cap.release()
cv.destroyAllWindows()


# --------------------------------------------------------------------------------}
# --- Info
# --------------------------------------------------------------------------------{
# Tools for fatigue analysis
#
# Taken from:
#    repository:  wetb
#    package:     wetb.fatigue_tools,
#    institution: DTU wind energy, Denmark
#    main author: mmpe
'''
Created on 04/03/2013
@author: mmpe

'eq_load' calculate equivalent loads using one of the two rain flow counting methods
'cycle_matrix' calculates a matrix of cycles (binned on amplitude and mean value)
'eq_load_and_cycles' is used to calculate eq_loads of multiple time series (e.g. life time equivalent load)

The methods uses the rainflow counting routines (See documentation in top of methods):
- 'rainflow_windap': (Described in "Recommended Practices for Wind Turbine Testing - 3. Fatigue Loads",
                      2. edition 1990, Appendix A)
or
- 'rainflow_astm' (based on the c-implementation by Adam Nieslony found at the MATLAB Central File Exchange
                   http://www.mathworks.com/matlabcentral/fileexchange/3026)
'''
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from future import standard_library
import warnings
standard_library.install_aliases()
import numpy as np

from . import fatigue_tools

__all__  = ['rainflow_astm', 'rainflow_windap','eq_load','eq_load_and_cycles','cycle_matrix','cycle_matrix2']

def check_signal(signal):
    # check input data validity
    if not type(signal).__name__ == 'ndarray':
        raise TypeError('signal must be ndarray, not: ' + type(signal).__name__)

    elif len(signal.shape) not in (1, 2):
        raise TypeError('signal must be 1D or 2D, not: ' + str(len(signal.shape)))

    if len(signal.shape) == 2:
        if signal.shape[1] > 1:
            raise TypeError('signal must have one column only, not: ' + str(signal.shape[1]))
    if np.min(signal) == np.max(signal):
        raise TypeError("Signal contains no variation")

def rainflow_windap(signal, levels=255., thresshold=(255 / 50)):
    """Windap equivalent rainflow counting

    Calculate the amplitude and mean values of half cycles in signal

    This algorithms used by this routine is implemented directly as described in
    "Recommended Practices for Wind Turbine Testing - 3. Fatigue Loads", 2. edition 1990, Appendix A

    Parameters
    ----------
    Signal : array-like
        The raw signal

    levels : int, optional
        The signal is discretize into this number of levels.
        255 is equivalent to the implementation in Windap

    thresshold : int, optional
        Cycles smaller than this thresshold are ignored
        255/50 is equivalent to the implementation in Windap

    Returns
    -------
    ampl : array-like
        Peak to peak amplitudes of the half cycles

    mean : array-like
        Mean values of the half cycles

    Examples
    --------
    >>> signal = np.array([-2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 5.0, 0.0, -1.0, 0.0, 3.0, 0.0, -4.0, 0.0, 4.0, 0.0, -2.0])
    >>> ampl, mean = rainflow_windap(signal)
    """
    check_signal(signal)
    #type <double> is required by <find_extreme> and <rainflow>
    signal = signal.astype(np.double)
    if np.all(np.isnan(signal)):
        return None
    offset = np.nanmin(signal)
    signal -= offset
    if np.nanmax(signal) > 0:
        gain = np.nanmax(signal) / levels
        signal = signal / gain
        signal = np.round(signal).astype(np.int)

        # If possible the module is compiled using cython otherwise the python implementation is used

        #Convert to list of local minima/maxima where difference > thresshold
        sig_ext = fatigue_tools.peak_trough(signal, thresshold)

        #rainflow count
        ampl_mean = fatigue_tools.pair_range_amplitude_mean(sig_ext)

        ampl_mean = np.array(ampl_mean)
        ampl_mean = np.round(ampl_mean / thresshold) * gain * thresshold
        ampl_mean[:, 1] += offset
        return ampl_mean.T

def rainflow_astm(signal):
    """Matlab equivalent rainflow counting

    Calculate the amplitude and mean values of half cycles in signal

    This implemementation is based on the c-implementation by Adam Nieslony found at
    the MATLAB Central File Exchange http://www.mathworks.com/matlabcentral/fileexchange/3026

    Parameters
    ----------
    Signal : array-like
        The raw signal

    Returns
    -------
    ampl : array-like
        peak to peak amplitudes of the half cycles (note that the matlab implementation
        uses peak amplitude instead of peak to peak)

    mean : array-like
        Mean values of the half cycles

    Examples
    --------
    >>> signal = np.array([-2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 5.0, 0.0, -1.0, 0.0, 3.0, 0.0, -4.0, 0.0, 4.0, 0.0, -2.0])
    >>> ampl, mean = rainflow_astm(signal)
    """
    check_signal(signal)

    # type <double> is reuqired by <find_extreme> and <rainflow>
    signal = signal.astype(np.double)

    # Import find extremes and rainflow.
    # If possible the module is compiled using cython otherwise the python implementation is used

    # Remove points which is not local minimum/maximum
    sig_ext = fatigue_tools.find_extremes(signal)

    # rainflow count
    ampl_mean = np.array(fatigue_tools.rainflowcount(sig_ext))

    return np.array(ampl_mean).T

def eq_load(signals, no_bins=46, m=[3, 4, 6, 8, 10, 12], neq=1, rainflow_func=rainflow_windap):
    """Equivalent load calculation

    Calculate the equivalent loads for a list of Wohler exponent and number of equivalent loads

    Parameters
    ----------
    signals : list of tuples or array_like
        - if list of tuples: list must have format [(sig1_weight, sig1),(sig2_weight, sig1),...] where\n
            - sigx_weight is the weight of signal x\n
            - sigx is signal x\n
        - if array_like: The signal
    no_bins : int, optional
        Number of bins in rainflow count histogram
    m : int, float or array-like, optional
        Wohler exponent (default is [3, 4, 6, 8, 10, 12])
    neq : int, float or array-like, optional
        The equivalent number of load cycles (default is 1, but normally the time duration in seconds is used)
    rainflow_func : {rainflow_windap, rainflow_astm}, optional
        The rainflow counting function to use (default is rainflow_windap)

    Returns
    -------
    eq_loads : array-like
        List of lists of equivalent loads for the corresponding equivalent number(s) and Wohler exponents

    Examples
    --------
    >>> signal = np.array([-2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 5.0, 0.0, -1.0, 0.0, 3.0, 0.0, -4.0, 0.0, 4.0, 0.0, -2.0])
    >>> eq_load(signal, no_bins=50, neq=[1, 17], m=[3, 4, 6], rainflow_func=rainflow_windap)
    [[10.311095426959747, 9.5942535021382174, 9.0789213365013932], # neq = 1, m=[3,4,6]
    [4.010099657859783, 4.7249689509841746, 5.6618639965313005]], # neq = 17, m=[3,4,6]

    eq_load([(.4, signal), (.6, signal)], no_bins=50, neq=[1, 17], m=[3, 4, 6], rainflow_func=rainflow_windap)
    [[10.311095426959747, 9.5942535021382174, 9.0789213365013932], # neq = 1, m=[3,4,6]
    [4.010099657859783, 4.7249689509841746, 5.6618639965313005]], # neq = 17, m=[3,4,6]
    """
    try:
        return eq_load_and_cycles(signals, no_bins, m, neq, rainflow_func)[0]
    except TypeError:
        return [[np.nan] * len(np.atleast_1d(m))] * len(np.atleast_1d(neq))

def eq_load_and_cycles(signals, no_bins=46, m=[3, 4, 6, 8, 10, 12], neq=[10 ** 6, 10 ** 7, 10 ** 8], rainflow_func=rainflow_windap):
    """Calculate combined fatigue equivalent load

    Parameters
    ----------
    signals : list of tuples or array_like
        - if list of tuples: list must have format [(sig1_weight, sig1),(sig2_weight, sig1),...] where\n
            - sigx_weight is the weight of signal x\n
            - sigx is signal x\n
        - if array_like: The signal
    no_bins : int, optional
        Number of bins for rainflow counting
    m : int, float or array-like, optional
        Wohler exponent (default is [3, 4, 6, 8, 10, 12])
    neq : int or array-like, optional
        Equivalent number, default is [10^6, 10^7, 10^8]
    rainflow_func : {rainflow_windap, rainflow_astm}, optional
        The rainflow counting function to use (default is rainflow_windap)

    Returns
    -------
    eq_loads : array-like
        List of lists of equivalent loads for the corresponding equivalent number(s) and Wohler exponents
    cycles : array_like
        2d array with shape = (no_ampl_bins, 1)
    ampl_bin_mean : array_like
        mean amplitude of the bins
    ampl_bin_edges
        Edges of the amplitude bins
    """
    cycles, ampl_bin_mean, ampl_bin_edges, _, _ = cycle_matrix(signals, no_bins, 1, rainflow_func)
    if 0:  #to be similar to windap
        ampl_bin_mean = (ampl_bin_edges[:-1] + ampl_bin_edges[1:]) / 2
    cycles, ampl_bin_mean = cycles.flatten(), ampl_bin_mean.flatten()
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        eq_loads = [[((np.nansum(cycles * ampl_bin_mean ** _m) / _neq) ** (1. / _m)) for _m in np.atleast_1d(m)]  for _neq in np.atleast_1d(neq)]
    return eq_loads, cycles, ampl_bin_mean, ampl_bin_edges

def cycle_matrix(signals, ampl_bins=10, mean_bins=10, rainflow_func=rainflow_windap):
    """Markow load cycle matrix

    Calculate the Markow load cycle matrix

    Parameters
    ----------
    Signals : array-like or list of tuples
        - if array-like, the raw signal\n
        - if list of tuples, list of (weight, signal), e.g. [(0.1,sig1), (0.8,sig2), (.1,sig3)]\n
    ampl_bins : int or array-like, optional
        if int, Number of amplitude value bins (default is 10)
        if array-like, the bin edges for amplitude
    mean_bins : int or array-like, optional
        if int, Number of mean value bins (default is 10)
        if array-like, the bin edges for mea
    rainflow_func : {rainflow_windap, rainflow_astm}, optional
        The rainflow counting function to use (default is rainflow_windap)

    Returns
    -------
    cycles : ndarray, shape(ampl_bins, mean_bins)
        A bi-dimensional histogram of load cycles(full cycles). Amplitudes are\
        histogrammed along the first dimension and mean values are histogrammed along the second dimension.
    ampl_bin_mean : ndarray, shape(ampl_bins,)
        The average cycle amplitude of the bins
    ampl_edges : ndarray, shape(ampl_bins+1,)
        The amplitude bin edges
    mean_bin_mean : ndarray, shape(ampl_bins,)
        The average cycle mean of the bins
    mean_edges : ndarray, shape(mean_bins+1,)
        The mean bin edges

    Examples
    --------
    >>> signal = np.array([-2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 5.0, 0.0, -1.0, 0.0, 3.0, 0.0, -4.0, 0.0, 4.0, 0.0, -2.0])
    >>> cycles, ampl_bin_mean, ampl_edges, mean_bin_mean, mean_edges = cycle_matrix(signal)
    >>> cycles, ampl_bin_mean, ampl_edges, mean_bin_mean, mean_edges = cycle_matrix([(.4, signal), (.6,signal)])
    """

    if isinstance(signals[0], tuple):
        weights, ampls, means = np.array([(np.zeros_like(ampl)+weight,ampl,mean) for weight, signal in signals for ampl,mean in rainflow_func(signal[:]).T], dtype=np.float64).T
    else:
        ampls, means = rainflow_func(signals[:])
        weights = np.ones_like(ampls)
    if isinstance(ampl_bins, int):
        ampl_bins = np.linspace(0, 1, num=ampl_bins + 1) * ampls[weights>0].max()
    cycles, ampl_edges, mean_edges = np.histogram2d(ampls, means, [ampl_bins, mean_bins], weights=weights)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        ampl_bin_sum = np.histogram2d(ampls, means, [ampl_bins, mean_bins], weights=weights * ampls)[0]
        ampl_bin_mean = np.nanmean(ampl_bin_sum / np.where(cycles,cycles,np.nan),1)
        mean_bin_sum = np.histogram2d(ampls, means, [ampl_bins, mean_bins], weights=weights * means)[0]
        mean_bin_mean = np.nanmean(mean_bin_sum / np.where(cycles, cycles, np.nan), 1)
    cycles = cycles / 2  # to get full cycles
    return cycles, ampl_bin_mean, ampl_edges, mean_bin_mean, mean_edges

def cycle_matrix2(signal, nrb_amp, nrb_mean, rainflow_func=rainflow_windap):
    """
    Same as wetb.fatigue_tools.fatigue.cycle_matrix but bin from min_amp to
    max_amp instead of 0 to max_amp.

    Parameters
    ----------

    Signal : ndarray(n)
        1D Raw signal array

    nrb_amp : int
        Number of bins for the amplitudes

    nrb_mean : int
        Number of bins for the means

    rainflow_func : {rainflow_windap, rainflow_astm}, optional
        The rainflow counting function to use (default is rainflow_windap)

    Returns
    -------

    cycles : ndarray, shape(ampl_bins, mean_bins)
        A bi-dimensional histogram of load cycles(full cycles). Amplitudes are\
        histogrammed along the first dimension and mean values are histogrammed
        along the second dimension.

    ampl_edges : ndarray, shape(no_bins+1,n)
        The amplitude bin edges

    mean_edges : ndarray, shape(no_bins+1,n)
        The mean bin edges

    """
    bins = [nrb_amp, nrb_mean]
    ampls, means = rainflow_func(signal)
    weights = np.ones_like(ampls)
    cycles, ampl_edges, mean_edges = np.histogram2d(ampls, means, bins,
                                                    weights=weights)
    cycles = cycles / 2  # to get full cycles

    return cycles, ampl_edges, mean_edges

# --------------------------------------------------------------------------------}
# --- Unittests
# --------------------------------------------------------------------------------{
import unittest

class TestFatigue(unittest.TestCase):

    def test_leq_1hz(self):
        """Simple test of wetb.fatigue_tools.fatigue.eq_load using a sine
        signal.
        """
        amplitude = 1
        m = 1
        point_per_deg = 100

        for amplitude in [1,2,3]:
            peak2peak = amplitude * 2
            # sine signal with 10 periods (20 peaks)
            nr_periods = 10
            time = np.linspace(0, nr_periods*2*np.pi, point_per_deg*180)
            neq = time[-1]
            # mean value of the signal shouldn't matter
            signal = amplitude * np.sin(time) + 5
            r_eq_1hz = eq_load(signal, no_bins=1, m=m, neq=neq)[0]
            r_eq_1hz_expected = ((2*nr_periods*amplitude**m)/neq)**(1/m)
            np.testing.assert_allclose(r_eq_1hz, r_eq_1hz_expected)

            # sine signal with 20 periods (40 peaks)
            nr_periods = 20
            time = np.linspace(0, nr_periods*2*np.pi, point_per_deg*180)
            neq = time[-1]
            # mean value of the signal shouldn't matter
            signal = amplitude * np.sin(time) + 9
            r_eq_1hz2 = eq_load(signal, no_bins=1, m=m, neq=neq)[0]
            r_eq_1hz_expected2 = ((2*nr_periods*amplitude**m)/neq)**(1/m)
            np.testing.assert_allclose(r_eq_1hz2, r_eq_1hz_expected2)

            # 1hz equivalent should be independent of the length of the signal
            np.testing.assert_allclose(r_eq_1hz, r_eq_1hz2)

    def test_rainflow_combi(self):
        """Signal with two frequencies and amplitudes
        """

        amplitude = 1
        # peak2peak = amplitude * 2
        m = 1
        point_per_deg = 100

        nr_periods = 10
        time = np.linspace(0, nr_periods*2*np.pi, point_per_deg*180)

        signal = (amplitude*np.sin(time)) + 5 + (amplitude*0.2*np.cos(5*time))
        cycles, ampl_bin_mean, ampl_edges, mean_bin_mean, mean_edges = \
            cycle_matrix(signal, ampl_bins=10, mean_bins=5)

        cycles.sum()

    def test_astm1(self):

        signal = np.array([-2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 5.0, 0.0, -1.0, 0.0, 3.0, 0.0, -4.0, 0.0, 4.0, 0.0, -2.0])

        ampl, mean = rainflow_astm(signal)
        np.testing.assert_array_equal(np.histogram2d(ampl, mean, [6, 4])[0], np.array([[ 0., 1., 0., 0.],
                                                                                [ 1., 0., 0., 2.],
                                                                                [ 0., 0., 0., 0.],
                                                                                [ 0., 0., 0., 1.],
                                                                                [ 0., 0., 0., 0.],
                                                                                [ 0., 0., 1., 2.]]))

    def test_windap1(self):
        signal = np.array([-2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 5.0, 0.0, -1.0, 0.0, 3.0, 0.0, -4.0, 0.0, 4.0, 0.0, -2.0])
        ampl, mean = rainflow_windap(signal, 18, 2)
        np.testing.assert_array_equal(np.histogram2d(ampl, mean, [6, 4])[0], np.array([[ 0., 0., 1., 0.],
                                                                                [ 1., 0., 0., 2.],
                                                                                [ 0., 0., 0., 0.],
                                                                                [ 0., 0., 0., 1.],
                                                                                [ 0., 0., 0., 0.],
                                                                                [ 0., 0., 2., 1.]]))

    def test_eq_load_basic(self):
        import numpy.testing
        signal1 = np.array([-2.0, 0.0, 1.0, 0.0, -3.0, 0.0, 5.0, 0.0, -1.0, 0.0, 3.0, 0.0, -4.0, 0.0, 4.0, 0.0, -2.0])
        M1=eq_load(signal1, no_bins=50, neq=[1, 17], m=[3, 4, 6], rainflow_func=rainflow_windap)
        M1_ref=np.array([[10.348414123746581, 9.635653414943068, 9.122399471334054], [4.024613313976801, 4.745357541147315, 5.68897815218057]])
        #M1_ref=np.array([[10.311095426959747, 9.5942535021382174, 9.0789213365013932],[4.010099657859783, 4.7249689509841746, 5.6618639965313005]])
        numpy.testing.assert_almost_equal(M1,M1_ref,decimal=5)
        #signal2 = signal1 * 1.1
        #         print (eq_load(signal1, no_bins=50, neq=17, rainflow_func=rainflow_windap))
        #         print (eq_load(signal1, no_bins=50, neq=17, rainflow_func=rainflow_astm))
        #         # equivalent load for default wohler slopes
        #         # Cycle matrix with 4 amplitude bins and 4 mean value bins
        #         print (cycle_matrix(signal1, 4, 4, rainflow_func=rainflow_windap))
        #         print (cycle_matrix(signal1, 4, 4, rainflow_func=rainflow_astm))
        #         # Cycle matrix where signal1 and signal2 contributes with 50% each
        #         print (cycle_matrix([(.5, signal1), (.5, signal2)], 4, 8, rainflow_func=rainflow_astm))

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


import pygenopt
import numpy

def ackley(x):
    return (-20. * numpy.exp(-0.2 * numpy.sqrt(0.5 * x[0]**2 + x[1]**2))
            -numpy.exp(0.5 * (numpy.cos(2 * numpy.pi * x[0]) +
                              numpy.cos(2 * numpy.pi * x[1]))) +
            numpy.exp(1) + 20.)

# Get the default parameters.
parameters = pygenopt.Optimiser.default_parameters()

# Use the rosenbrock function as defined above to be the fitness function.
parameters["fitness_function"] = ackley

# In this case we wish to minimise the function instead of maximise it.
parameters["maximise"] = False

# Set the population options.
parameters["population_options"]["population_size"] = 1000
# Evaluate the rosenbrock function with a parameter such as [x, y]
parameters["population_options"]["chromosome_shape"] = (1, 2)
# Only let chromosomes vary between -10 and 10 in both x and y.
parameters["population_options"]["upper_limits"] = [5., 5.]
parameters["population_options"]["lower_limits"] = [-5., -5.]
parameters["population_options"]["use_sensible_seeder"] = False

# Give the optimiser the new parameters.
optimiser = pygenopt.Optimiser(parameters)
# Run the optimisation.
optimiser.optimise()

# Visualise the optimisation.
visualisation = pygenopt.Visualisation(optimiser)
visualisation.plot(population_data=True,
                   mean=True,
                   standard_deviation=True,
                   without_worst=5,
                   legend=True)
visualisation.show()


from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools.tools import add_constant
import numpy as np
from sklearn.linear_model import LogisticRegressionCV, LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix

def print_vif(df):
    X = add_constant(df)
    for i, vif in enumerate([variance_inflation_factor(X.values, i) for i in range(1, X.shape[1])]):
        if vif > 10:
            print(df.columns[i] + ' VIF: ' + str(round(vif, 3)))

def print_condition_number(df):
    X = np.insert(np.array(df.values), 0, 1, axis=1)
    xpx = np.matmul(np.transpose(X), X)
    eigvals = [np.real(eig) for eig in np.linalg.eigvals(xpx)]
    print('Condition Number:' + str(abs(max(eigvals) / min(eigvals))))

def print_strong_correlations(df):
    corr = df.corr().values

    for i in range(len(df.columns) - 1):
        for j in range(i, len(df.columns) - 1):
            if i != j:
                if abs(corr[i, j]) > 0.9:
                    print('Strong correlation between ' + df.columns[i] + ' and ' + df.columns[
                        j] + ': ' + str(round(corr[i, j], 3)))

def print_log_regression_metrics(X, Y, cv=False):
    if cv:
        log_reg = LogisticRegressionCV(multi_class='multinomial', solver='newton-cg', max_iter=500)
    else:
        log_reg = LogisticRegression(multi_class='multinomial', penalty='none', solver='newton-cg', max_iter=500)
    log_reg.fit(X, Y)

    print('Accuracy: ' + str(round(accuracy_score(Y, log_reg.predict(X)),  3)))
    print(confusion_matrix(Y, log_reg.predict(X)))

def plot_roc_precision_recall(classifier, name, X, y, groups):
    fig = plt.figure(1, figsize=(16, 6))
    axes = fig.add_subplot(121), fig.add_subplot(122)
    plot_precision_recall_ci(classifier, name, X, y, axes[1], groups)
    plot_roc_ci(classifier, name, X, y, axes[0], groups)

def plot_precision_recall_ci(classifier, name, X, y, ax, groups):
    num_splits = 10

    cv = GroupShuffleSplit(n_splits=num_splits, test_size=0.2, random_state=1337)

    pre = []
    aucs = []
    mean_rc = np.linspace(0, 1, 1000)

    splits = cv.split(X, y, groups) if groups is not None else cv.split(X, y)

    for i, (train, test) in enumerate(splits):
        classifier.fit(X[train], y[train])
        predict = classifier.predict_proba(X[test])[:, 1]
        precision, recall, thresholds = precision_recall_curve(y[test], predict)
        pr_auc = auc(recall, precision)
        interp_pre = interp(mean_rc, precision, recall)
        interp_pre[0] = 1.0
        pre.append(interp_pre)
        aucs.append(pr_auc)

    chance = len(y[y == 1]) / len(y)

    mean_pre = np.mean(pre, axis=0)
    mean_pre[-1] = 0.0
    mean_auc = np.mean(aucs)
    std_auc = np.std(aucs) * 2
    ax.plot(mean_rc, mean_pre, color='b',
            label=r'AUC = %0.3f $\pm$ %0.3f' % (mean_auc, std_auc),
            lw=2, alpha=.8)

    std_pre = np.std(pre, axis=0)
    pre_upper = np.minimum(mean_pre + std_pre * 2, 1)
    pre_lower = np.maximum(mean_pre - std_pre * 2, 0)
    ax.fill_between(mean_rc, pre_lower, pre_upper, color='grey', alpha=.2,
                    label=r'$\pm$ 2 std. devs.')

    ax.set(xlim=[-0.05, 1.05], ylim=[-0.05, 1.05],
           title="Precision-Recall Curve: " + name)
    ax.legend(loc="lower left")
    ax.set_ylabel('Precision')
    ax.set_xlabel('Recall')

def plot_roc_ci(classifier, name, X, y, ax, groups=None, trained=False):
    num_splits = 10

    if groups is not None:
        cv = GroupShuffleSplit(n_splits=num_splits, test_size=0.2, random_state=1337)
    else:
        cv = StratifiedKFold(n_splits=num_splits, shuffle=True, random_state=1337)

    tprs = []
    aucs = []
    mean_fpr = np.linspace(0, 1, 1000)

    tp_rate = []
    tn_rate = []

    splits = cv.split(X, y, groups) if groups is not None else cv.split(X, y)
    for i, (train, test) in enumerate(splits):
        if not trained:
            classifier.fit(X[train], y[train])
        predict = classifier.predict_proba(X[test])[:, 1]
        fpr, tpr, thresholds = roc_curve(y[test], predict)
        roc_auc = auc(fpr, tpr)
        interp_tpr = interp(mean_fpr, fpr, tpr)
        interp_tpr[0] = 0.0
        tprs.append(interp_tpr)
        aucs.append(roc_auc)
        model_predict = [1 if p >= 0.5 else 0 for p in predict]
        tn_rate.append(recall_score(y[test], model_predict))
        tp_rate.append(recall_score([1 - p for p in y[test]], [1 - p for p in model_predict]))

    ax.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r',
            label='Chance', alpha=.8)

    mean_tpr = np.mean(tprs, axis=0)
    mean_tpr[-1] = 1.0
    mean_auc = auc(mean_fpr, mean_tpr)
    std_auc = np.std(aucs) * 2
    ax.plot(mean_fpr, mean_tpr, color='b',
            label=r'Mean ROC (AUC = %0.3f $\pm$ %0.3f)' % (mean_auc, std_auc),
            lw=2, alpha=.8)

    std_tpr = np.std(tprs, axis=0)
    tprs_upper = np.minimum(mean_tpr + std_tpr * 2, 1)
    tprs_lower = np.maximum(mean_tpr - std_tpr * 2, 0)
    ax.fill_between(mean_fpr, tprs_lower, tprs_upper, color='grey', alpha=.2,
                    label=r'$\pm$ 2 std. devs.')

    ax.set(xlim=[-0.05, 1.05], ylim=[-0.05, 1.05],
           title="ROC Curve: " + name)
    ax.legend(loc="lower right")
    ax.set_ylabel('True Positive Rate')
    ax.set_xlabel('False Positive Rate')

    plt.show()

    fp_rate = [1 - x for x in tp_rate]
    fn_rate = [1 - x for x in tn_rate]

    fpr_avg = np.mean(fp_rate)
    fnr_avg = np.mean(fn_rate)
    fpr_ci = np.std(fp_rate) * 2
    fnr_ci = np.std(fn_rate) * 2
    splits = cv.split(X, y, groups) if groups is not None else cv.split(X, y)
    print(f'False Positive Rate: {fpr_avg:.2f} +- {fpr_ci:.2f}')
    print(f'False Negative Rate: {fnr_avg:.2f} +- {fnr_ci:.2f}')


from server import Scheduler, ProcessServer, Core
from SimulationTable import SimulationTable
from statistics import StatisticsLogger
import tkinter as tk
import wx

inputs = []
f = open('input.txt')
for i in range(101):
    inputs.append(f.readline().strip().split(' '))  # Reading the input from file.

num_of_servers = int(inputs[0][0])  # Number of Servers in the system.
work_arrival_rate = float(inputs[0][1])  # The rate in which works enter the system.
deadline_mean = float(inputs[0][2])  # The average time for the deadlines.
scheduler_service_rate = float(inputs[0][3])  # The service rate of scheduler.

scheduler = Scheduler(scheduler_service_rate)  # Initializing the Scheduler.

servers = []  # List of all servers in the System.
core_counter = 0
core_list = []  # core_list[i] = Core Object with the id = i
processor_id_list = []  # processor_id_list[i] = ID of the server which corresponds to a given core ID.

for i in range(1, num_of_servers + 1):

    num_of_cores = int(inputs[i][0])
    core_rates_list = []

    for s in range(1, len(inputs[i])):
        # Initializing the Core List
        core_rates_list.append(float(inputs[i][s]))
        new_core = Core(float(inputs[i][s]), core_counter + s)
        core_list.append(new_core)
        processor_id_list.append(i)

    new_server = ProcessServer(num_of_cores, core_rates_list, i,
                               core_counter)  # Creating a process server with the initialized Core List.
    core_counter = core_counter + len(inputs[i]) - 1  # Updating the core counter for the next server.
    servers.append(new_server)  # Updating the servers list.

stat_logger = StatisticsLogger(n_servers=num_of_servers)
sim_table = SimulationTable(servers, scheduler, work_arrival_rate, core_list, processor_id_list, stat_logger,
                            deadline_mean)

def start_sim():
    for i in range(100):
        sim_table.step()  # Go one Step forward in the simulation.
        # sim_table.show_table() #Show the results of the simulation in a brief way.
        print(stat_logger.check_accuracy())

    stat_logger.print_results()  # Show statistical Results after the finish.

print(len(stat_logger.system_departures))

# root = tk.Tk()
# frame = tk.Frame(root)
# frame.pack()

# button = tk.Button(frame,
#                    text="QUIT",
#                    fg="red",
#                    command=start_sim)

#root.mainloop()
#start_sim()

def onButton(event):
    start_sim()

app = wx.App()
frame = wx.Frame(None, -1, 'win.py')
frame.SetDimensions(0,0,200,50)

panel = wx.Panel(frame, wx.ID_ANY)
button = wx.Button(panel, wx.ID_ANY, 'Start', (10, 10))
button.Bind(wx.EVT_BUTTON, onButton)

frame.Show()
frame.Centre()
app.MainLoop()


import RPi.GPIO as GPIO
import time

# Set our GPIO numbering to BCM
GPIO.setmode(GPIO.BCM)

# Define the GPIO pin that we have our digital output from our sensor connected to
pin = 4
# Set the GPIO pin to an input
GPIO.setup(pin, GPIO.IN)

while True:
    print(GPIO.input(pin)) # 1 for dry, 0 for wet


#!/usr/bin/env python
import roslib;
roslib.load_manifest('cob_lookat_controller')
import rospy
from std_msgs.msg import Float64MultiArray

def start_node():
    rospy.init_node('test_cmd_vel_publisher', anonymous=True)
    #advertise topic
    pub = rospy.Publisher('/driver/command_vel', Float64MultiArray, queue_size=1)
    rospy.sleep(1.0)

    msg = Float64MultiArray()
    #'lookat_lin_joint'
    msg.data.append(0.1)
    #'lookat_x_joint'
    msg.data.append(0.0)
    #'lookat_y_joint'
    msg.data.append(0.0)
    #'lookat_z_joint'
    msg.data.append(0.0)

    #print msg
    rospy.loginfo("publishing now!")
    pub.publish(msg)
    rospy.sleep(1.0)

if __name__ == '__main__':
    start_node()


"""Lesson 26 Task1
Task 1

A bubble sort can be modified to “bubble” in both directions.
The first pass moves “up” the list and the second pass moves “down.”
This alternating pattern continues until no more passes are necessary.
Implement this variation and describe under what circumstances it might be appropriate."""

def bubble(number):
    n = len(number)

    for i in range(n):

        for ia in range(0, n - i - 1):
            if number[ia] > number[ia + 1]:
                number[ia], number[ia + 1] = number[ia + 1], number[ia]

number = [5, 7, 1, 4, 5, 457, 12]
bubble(number)
for i in range(len(number)):
    print(number[i])


# Standard library imports
from __future__ import (absolute_import, print_function,
                        division, unicode_literals)
from pathlib import Path
import os
import sys
import uuid
import glob
import shutil
import datetime
from copy import deepcopy

# http://www.numpy.org/
import numpy as np

# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataModelDict as DM

# https://github.com/usnistgov/atomman
import atomman as am
import atomman.lammps as lmp
import atomman.unitconvert as uc

# https://github.com/usnistgov/iprPy
import iprPy

import matplotlib.pyplot as plt

record_style = 'calculation_point_defect_mobility'

def main(*args):
    """Main function called when script is executed directly."""

    # Read input file in as dictionary

    with open(args[0]) as f:
        input_dict = iprPy.input.parse(f, allsingular=True)

    # Interpret and process input parameters

    process_input(input_dict, *args[1:])

    results_dict = DM()

    results_dict['neb_log'] = calc_neb( input_dict['lammps_command'],
                                        input_dict['initialsystem'],
                                        input_dict['potential'],
                                        input_dict['initialdefect_number'],
                                        input_dict['defectpair_number'],
                                        input_dict['point_mobility_kwargs'],
                                        input_dict['allSymbols'],
                                        mpi_command = input_dict['mpi_command'],
                                        etol = input_dict['energytolerance'], #From lammps_min
                                        ftol = input_dict['forcetolerance'], #From lammps_min
                                        dmax = input_dict['maxatommotion'], #From lammps_min
                                        nreplicas = input_dict['numberreplicas'],  #For NEB
                                        springconst = input_dict['springconst'], #For NEB
                                        thermosteps = input_dict['thermosteps'],  #For NEB
                                        dumpsteps = input_dict['dumpsteps'], # For minimization settings
                                        timestep = input_dict['timestep'], # For minimization setings
                                        minsteps = input_dict['minsteps'], #For NEB
                                        climbsteps = input_dict['climbsteps'] #For NEB
                                        )

    # Load log from completed NEB

    neb = lmp.NEBLog()

    #Printing the number of replicas, and the log for the minruns and climbruns

    print('There were', neb.nreplicas, 'replicas')
    print(neb.minrun)
    print(neb.climbrun)

    #Creating a figure which contains the energy vs movement coordinate information
    #for the initial system, the final minimized system, and the climbed system

    fig = plt.figure()

    rx, e = neb.get_neb_path(0)

    results_dict['unrelaxed_run'] = DM()
    results_dict['unrelaxed_run']['coordinates'] = rx.tolist()
    results_dict['unrelaxed_run']['energy'] = e.tolist()

    plt.plot(rx, e, 'o:', label='unrelaxed')

    rx, e = neb.get_neb_path(neb.minrun.Step.values[-1])

    results_dict['final_minimized_run'] = DM()
    results_dict['final_minimized_run']['coordinates'] = rx.tolist()
    results_dict['final_minimized_run']['energy'] = e.tolist()

    plt.plot(rx, e, 'o:',label='after min run')

    rx, e = neb.get_neb_path(neb.climbrun.Step.values[-1])

    plt.plot(rx, e, 'o:',label='after climb run')

    results_dict['final_climb_run'] = DM()
    results_dict['final_climb_run']['coordinates'] = rx.tolist()
    results_dict['final_climb_run']['energy'] = e.tolist()

    plt.legend()

    plt.title('Defect Formation energy vs Normalized Migration Coordinate')
    plt.xlabel('Migration Coordinate')
    plt.ylabel('Change in formation energy (eV)')

    fig.savefig('EnergyvsCoord.png')

    #Creating a figure which combines the minimum energy path after the
    #minimization step and the climb steps, to give the fullest description
    #of the minimum energy path

    fig2 = plt.figure()

    rx1, e1 = neb.get_neb_path(neb.minrun.Step.values[-1])
    rx2, e2 = neb.get_neb_path(neb.climbrun.Step.values[-1])

    rx = []
    e = []
    index1 = 0
    index2 = 0

    while index2 < len(rx2):            #Going through the coordinates of the
        if rx1[index1] < rx2[index2]:   #minimum and climb steps so that they
            rx.append(rx1[index1])      #are properly ordered
            e.append(e1[index1])
            index1 = index1+1
        elif rx1[index1] > rx2[index2]:
            rx.append(rx2[index2])
            e.append(e2[index2])
            index2 = index2+1
        elif rx1[index1]==rx2[index1]:
            rx.append(rx1[index1])
            e.append(e1[index1])
            index1 = index1+1
            index2 = index2+1

    #Storing and ploting resulting information

    results_dict['min_and_climb_run'] = DM()
    results_dict['min_and_climb_run']['coordinates'] = rx
    results_dict['min_and_climb_run']['energy'] = e

    plt.plot(rx, e, 'o:',label='Min and Climb Run Combined')
    plt.legend()

    plt.title('Defect Formation energy vs Normalized Migration Coordinate')
    plt.xlabel('Migration Coordinate')
    plt.ylabel('Change in formation energy (eV)')

    #Creating a record using the calc_point_defect_mobility format

    record = iprPy.load_record(record_style)

    fig2.savefig('min_climb_combined.png')

    #Printing the information on the forward and reverse energy barrier,
    #and storing it in the results dict

    print('Forward barrier =', uc.get_in_units(neb.get_barrier(), 'eV'), 'eV')
    print('Reverse barrier =', uc.get_in_units(neb.get_barrier(reverse=True), 'eV'), 'eV')

    script = os.path.splitext(os.path.basename(__file__))[0]

    results_dict['barrier'] = DM()
    results_dict['barrier']['energy_units'] = 'eV'
    results_dict['barrier']['forward_barrier'] = uc.get_in_units(neb.get_barrier(), 'eV')
    results_dict['barrier']['reverse_barrier'] = uc.get_in_units(neb.get_barrier(reverse=True), 'eV')

    #building a record and printing it

    record.buildcontent(script, input_dict, results_dict)

    with open('results.json', 'w') as f:
        record.content.json(fp=f, indent=4)

def calc_neb(lammps_command, system_info, potential, initial_defect_number,
             defect_pair_number,defect_mobility_kwargs, allSymbols, mpi_command = None,
             etol=0.0, ftol=1e-4, dmax =uc.set_in_units(0.01, 'angstrom'),
             nreplicas=11, springconst = 5, thermosteps = 100,
             dumpsteps = 10000, timestep = 0.01, minsteps = 10000,
             climbsteps = 10000):

    #Section for making alterations to the overall simulation structure

    #Defining the initial perfect system using the original info

    initial_system = system_info

    #Adding defects to the system which will stay in the same position during the simulation

    for defectIndex in range(int(initial_defect_number)):
        point_kwargs = defect_mobility_kwargs['initial'][defectIndex]
        if point_kwargs['ptd_type'].lower() == 'v':
            initial_system = am.defect.vacancy(initial_system, pos=point_kwargs['pos'])
        elif point_kwargs['ptd_type'].lower() == 'i':
            initial_system = am.defect.interstitial(initial_system, pos=point_kwargs['pos'],atype = point_kwargs['atype'])
        elif point_kwargs['ptd_type'].lower() == 's':
            initial_system = am.defect.substitutional(initial_system, pos=point_kwargs['pos'],atype = point_kwargs['atype'])
        elif point_kwargs['ptd_type'].lower() == 'db':
            initial_system = am.defect.dumbbell(initial_system, pos=point_kwargs['pos'],db_vect=point_kwargs['db_vect'])
        else:
            raise ValueError('Invalid Defect Type')
    currentSymbols = []

    for x in range(initial_system.natypes):  #Checking to see if the alteration of the system has added any new atom types
        currentSymbols.append(allSymbols[x]) #and adding the appropriate symbols for those new atoms

    initial_system.symbols = currentSymbols

    #Adding moving defects to the system in their start position

    start_system = initial_system

    for defectIndex in range(int(defect_pair_number)):
        point_kwargs = defect_mobility_kwargs['start'][defectIndex]
        if point_kwargs['ptd_type'].lower() == 'v':
            start_system = am.defect.vacancy(start_system, pos=point_kwargs['pos'])
        elif point_kwargs['ptd_type'].lower() == 'i':
            start_system = am.defect.interstitial(start_system, pos=point_kwargs['pos'],atype = point_kwargs['atype'])
        elif point_kwargs['ptd_type'].lower() == 'db':
            start_system = am.defect.dumbbell(start_system, pos=point_kwargs['pos'],db_vect=point_kwargs['db_vect'])
        elif point_kwargs['ptd_type'].lower() == 's':
            print('not implemented for subsutitutional defect type.  To simulate a substitutional vacancy jump, define the position of a subsitutional atom in the initial system, and make the end position of the vacancy the same position as the subsitutional')
        else:
            raise ValueError('Invalid Defect Type')

    #Checking again to see if symbols need to be added

    currentSymbols = []
    for x in range(start_system.natypes):
        currentSymbols.append(allSymbols[x])

    #Creating a list of atoms in the start system which the next segment uses to find the atom id for atoms in a certain position

    start_system.symbols = currentSymbols
    start_system_atoms = start_system.atoms
    start_natoms = start_system.natoms

    #Dumps the start system to be used for NEB simulations

    start_system_info = start_system.dump('atom_data', f='init.dat')

    #Check to see which defect type is being used, finding the position of that atom, extracting
    #the atom id, and then generating a list of new positions used to define the final system for
    #the neb simulation

    final_system = start_system
    movedAtomIndexes = []
    for defectIndex in range(int(defect_pair_number)):
        point_kwargs = defect_mobility_kwargs['end'][defectIndex] #End kwargs, used to define the end positions
        point_kwargs_start = defect_mobility_kwargs['start'][defectIndex] #Start kwargs, used to find the original position of the atoms
        if point_kwargs['ptd_type'].lower() == 'v':
            for x in range(start_natoms):
                xPos = round(start_system_atoms.pos[x,0],3) == round(point_kwargs['pos'][0],3)
                yPos = round(start_system_atoms.pos[x,1],3) == round(point_kwargs['pos'][1],3)
                zPos = round(start_system_atoms.pos[x,2],3) == round(point_kwargs['pos'][2],3)
                if ((xPos and yPos) and zPos):
                    final_system.atoms.pos[x] = point_kwargs_start['pos']
                    movedAtomIndexes.append(x)
        elif point_kwargs['ptd_type'].lower() == 'i':
            for x in range(start_natoms):
                xPos = round(start_system_atoms.pos[x,0],3) == round(point_kwargs_start['pos'][0],3)
                yPos = round(start_system_atoms.pos[x,1],3) == round(point_kwargs_start['pos'][1],3)
                zPos = round(start_system_atoms.pos[x,2],3) == round(point_kwargs_start['pos'][2],3)
                if ((xPos and yPos) and zPos):
                    final_system.atoms.pos[x] = point_kwargs['pos']
                    movedAtomIndexes.append(x)
        elif point_kwargs['ptd_type'].lower() == 's':
            print('not implemented for subsutitutional defect type.  To simulate a substitutional vacancy jump, define the position of a subsitutional atom in the initial system, and make the end position of the vacancy the same position as the subsitutional')
        elif point_kwargs['ptd_type'].lower() == 'db':
            for x in range(start_natoms):
                xPos = round(start_system_atoms.pos[x,0],3) == round(point_kwargs_start['pos'][0]-point_kwargs_start['db_vect'][0],3)
                yPos = round(start_system_atoms.pos[x,1],3) == round(point_kwargs_start['pos'][1]-point_kwargs_start['db_vect'][1],3)
                zPos = round(start_system_atoms.pos[x,2],3) == round(point_kwargs_start['pos'][2]-point_kwargs_start['db_vect'][2],3)
                if ((xPos and yPos) and zPos):
                    final_system.atoms.pos[x] = point_kwargs['pos']
                    movedAtomIndexes.append(x)
            for y in range(start_natoms):
                xPos = round(start_system_atoms.pos[y,0],3) == round(point_kwargs_start['pos'][0]+point_kwargs_start['db_vect'][0],3)
                yPos = round(start_system_atoms.pos[y,1],3) == round(point_kwargs_start['pos'][1]+point_kwargs_start['db_vect'][1],3)
                zPos = round(start_system_atoms.pos[y,2],3) == round(point_kwargs_start['pos'][2]+point_kwargs_start['db_vect'][2],3)
                if ((xPos and yPos) and zPos):
                    final_system.atoms.pos[y] = point_kwargs['pos']-point_kwargs['db_vect']
                    movedAtomIndexes.append(y)
            for z in range(start_natoms):
                xPos = round(start_system_atoms.pos[z,0],3) == round(point_kwargs['pos'][0],3)
                yPos = round(start_system_atoms.pos[z,1],3) == round(point_kwargs['pos'][1],3)
                zPos = round(start_system_atoms.pos[z,2],3) == round(point_kwargs['pos'][2],3)
                if ((xPos and yPos) and zPos):
                    final_system.atoms.pos[z] = point_kwargs['pos']+point_kwargs['db_vect']
                    movedAtomIndexes.append(z)
        else:
            raise ValueError('Invalid Defect Type')

    final_system_pos = final_system.atoms.pos[movedAtomIndexes]
    movedAtomIds = [x+1 for x in movedAtomIndexes]

    #Writing the final position of the moving atoms to be used in the final system

    with open('final.dat', 'w') as f:
        f.write('%i\n' % len(movedAtomIds))
        for x in range(len(movedAtomIds)):
            f.write('%i ' % movedAtomIds[x])
            for y in range(len(final_system_pos[x])):
                f.write('%.13f ' % final_system_pos[x][y])
            f.write('\n')

    #Get script's location
    script_dir = Path(__file__).parent
    # Get lammps units
    lammps_units = lmp.style.unit(potential.units)

    #Get lammps version date
    lammps_date = lmp.checkversion(lammps_command)['date']

    # Define lammps variables
    lammps_terms = {}
    lammps_terms['nreplicas'] = nreplicas
    lammps_terms['springconst'] = springconst
    lammps_terms['thermosteps'] = thermosteps
    lammps_terms['dumpsteps'] = dumpsteps
    lammps_terms['timestep'] = timestep
    lammps_terms['minsteps'] = minsteps
    lammps_terms['climbsteps'] = climbsteps
    lammps_terms['dmax'] = dmax
    lammps_terms['etol'] = etol
    lammps_terms['ftol'] = ftol
    lammps_terms['atomman_system_info'] = start_system_info
    lammps_terms['atomman_pair_info'] = potential.pair_info(start_system.symbols)
    lammps_terms['final_system'] = 'final.dat'

    # Set dump_modify_format based on lammps_date
    if lammps_date < datetime.date(2016, 8, 3):
        lammps_terms['dump_modify_format'] = '"%d %d %.13e %.13e %.13e %.13e %.13e %.13e %.13e"'
    else:
        lammps_terms['dump_modify_format'] = 'float %.13e'

    # Write lammps input script
    template_file = Path(script_dir, 'neb_lammps.template')
    input_file = 'neb_lammps.in'
    with open(template_file) as f:
        template = f.read()

    with open(input_file, 'w') as f:
        f.write(am.tools.filltemplate(template, lammps_terms, '<', '>'))

    #Running the calc_neb
    output = lmp.run(lammps_command, 'neb_lammps.in', mpi_command=mpi_command)
    neb = lmp.NEBLog()

    return neb

def process_input(input_dict, UUID=None, build=True):
    """
    Processes str input parameters, assigns default values if needed, and
    generates new, more complex terms as used by the calculation.

    Parameters
    ----------
    input_dict :  dict
        Dictionary containing the calculation input parameters with string
        values.  The allowed keys depends on the calculation style.
    UUID : str, optional
        Unique identifier to use for the calculation instance.  If not
        given and a 'UUID' key is not in input_dict, then a random UUID4
        hash tag will be assigned.
    build : bool, optional
        Indicates if all complex terms are to be built.  A value of False
        allows for default values to be assigned even if some inputs
        required by the calculation are incomplete.  (Default is True.)
    """

    # Set calculation UUID
    if UUID is not None:
        input_dict['calc_key'] = UUID
    else:
        input_dict['calc_key'] = input_dict.get('calc_key', str(uuid.uuid4()))

    # Set default input/output units

    iprPy.input.subset('units').interpret(input_dict)

    # These are calculation-specific default strings
    input_dict['numberreplicas'] = input_dict.get('numberreplicas', '8')
    input_dict['springconst'] = input_dict.get('springconst', '5')
    input_dict['thermosteps'] = input_dict.get('thermosteps','50')
    input_dict['timestep'] = input_dict.get('timestep', '0.01')
    input_dict['dumpsteps'] = input_dict.get('dumpsteps', '10000')
    input_dict['minsteps'] = input_dict.get('minsteps', '10000')
    input_dict['climbsteps'] = input_dict.get('climbsteps', '10000')

    # These are calculation-specific default booleans
    # None for this calculation

    # These are calculation-specific default integers
    # None for this calculation

    # These are calculation-specific default unitless floats
    # None for this calculation

    # These are calculation-specific default floats with units
    # None for this calculation

    #Using lammps_minimize to gather most of the information about
    iprPy.input.subset('lammps_minimize').interpret(input_dict)

    # Check lammps_command and mpi_command
    iprPy.input.subset('lammps_commands').interpret(input_dict)

    # Load potential
    iprPy.input.subset('lammps_potential').interpret(input_dict)

    # Load the initial system
    iprPy.input.subset('atomman_systemload').interpret(input_dict, build=build)

    # Construct initialsystem by manipulating ucell system
    iprPy.input.subset('atomman_systemmanipulate').interpret(input_dict, build=build)

    #Using pointdefect to define initial and final positions for atoms in the strucutre

    iprPy.input.subset('pointdefectmobility').interpret(input_dict, build=build)

if __name__ == '__main__':
    main(*sys.argv[1:])