# -*- coding: UTF-8 -*-
import networkx as nx
import random
import copy
import os
import BigPoint
import time

# 3条最优路径,且同时产生
# 在slack允许的情况下找等待时间最长的点进行插入
# 对待插入的点，随机选择一天插入
# 对每一条数据进行测试
# Super-POI的值如果小于1000的话，增大10倍。如果原始值为0，那么设置为5000

def createGraph(myGraph, fileName):
    categoryMap = {1:70, 2:40, 3:20, 4:10, 5:5}

    file = open(fileName)
    # 略过两行注释
    file.readline()
    file.readline()
    lists = file.readline().strip().split(';')
    # print(lists)
    G.graph['nb_nodes'] = int(lists[0])
    G.graph['RouteMaxDuration'] = int(lists[1])
    G.graph['TotalMaxDuration'] = int(lists[2])
    print(G.graph)

    # 略过两行注释
    file.readline()
    file.readline()
    for i in range(G.graph['nb_nodes']):
        lists = file.readline().strip().split(';')
        node = int(lists[0])
        G.add_node(node)
        G.nodes[node]['ID'] = node
        G.nodes[node]['ServiceTime'] = categoryMap[int(lists[1])]
        G.nodes[node]['Priority'] = int(lists[2])
        G.nodes[node]['Profit'] = int(lists[3])
        G.nodes[node]['Probability'] = float(lists[4])
        if int(lists[1] == 1):
            if tmpP <= 0:
                tmpP = 5000
            if tmpP < 1000:
                tmpP = tmpP * 10
            G.nodes[node]['Profit'] = tmpP
        TWS = lists[5].split(',')
        # for TW in TWS:
        timeWindows = [{} for _ in range(4)]
        for TW in TWS:
            window = {}
            params = TW.split(':')
            window['day'] = int(params[0])
            window['opentime'] = int(params[1].split('-')[0])
            window['closetime'] = int(params[1].split('-')[1])
            index = int(params[0])
            if timeWindows[index].get('day', False) == False:
                timeWindows[index] = window
            else:
                timeWindows[index]['closetime'] = window['opentime']
        for index, TW in enumerate(timeWindows):
            if TW == {}:
                opentime = random.randrange(0, 600)
                closetime = random.randrange(0, 600)
                if opentime > closetime:
                    opentime, closetime = closetime, opentime
                while closetime - opentime < 200:
                    opentime = random.randrange(0, 600)
                    closetime = random.randrange(0, 600)
                    if opentime > closetime:
                        opentime, closetime = closetime, opentime
                TW['day'] = index
                TW['opentime'] = opentime
                TW['closetime'] = closetime
        G.nodes[node]['TimeWindows'] = tuple(timeWindows[:])
    # print(G.nodes.data())

    # 略过两行注释
    file.readline()
    file.readline()
    arcs = file.readlines()
    for line in arcs:
        lists = line.strip().split(';')
        s = int(lists[0]); t = int(lists[1]); duration = int(lists[2])
        G.add_edge(s, t)
        G.edges[s, t]['duration'] = duration
    # print(G.edges.data())

    file.close()

def isCompleteGraph(G):
    nodeNum = len(G.nodes)
    edgeNum = len(G.edges)
    print(nodeNum * (nodeNum - 1) / 2)
    print(edgeNum)

def calcuSlack(myGraph, travelPath, node, insertLocation, timeParamDict):
    # 插入到insertLocation之前
    travelPath.insert(insertLocation, {'ID':node['ID']})
    travelPath[insertLocation]['aTime'] = timeParamDict['arriveTimeToCandiNode']
    travelPath[insertLocation]['dTime'] = timeParamDict['deparTimeOnCandiNode']
    travelPath[insertLocation]['closetime'] = node['TimeWindows'][timeParamDict['day']]['closetime']
    preComponentID = node['ID']
    nextComponentID = -1

    # 对插入点之后的点进行时间更新
    for index, pathComponent in enumerate(travelPath[insertLocation+1:]):
        # !!!注意index的值!!!
        index = index + insertLocation + 1

        nextComponentID = pathComponent['ID']
        duration = myGraph.edges[preComponentID, nextComponentID]['duration']
        arriveToNextComponent = travelPath[index-1]['dTime'] + duration
        window = myGraph.nodes[nextComponentID]['TimeWindows'][timeParamDict['day']]
        deparTimeOnNextComponent = max(arriveToNextComponent, window['opentime']) + myGraph.nodes[nextComponentID]['ServiceTime']
        travelPath[index]['aTime'] = arriveToNextComponent
        travelPath[index]['dTime'] = deparTimeOnNextComponent
        travelPath[index]['closetime'] = window['closetime']
        preComponentID = nextComponentID

    # 计算终点的slack值
    tmpSlack = travelPath[-1]['slack'] = myGraph.graph['RouteMaxDuration'] - travelPath[-1]['aTime']
    totalSlack = tmpSlack
    # 全体slack更新
    travelPath[0]['closetime'] = 10000000
    for pathComponent in travelPath[-2::-1]:
        pathComponent['slack'] = min(pathComponent['closetime']-pathComponent['dTime'], tmpSlack)
        tmpSlack = pathComponent['slack']
        totalSlack = totalSlack + tmpSlack

    return totalSlack, travelPath

# 从头重新计算各自的时间
def calcuSlack2(myGraph, travelPath, node, insertLocation, timeParamDict):
    # 插入到insertLocation之前
    travelPath.insert(insertLocation, {'ID':node['ID']})
    # travelPath[insertLocation]['aTime'] = timeParamDict['arriveTimeToCandiNode']
    # travelPath[insertLocation]['dTime'] = timeParamDict['deparTimeOnCandiNode']
    # travelPath[insertLocation]['closetime'] = node['TimeWindows'][timeParamDict['day']]['closetime']
    preComponentID = travelPath[0]['ID']
    nextComponentID = -1

    # 对插入点之后的点进行时间更新
    for index, pathComponent in enumerate(travelPath[1:]):
        # !!!注意index的值!!!
        index = index + 1

        nextComponentID = pathComponent['ID']
        duration = myGraph.edges[preComponentID, nextComponentID]['duration']
        # if index == 1:
        #     print(travelPath[index-1]['dTime'], duration)
        arriveToNextComponent = travelPath[index-1]['dTime'] + duration
        window = myGraph.nodes[nextComponentID]['TimeWindows'][timeParamDict['day']]
        deparTimeOnNextComponent = max(arriveToNextComponent, window['opentime']) + myGraph.nodes[nextComponentID]['ServiceTime']
        travelPath[index]['aTime'] = arriveToNextComponent
        travelPath[index]['dTime'] = deparTimeOnNextComponent
        travelPath[index]['closetime'] = window['closetime']
        travelPath[index]['waitTime'] = window['opentime'] - arriveToNextComponent
        if travelPath[index]['waitTime'] < 0:
            travelPath[index]['waitTime'] = 0
        preComponentID = nextComponentID

    # 计算终点的slack值
    tmpSlack = travelPath[-1]['slack'] = myGraph.graph['RouteMaxDuration'] - travelPath[-1]['aTime']
    totalSlack = tmpSlack
    # 全体slack更新
    travelPath[0]['closetime'] = 10000000
    for pathComponent in travelPath[-2::-1]:
        # print(pathComponent)
        pathComponent['slack'] = min(pathComponent['closetime'] - pathComponent['dTime'], tmpSlack)
        tmpSlack = pathComponent['slack']
        totalSlack = totalSlack + tmpSlack

    return totalSlack, travelPath

def toptw(startDestList, myGraph, bigPointDir):

    # 用来记录加入到路径中的点
    existList = []

    routeMaxDuration = myGraph.graph['RouteMaxDuration']
    threeDayPath = []
    threeDayProfitList = [0, 0, 0]
    threeDayBestRatioList = [-1, -1, -1]
    for i, val in enumerate(startDestList):
        s = val['s']
        t = val['t']
        existList.append(s)
        existList.append(t)
        tP = [{'ID':s}, {'ID':t}]
        duration = myGraph.edges[s, t]['duration']
        startSlack = 0
        destSlack = routeMaxDuration - duration
        tP[0]['slack'] = startSlack
        tP[0]['aTime'] = 0
        tP[0]['dTime'] = 0
        tP[0]['waitTime'] = 0
        tP[1]['slack'] = destSlack
        tP[1]['aTime'] = duration
        tP[1]['dTime'] = duration
        # 终点的等待时间，如何确定呢
        tP[1]['waitTime'] = myGraph.nodes[t]['TimeWindows'][i+1]['opentime'] - duration
        if tP[1]['waitTime'] < 0:
            tP[1]['waitTime'] = 40
        threeDayPath.append(tP)

    finish = False
    while finish == False:
        finish = True
        # top-k最优路径
        # k = 5
        # bestKPath = []
        # bestKRatio = []
        # bestKProfit = []
        # bestKNodeId = []
        # 寻找一个合适点进行插入
        for data in myGraph.nodes.data():
            node = data[1]
            if node['ID'] in existList:
                continue

            threeDayRatioList = [-1, -1, -1]
            threeDayTmpPathList = [[] for i in range(3)]
            threeDayTmpProfitList = [x for x in threeDayProfitList]

            # 遍历三条路径，选择一条最适合的插入这个点
            for day, travelPath in enumerate(threeDayPath):
                day = day + 1
                # 找一个最匹配的slack插入到它前边
                bestMatch = -1
                tmpWaitTime = -1
                gapTime = 10000000
                for index, _ in enumerate(travelPath[1:]):
                    # index值是阶段后的列表中的索引值
                    index = index + 1
                    preComponent = travelPath[index-1]
                    preToCandiNodeDuration = myGraph.edges[preComponent['ID'], node['ID']]['duration']
                    arriveTimeToCandiNode = preComponent['dTime'] + preToCandiNodeDuration
                    if (arriveTimeToCandiNode > routeMaxDuration
                    or max(arriveTimeToCandiNode, node['TimeWindows'][day]['opentime']) + node['ServiceTime'] > routeMaxDuration
                    or node['TimeWindows'][day]['closetime'] - arriveTimeToCandiNode < node['ServiceTime']):
                        break

                    deparTimeOnCandiNode = max(arriveTimeToCandiNode, node['TimeWindows'][day]['opentime']) + node['ServiceTime']
                    curComponent = travelPath[index]
                    candiNodeToCurNodeDuration = myGraph.edges[node['ID'], curComponent['ID']]['duration']
                    arriveTimeToCurNode = deparTimeOnCandiNode + candiNodeToCurNodeDuration
                    # 由于插入这个点增加的时间
                    # t1为加入的点带来的时间duraion，t2为原先的pre到cur的duration
                    t1 = arriveTimeToCurNode - preComponent['dTime']
                    t2 = curComponent['aTime'] - preComponent['dTime']
                    deltaTime = t1 - t2
                    # 在slack允许的情况下找等待时间最长的点进行插入
                    curGapTime = curComponent['slack'] - deltaTime
                    if curGapTime < 0:
                        continue
                    if travelPath[index]['waitTime'] > tmpWaitTime:
                        bestMatch = index
                        tmpWaitTime = travelPath[index]['waitTime']

                    # # 更新当前的间隔值
                    # if curGapTime < gapTime:
                    #     gapTime = curGapTime
                    #     bestMatch = index

                # 没有合适的插入点
                if bestMatch == -1:
                    continue

                # 计算插入后的总收益与slack的比值
                tmpTotalProfit = threeDayProfitList[day-1] + node['Profit']
                tmpTravelPath = [copy.copy(x) for x in travelPath]
                timeParamDict = {
                                'arriveTimeToCandiNode':arriveTimeToCandiNode,
                                'deparTimeOnCandiNode':deparTimeOnCandiNode,
                                'arriveTimeToCurNode':arriveTimeToCurNode,
                                'day':day
                                }
                tmpTotalSlack, tmpTravelPath = calcuSlack2(myGraph, tmpTravelPath, node, bestMatch, timeParamDict)
                if float(tmpTotalSlack) == 0:
                    continue
                ratio = float(tmpTotalProfit) / float(tmpTotalSlack)
                threeDayRatioList[day-1] = ratio
                threeDayTmpPathList[day-1] = [copy.copy(x) for x in tmpTravelPath]
                threeDayTmpProfitList[day-1] = tmpTotalProfit

            # 随机选择一天进行插入
            accept = False

            dieTime = 0
            while accept == False:
                randomDay = random.randrange(0, 3)
                if threeDayRatioList[randomDay] > threeDayBestRatioList[randomDay]:
                    threeDayBestRatioList[randomDay] = threeDayRatioList[randomDay]
                    threeDayPath[randomDay] = [copy.copy(x) for x in threeDayTmpPathList[randomDay]]
                    threeDayProfitList[randomDay] = threeDayTmpProfitList[randomDay]
                    accept = True
                dieTime = dieTime + 1
                if dieTime > 15:
                    break

            # 取threeDayRatioList中最大值的那条路就是要插入的路径
            # accept = False
            # for i in range(3):
            #     if accept == False:
            #         bestRatio = max(threeDayRatioList)
            #         whichDay = threeDayRatioList.index(bestRatio)
            #         if bestRatio > threeDayBestRatioList[whichDay]:
            #             threeDayBestRatioList[whichDay] = bestRatio
            #             threeDayPath[whichDay] = [copy.copy(x) for x in threeDayTmpPathList[whichDay]]
            #             threeDayProfitList[whichDay] = threeDayTmpProfitList[whichDay]
            #             accept = True
            #         threeDayRatioList[whichDay] = -5

            if accept == True:
                existList.append(node['ID'])
                finish = False

    profitSum = sum(threeDayProfitList)
    bigPointPaths = os.listdir(bigPointDir)
    for day, path in enumerate(threeDayPath):
        print(path)
        for component in path:
            if str(component['ID']) in bigPointPaths:
                smallG = nx.read_gml(bigPointDir + '\\' + str(component['ID']))
                smallG = nx.convert_node_labels_to_integers(smallG)
                tmpP = BigPoint.dfsTraverse(smallG, component['aTime'] + component['waitTime'], component['dTime'], day+1)
                profitSum = profitSum + tmpP
                profitSum = profitSum - myGraph.nodes[component['ID']]['Profit']
        print()
    print('total profit:', profitSum)

    #         # 检查当前点是否可以插入到bestKPath中
    #         # 当前的ratio比存储的k条路径中的最差路径好
    #         if len(bestKRatio) < k:
    #             bestKPath.append([copy.copy(x) for x in tmpTravelPath])
    #             bestKRatio.append(ratio)
    #             bestKProfit.append(tmpTotalProfit)
    #             bestKNodeId.append(node['ID'])
    #             # 代表还有比较好的点
    #             finish = False
    #         elif ratio > min(bestKRatio):
    #             index = bestKRatio.index(min(bestKRatio))
    #             del bestKPath[index]
    #             del bestKRatio[index]
    #             del bestKNodeId[index]
    #             del bestKProfit[index]
    #             bestKPath.append([copy.copy(x) for x in tmpTravelPath])
    #             bestKRatio.append(ratio)
    #             bestKProfit.append(tmpTotalProfit)
    #             bestKNodeId.append(node['ID'])
    #             # 代表还有比较好的点
    #             finish = False

    #     # 从k个候选者中随机挑出一个插入,
    #     # ！！！！！注意k个候选者没有选满的情况啊啊啊啊啊啊啊啊啊啊
    #     # 更新路径travelPath
    #     length = min(k, len(bestKPath))
    #     if length == 0:
    #         continue
    #     selectNode = random.randrange(0, length)
    #     travelPath = [copy.copy(x) for x in bestKPath[selectNode]]
    #     bestRatio = bestKRatio[selectNode]
    #     totalProfit = bestKProfit[selectNode]
    #     existList.append(bestKNodeId[selectNode])
    # # print(travelPath)
    # return travelPath;

# os.chdir('instances')
# fileList = os.listdir('.')
# for f in fileList:
#     if os.path.isfile(f):
#         G = nx.Graph()
#         createGraph(G, f)
#         ll = random.sample(G.nodes, 6)
#         # print(ll)
#         startDestList = [{'s':ll[0],'t':ll[1]}, {'s':ll[2],'t':ll[3]}, {'s':ll[4],'t':ll[5]}]
#         # print(startDestList)
#         toptw(startDestList, G, f.split('.')[0])

f = 'd:\PythonCode\TOPTW\instances\TPA_6_40-3.txt'
G = nx.Graph()
createGraph(G, f)
ll = random.sample(G.nodes, 6)
# print(ll)
startDestList = [{'s':ll[0],'t':ll[1]}, {'s':ll[2],'t':ll[3]}, {'s':ll[4],'t':ll[5]}]
# print(startDestList)
t1 = time.time()
toptw(startDestList, G, f.split('.')[0])
t2 = time.time()
print('time:', t2 - t1)


import numpy

import chainer
from chainer.backends import cuda
from chainer.backends import intel64
from chainer import configuration
from chainer import function_node
from chainer.utils import argument
from chainer.utils import type_check

class Dropout(function_node.FunctionNode):

    """Dropout regularization."""

    mask = None

    def __init__(self, dropout_ratio):
        if not 0.0 <= dropout_ratio < 1.0:
            raise ValueError('dropout_ratio must be in the range [0, 1)')
        self.dropout_ratio = dropout_ratio

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 1)
        type_check.expect(in_types[0].dtype.kind == 'f')

    def forward(self, x):
        if (intel64.should_use_ideep('>=auto')
                and intel64.inputs_all_ready(x)):
            return self._forward_ideep(x)

        if self.mask is not None:
            y = x[0] * self.mask
        else:
            scale = x[0].dtype.type(1. / (1 - self.dropout_ratio))
            xp = cuda.get_array_module(*x)
            if xp == numpy:
                flag = xp.random.rand(*x[0].shape) >= self.dropout_ratio
                self.mask = scale * flag
                y = x[0] * self.mask
            else:
                rand = xp.random.rand(*x[0].shape, dtype=numpy.float32)
                self.mask, y = cuda.elementwise(
                    'T x, R r, T scale, T ratio', 'T mask, T y',
                    '''
                    mask = (r >= ratio) * scale;
                    y = x * mask;
                    ''',
                    'dropout_fwd',
                )(x[0], rand, scale, self.dropout_ratio)
        return y,

    def _forward_ideep(self, x):
        mask, y = intel64.ideep.dropout.Forward(
            intel64.ideep.array(x[0]),
            self.dropout_ratio)
        self.mask = mask
        return y,

    def backward(self, x, gy):
        return DropoutGrad(self.mask).apply(gy)

class DropoutGrad(function_node.FunctionNode):
    """Computes the gradient of the Dropout function."""

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

    def forward(self, inputs):
        if (intel64.should_use_ideep('>=auto')
                and intel64.inputs_all_ready(inputs)):
            return self._forward_ideep(inputs)

        y = inputs[0] * self.mask
        return y,

    def _forward_ideep(self, inputs):
        return intel64.ideep.dropout.Backward(
            intel64.ideep.array(self.mask),
            intel64.ideep.array(inputs[0])),

    def backward(self, indexes, gy):
        return DropoutGrad(self.mask).apply(gy)

def dropout(x, ratio=.5, **kwargs):
    """dropout(x, ratio=.5)

    Drops elements of input variable randomly.

    This function drops input elements randomly with probability ``ratio`` and
    scales the remaining elements by factor ``1 / (1 - ratio)``. In testing
    mode, it does nothing and just returns ``x``.

    .. warning::

       ``train`` argument is not supported anymore since v2.
       Instead, use ``chainer.using_config('train', boolean)``.
       See :func:`chainer.using_config`.

    Args:
        x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
        :class:`cupy.ndarray`):
            Input variable. A :math:`(s_1, s_2, ..., s_N)` -shaped float array.
        ratio (float):
            Dropout ratio. The ``ratio`` must be ``0.0 <= ratio < 1.0``.

    Returns:
        ~chainer.Variable: Output variable.

    See the paper by G. Hinton: `Improving neural networks by preventing \
    co-adaptation of feature detectors <https://arxiv.org/abs/1207.0580>`_.

    .. admonition:: Example

        >>> x = np.array([[-1, 0], [2, -3], [-2, 1]], np.float32)
        >>> with chainer.using_config('train', True):
        ...     y = F.dropout(x)
        >>> y.data
        array([[-2.,  0.],
               [ 4., -6.],
               [-0.,  2.]], dtype=float32)
        >>> with chainer.using_config('train', True):
        ...     y = F.dropout(x, ratio=0.0) \
# dropout returns original input if ratio=0.0
        >>> (x == y.data).all()
        True
        >>> with chainer.using_config('train', False):
        ...     y = F.dropout(x) \
# dropout in test mode returns original input
        >>> (x == y.data).all()
        True

    """
    argument.check_unexpected_kwargs(
        kwargs, train='train argument is not supported anymore. '
        'Use chainer.using_config')
    argument.assert_kwargs_empty(kwargs)

    if configuration.config.train:
        return Dropout(ratio).apply((x,))[0]
    return chainer.as_variable(x)


import logging

import tensorflow as tf

LOGGER = logging.getLogger('cve-score')

def _parse_encoder(params):
    '''Unpacks encoding parameters into at data specifying `tf.Tensor`.
    Returns a triple of the form (<name>, <shape>, <dtype>).
    '''
    if 'vocabulary' in params:
        return (params['key'], [len(params['vocabulary'])], tf.float32)
    if params.get('isLabel', False):
        return (params['key'], [1], tf.int64)
    if params['key'] == 'weight':
        return ('weight', [1], tf.float32)

    raise ValueError('invalid encoding params %s' % params)

def get_parser(config):
    '''Converts a config object into protobuf parser.

    Arguments:
        config  [list] list of dictionaries, each defining an encoder.

    Returns a function with the signature `<protobuf> => (<dict>, <tensor>)`.
    The input is a serialized `tf.train.Example` object, and the output
    is a pair of features/label tensors.
    '''
    decoders = {
        name: tf.FixedLenFeature(shape, dtype)
        for (name, shape, dtype) in map(_parse_encoder, config)
    }
    LOGGER.debug('decoders => %s', decoders)

    label_keys = [
        item['key'] for item in config if item.get('isLabel', False)
    ]
    if len(label_keys) != 1:
        raise ValueError('missing or multiple labels: %s' % label_keys)

    def parser(serialized):
        example = tf.parse_single_example(serialized, decoders)
        label = example.pop(label_keys[0])
        return (example, label)

    return parser

def get_feature_columns(config):
    '''Converts a config object into list of `tf.feature_column` objects
    for use with `tf.estiimator` module.

    Arguments:
        config  [list] list of dictionaries, each defining an encoder.
    '''
    features = [item for item in config if not item.get('isLabel')]
    return [
        tf.feature_column.numeric_column(key, shape, dtype=dtype)
        for (key, shape, dtype) in map(_parse_encoder, features)
    ]


conjunto = "Italia", "Grecia", "Italia", "China", "Grecia", "Brasil"
paises = set(conjunto)
europa = set({"Francia", "Italia", "España", "Grecia", "Alemania", "Portugal"})

def listado(conjunto):
	for pais in conjunto:
		print(pais.ljust(15), end="")

paises.remove("China")
paises.add("Turquia")
paises.add("Alemania")

print("Contenido actual del listado de paises: ")
listado(paises)

print("\n\nContenido actual del listado de Europa: ")
listado(europa)

print("\n\nUnion de los dos conjuntos: \n")
listado(paises | europa)

print("\n\nIntersección de los dos conjuntos (elementos en común): ")
listado(paises.intersection(europa))

print("\n\nDiferencia de los dos conjuntos (elementos de paises que no están en europa): ")
listado(paises.difference(europa))

print("\n\nDiferencia simétrica de los dos conjuntos (elementos que no están a la vez en ambos conjuntos: ")
listado(paises.symmetric_difference(europa))

paises.update(europa)
print("\n\nActualización de paises con el contenido de europa: ")
listado(paises)


#!python

# get adjs
adjs_subset = {'happy'}

# get nouns
nouns_subset = {}
nouns_fl = open('../merged_nouns_sorted.txt', 'r')
lines = nouns_fl.readlines()

for line in lines:
    line_splits = line.strip().split(' ')
    nouns_subset[line_splits[0]] = line_splits[1]

# get anps
anps_subset = {}
anps_fl = open('../merged_anps.txt', 'r')
lines = anps_fl.readlines()

cc = 1
for line in lines:
    line = line.strip()
    line_splits = line.split('_')
    adj = line_splits[0]
    noun = line_splits[1]

    if adj in adjs_subset and noun in nouns_subset:
        anps_subset[line] = cc

    cc += 1

#print anps
anps = sorted(anps_subset.items(), key=lambda x:x[0])
f = open("anps_happy.txt","w")
for anp in anps:
    f.write(anp[0] + ' ' + str(anp[1]) + '\n')
f.close()

#gen adjs and nouns
adjs = {}
nouns = {}
for anp in anps_subset.keys():
    anp = anp.strip()
    anp_splits = anp.split('_')
    adj = anp_splits[0]
    noun = anp_splits[1]

    if not adj in adjs:
        adjs[adj] = 0
    adjs[adj] += 1

    if not noun in nouns:
        nouns[noun] = 0
    nouns[noun] += 1

#print adjs and nouns
adjs_sorted = sorted(adjs.items(), key=lambda x:x[1], reverse=True)
f = open("adjectives_happy_sorted.txt","w")
for adj in adjs_sorted:
    f.write(adj[0] + ' ' + str(adj[1]) + '\n')
f.close()

adjs_sorted = sorted(adjs.items(), key=lambda x:x[0])
f = open("adjectives_happy.txt","w")
i = 1
for adj in adjs_sorted:
    f.write(adj[0] + ' ' + str(i) + '\n')
    i += 1
f.close()
#
nouns_sorted = sorted(nouns.items(), key=lambda x:x[1], reverse=True)
f = open("nouns_happy_sorted.txt","w")
for noun in nouns_sorted:
    f.write(noun[0] + ' ' + str(noun[1]) + '\n')
f.close()

nouns_sorted = sorted(nouns.items(), key=lambda x:x[0])
f = open("nouns_happy.txt","w")
i = 1
for noun in nouns_sorted:
    f.write(noun[0] + ' ' + str(i) + '\n')
    i += 1
f.close()


from __future__ import print_function

import os
import numpy as np
from skimage.io import imread

image_rows = int(256)
image_cols = int(256)
image_depth = 16

def create_train_data(options, labels):
    train_data_path = options.outputdir+"/train/"
    mask_data_path = options.outputdir+'/masks/'
    dirs = os.listdir(train_data_path)
    total = int(len(dirs)*16*2)

    imgs = np.ndarray((total, image_depth, image_rows, image_cols), dtype=np.uint8)
    imgs_mask = np.ndarray((total, image_depth, image_rows, image_cols), dtype=np.uint8)

    imgs_temp = np.ndarray((total, image_depth//2, image_rows, image_cols), dtype=np.uint8)
    imgs_mask_temp = np.ndarray((total, image_depth//2, image_rows, image_cols), dtype=np.uint8)

    i = 0
    print('-'*30)
    print('Creating training images...')
    print('-'*30)
    for dirr in sorted(os.listdir(train_data_path)):
        j = 0
        dirr = train_data_path+"/"+dirr
        if not os.path.isdir(dirr):
            continue
        images = sorted(os.listdir(dirr))
        count = total
        for image_name in images:
            if not image_name.endswith('.png'):
                print('Ignored invalid file: ', image_name)
                continue
            img = imread(os.path.join(dirr, image_name), as_gray=True)
            img = img.astype(np.uint8)
            img = np.array([img])
            imgs_temp[i, j] = img
            j += 1
            if j % (image_depth/2) == 0:
                j = 0
                i += 1
                print('Done: {0}/{1} 3d images'.format(i, count), end='\r')

    for x in range(0, imgs_temp.shape[0]-1):
        imgs[x] = np.append(imgs_temp[x], imgs_temp[x+1], axis=0)

    print('Loading of train data done.')
    imgs = preprocess(imgs)
    np.save(options.outputdir+'/imgs_train.npy', imgs)
    print('Training NPY saved at: ' + options.outputdir + '/imgs_train.npy')

    print('-' * 30)
    print('Creating labeled images...')
    print('-' * 30)

    for label in labels:
        create_mask_data(options, label)
    print('Loading all labels done.')

    # Convert the whole volume to .npy
    print('Processing the whole mask...')
    i = 0
    for dirr in sorted(os.listdir(train_data_path)):
        j = 0
        dirr = mask_data_path + dirr + '/whole'
        if not os.path.exists(dirr):
            return
        images = sorted(file for file in os.listdir(dirr) if file.endswith('.png'))
        count = total
        for mask_name in images:
            img_mask = imread(dirr + '/' + mask_name, as_gray=True)
            img_mask = img_mask.astype(np.uint16)
            img_mask = np.array([img_mask])
            imgs_mask_temp[i, j] = img_mask

            j += 1
            if j % (image_depth / 2) == 0:
                j = 0
                i += 1
                print('Done: {0}/{1} 3d images'.format(i, count), end='\r')

    for x in range(0, imgs_mask_temp.shape[0] - 1):
        imgs_mask[x] = np.append(imgs_mask_temp[x], imgs_mask_temp[x + 1], axis=0)

    imgs_mask = preprocess(imgs_mask)
    np.save(options.outputdir + '/imgs_mask_train.npy', imgs_mask)
    print('Saving to .npy files: done.')

def create_mask_data(options, label):
    train_data_path = options.outputdir+"/train/"
    mask_data_path = options.outputdir+'/masks/'
    dirs = os.listdir(train_data_path)
    total = int(len(dirs)*16*2)

    imgs_mask = np.ndarray((total, image_depth, image_rows, image_cols), dtype=np.uint8)
    imgs_mask_temp = np.ndarray((total, image_depth//2, image_rows, image_cols), dtype=np.uint8)

    i = 0
    print('-' * 30)
    print('Processing label ' + str(label))
    for dirr in sorted(os.listdir(train_data_path)):
        if not os.path.isdir(train_data_path + dirr):
            continue
        j = 0
        dirr = mask_data_path + dirr + '/label-' + "{:0>5}".format(str(label))

        # Label did not exist
        if not os.path.exists(dirr):
            return
        images = sorted(file for file in os.listdir(dirr) if file.endswith('.png'))
        count = total
        for mask_name in images:
            img_mask = imread(dirr + '/' + mask_name, as_gray=True)
            img_mask = img_mask.astype(np.uint16)
            img_mask = np.array([img_mask])
            imgs_mask_temp[i, j] = img_mask

            j += 1
            if j % (image_depth / 2) == 0:
                j = 0
                i += 1
                print('Done: {0}/{1} 3d images'.format(i, count), end='\r')

    for x in range(0, imgs_mask_temp.shape[0] - 1):
        imgs_mask[x] = np.append(imgs_mask_temp[x], imgs_mask_temp[x + 1], axis=0)

    imgs_mask = preprocess(imgs_mask)
    np.save(options.outputdir + '/label-' + "{:0>5}".format(str(label)) + '_mask_train.npy', imgs_mask)
    print('Size of .npy file: ' + str(imgs_mask.shape))
    print('NPY for label ' + "{:0>5}".format(str(label)) + ' saved.')

def preprocess(imgs):
    imgs = np.expand_dims(imgs, axis=4)
    return imgs

def preprocess_squeeze(imgs):
    imgs = np.squeeze(imgs, axis=4)
    return imgs

if __name__ == '__main__':
    create_train_data()


import os
import re
from mp3_tagger import MP3File

basepath = input('music folder path :')
rename = input("do you want to rename the songs? Y/N ")
blacklist = ["-", ".","[" , "]" , "(", ")" , "_" , "YouTube" , "Video" , "Official", "mp3" , "Audio" , "Lyric" , "Clip"]

for entry in os.listdir(basepath):
 if entry.endswith(".mp3"):
   print(entry)
   entry_artist = entry.partition("-")[0]
   entry_artist =  re.sub(r'|'.join(map(re.escape, blacklist)), '', entry_artist)
   print ("artist 1 : ", entry_artist)
   entry_title = entry.partition("-")[2]
   artist = ""
   if "ft. " in entry_title :
       artist = entry_title.partition("ft. ")[2]
       artist =  re.sub(r'|'.join(map(re.escape, blacklist)), '', artist)
       print ("artist 2 : " , artist)
       entry_title = entry_title.partition("ft. ")[0]
   entry_title = entry_title.partition("(" or "[" or "." )[0]
   entry_title =  re.sub(r'|'.join(map(re.escape, blacklist)), '', entry_title)
   print("song name : ", entry_title)
   entry_name = entry_title
   p= (basepath + "/")
   if (entry_name!=""):
       audiofile = MP3File( p + entry)
       audiofile.artist = (entry_artist + " / " + artist)
       audiofile.song = (entry_title)
       audiofile.save()
       try :
        if (rename=="Y") or (rename=="y"):
           os.rename ( p + entry , p + entry_name + ".mp3")
       except :
           continue


from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
import sqlite3

class Event(Resource):
    TABLE_NAME = 'events'

    parser = reqparse.RequestParser()
    # Add argument date
    parser.add_argument('name',
        type=str,
        required=True,
        help="This field cannot be left blank!"
    )
    parser.add_argument('date',
        type=str,
        required=True,
        help="This field cannot be left blank!"
    )

    parser.add_argument('lieu',
        type=str,
        required=True,
        help="This field cannot be left blank!"
    )

    parser.add_argument('objet',
        type=str,
        required=True,
        help="This field cannot be left blank!"
    )

    @jwt_required()
    def get(self, name):
        event = self.find_by_name(name)
        if event:
            return event
        return {'message': 'Event not found'}, 404

    @classmethod
    def find_by_name(cls, name):
        #Find an event by its name
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "SELECT * FROM {table} WHERE name=?".format(table=cls.TABLE_NAME)
        result = cursor.execute(query, (name,))
        row = result.fetchone()
        connection.close()

        if row:
            return {'event': {'name': row[0], 'date': row[1], 'lieu': row[2]}}

    def post(self, name):
        if self.find_by_name(name):
            return {'message': "An event with name '{}' already exists.".format(name)}

        data = Event.parser.parse_args()

        event = {'name': name, 'date': data['date'], 'lieu': data['lieu'], 'objet': data['objet'] }

        try:
            Event.insert(event)
        except:
            return {"message": "An error occurred inserting the event."}

        return event

    @classmethod
    def insert(cls, event):
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "INSERT INTO {table} VALUES(?, ?, ?, ?)".format(table=cls.TABLE_NAME)
        cursor.execute(query, (event['name'], event['date'], event['lieu'], event['objet']))

        connection.commit()
        connection.close()

    @jwt_required()
    def delete(self, name):
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "DELETE FROM {table} WHERE name=?".format(table=self.TABLE_NAME)
        cursor.execute(query, (name,))

        connection.commit()
        connection.close()

        return {'message': 'Event deleted'}

    @jwt_required()
    def put(self, name):
        data = Event.parser.parse_args()
        event = self.find_by_name(name)
        updated_event = {'name': name, 'date': data['date'], 'lieu': ['lieu'], 'objet': ['objet']}
        if event is None:
            try:
                Event.insert(updated_event)
            except:
                return {"message": "An error occurred inserting the event."}
        else:
            try:
                Event.update(updated_event)
            except:
                raise
                return {"message": "An error occurred updating the event."}
        return updated_event

    @classmethod
    def update(cls, event):
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "UPDATE {table} SET date=? WHERE name=?".format(table=cls.TABLE_NAME)
        cursor.execute(query, (event['date'], event['name']))

        connection.commit()
        connection.close()

class EventList(Resource):
    TABLE_NAME = 'events'

    def get(self):
        connection = sqlite3.connect('data.db')
        cursor = connection.cursor()

        query = "SELECT * FROM {table}".format(table=self.TABLE_NAME)
        result = cursor.execute(query)
        events = []
        for row in result:
            events.append({'name': row[0], 'date': row[1], 'lieu': row[2], 'objet': row[3]})
        connection.close()

        return {'events': events, 'status': 'SUCCESS'}


from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    url(r'^', include('buynsell.urls')),
    # Examples:
    # url(r'^$', 'txsq_v3.views.home', name='home'),
    # url(r'^txsq_v3/', include('txsq_v3.foo.urls')),

)

urlpatterns += patterns('',
    url(r'^items', include('commodities.urls')),
    # Examples:
    # url(r'^$', 'txsq_v3.views.home', name='home'),
    # url(r'^txsq_v3/', include('txsq_v3.foo.urls')),

)


'''
------------------------------------------------------------------------------------------------------------------------
Name:       CPT GAME2.py
Purpose:    Aura Antivirus game CPT

Author: Jason Tai

Created:    11/06/2019
------------------------------------------------------------------------------------------------------------------------
'''

import arcade
import random

# SCREEN DIMENSIONS
WIDTH = 1080
HEIGHT = 700

#   DISPLAYS
start_screen = True
load_screen = False
play_screen = False
end_screen = False

#   PLAYER CONTROLS
up_pressed = False
down_pressed = False
right_pressed = False
left_pressed = False

#   DEAD VARIABLE
dead = False
spawn_protection = True
respawn = False

#   PLAYER START POSITION
player_x = WIDTH / 2
player_y = HEIGHT / 2

#   AVOID THE VIRUS PARAMETERS (TEST    )
player_speed = 1
virus_speed_x = 4
virus_speed_y = 4
trace_virus_speed = 1

#   AURA RADIUS
aura_radius = 50

#   SCORE TRACKER
score = 0

#   LOAD SCREEN TIMER FOR TIP CYCLING
loading_timer = 0

#   TRACING VIRUS SPAWN COORDINATES
tracing_virus_x = 100
tracing_virus_y = 100

#   TITLE DIMENSIONS
title_x = 100
title_y = 600
title_delta_y = 0.2

#  VIRUS VARIABLES
viruses = []

#   GAME TIMER
game_timer = 0
game_length = 20

#   LIST OF TIPS THAT CYCLE DURING THE LOAD SCREEN
title_tips = ["Malware is software that harms your computer",
              "Keep your computer up to date with frequent updates",
              "Report cyberbullying to adults you trust",
              "A Trojan is a virus that \ndisguises itself as helpful",
              "If computer starts lagging with lots of Chrome tabs open, \nit may be time to upgrade the RAM",
              "Avoid downloading software that seems to be \n'too good to be true'",
              "Don't give out your personal information online"]

#   TIP CYCLING
tip_1 = random.randint(0, len(title_tips) - 1)
tip_2 = random.randint(0, len(title_tips) - 1)

#   TEXTURE LOADING
start_background = arcade.load_texture("CPT game 2 dir/45e136031edebdabec2032a296bf3184.png")
button_1 = arcade.load_texture("CPT game 2 dir/button1.png")
button_video = arcade.load_texture("CPT game 2 dir/button.png")
load_background = arcade.load_texture("CPT game 2 dir/49373.jpg")
game_background = arcade.load_texture("CPT game 2 dir/1fe9fd735b4c3b198d10236a5fa592f8.png")
virus_image = arcade.load_texture("CPT game 2 dir/computer+virus.png")
trace_virus_image = arcade.load_texture("CPT game 2 dir/67-675122_virus-clipart-black-and-white-virus-icon-png.png")
easy_button = arcade.load_texture("CPT game 2 dir/Easy button.png")
medium_button = arcade.load_texture("CPT game 2 dir/Medium button.png")
hard_button = arcade.load_texture("CPT game 2 dir/Hard button.png")
player_image = arcade.load_texture("CPT game 2 dir/i_am_a_square.png")

#   BUTTON CHARACTERISTICS
expansion_button_1 = 0
expansion_easy_button = 0
expansion_medium_button = 0
expansion_hard_button = 0
transparency_button_1 = 1
transparency_easy_button = 1
transparency_medium_button = 1
transparency_hard_button = 1

#   START SCREEN
def game_start_screen():
    global title_x, title_y, title_delta_y, loading_timer
    #   TITLE MOVEMENT
    arcade.draw_texture_rectangle(475, HEIGHT / 2, 0.7 * start_background.width, 0.7 * start_background.height,
                                  start_background, 0)
    title_y += title_delta_y
    if title_y >= 610:
        title_delta_y *= -1
    if title_y <= 590:
        title_delta_y *= -1

    arcade.draw_text("Aura Antivirus", title_x, title_y, (210, 255, 248), 50, font_name='CONSOLAS')
    arcade.draw_text(
        "Avoid the Virus, \nthe aura of antivirus, \ngives you score \nAntivirus doesn't \nprotect you completly \nso play smart \njust like being \nsmart online",
        100, 500, (210, 255, 248), 25, font_name='CONSOLAS')
    arcade.draw_text("Use W A S D to control", 100, 150, (210, 255, 248), 15, font_name='CONSOLAS')
    arcade.draw_texture_rectangle(800, 400, 0.8 * button_1.width + expansion_button_1, 0.8 * button_1.height + expansion_button_1,
                                  button_1, alpha=transparency_button_1)

    #   BUTTONS
    arcade.draw_texture_rectangle(750, 300, easy_button.width + expansion_easy_button, easy_button.height + expansion_easy_button, easy_button,
                                  alpha=transparency_easy_button)
    arcade.draw_texture_rectangle(750, 200, medium_button.width + expansion_medium_button, medium_button.height + expansion_medium_button, medium_button,
                                  alpha=transparency_medium_button)
    arcade.draw_texture_rectangle(750, 100, hard_button.width + expansion_hard_button, hard_button.height + expansion_hard_button, hard_button,
                                  alpha=transparency_hard_button)

    #   RESET LOADING TIMER
    loading_timer = 0

#   LOAD SCREEN
def game_load_screen():
    global load_screen, play_screen, tip_1, aura_radius
    arcade.set_background_color(arcade.color.BLUE)
    arcade.draw_texture_rectangle(WIDTH / 2, HEIGHT / 2, 0.7 * load_background.width, 0.7 * load_background.height,
                                  load_background, 0)
    arcade.draw_text("LOADING", 100, 550, arcade.color.PINK_LAVENDER, 60, font_name='CONSOLAS')

    #   LOADING DOT ANIMATION
    if loading_timer >= 1.5:
        arcade.draw_circle_filled(425, 550, 5, arcade.color.PINK_LAVENDER)
    if loading_timer >= 3:
        arcade.draw_circle_filled(450, 550, 5, arcade.color.PINK_LAVENDER)
    if loading_timer >= 4.5:
        arcade.draw_circle_filled(475, 550, 5, arcade.color.PINK_LAVENDER)

    arcade.draw_texture_rectangle(100, 100, 0.5 * virus_image.width, 0.5 * virus_image.height, virus_image)
    arcade.draw_text("Don't touch this virus", 150, 100, arcade.color.PINK_LAVENDER, 15, font_name='CONSOLAS')
    arcade.draw_texture_rectangle(500, 100, 0.15 * trace_virus_image.width, 0.15 * trace_virus_image.height,
                                  trace_virus_image)
    arcade.draw_text("Don't touch this one either, \nthis one chases you", 550, 100, arcade.color.PINK_LAVENDER, 15,
                     font_name='CONSOLAS')
    #arcade.draw_circle_filled(100, 250, 25, arcade.color.BLACK)
    arcade.draw_texture_rectangle(100, 250, 0.3*player_image.width, 0.3*player_image.height, player_image)
    arcade.draw_text("This is you", 150, 250, arcade.color.PINK_LAVENDER, 15, font_name='CONSOLAS')

    #   AURA INSTRUCTION ANIMATION
    aura_radius += 0.4
    if aura_radius >= 100:
        aura_radius = 50
    arcade.draw_circle_filled(500, 250, aura_radius, (92, 244, 66, 95))
    arcade.draw_text("Stay within this Aura to gain points", 550, 250, arcade.color.PINK_LAVENDER, 15,
                     font_name='CONSOLAS')
    if loading_timer <= 4:
        arcade.draw_text(title_tips[tip_1], 100, 425,
                         arcade.color.PINK_LAVENDER, 25, font_name='CONSOLAS')
    if loading_timer > 4:
        arcade.draw_text(title_tips[tip_2], 100, 425,
                         arcade.color.PINK_LAVENDER, 25, font_name='CONSOLAS')

#   GAME SCREEN
def game_play_screen():
    arcade.set_background_color(arcade.color.GREEN)
    arcade.draw_texture_rectangle(WIDTH / 2, HEIGHT / 2, 0.7 * game_background.width, 0.7 * game_background.height,
                                  game_background, 90)
    player()
    virus()
    tracing_virus()
    on_collision()
    arcade.draw_text("Score:    " + str(score), 100, 100, arcade.color.WHITE, 20, font_name='CONSOLAS')
    arcade.draw_text("Time :    " + str(round((game_length - game_timer), 2)), 800, 600, arcade.color.WHITE, 20,
                     font_name='CONSOLAS')
    if spawn_protection:
        arcade.draw_text("Spawn Protection is on \npress 't' to disable", WIDTH / 2, HEIGHT / 2, arcade.color.GREEN, 20,
                         font_name='CONSOLAS')

#   OBJECT FOR THE PLAYER
class Person:
    def __init__(self, x, y, radius, color):
        self.x = x
        self.y = y
        self.radius = radius
        self.color = color

person = Person(WIDTH / 2, HEIGHT / 2, 25, arcade.color.BLACK)

#   OBJECT FOR THE VIRUS
class Virus:
    def __init__(self, x, y, width, height, texture, speed_x, speed_y):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.texture = texture
        self.speed_x = speed_x
        self.speed_y = speed_y

#   ADDING VIRUS TO THE LIST
for i in range(2):
    viruses.append(
        Virus(random.randint(25, 1080), random.randint(25, 700), virus_image.width, virus_image.height, virus_image,
              virus_speed_x, virus_speed_y))

#   VIRUS DRAWING AND AURA DRAWING
def virus():
    global viruses, aura_radius
    for i in range(len(viruses)):
        viruses[i].x += viruses[i].speed_x
        viruses[i].y += viruses[i].speed_y
        aura_radius += 0.2
        if aura_radius >= 125:
            aura_radius = 50
        arcade.draw_circle_filled(viruses[i].x, viruses[i].y, aura_radius, (92, 244, 66, 95))
        arcade.draw_texture_rectangle(viruses[i].x, viruses[i].y, 0.5 * viruses[i].width, 0.5 * viruses[i].height,
                                      viruses[i].texture)

#   DRAWING PLAYER
def player():
    #arcade.draw_circle_filled(person.x, person.y, person.radius, person.color)
    arcade.draw_texture_rectangle(person.x, person.y, 0.25*player_image.width, 0.25*player_image.height, player_image)

#   USELESS
def game_end_screen():
    arcade.set_background_color(arcade.color.RED)

#   TRACING VIRUS
def tracing_virus():
    global person, tracing_virus_x, tracing_virus_y, trace_virus_speed

    if tracing_virus_x < person.x:
        tracing_virus_x += trace_virus_speed
    if tracing_virus_x > person.x:
        tracing_virus_x -= trace_virus_speed
    if tracing_virus_y < person.y:
        tracing_virus_y += trace_virus_speed
    if tracing_virus_y > person.y:
        tracing_virus_y -= trace_virus_speed

    # arcade.draw_circle_filled(tracing_virus_x, tracing_virus_y, 25, arcade.color.WHITE)
    arcade.draw_texture_rectangle(tracing_virus_x, tracing_virus_y, 0.15 * trace_virus_image.width,
                                  0.15 * trace_virus_image.height, trace_virus_image)

#   COLLISION
def on_collision():
    global person, dead, spawn_protection, score, tracing_virus_x, tracing_virus_y
    if spawn_protection == False:
        for i in range(len(viruses)):
            distance = ((person.x - viruses[i].x) ** 2 + (person.y - viruses[i].y) ** 2) ** 0.5
            if distance <= 60:
                dead = True

    for i in range(len(viruses)):
        if viruses[i].x <= 25 or viruses[i].x >= 1105:
            viruses[i].speed_x *= -1
        if viruses[i].y <= 25 or viruses[i].y >= 725:
            viruses[i].speed_y *= -1

    distance_trace_virus = ((person.x - tracing_virus_x) ** 2 + (person.y - tracing_virus_y) ** 2) ** 0.5
    if spawn_protection == False:
        if distance_trace_virus < 50:
            dead = True

    #   WALL COLLISION FOR PERSON
    if person.x < 25:
        person.x = 25
    if person.x > 1055:
        person.x = 1055
    if person.y < 25:
        person.y = 25
    if person.y > 675:
        person.y = 675

    if spawn_protection == False:
        if dead is False:
            for i in range(len(viruses)):
                distance = ((person.x - viruses[i].x) ** 2 + (person.y - viruses[i].y) ** 2) ** 0.5
                if distance <= 150:
                    score += 2

def on_update(delta_time):
    global play_screen, player_y, player_x, up_pressed, down_pressed, right_pressed, left_pressed, WIDTH, HEIGHT, player_speed
    if play_screen:
        if up_pressed:
            person.y += player_speed
        if down_pressed:
            person.y -= player_speed
        if right_pressed:
            person.x += player_speed
        if left_pressed:
            person.x -= player_speed

    global dead, start_screen, load_screen, viruses, spawn_protection, respawn, score, virus_speed_x, virus_speed_y, game_timer, game_length, tracing_virus_x, tracing_virus_y
    if dead:
        if respawn is True:
            viruses = []
            for i in range(2):
                viruses.append(
                    Virus(random.randint(25, 1080), random.randint(25, 700), virus_image.width, virus_image.height,
                          virus_image, virus_speed_x, virus_speed_y))
            person.x = WIDTH / 2
            person.y = HEIGHT / 2
            tracing_virus_x = 100
            tracing_virus_y = 100
            up_pressed = False
            down_pressed = False
            right_pressed = False
            left_pressed = False
            spawn_protection = True
            dead = False
            respawn = False
            score = 0
            game_timer = 0
    global loading_timer
    if load_screen:
        loading_timer += delta_time
        if loading_timer >= 8:
            load_screen = False
            play_screen = True
    if spawn_protection == False and dead == False:
        game_timer += delta_time
        if game_timer >= game_length:
            dead = True

def on_draw():
    arcade.start_render()

    if start_screen:
        #   DRAW START HERE
        game_start_screen()
    elif play_screen:
        #   DRAW GAME HERE
        game_play_screen()
    elif load_screen:
        game_load_screen()
    elif end_screen:
        game_end_screen()

    if dead:
        arcade.draw_text("You died, \nyour score was " + str(score) + "\n press 'f' to reset", 100, 500,
                         (210, 255, 248), 50, font_name='CONSOLAS')
        arcade.draw_text("Press 'r' to return to main menu", 500, 100, (210, 255, 248), 15, font_name='CONSOLAS')

def on_key_press(key, modifiers):
    global start_screen, play_screen, load_screen
    if load_screen:
        if key == arcade.key.E:
            start_screen = False
            load_screen = False
            play_screen = True

    if play_screen:
        global up_pressed, down_pressed, right_pressed, left_pressed, player_y, player_x, spawn_protection, score, dead, viruses, respawn, game_timer, tracing_virus_x, tracing_virus_y
        if key == arcade.key.W:
            up_pressed = True
        if key == arcade.key.S:
            down_pressed = True
        if key == arcade.key.D:
            right_pressed = True
        if key == arcade.key.A:
            left_pressed = True

        if key == arcade.key.UP:
            up_pressed = True
        if key == arcade.key.DOWN:
            down_pressed = True
        if key == arcade.key.RIGHT:
            right_pressed = True
        if key == arcade.key.LEFT:
            left_pressed = True
        if key == arcade.key.R:
            play_screen = False
            start_screen = True
            person.x = WIDTH / 2
            person.y = HEIGHT / 2
            tracing_virus_x = 100
            tracing_virus_y = 100
            up_pressed = False
            down_pressed = False
            right_pressed = False
            left_pressed = False
            viruses = []
            for i in range(2):
                viruses.append(
                    Virus(random.randint(25, 1080), random.randint(25, 700), virus_image.width, virus_image.height,
                          virus_image, virus_speed_x, virus_speed_y))
            dead = False
            score = 0
            game_timer = 0
            spawn_protection = True
        if key == arcade.key.T:
            spawn_protection = False

        if dead:
            if key == arcade.key.F:
                respawn = True

def on_key_release(key, modifiers):
    if play_screen:
        global up_pressed, down_pressed, left_pressed, right_pressed
        if key == arcade.key.W:
            up_pressed = False
        if key == arcade.key.S:
            down_pressed = False
        if key == arcade.key.D:
            right_pressed = False
        if key == arcade.key.A:
            left_pressed = False

        if key == arcade.key.UP:
            up_pressed = False
        if key == arcade.key.DOWN:
            down_pressed = False
        if key == arcade.key.RIGHT:
            right_pressed = False
        if key == arcade.key.LEFT:
            left_pressed = False

#   MODE SELECTION
def on_mouse_press(x, y, button, modifiers):
    global start_screen, play_screen, button_video, load_screen, easy_button, medium_button, hard_button, easy, medium, hard, mode, virus_speed_y, virus_speed_x, player_speed, trace_virus_speed
    if start_screen:
        if (x > 800 - (button_1.width) / 2 and x < 800 + (button_1.width) / 2 and y > 400 - (
                button_1.height) / 2 and y < 400 + (button_1.height) / 2):
            print("click")
            player_speed = 5
            trace_virus_speed = 2.5
            start_screen = False
            load_screen = True

        if (x > 750 - (easy_button.width) / 2 and x < 800 + (easy_button.width) / 2 and y > 300 - (
                easy_button.height) / 2 and y < 300 + (easy_button.height) / 2):
            print("yes")
            player_speed = 9
            trace_virus_speed = 1.2
            start_screen = False
            load_screen = True

        if (x > 750 - (medium_button.width) / 2 and x < 800 + (medium_button.width) / 2 and y > 200 - (
                medium_button.height) / 2 and y < 200 + (medium_button.height) / 2):
            player_speed = 7
            trace_virus_speed = 2.2
            start_screen = False
            load_screen = True

        if (x > 750 - (hard_button.width) / 2 and x < 800 + (hard_button.width) / 2 and y > 100 - (
                hard_button.width) / 2 and y < 100 + (hard_button.height) / 2):
            player_speed = 5
            trace_virus_speed = 2.7
            start_screen = False
            load_screen = True

#   BUTTON HOVER ANIMATION
def mouse(x, y, dx, dy):
    global expansion, transparency_button_1, transparency_easy_button, transparency_medium_button, transparency_hard_button, expansion_button_1, expansion_easy_button, expansion_medium_button, expansion_hard_button

    if (x > 800 - (button_1.width) / 2 and x < 800 + (button_1.width) / 2 and y > 400 - (
            button_1.height) / 2 and y < 400 + (button_1.height) / 2):
        expansion_button_1 = -5
        transparency_button_1 = 0.7
    else:
        expansion_button_1 = 0
        transparency_button_1 = 1

    if (x > 750 - (easy_button.width) / 2 and x < 800 + (easy_button.width) / 2 and y > 300 - (
            easy_button.height) / 2 and y < 300 + (easy_button.height) / 2):
        expansion_easy_button = -5
        transparency_easy_button = 0.7
    else:
        expansion_easy_button = 0
        transparency_easy_button = 1

    if (x > 750 - (medium_button.width) / 2 and x < 800 + (medium_button.width) / 2 and y > 200 - (
            medium_button.height) / 2 and y < 200 + (medium_button.height) / 2):
        expansion_medium_button = -5
        transparency_medium_button = 0.7
    else:
        expansion_medium_button = 0
        transparency_medium_button = 1

    if (x > 750 - (hard_button.width) / 2 and x < 800 + (hard_button.width) / 2 and y > 100 - (
            hard_button.width) / 2 and y < 100 + (hard_button.height) / 2):
        expansion_hard_button = -5
        transparency_hard_button = 0.7
    else:
        expansion_hard_button = 0
        transparency_hard_button = 1

def setup():
    arcade.open_window(WIDTH, HEIGHT, "Aura Antivirus")
    arcade.set_background_color(arcade.color.WHITE)
    arcade.schedule(on_update, 1 / 240)

    # Override arcade window methods
    window = arcade.get_window()
    window.on_draw = on_draw
    window.on_key_press = on_key_press
    window.on_key_release = on_key_release
    window.on_mouse_press = on_mouse_press
    window.on_mouse_motion = mouse

    arcade.run()

if __name__ == '__main__':
    setup()


import unittest
from itertools import zip_longest

class TestRecursive(unittest.TestCase):
    def assertEqualRecursive(self, first, second):
        """
        Asserts that two nested JSON-like structures consisting of dictionaries and lists are fully equal.

        >>> TestRecursive().assertEqualRecursive({1: [{'a': 2}, 'b']}, {1: [{'a': 3}, 'b']})
        Traceback (most recent call last):
        ...
        AssertionError: 1 error:
        Values differ: 2 != 3 at [1][0][a]

        """
        paths = self._check_equal_recursive(first, second)
        if paths:
            msg = '{} error{}:\n'.format(len(paths), 's' if len(paths) > 1 else '') + '\n'.join(paths)
            raise self.failureException(msg)

    def _check_equal_recursive(self, first, second, *path_so_far):
        diffs = []
        if isinstance(first, list) and isinstance(second, list):
            for i, (f, s) in enumerate(zip_longest(first, second)):
                diffs.extend(
                    self._check_equal_recursive(f, s, str(i), *path_so_far)
                )
            return diffs

        joined_path = ']['.join(str(i) for i in reversed(path_so_far))
        if isinstance(first, dict) and isinstance(second, dict):
            keys1 = first.keys()
            keys2 = second.keys()
            for k in keys1 - keys2:
                diffs.append('`{k}: {v}` not found in second object at [{path}] '.format(
                    path=joined_path,
                    k=k,
                    v=first[k]
                ))
            for k in keys2 - keys1:
                diffs.append('`{k}: {v}` not found in first object at [{path}] '.format(
                    path=joined_path,
                    k=k,
                    v=second[k]
                ))
            for k in keys1 & keys2:
                diffs.extend(
                    self._check_equal_recursive(first[k], second[k], k, *path_so_far)
                )
        elif not first == second:
            # If one is still a dict or list, don't display (since it might be large),
            # and don't str() since it's a json type
            if {type(first), type(second)} & {dict, list}:
                diffs.append('Types differ: {first} != {second} at [{path}]'.format(
                    path=joined_path,
                    first=type(first),
                    second=type(second)
                ))
            # Also don't compare other json types as strings
            elif {type(first), type(second)} & {int, float, bool, type(None)} or \
                    not str(first) == str(second):
                diffs.append('Values differ: {first} != {second} at [{path}]'.format(
                    path=joined_path,
                    first=first,
                    second=second
                ))

        return diffs


# Otto-Grabber - Grabbs Products from Otto.de
#
# Creation:    30.09.2019
# Last Update: 04.10.2019
#
#
# MIT License
#
# Copyright (c) 2019 by PiereLucas
# https://github.com/pierelucas
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

#
# Module
#
import requests, os, subprocess, re
from bs4 import BeautifulSoup

#
# Output
#
def out():

    subprocess.call("clear", shell=True)

    print("""
    This tool is for scarping new Base_URLS and save to csv.
    After that, just copy the new URLS in the grabby.py

    [1] Multimedia
    [2] Haushalt
    [3] Kueche
    [0] Exit
    """)

#
# Grab Function
#
def grab(url, sec):
    # Open file
    if os.path.exists("new_urls_" + sec):
        subprocess.call("rm -rf new_urls_" + sec, shell=True)
        os.mkdir("new_urls" + sec)
        new_urls = open("new_urls_" + sec + "/new_urls.csv", 'wt')
    else:
        os.mkdir("new_urls" + sec)
        new_urls = open("new_urls_" + sec + "/new_urls.csv", 'wt')

    # Parse URL to get new_urls
    url = requests.get(url)
    urltext = url.text
    urlsoup = BeautifulSoup(urltext, 'html.parser')

    url_list = urlsoup.find_all('a', 'href', class_="ts-link")
    for item in url_list:
        item = str(item)
        url_list_item = re.findall("href=\".*\"", item)

        for item in url_list_item:
            # Regex
            link = re.sub("href=\"", "", item)
            link = re.sub("><span.*", "", link)
            link = re.sub("\"", "", link)
            link = re.sub("\?selektion", "", link)
            link = re.sub("target=.*", "", link)
            link = re.sub("/shoppages.*", "", link)
            link = re.sub("/user.*", "", link)
            link = re.sub("/reblog.*", "", link)
            link = re.sub("/twoforfashion.*", "", link)
            link = re.sub("/roombeez.*", "", link)
            link = re.sub("/soulfully.*", "", link)
            link = re.sub("/supermarkt.*", "", link)
            link = re.sub("/datenschutz.*", "", link)
            link = re.sub("https.*", "", link)
            link = re.sub("#SVGID.*", "", link)
            link = re.sub(" ", "", link)
            link = re.sub("/=\(.*", "", link)
            link = "https://otto.de" + link

            print(link)
            # Write to file
            new_urls.write(link + "\n")
    # Close to file
    new_urls.close()

#
# Main Function
#
def run():

    out()
    choice = str(input("Which option number : "))

    if choice == '1':

        sec = "multimedia"
        url = "https://www.otto.de/technik/multimedia/"
        grab(url, sec)

    elif choice == '2':
        sec = "haushalt"
        url = "https://www.otto.de/haushalt/"
        grab(url, sec)

    elif choice == '3':
        sec = kueche
        url = "https://www.otto.de/moebel/?ansicht=einstieg&thema=kueche"
        grab(url, sec)

# TO BE CONTINUED ...

out()
run()


from JumpScale import j
import re

BASECMD = "btrfs"

KB = 1024
MB = KB * 1024
GB = MB * 1024
TB = GB * 1024

FACTOR = {None: 1,
          'KB': KB,
          'MB': MB,
          'GB': GB,
          'TB': TB}

class BtrfsExtension(object):

    def __init__(self):
        self.__conspattern = re.compile("^(?P<key>[^:]+): total=(?P<total>[^,]+), used=(?P<used>.+)$", re.MULTILINE)
        self.__listpattern = re.compile("^ID (?P<id>\d+).+?path (?P<name>.+)$", re.MULTILINE)

    def __btrfs(self, command, action, *args):
        cmd = "%s %s %s %s" % (BASECMD, command, action, " ".join(['"%s"' % a for a in args]))
        code, out, err = j.system.process.run(cmd, stopOnError=False)

        if code:
            raise RuntimeError(err)

        return out

    def snapshotReadOnlyCreate(self, path, dest):
        """
        Create a readonly snapshot
        """
        self.__btrfs("subvolume", "snapshot -r", path, dest)

    def subvolumeCreate(self, path, name):
        """
        Create a subvolume in <dest> (or the current directory if not passed).
        """
        self.__btrfs("subvolume", 'create', j.system.fs.joinPaths(path, name))

    def subvolumeDelete(self, path, name):
        """
        Delete the subvolume <name>.
        """
        self.__btrfs("subvolume", "delete", j.system.fs.joinPaths(path, name))

    def subvolumeList(self, path):
        """
        List the snapshot/subvolume of a filesystem.
        """
        out = self.__btrfs("subvolume", "list", path)
        result = []
        for m in self.__listpattern.finditer(out):
            result.append(m.groupdict())
        return result

    def deviceAdd(self, path, dev):
        """
        Add a device to a filesystem.
        """
        self.__btrfs("device", 'add', dev, path)

    def deviceDelete(self, dev, path):
        """
        Remove a device from a filesystem.
        """
        self.__btrfs("device", 'delete', dev, path)

    def __consumption2kb(self, word):
        m = re.match("(\d+.\d+)(\D{2})?", word)
        if not m:
            raise ValueError("Invalid input '%s' should be in the form of 0.00XX" % word)
        value = float(m.group(1)) * FACTOR[m.group(2)]
        return value / 1024 #in KB

    def getSpaceUsage(self, path):
        out = self.__btrfs("filesystem", "df", path)
        result = {}
        for m in self.__conspattern.finditer(out):
            cons = m.groupdict()
            key = cons['key'].lower()
            key = key.replace(", ", "-")
            values = {'total': self.__consumption2kb(cons['total']),
                      'used': self.__consumption2kb(cons['used'])}
            result[key] = values

        return result


import pytest

from mirakuru import TCPExecutor

@pytest.fixture
def use_local_matrix_server():
    """
    If True, try to test with a real client and start a fresh local
    matrix server for each test. This should be used for integration
    tests only.
    If False, use the mock matrix client.
    """
    return False

# the empty fixtures are overwritten in integration/conftest.py
@pytest.fixture
def local_matrix():
    return None

@pytest.fixture
def matrix_host():
    return None

@pytest.fixture
def matrix_port():
    return None

@pytest.fixture
def local_matrix_server(
        use_matrix,
        use_local_matrix_server,
        local_matrix,
        matrix_host,
        matrix_port
):

    if not (use_matrix and use_local_matrix_server):
        yield None
        return

    assert local_matrix is not None, \
        "No command to start the local matrix server given. (--local-matrix option)"

    server = TCPExecutor(
        local_matrix,
        host=matrix_host,
        port=matrix_port,
        timeout=120,
        sleep=0.1,
        shell=True
    )

    server.start()
    yield 'http://{}:{}'.format(matrix_host, matrix_port)
    server.stop()


# -*- coding: utf-8 -*-
'''
		   @file: input.py
		   @date:
		 @author: Carlos Adir (carlos.adir.leite@gmail.com)
	@description: This code is to be the inputs of the codes, only for don't repeat the same part of code
					in all the files

'''

import sympy as sp
import numpy as np
import aux

limites = [	[1, 3],\
			[1, 5],\
			[1, 3],\
			[1, 3],\
			[1, 3]]

def get(algorithm, number):
	limite = limites[algorithm-1]
	if number < limite[0]:
		number = limite[0]
	if number > limite[1]:
		number = limite[1]

	if algorithm == 1:
		return lambda : in1(number)
	elif algorithm == 2:
		return lambda : in2(number)
	elif algorithm == 3:
		return lambda : in3(number)
	elif algorithm == 4:
		return lambda : in4(number)
	elif algorithm == 5:
		return lambda : in5(number)

def in1(number):
	t		= sp.symbols('t')
	if number == 1:
		a, b    = 1, 2							# The interval, it's suppose that a < b
		f       = t**2 - 3						# The function
		tol     = 1e-5 							# The max error acceptable
		nmax    = 10 							# Max number iteractions
	elif number == 2:
		a, b    = 2, 4							# The interval, it's suppose that a < b
		f       = t**2-2*t-4	 				# The function
		tol     = 1e-5 							# The max error acceptable
		nmax    = 10 							# Max number iteractions
	elif number == 3:
		a, b    = 1, 2							# The interval, it's suppose that a < b
		f       = t**3+4*t**2-10 				# The function
		tol     = 1e-5							# The max error acceptable
		nmax    = 10							# Max number iteractions

	# The begin to start the calculations
	feval 	= sp.lambdify(t, f, "numpy")
	flatex	= "$f(t) = " + aux.toLaTeX(f)
	f		= aux.Funcao(feval, flatex)
	return a, b, f, tol, nmax

def in2(number):
	t		= sp.symbols('t')
	if 1 <= number <= 5:
		p0 		= 1.5 							# The initial aproximation
		f       = t**3+4*t**2-10 				# The function that we want to calculate the roots
		tol     = 1e-5 							# The max error acceptable
		nmax    = 10 							# Max number iteractions
		if number == 1:
			g 		= t - t**3 - 4*t**2 + 10				# It doesn't converg
		elif number == 2:
			g 		= sp.sqrt(4*t - 10/t)						# It doesn't converg
		elif number == 3:
			g 		= sp.sqrt(10-t**3)/2					# The fixed point function, using f(x) = 0 we can get x = sqrt(10-x**3)/2
		elif number == 4:
			g 		= sp.sqrt(10/(4+t))						# It converges quite well
		elif number == 5:
			g 		= t - (t**3+4*t**2-10)/(3*t**2 + 8*t)	# It converges very well, we will see this funcion in the Newton's method

	g_ 		= sp.diff(g, t)						# The function g' derivative of g

	feval 	= sp.lambdify(t, f, "numpy")
	flatex	= "$f(t) = " + aux.toLaTeX(f)
	f		= aux.Funcao(feval, flatex)

	geval 	= sp.lambdify(t, g, "numpy")
	glatex	= "$g(t) = " + aux.toLaTeX(g)
	g		= aux.Funcao(geval, glatex)

	g_eval 	= sp.lambdify(t, g_, "numpy")
	g_latex	= "$g'(t) = " + aux.toLaTeX(g_)
	g_		= aux.Funcao(g_eval, g_latex)

	return p0, f, g, g_, tol, nmax

def in3(number):
	t		= sp.symbols('t')
	if number == 1:
		p0		= 1.5							# The interval, it's suppose that a < b
		f       = t**2 - 3						# The function
		tol     = 1e-5 							# The max error acceptable
		nmax    = 10 							# Max number iteractions
	elif number == 2:
		p0 		= 3								# The interval, it's suppose that a < b
		f       = t**2-2*t-4	 				# The function
		tol     = 1e-5 							# The max error acceptable
		nmax    = 10 							# Max number iteractions
	elif number == 3:
		p0 		= 1.5							# The interval, it's suppose that a < b
		f       = t**3+4*t**2-10 				# The function
		tol     = 1e-5							# The max error acceptable
		nmax    = 10							# Max number iteractions

	f_ 		= sp.diff(f, t)						# The function f' derivative of f

	# The begin to start the calculations
	feval 	= sp.lambdify(t, f, "numpy")
	flatex	= "$f(t) = " + aux.toLaTeX(f)
	f		= aux.Funcao(feval, flatex)

	f_eval 	= sp.lambdify(t, f_, "numpy")
	f_latex	= "$f'(t) = " + aux.toLaTeX(f_)
	f_		= aux.Funcao(f_eval, f_latex)

	return p0, f, f_, tol, nmax

def in4(number):
	t		= sp.symbols('t')
	if number == 1:
		p0, p1	= 1, 2							# The interval, it's suppose that a < b
		f		= t**2 - 3						# The function
		tol		= 1e-5 							# The max error acceptable
		nmax	= 10 							# Max number iteractions
	elif number == 2:
		p0, p1  = 2, 4							# The interval, it's suppose that a < b
		f       = t**2-2*t-4	 				# The function
		tol     = 1e-5 							# The max error acceptable
		nmax    = 10 							# Max number iteractions
	elif number == 3:
		p0, p1	= 1, 2							# The interval, it's suppose that a < b
		f       = t**3+4*t**2-10 				# The function
		tol     = 1e-5							# The max error acceptable
		nmax    = 10							# Max number iteractions

	# The begin to start the calculations
	feval 	= sp.lambdify(t, f, "numpy")
	flatex	= "$f(t) = " + aux.toLaTeX(f)
	f		= aux.Funcao(feval, flatex)
	return p0, p1, f, tol, nmax

def in5(number):
	return in4(number)


def minion_game(string):

    ls = []

    # Two variables to store a score
    Stuart = 0
    Kevin = 0

    for i in range(len(string)):
        for j in range(len(string)):
            #print(string[i:j + 1])
            ls.append(string[i:j + 1])

    #print(ls)
    ls = ' '.join(ls).split()
    #print(ls)

    for i in range(len(ls)):
        #print(ls[i][0])
        if ls[i][0] in ('A', 'E', 'I', 'O', 'U'):
            Kevin += 1
        elif (ord(ls[i][0]) >= 65 and ord(ls[i][0]) <= 90):
            Stuart += 1

    if (Kevin > Stuart):
        print("Kevin", Kevin)
    elif (Kevin < Stuart):
        print("Stuart", Stuart)
    else:
        print("Draw")

if __name__ == '__main__':
    s = input()
    minion_game(s)


from bin import data_specification as data_specs
from bin import isa
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

from bin import auftriebsbeiwertverteilung as diederich
from bin import fe1_wing
from bin import mass_roskam as imp_mass
from bin import mass_torenbeek
from bin import fe1_wing
from bin import schwerpunkt
from bin import det_drag
from bin import widerstand as imp_drag
from bin import isa
from bin import performance
import csv

class doc:

    def __init__(self):
        self.class_data = data_specs.specs().data()
        self.isa = isa.isa()
        self.data_fe1wing = fe1_wing.calc_fe1_wing()
        self.class_SP = schwerpunkt.center_of_mass()
        self.data_mission = self.class_data[3]
        self.altitude_ica = self.data_mission[2]
        self.data_mass = self.class_data[0]
        self.data_wing = self.class_data[1]
        self.data_crew = self.class_data[2]
        self.data_data_airfoil = self.class_data[4]
        self.data_fuselage = self.class_data[5]
        self.data_propulsion = self.class_data[6]
        self.data_cabin = self.class_data[7]
        self.data_cargo = self.class_data[8]
        self.data_airfoiltail = self.class_data[9]
        self.data_tail = self.class_data[10]
        self.data_SP = self.class_data[11]
        self.data_gear = self.class_data[12]
        self.data_narc = self.class_data[13]
        self.data_seat = self.class_data[14]
        self.data_detdrag = det_drag.det_drag()

        # ICA
        [self.rho_ica, self.p_ica, self.T_ica, self.a_ica] = self.isa.calc_isa(self.altitude_ica)

        # MASSES
        [group1, group2, group3, group4, group5, subtotal, self.W_DE, self.W_OE, self.W_TO] = \
            mass_torenbeek.torenbeek_mass().iter_all()
        self.payload = self.data_mass[3] + 2000
        imp_mass.calc_mass()
        [self.m_fuel, self.imp_m_oe, self.imp_m_to, self.imp_kappa, self.imp_mff25] = imp_mass.calc_mass().fuelfactor()

        # CREW
        self.n_crew = self.data_crew[0] + self.data_crew[2]

        # MISSION
        self.range_design = self.data_mission[0]
        self.Ma_ica = self.data_mission[1]
        self.n_pax_eco = 110
        self.n_pax_2c = 18 * 5 + 3 * 4

        # PROPULSION
        self.eng_thrust = self.data_propulsion[1]

    def calc_total(self):
        # standard case
        range_sta= 500 * 1852 / 1000 # standard range in km
        self.indepentent_cost()
        [self.C2_sta, self.cost_dist_sta, self.FC_sta] = self.dependent_cost(range_sta)

        self.DOC_sta = self.C1 + self.C2_sta
        self.C1C2_sta = [self.C1, self.C2_sta]

        # design case
        range_des = self.range_design / 1000 # design range in km
        [self.C2_des, self.cost_dist_des, self.FC_des] = self.dependent_cost(range_des)

        self.DOC_des = self.C1 + self.C2_des
        self.C1C2_des = [self.C1, self.C2_des]

        # write c1c2 and cost distribution in 'data_doc.csv
        self.write_csv()

        # calculate seat mile kilometer (SMK)
        # 1. for standard range
        self.SMK_sta = self.SMK(range_sta, self.FC_sta, self.DOC_sta)
        self.SMK_des = self.SMK(range_des, self.FC_des, self.DOC_des)

        # additional cargo
        [self.n_pax_cargo_eco, self.n_pax_cargo_2c] = self.add_cargo()

        # DOC Correction
        SMK_sta_eco_cor = self.SMK_sta[0] * (self.n_pax_eco/(self.n_pax_eco + self.n_pax_cargo_eco))
        SMK_sta_2c_cor = self.SMK_sta[1] * (self.n_pax_2c/(self.n_pax_2c + self.n_pax_cargo_2c))
        SMK_des_eco_cor = self.SMK_des[0] * (self.n_pax_eco/(self.n_pax_eco + self.n_pax_cargo_eco))
        SMK_des_2c_cor = self.SMK_sta[1] * (self.n_pax_2c/(self.n_pax_2c + self.n_pax_cargo_2c))

        [self.UC_range, self.DOC_SKO_AB_des_2c, self.DOC_SKO_BC_des_2c, self.DOC_SKO_CD_des_2c, self.DOC_SKO_AB_des_2c_corr] = self.unit_cost()

        # EMISSIONS
        em_flight = self.emissions(self.m_fuel)
        em_year = self.emissions(1937 * self.m_fuel)
        em_12year = self.emissions(12 * 1937 * self.m_fuel)
        test = 1

        self.plots()

        # ONLY FOR DEBUGGING
        # fixme: check if SMK is legit
        # plt.close(1)
        # plt.close(2)
        # plt.close(3)
        # plt.close(4)
        # plt.close(5)
        # plt.close(6)
        test = 1

    def indepentent_cost(self):
        # route independent costs
        # capital costs
        P_oew = 1245 # price per kg OEW €/kg
        IR = .05 # interest rate
        DP = 12 # depreciation period 12y.
        f_rv = .15 # residual value factor
        f_ins = .005 # insurance rate
        a = IR * ((1 - f_rv * (1/(1 - IR))**DP)/(1 - (1/(1 + IR))**DP))
        C_cap = P_oew * self.W_OE * (a + f_ins)

        # crew
        CC = self.n_crew # number of crew
        PL_max = self.payload # max. payload
        S_fa = 30000 # avg. salary of flight attendant p.a.
        S_pil = 300000 # avg. salary for both pilots p.a.
        C_crew = CC * (S_fa * (PL_max/5000) + S_pil)

        # returns
        self.C_cap = C_cap
        self.C_crew = C_crew
        self.C1 = C_cap + C_crew

    def dependent_cost(self, range):
        # determine the avg. fuel price over the last 12 months [Apr18 - Mar19]
        fp09 = np.average([1.22, 1.32, 1.20, 1.31, 1.33, 1.35])
        fp10 = np.average([1.44, 1.45, 1.55, 1.67, 1.64, 1.69, 1.58, 1.62, 1.62, 1.62, 1.69, 1.86])
        fp11 = np.average([1.96, 2.08, 2.23, 2.26, 2.15, 2.12, 2.20, 2.10, 2.14, 2.16, 2.24, 2.18])
        fp12 = np.average([2.39, 2.43, 2.47, 2.45, 2.32, 2.14, 2.36, 2.55, 2.48, 2.39, 2.31, 2.24])
        fp13 = np.average([2.33, 2.41, 2.29, 2.16, 2.10, 2.10, 2.21, 2.26, 2.20, 2.12, 2.10, 2.16])
        fp14 = np.average([2.15, 2.17, 2.09, 2.09, 2.09, 2.12, 2.08, 2.13, 2.12, 1.94, 1.84, 1.46])
        fp15 = np.average([1.29, 1.56, 1.50, 1.58, 1.66, 1.54, 1.41, 1.25, 1.24, 1.24, 1.23, .99])
        fp16 = np.average([.86, .88, .96, 1.01, 1.15, 1.23, 1.15, 1.16, 1.18, 1.32, 1.25, 1.41])
        fp17 = np.average([1.43, 1.45, 1.35, 1.41, 1.28, 1.15, 1.23, 1.32, 1.51, 1.41, 1.50, 1.54])
        fp18 = np.average([1.60, 1.50, 1.51, 1.64, 1.82, 1.79, 1.80, 1.83, 1.88, 1.96, 1.71, 1.49])
        fp19 = np.average([1.56, 1.69, 1.68])

        P_f = [fp09, fp10, fp11, fp12, fp13, fp14, fp15, fp16, fp17, fp18, fp19] # fuel price (€/gallon)
        P_f = np.divide(P_f, .26) # fuel price in €/kg
        P_f_avg = np.average(P_f)

        P_l = .01 # landing fees (€/kg)
        T_f = self.m_fuel # in kg
        if range == (500 * 1852 / 1000):
            T_f = .45 * T_f
        P_h = .1 # handling fees (€/kg)
        payload = self.payload

        fun_R = .6 # ATC price factor far east

        v = self.Ma_ica * self.a_ica * 3600
        FC = 6011/((range * 1000)/v + 1.83)
        FT = range * 1000 / v

        # Maintainance costs calculation
        LR = 50 # labor rate (€/h)
        B = 2 # cost burden, sugg.: 2
        N_eng = 4 # number of engines
        SLST = self.eng_thrust/(9.80655 * 1000)
        MC_af_mat = self.W_OE/1000 * (.2 * FT + 13.7) + 57.5
        MC_af_per = LR * (1 + B) * ((.655 + .01 * self.W_OE/1000) * FT + .254 + .01 * self.W_OE/1000)
        MC_eng = N_eng * (1.5 * SLST + 30.5 * FT + 10.6)
        MC_total = MC_af_mat + MC_af_per + MC_eng

        C2 = FC * (P_f * T_f + P_h * payload + P_l * self.W_TO + fun_R * range * np.sqrt(self.W_TO/1000/50) + MC_total)

        # summaries for piechart
        pie = [self.C_cap/12, self.C_crew, (P_f * T_f * FC), (P_h * payload * FC), (P_l * self.W_TO * FC),
                (fun_R * range * np.sqrt(self.W_TO/(1000 * 50)) * FC), (MC_total * FC)]

        return C2, pie, FC

    def SMK(self, range, FC, DOC):
        # seat mile kilometer
        n_pax_eco = self.n_pax_eco
        n_pax_2c = self.n_pax_2c

        # ALL ECO
        SK0_etops_eco = n_pax_eco * range * FC
        SMK_eco = DOC/SK0_etops_eco

        # 2 class
        SK0_etops_2c = n_pax_2c * range * FC
        SMK_2c = DOC / SK0_etops_2c

        return [SMK_eco, SMK_2c]

    def add_cargo(self):
        FR = .2 # euro/kg
        E_PAX = 100 # rev. per seat and flight 100 euro/SO
        G_Pmax = self.payload * 9.80655
        n_PAX_eco = 110
        n_PAX_2c = 102
        def eco_2c(n_PAX):
            G_pax = n_PAX * 100 * 9.80655
            E_cargo = FR * (G_Pmax - G_pax)
            n_PAX_cargo = E_cargo/E_PAX
            return n_PAX_cargo
        n_pax_cargo_eco = eco_2c(n_PAX_eco)
        n_pax_cargo_2c = eco_2c(n_PAX_2c)
        return [n_pax_cargo_eco, n_pax_cargo_2c]

    def unit_cost(self):
        [NLD_range, NLD_mA, NLD_RDP, m] = performance.performance().p2_NLD()
        delta_y = -.154
        delta_x = 2778
        m = delta_y/delta_x
        range_AB = np.linspace(NLD_range[1], NLD_range[2], 1000)
        range_BC = np.linspace(NLD_range[2], NLD_range[3], 1000)
        range_CD = np.linspace(NLD_range[3], NLD_range[4], 1000)
        # unit costs over the years
        # UC_range = np.zeros((3, len(self.DOC_des)))
        DOC_SKO_AB_des_2c = np.zeros((11, len(range_AB)))
        DOC_SKO_AB_des_2c_corr = np.zeros((11, len(range_AB)))
        DOC_SKO_BC_des_2c = np.zeros((11, len(range_AB)))
        DOC_SKO_CD_des_2c = np.zeros((11, len(range_AB)))
        for i in range(0, len(self.DOC_des)):
            # AB
            DOC_SKO_AB_des_2c[i] = self.DOC_des[i] / (self.n_pax_2c * self.FC_des * range_AB)
            DOC_SKO_AB_des_2c_corr[i] = DOC_SKO_AB_des_2c[i] * (self.n_pax_eco/(self.n_pax_2c + self.n_pax_cargo_2c))

            # BC
            vec_BC = ((m * range_BC) + 1 - (self.W_OE/self.W_TO)) * self.W_TO
            DOC_TKO_BC_des_2c = self.FC_des * vec_BC * range_BC
            DOC_SKO_BC_des_2c[i] = self.DOC_des[i]/((DOC_TKO_BC_des_2c - 2000*self.FC_des * range_BC)/90)

            # CD
            vec_CD = ((m * range_CD) + 1 - (self.W_OE/self.W_TO)) * self.W_TO
            DOC_TKO_CD_des_2c = self.FC_des * vec_CD * range_CD
            DOC_SKO_CD_des_2c[i] = self.DOC_des[i] / ((DOC_TKO_CD_des_2c - (2000*self.FC_des * range_CD)) / 90)
        UC_range = [range_AB, range_BC, range_CD]

        return [UC_range, DOC_SKO_AB_des_2c, DOC_SKO_BC_des_2c, DOC_SKO_CD_des_2c, DOC_SKO_AB_des_2c_corr]

    def  emissions(self, m_fuel):
        cO2 = 3.15
        H2O = 1.24
        NO = .006
        CO = .001
        UHC = .0003
        Soot = .00002

        em_co2 = m_fuel * cO2
        em_h20 = m_fuel * H2O
        em_no = m_fuel * NO
        em_co = m_fuel * CO
        em_uhc = m_fuel * UHC
        em_soot = m_fuel * Soot

        return [em_co2, em_h20, em_no, em_co, em_uhc, em_soot]

    def plots(self):
        plt.figure()
        plt.plot(self.UC_range[0], self.DOC_SKO_AB_des_2c[0])
        plt.plot(self.UC_range[1], self.DOC_SKO_BC_des_2c[0])
        plt.plot(self.UC_range[2], self.DOC_SKO_CD_des_2c[0])
        plt.plot(self.UC_range[0], self.DOC_SKO_AB_des_2c_corr[0])
        plt.grid()
        plt.title('Stückkostenverlauf')
        plt.xlabel('Reichweite [km]')
        plt.ylabel('DOC/SKO')
        plt.legend(['AB', 'BC', 'CD', 'AB, korr.'])
        plt.xlim([0, 6000])
        plt.ylim([0.5, 2])

        plt.figure(67)
        plt_pf = []
        for i in range(0, len(self.DOC_SKO_AB_des_2c)):
            clr = cm.autumn(i/11, 1)
            [dummy, ] = plt.plot(self.UC_range[0], self.DOC_SKO_AB_des_2c[i], '-', c=clr)
            plt.plot(self.UC_range[1], self.DOC_SKO_BC_des_2c[i], '--', c=clr)
            plt.plot(self.UC_range[2], self.DOC_SKO_CD_des_2c[i], '.-', c=clr)
            plt.plot(self.UC_range[0], self.DOC_SKO_AB_des_2c_corr[i], c=clr )
            plt_pf.append(dummy)
        plt.legend([plt_pf[0], plt_pf[1], plt_pf[2], plt_pf[3], plt_pf[4], plt_pf[5], plt_pf[6], plt_pf[7], plt_pf[8], plt_pf[9], plt_pf[10]],
                   ['09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19'])
        plt.grid()
        plt.title('Stückkostenverlauf durch den Kerosinpreis (09 - 19)')
        plt.xlabel('Reichweite [km]')
        plt.ylabel('DOC/SKO')
        # plt.legend(['AB', 'BC', 'CD', 'AB, korr.'])
        plt.xlim([0, 6000])
        plt.ylim([0.5, 2])

        # for i in range(0, len(self.H)):
        #     clr = cm.winter(i / 9, 1)
        #     [dummy, ] = col.plot(self.plt_VEAS[subplt_iter][i], self.plt_eps[subplt_iter][i], c=clr)
        #     plt_H.append(dummy)
        #     col.plot(self.plt_VEAS[subplt_iter][i], self.plt_SG_vorh[subplt_iter][i], c=clr)
        # col.set_xlabel('$V_{EAS}$ [m/s]')
        # col.set_ylabel('$eps$ [-]')
        # col.legend([plt_H[0], plt_H[1], plt_H[2], plt_H[3], plt_H[4], plt_H[5], plt_H[6], plt_H[7], plt_H[8]],
        #            ['H = ' + str(self.H[0]) + ' m', 'H = ' + str(self.H[1]) + ' m', 'H = ' + str(self.H[2]) + ' m',
        #             'H = ' + str(self.H[3]) + ' m', 'H = ' + str(self.H[4]) + ' m', 'H = ' + str(self.H[5]) + ' m',
        #             'H = ' + str(self.H[6]) + ' m', 'H = ' + str(self.H[7]) + ' m', 'H = ' + str(self.H[8]) + ' m'],
        #            loc='upper left')
        #

        plt.show()

    def write_csv(self):
        with open('../export/data_doc.csv', mode='w', newline='') as export_file:
            data_writer = csv.writer(export_file, delimiter=',', quotechar='"')
            c1c2_sta = self.C1C2_sta
            c1c2_sta.insert(0,'C1C2 standard')
            data_writer.writerow(c1c2_sta)
            cost_dist_sta = self.cost_dist_sta
            cost_dist_sta.insert(0, 'cost distribution standard')
            data_writer.writerow(cost_dist_sta)

            c1c2_des = self.C1C2_des
            c1c2_des.insert(0,'C1C2 design')
            data_writer.writerow(c1c2_des)
            cost_dist_des = self.cost_dist_des
            cost_dist_des.insert(0, 'cost distribution design')
            data_writer.writerow(cost_dist_des)

doc().calc_total()


# Default PPA settings
pop_size = 30
max_offspring = 5  # n_max

# run settings
max_evaluations = 50_000

# the size of tournaments used in the tournament selection methods
tournament_size = 7

# ==================
# Used for a single run
# ==================
# benchmarks
benchmark_name = 'Rosenbrock'  # Six Hump Camel, Martin-Gaddy

# survivor selection
survivor_selection = 'single_elitist_tournament'  # mupluslambda, mulambda, tournament, roulette_wheel, linear_ranking,

# ==================
# used for multi processing numerous runs
all_benchmarks = ['Six-Hump-Camel', 'Martin-Gaddy', 'Goldstein-Price', 'Branin', 'Easom', 'Rosenbrock', 'Ackley',
                  'Griewank', 'Rastrigrin', 'Schwefel', 'Ellipse', 'Cigar', 'Tablet', 'Sphere']

all_selection_methods = ['mupluslambda', 'mulambda', 'tournament', 'roulette_wheel', 'linear_ranking',
                         'single_elitist_rws', 'single_elitist_tournament', 'no_replacement_tournament']

n_dim_benchmarks = ['Ackley', 'Rosenbrock', 'Griewank', 'Rastrigrin', 'Schwefel', 'Ellipse', 'Cigar', 'Tablet',
                    'Sphere']
n_dimensions = [2, 5, 10, 20, 50, 100]


import time
import os
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from keras.utils import to_categorical
from keras.models import (
                          Model,
                          )
from keras.layers import (
                          Activation,
                          Conv2D,
                          Dense,
                          Flatten,
                          Input,
                          MaxPooling2D,
                          Dropout,
                          )
import keras
from keras.models import Sequential

# Required magic to display matplotlib plots in notebooks
#%matplotlib inline

# Set up a figure of an appropriate size
# create empty list
images_dataset = []
class_labels = []
batch_size = 128
epochs = 50

# Helper function to resize image proportionally. size is a tuple (height,width)
def resize_image(img, size):
    from PIL import Image, ImageOps

    # resize the image so the longest dimension matches our target size
    img.thumbnail(size, Image.ANTIALIAS)

    # Create a new square white background image
    newimg = Image.new("RGB", size, (255, 255, 255))

    # Paste the resized image into the center of the square background
    if np.array(img).shape[2] == 4:
        # If the source is in RGBA format, use a mask to eliminate the transparency
        newimg.paste(img, (int((size[0] - img.size[0]) / 2), int((size[1] - img.size[1]) / 2)), mask=img.split()[3])
    else:
        newimg.paste(img, (int((size[0] - img.size[0]) / 2), int((size[1] - img.size[1]) / 2)))

    # return the resized image
    return newimg

# loop through the subfolders in the input directory
image_base_dir = './train'
n = 0
for root, folders, filenames in os.walk(image_base_dir):
    for folder in folders:
        class_labels.append(folder)
        print('processing folder:{}'.format(folder))
        n = n+1
        files = os.listdir(os.path.join(root,folder))
        for file in files:
            # construct the fully image filename(including path)
            imgFile = os.path.join(image_base_dir,folder, file)
            # read image data
            img = Image.open(imgFile)
            # resize image
            img = resize_image(img,(128,128))
            # images_dataset is list of numpy array and label
            images_dataset.append([np.array(np.array(img)),folder])

print('n={}'.format(n))
# shuffle the dataset
np.random.shuffle(images_dataset)

# fetch image data from gear_dataset
images_data = list(map(
                       lambda item: item[0],
                       images_dataset
                       ))

# fetch label data from gear_dataset
images_labels = list(map(
                       lambda item: item[1],
                       images_dataset,
                       ))
# images_data and images_labels are list now, should be converted to np.array
images_data = np.array(images_data,dtype=np.float)/255.
images_labels = np.array(images_labels)

# one hot encoding labels
# encode the labels into one hot encoding
encoder = preprocessing.LabelEncoder()
encoder.fit(images_labels)
print('class={}'.format(encoder.classes_))   # ['cats' 'dogs']
le_classes = encoder.transform(encoder.classes_)  # [0,1]
# zip pack the two object's element into a tuple: [0:'cats,1:'dogs']
# create a dictionary from a list of tuple
le_name_mapping = dict(zip(le_classes,encoder.classes_))
print(le_name_mapping,le_name_mapping[0])
output2 = open('pzsmodel2_labdic.pkl', 'wb')
pickle.dump(le_name_mapping, output2)
output2.close()

# save the digits and its corresponding labels
transfomed_label = encoder.fit_transform(class_labels)
print(transfomed_label)

# string to number. cats->0 dogs->1
labels_id = encoder.transform(images_labels)
# one hot encoding. Converts a class vector (integers) to binary class matrix. A binary matrix representation of the input. The classes axis is placed last.
labels_encoded = to_categorical(labels_id)
# split training and testing dataset
train_x,test_x,train_y,test_y = train_test_split(images_data,labels_encoded,test_size=0.2)
#print('shape={}'.format(np.array(images_dataset).shape))

#
model = Sequential()
# strides=(1,1) padding='valid'
model.add(Conv2D(32, (3, 3), activation='relu',input_shape=(128,128,3)))
print('output shape1={}'.format(model.output_shape))
model.add(Dropout(0.2))
print('output shape2={}'.format(model.output_shape))
# pool_size: integer or tuple of 2 integers, factors by which to downscale (vertical, horizontal).
# strides: Integer, tuple of 2 integers, or None. Strides values. If None, it will default to pool_size.
model.add(MaxPooling2D(pool_size=(3, 3)))
print('output shape3={}'.format(model.output_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
print('output shape4={}'.format(model.output_shape))
model.add(MaxPooling2D(pool_size=(3, 3)))
print('output shape5={}'.format(model.output_shape))
model.add(Dropout(0.2))
model.add(Conv2D(128, (3, 3), activation='relu'))
print('output shape6={}'.format(model.output_shape))
model.add(MaxPooling2D(pool_size=(3, 3)))
print('output shape7={}'.format(model.output_shape))
model.add(Flatten())
print('output shape8={}'.format(model.output_shape))
model.add(Dense(128, activation='relu'))
# Softmax makes the output sum up to 1 so the output can be interpreted as probabilities.
model.add(Dense(n, activation='softmax'))
print('output shape9={}'.format(model.output_shape))
# Configures the model for training.
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adam(),
              metrics=['accuracy'])

# Trains the model for a given number of epochs (iterations on a dataset).
history= model.fit(train_x, train_y,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(test_x, test_y))

# Returns the loss value & metrics values for the model in test mode.
score = model.evaluate(test_x, test_y, verbose=0)
print('score={}'.format(score))
#print('history={}'.format(history.accuracy))

# load predict images
predict_data = []
predict_images = []
size = (128,128)
files = os.listdir('./predict')
for f in files:
    if not 'jpg' in f:
        continue
    img = Image.open(os.path.join('./predict',f))
    # resize images
    img = resize_image(img,size)
    predict_data.append(np.array(img))

#img = Image.open('resized_images/hardshell_jackets_test/resized_10269570x1012905_zm.jpeg')
predict_data = np.array(predict_data,dtype='float')/255.

predicted_labels_encoded = model.predict(
                                 predict_data,
                                 # batch_size=128,
                                 )
# predicted_labels_encoded is an array ,so np.argmax must specify the axis, so the result is also an arrar
predicted_labels = np.argmax(predicted_labels_encoded,axis=1)
print('predicted digits={}'.format(predicted_labels))
predicted_labels = encoder.inverse_transform(predicted_labels)
print('predicted labels=',predicted_labels)

# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

i = 0
#fig = plt.figure(figsize=(10, 10))
for data in predict_data:
    ax = plt.subplot(1,4,i+1)
    #img = Image.open(test_img_url)
    #img = np.array(img)
    data = (data * 255.).astype(np.uint8)
    imgplot = plt.imshow(data)
    ax.set_title(predicted_labels[i])
    i = i+1
plt.show()
# save the model

model.save('catsdogs.h5')


#!/usr/bin/env python3

import sys
import re
import math

import numpy as np

def simulate_motion(moons, velocity):
    velocity_diff = np.zeros(moons.shape)

    for axis in range(0, 3):
        for moon_index_1 in range(0, moons.shape[0]):
            for moon_index_2 in range(0, moons.shape[0]):
                if moon_index_1 != moon_index_2:
                    if moons[moon_index_1][axis] < \
                            moons[moon_index_2][axis]:
                        velocity_diff[moon_index_1][axis] += 1
                    elif moons[moon_index_1][axis] > \
                            moons[moon_index_2][axis]:
                        velocity_diff[moon_index_1][axis] -= 1

    for moon_index in range(0, moons.shape[0]):
        velocity[moon_index] = velocity[moon_index] + velocity_diff[moon_index]
        moons[moon_index] = moons[moon_index] + velocity[moon_index]

def find_repeat(moons):
    moons_first = np.copy(moons)
    velocity = np.zeros(moons.shape)

    full_repeat = 1
    repeated = [0] * moons.shape[1]

    step = 0

    while True:
        simulate_motion(moons, velocity)
        step += 1

        for axis in range(0, 3):
            if repeated[axis] == 0:
                flag_1 = np.array_equal(
                    moons[:, axis],
                    moons_first[:, axis])

                flag_2 = np.array_equal(
                    velocity[:, axis],
                    np.array([0] * moons.shape[0]))

                if flag_1 and flag_2:
                    full_repeat = full_repeat * step // \
                        math.gcd(full_repeat, step)
                    repeated[axis] = 1

        if sum(repeated) == moons.shape[1]:
            break

    return full_repeat

def parse_input(data):
    moons_lst = []

    for line in data:
        line = line.strip()

        m = re.match(r'<x=(.+), y=(.+), z=(.+)>', line)

        if m:
            moons_lst.append(list(map(int, m.groups())))

    return np.array(moons_lst)

class TestClass:
    def test_find_repeat_0(self):
        data = [
            '<x=-1, y=0, z=2>',
            '<x=2, y=-10, z=-7>',
            '<x=4, y=-8, z=8>',
            '<x=3, y=5, z=-1>']

        moons = parse_input(data)

        step = find_repeat(moons)

        assert step == 2772

    def test_find_repeat_1(self):
        data = [
            '<x=-8, y=-10, z=0>',
            '<x=5, y=5, z=10>',
            '<x=2, y=-7, z=3>',
            '<x=9, y=-8, z=-3>']

        moons = parse_input(data)

        step = find_repeat(moons)

        assert step == 4686774924

if __name__ == '__main__':
    data = sys.stdin.readlines()

    moons = parse_input(data)

    step = find_repeat(moons)

    print(step)


import sys
import logging

APP_LOGGER_NAME = 'snappi_ixnetwork'

def setup_ixnet_logger(log_level, file_name=None, module_name=None):
    logger = logging.getLogger(APP_LOGGER_NAME)
    logger.setLevel(log_level)
    formatter = logging.Formatter(fmt="%(asctime)s [%(name)s] [%(levelname)s] %(message)s",
                                  datefmt="%Y-%m-%d %H:%M:%S")
    sh = logging.StreamHandler(sys.stdout)
    sh.setFormatter(formatter)
    if len(logger.handlers) > 0:
        del logger.handlers[:]
    logger.addHandler(sh)
    if file_name:
        fh = logging.FileHandler(file_name)
        fh.setFormatter(formatter)
        logger.addHandler(fh)
    if module_name is not None:
        logger = get_ixnet_logger(module_name)
    return logger

def get_ixnet_logger(module_name):
    module_name = ".".join(str(module_name).split(".")[1:])
    return logging.getLogger(APP_LOGGER_NAME).getChild(module_name)