import numpy as np
import cv2
from hog_fitures import HOG_fitures
from utils import *

fhog = HOG_fitures()

class KCFTracker:
    def __init__(self, hog=False, fixed_window=True, multiscale=False):
        self.lambda_reg          = 0.0001  # регуляризация
        self.padding             = 2.5     # дополнительная область вокруг цели
        self.output_sigma_factor = 0.125   # полоса пропускания гауссовой цели

        if(hog):  # HOG
            # VOT
            self.interp_factor = 0.012     # коэффициент линейной интерполяции для адаптации
            self.sigma = 0.6               # пропускная способность гауссовского ядра
            self.cell_size = 4             # HOG размер ячейки
            self._hogfeatures = True
        else:
            self.interp_factor = 0.075
            self.sigma = 0.2
            self.cell_size = 1
            self._hogfeatures = False

        if(multiscale):
            self.template_size = 96        # размер шаблона
            self.scale_step = 1.05         # шаг шкалы для многомасштабной оценки
            self.scale_weight = 0.96       # для снижения показателей обнаружения других шкал для дополнительной стабильности
        elif(fixed_window):
            self.template_size = 96
            self.scale_step = 1
        else:
            self.template_size = 1
            self.scale_step = 1

        self._tmpl_sz = [0, 0]
        self._roi = [0., 0., 0., 0.]
        self.size_patch = [0, 0, 0]
        self._scale = 1.
        self._alphaf = None
        self._prob = None
        self._tmpl = None
        self.hann = None

    def subPixelPeak(self, left, center, right):
        divisor = 2 * center - right - left
        return (0 if abs(divisor) < 1e-3 else 0.5 * (right - left) / divisor)

    def createHanningMats(self):
        hann2t, hann1t = np.ogrid[0:self.size_patch[0], 0:self.size_patch[1]]

        hann1t = 0.5 * (1 - np.cos(2 * np.pi * hann1t / (self.size_patch[1] - 1)))
        hann2t = 0.5 * (1 - np.cos(2 * np.pi * hann2t / (self.size_patch[0] - 1)))
        hann2d = hann2t * hann1t

        if(self._hogfeatures):
            hann1d = hann2d.reshape(self.size_patch[0] * self.size_patch[1])
            self.hann = np.zeros((self.size_patch[2], 1), np.float32) + hann1d
        else:
            self.hann = hann2d
        self.hann = self.hann.astype(np.float32)

    def createGaussianPeak(self, sizey, sizex):
        syh, sxh = sizey / 2, sizex / 2
        output_sigma = np.sqrt(sizex * sizey) / self.padding * self.output_sigma_factor
        mult = -0.5 / (output_sigma * output_sigma)
        y, x = np.ogrid[0:sizey, 0:sizex]
        y, x = (y - syh)**2, (x - sxh)**2
        res = np.exp(mult * (y + x))
        return fftd(res)

    def gaussianCorrelation(self, x1, x2):
        if(self._hogfeatures):
            c = np.zeros((self.size_patch[0], self.size_patch[1]), np.float32)
            for i in range(self.size_patch[2]):
                x1aux = x1[i, :].reshape((self.size_patch[0], self.size_patch[1]))
                x2aux = x2[i, :].reshape((self.size_patch[0], self.size_patch[1]))
                caux = cv2.mulSpectrums(fftd(x1aux), fftd(x2aux), 0, conjB=True)
                caux = real(fftd(caux, True))
                #caux = rearrange(caux)
                c += caux
            c = rearrange(c)
        else:
            c = cv2.mulSpectrums(fftd(x1), fftd(x2), 0, conjB=True)   # 'conjB=' is necessary!
            c = fftd(c, True)
            c = real(c)
            c = rearrange(c)

        if(x1.ndim == 3 and x2.ndim == 3):
            d = (np.sum(x1[:, :, 0] * x1[:, :, 0]) + np.sum(x2[:, :, 0] * x2[:, :, 0]) - 2.0 * c) / (self.size_patch[0] * self.size_patch[1] * self.size_patch[2])
        elif(x1.ndim == 2 and x2.ndim == 2):
            d = (np.sum(x1 * x1) + np.sum(x2 * x2) - 2.0 * c) / (self.size_patch[0] * self.size_patch[1] * self.size_patch[2])

        d = d * (d >= 0)
        d = np.exp(-d / (self.sigma * self.sigma))

        return d

    def getFeatures(self, image, inithann, scale_adjust=1.0):
        extracted_roi = [0, 0, 0, 0]
        cx = self._roi[0] + self._roi[2] / 2
        cy = self._roi[1] + self._roi[3] / 2

        if(inithann):
            padded_w = self._roi[2] * self.padding
            padded_h = self._roi[3] * self.padding

            if(self.template_size > 1):
                if(padded_w >= padded_h):
                    self._scale = padded_w / float(self.template_size)
                else:
                    self._scale = padded_h / float(self.template_size)
                self._tmpl_sz[0] = int(padded_w / self._scale)
                self._tmpl_sz[1] = int(padded_h / self._scale)
            else:
                self._tmpl_sz[0] = int(padded_w)
                self._tmpl_sz[1] = int(padded_h)
                self._scale = 1.

            if(self._hogfeatures):
                self._tmpl_sz[0] = int(self._tmpl_sz[0]) // (2 * self.cell_size) * 2 * self.cell_size + 2 * self.cell_size
                self._tmpl_sz[1] = int(self._tmpl_sz[1]) // (2 * self.cell_size) * 2 * self.cell_size + 2 * self.cell_size
            else:
                self._tmpl_sz[0] = int(self._tmpl_sz[0]) // 2 * 2
                self._tmpl_sz[1] = int(self._tmpl_sz[1]) // 2 * 2

        extracted_roi[2] = int(scale_adjust * self._scale * self._tmpl_sz[0])
        extracted_roi[3] = int(scale_adjust * self._scale * self._tmpl_sz[1])
        extracted_roi[0] = int(cx - extracted_roi[2] / 2)
        extracted_roi[1] = int(cy - extracted_roi[3] / 2)

        z = subwindow(image, extracted_roi, cv2.BORDER_REPLICATE)
        if(z.shape[1] != self._tmpl_sz[0] or z.shape[0] != self._tmpl_sz[1]):
            z = cv2.resize(z, tuple(self._tmpl_sz))

        if(self._hogfeatures):
            mapp = {'sizeX': 0, 'sizeY': 0, 'numFeatures': 0, 'map': 0}
            mapp = fhog.getFeatureMaps(z, self.cell_size, mapp)
            mapp = fhog.normalizeAndTruncate(mapp, 0.2)
            mapp = fhog.PCAFeatureMaps(mapp)
            self.size_patch = list(map(int, [mapp['sizeY'], mapp['sizeX'], mapp['numFeatures']]))
            FeaturesMap = mapp['map'].reshape((self.size_patch[0] * self.size_patch[1], self.size_patch[2])).T
        else:
            if(z.ndim == 3 and z.shape[2] == 3):
                FeaturesMap = cv2.cvtColor(z, cv2.COLOR_BGR2GRAY)
            elif(z.ndim == 2):
                FeaturesMap = z
            FeaturesMap = FeaturesMap.astype(np.float32) / 255.0 - 0.5
            self.size_patch = [z.shape[0], z.shape[1], 1]

        if(inithann):
            self.createHanningMats()

        FeaturesMap = self.hann * FeaturesMap
        return FeaturesMap

    def detect(self, z, x):
        k = self.gaussianCorrelation(x, z)
        res = real(fftd(complex_multiplication(self._alphaf, fftd(k)), True))

        _, pv, _, pi = cv2.minMaxLoc(res)
        p = [float(pi[0]), float(pi[1])]

        if(pi[0] > 0 and pi[0] < res.shape[1] - 1):
            p[0] += self.subPixelPeak(res[pi[1], pi[0] - 1], pv, res[pi[1], pi[0] + 1])
        if(pi[1] > 0 and pi[1] < res.shape[0] - 1):
            p[1] += self.subPixelPeak(res[pi[1] - 1, pi[0]], pv, res[pi[1] + 1, pi[0]])

        p[0] -= res.shape[1] / 2.
        p[1] -= res.shape[0] / 2.

        return p, pv

    def train(self, x, train_interp_factor):
        k = self.gaussianCorrelation(x, x)
        alphaf = complex_division(self._prob, fftd(k) + self.lambda_reg)

        self._tmpl = (1 - train_interp_factor) * self._tmpl + train_interp_factor * x
        self._alphaf = (1 - train_interp_factor) * self._alphaf + train_interp_factor * alphaf

    def init(self, roi, image):
        self._roi = list(map(float, roi))
        assert(roi[2] > 0 and roi[3] > 0)
        self._tmpl = self.getFeatures(image, 1)
        self._prob = self.createGaussianPeak(self.size_patch[0], self.size_patch[1])
        self._alphaf = np.zeros((self.size_patch[0], self.size_patch[1], 2), np.float32)
        self.train(self._tmpl, 1.0)

    def update(self, image):
        if(self._roi[0] + self._roi[2] <= 0):
            self._roi[0] = -self._roi[2] + 1
        if(self._roi[1] + self._roi[3] <= 0):
            self._roi[1] = -self._roi[2] + 1
        if(self._roi[0] >= image.shape[1] - 1):
            self._roi[0] = image.shape[1] - 2
        if(self._roi[1] >= image.shape[0] - 1):
            self._roi[1] = image.shape[0] - 2

        cx = self._roi[0] + self._roi[2] / 2.
        cy = self._roi[1] + self._roi[3] / 2.

        loc, peak_value = self.detect(self._tmpl, self.getFeatures(image, 0, 1.0))

        if(self.scale_step != 1):
            # Маленький scale
            new_loc1, new_peak_value1 = self.detect(self._tmpl, self.getFeatures(image, 0, 1.0 / self.scale_step))
            # Большой scale
            new_loc2, new_peak_value2 = self.detect(self._tmpl, self.getFeatures(image, 0, self.scale_step))

            if(self.scale_weight * new_peak_value1 > peak_value and new_peak_value1 > new_peak_value2):
                loc = new_loc1
                peak_value = new_peak_value1
                self._scale /= self.scale_step
                self._roi[2] /= self.scale_step
                self._roi[3] /= self.scale_step
            elif(self.scale_weight * new_peak_value2 > peak_value):
                loc = new_loc2
                peak_value = new_peak_value2
                self._scale *= self.scale_step
                self._roi[2] *= self.scale_step
                self._roi[3] *= self.scale_step

        self._roi[0] = cx - self._roi[2] / 2.0 + loc[0] * self.cell_size * self._scale
        self._roi[1] = cy - self._roi[3] / 2.0 + loc[1] * self.cell_size * self._scale

        if(self._roi[0] >= image.shape[1] - 1):
            self._roi[0] = image.shape[1] - 1
        if(self._roi[1] >= image.shape[0] - 1):
            self._roi[1] = image.shape[0] - 1
        if(self._roi[0] + self._roi[2] <= 0):
            self._roi[0] = -self._roi[2] + 2
        if(self._roi[1] + self._roi[3] <= 0):
            self._roi[1] = -self._roi[3] + 2
        assert(self._roi[2] > 0 and self._roi[3] > 0)

        x = self.getFeatures(image, 0, 1.0)
        self.train(x, self.interp_factor)

        return self._roi


class Node:
    def __init__(self, value):
        self.data = value
        self.next = None

class SLinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def insertSLL(self, value, loc):
        newNode = Node(value)
        if self.head is None:
            self.head = newNode
            self.tail = newNode
        else:
            if loc == 0:
                newNode.next = self.head
                self.head = newNode
            elif loc == -1:
                self.tail.next = newNode
                self.tail = newNode
            else:
                node = self.head
                index = 0
                while index < loc - 1:
                    node = node.next
                    index += 1

                if self.tail is not node:
                    newNode.next = node.next
                    node.next = newNode
                else:
                    self.tail.next = newNode
                    self.tail = newNode

        return newNode

    def deleteSLL(self, loc):
        if self.head is None:
            return 'SLL is empty'

        if loc == 0:
            if self.head == self.tail:
                self.head = None
                self.tail = None
                return 'Node removed from SLL!'
            else:
                tempNode = self.head.next
                self.head.next = None
                self.head = tempNode
                return 'Node removed from head!'

        elif loc == -1:
            if self.head == self.tail:
                self.head = None
                self.tail = None
                return 'Node removed from SLL!'
            else:
                cNode = self.head
                while cNode.next.next is not None:
                    cNode = cNode.next

                cNode.next = None
                self.tail = cNode

        else:
            cNode = self.head
            index = 0
            while index < loc - 1:
                cNode = cNode.next
                index += 1

            if cNode.next is not self.tail:
                cNode.next = cNode.next.next
            else:
                cNode.next = self.tail.next
                self.tail = cNode

    def findLLength(self):
        node = self.head
        count = 0
        while node is not None:
            node = node.next
            count += 1
        return count

    def findLLLengthRec(self, node):
        if self.head is None:
            return 'SLL is empty!'

        if node is None:
            return 0
        return 1 + self.findLLLengthRec(node.next)

    def searchVal(self, value):
        node = self.head
        while node is not None:
            if node.data == value:
                return value
            node = node.next
        return 'Value does not exist!'

    def searchValRec(self, node, value):
        if node.data == value:
            return node.data
        if node.next is not None:
            return self.searchValRec(node.next, value)
        else:
            return 'Value does not exist!'

    def findNthVal(self, index):
        node = self.head
        cIndex = 0
        while cIndex < index - 1:
            if node.next:
                node = node.next
            else:
                return 'Index value out of range!'
            cIndex += 1
        return node.data

    def findNFromEnd(self, index):
        resIndex = self.findLLLengthRec(self.head) - index
        return self.findNthVal(resIndex)

    def findMiddle(self):
        total_length = self.findLLength()
        middle = total_length // 2

        node = self.head
        index = 0
        while index < middle:
            node = node.next
            index += 1
        return node.data

    def findOccurrence(self, value):
        node = self.head
        count = 0
        while node is not None:
            if node.data == value:
                count += 1
            node = node.next
        return count

    def detectLoop(self):
        s = set()
        node = self.head
        while node is not None:
            if node not in s:
                s.add(node)
                node = node.next
            else:
                return 'Loop detected!'

        return 'No Loop!'

    def lengthOfLoop(self):
        d = {}
        node = self.head
        index = 0
        while node is not None:
            d[node] = index
            if node.next not in d:
                node = node.next
                index += 1
            else:
                return d[node] - d[node.next]
        return 'No loop detected!'

    def lengthOfLoopChase(self):
        slow = self.head
        fast = self.head
        count = 0
        while slow is not None:
            slow = slow.next
            if fast.next is None:
                return 'No Loop!'
            fast = fast.next.next
            count += 1
            if slow == fast:
                return count - 1

        return 'No Loop!'

    def reverseSLL(self):

        prev = None
        self.tail = self.head
        currNode = self.head

        while currNode is not None:
            next = currNode.next
            currNode.next = prev
            prev = currNode
            currNode = next

        self.head = prev

    def checkPalindrome(self):
        count = 0
        # Find total length
        node = self.head
        while node is not None:
            node = node.next
            count += 1

        # Find middle
        if count % 2 == 0:
            mid = (count // 2) - 1
        else:
            mid = (count // 2)

        # Check palindrome
        loop_count = 0
        cNode = self.head
        while loop_count <= mid:
            last_ele = self.findNFromEnd(loop_count)
            if cNode.data != last_ele:
                return False
            cNode = cNode.next
            loop_count += 1

        return True

    def removeDuplicatesSorted(self):

        node = self.head
        same = self.head

        while node.next is not None:

            if node.next.data != same.data or node.next is None:
                same.next = node.next
                same = node.next

            node = node.next

        self.tail = same

    def removeDuplicatesUnsorted(self):

        node = self.head
        exists = set()
        exists.add(node.data)
        last_ele = self.head
        while node.next:

            if node.next.data not in exists:

                last_ele.next = node.next
                exists.add(node.next.data)
                last_ele = node.next

            if node.next == self.tail:
                last_ele.next = self.tail.next
                self.tail = last_ele

            if node.next:
                node = node.next

        self.tail = last_ele

    def swapNodes(self, nodeA_data, nodeB_data):
        nodeA_data = str(nodeA_data)
        nodeB_data = str(nodeB_data)
        nodeA_isHead = False
        nodeB_isHead = False
        nodeA_prev = None
        nodeB_prev = None
        if self.head.data == nodeA_data:
            nodeA_isHead = True
        if self.head.data == nodeB_data:
            nodeB_isHead = True

        node = self.head
        while node.next is not None:
            if node.next.data == nodeA_data and not nodeA_isHead:
                nodeA_prev = node
            if node.next.data == nodeB_data and not nodeB_isHead:
                nodeB_prev = node
            node = node.next

        if nodeA_isHead:
            nodeA_prev = self.head
            nodeA_next = nodeA_prev.next
            nodeA_prev.next = nodeB_prev.next.next
            nodeB_next = nodeB_prev.next
            nodeB_prev.next = nodeA_prev
            self.head = nodeB_next
            nodeB_next.next = nodeA_next

        if nodeB_isHead:
            nodeB_prev = self.head
            nodeB_next = nodeB_prev.next
            nodeB_prev.next = nodeA_prev.next.next
            nodeA_next = nodeA_prev.next
            nodeA_prev.next = nodeB_prev
            self.head = nodeA_next
            nodeA_next.next = nodeB_next

        if not nodeA_isHead and not nodeB_isHead:
            nodeA = nodeA_prev.next
            nodeB = nodeB_prev.next

            nodeA_next = nodeA.next
            nodeB_next = nodeB.next

            #Swap the next nodes first
            temp = nodeA_next
            nodeA.next = nodeB_next
            nodeB.next = temp

            # Swap the actual nodes now
            temp = nodeA_prev.next
            nodeA_prev.next = nodeB_prev.next
            nodeB_prev.next = temp

    def pairWiseSwap(self):
        index = 0
        node = self.head
        while node.next is not None:
            if index % 2 == 0:
                temp = node.data
                node.data = node.next.data
                node.next.data = temp
            index += 1
            node = node.next

    def moveLastToFirst(self):
        # Find the second last ele
        node = self.head
        while node.next.next:
            node = node.next

        node.next.next = self.head
        self.head = node.next
        node.next = None
        self.tail = node

    def evenAndOdd(self):
        node = self.head
        prev_node = None
        tail_node = self.tail
        while node.next != tail_node:
            if int(node.data) % 2 != 0:
                if self.head.data == node.data:
                    self.head = node.next
                    self.tail.next = node
                    next_node = node.next
                    node.next = None
                    self.tail = node
                    node = next_node
                else:
                    prev_node.next = node.next
                    self.tail.next = node
                    next_node = node.next
                    node.next = None
                    self.tail = node
                    node = next_node
            else:
                prev_node = node
                node = node.next

    def reverseLinkedList(self):
        node = self.head
        self.tail = self.head
        prev_node = None
        while node is not None:
            next_node = node.next
            node.next = prev_node
            prev_node = node
            node = next_node

        self.head = prev_node

    def reverseSLLRecursion(self, currNode):
        if currNode.next is None:
            self.head = currNode
            return currNode
        else:
            tailNode = self.reverseSLLRecursion(currNode.next)
            currNode.next = None
            tailNode.next = currNode
            return currNode

    def reverseSLLTwoPointers(self):
        pass

def findIntersection(startNodeA, startNodeB):

    # Find length of both SLL
    a_length = 0
    nodeA = startNodeA
    while nodeA is not None:
        a_length += 1
        nodeA = nodeA.next

    b_length = 0
    nodeB = startNodeB
    while nodeB is not None:
        b_length += 1
        nodeB = nodeB.next

    # Find the difference in length
    diff_length = a_length - b_length if a_length >= b_length else b_length - a_length

    if diff_length > 0:
        if a_length > b_length:
            indexA = 0
            nodeA = startNodeA
            nodeB = startNodeB
            while indexA < diff_length:
                indexA += 1
                nodeA = nodeA.next
        else:
            indexB = 0
            nodeA = startNodeA
            nodeB = startNodeB
            while indexB < diff_length:
                indexB += 1
                nodeB = nodeB.next
    else:
        nodeA = startNodeA
        nodeB = startNodeB

    while nodeA != None and nodeB != None:
        if nodeA.data == nodeB.data:
            return 'Intersection at ' + nodeA.data

        nodeA = nodeA.next
        nodeB = nodeB.next

    return "No Intersection!"

P = SLinkedList()
P.insertSLL('11', -1)
P.insertSLL('13', -1)
P.insertSLL('21', -1)
P.insertSLL('32', -1)
P.insertSLL('23', -1)
P.insertSLL('44', -1)

S = SLinkedList()
P.insertSLL('22', -1)
P.insertSLL('33', -1)
P.insertSLL('23', -1)
P.insertSLL('44', -1)

print()

print(findIntersection(P.head, S.head))

node = P.head
while node:
    if node.next:
        print(node.data, end=' --> ')
    else:
        print(node.data, end=' ')
    node = node.next


from openerp.osv.orm import Model

class sale_order_line(Model):
    _inherit = 'sale.order.line'

    def product_id_change(
            self, cr, uid, ids, pricelist, product, qty=0, uom=False,
            qty_uos=0, uos=False, name='', partner_id=False, lang=False,
            update_tax=True, date_order=False, packaging=False,
            fiscal_position=False, flag=False, context=None):
        res = super(sale_order_line, self).product_id_change(
            cr, uid, ids, pricelist, product, qty=qty, uom=uom,
            qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id,
            lang=lang, update_tax=update_tax, date_order=date_order,
            packaging=packaging, fiscal_position=fiscal_position, flag=flag,
            context=context)
        if self.pool['res.users'].has_group(
                cr, uid,
                'sale_line_change_custom.group_sale_order_line_no_warning'):
            res.pop('warning', False)
        return res


'''Foram anotadas as idades e alturas de 30 alunos. Faça um Programa que determine quantos alunos com mais de 13 anos possuem altura inferior à média de altura desses alunos.'''

idade_alunos: list = []
altura_alunos: list = []

for posição in range(1, 6):
    idade = int(input(f'Digite a idade do {posição}º aluno: '))
    altura = float(input(f'Digite a altura do {posição}º aluno: '))
    idade_alunos.append(idade)
    altura_alunos.append(altura)

media_altura_alunos = sum(altura_alunos) / len(altura_alunos)
idades_e_alturas = list(zip(idade_alunos, altura_alunos))

quantidade_pessoas_baixas = 0
for dados in idades_e_alturas:
    idade, altura = dados
    if idade > 13 and altura < media_altura_alunos:
        quantidade_pessoas_baixas += 1

print(f'''Entre os alunos registrados há {quantidade_pessoas_baixas}
alunos maiores de 13 anos com altura menor que a média ({media_altura_alunos:.1f})''')


import utility as utl
import torchnet.meter as tnt
import performance_tracker as pt
import checkpoint as ckpt
import summary
import sensitivity_analysis as sa
import collector
import logging
import config
import math
import time
import random
from collections import OrderedDict
from torch.autograd import Variable
from apex import amp
from functools import partial
import logging
import torch
import numpy as np

msglogger = logging.getLogger()
# Currently, YOLOv1 only follow the regression loss, the class meter thus remove at this stage:
def _log_training_progress(args, losses, epoch, steps_completed, steps_per_epoch, batch_time, optimizer, loggers):
    # Log some statistics
    errs = OrderedDict()

    #if not early_exit_mode(args):
    """
    Early exist model may be incorporated in the future.
    else:
        # For Early Exit case, the Top1 and Top5 stats are computed for each exit.
        for exitnum in range(args.num_exits):
            errs['Top1_exit' + str(exitnum)] = args.exiterrors[exitnum].value(1)
            errs['Top5_exit' + str(exitnum)] = args.exiterrors[exitnum].value(5)
    """
    stats_dict = OrderedDict()
    for loss_name, meter in losses.items():
        stats_dict[loss_name] = meter.mean

    stats_dict.update(errs)
    stats_dict['LR'] = optimizer.param_groups[0]['lr']
    stats_dict['Time'] = batch_time.mean
    stats = ('Performance/Training/', stats_dict)

    params = model.named_parameters() if args.log_params_histograms else None
    utl.log_training_progress(stats, params, epoch, steps_completed,
                              steps_per_epoch, args.print_freq, loggers)

def light_train_with_distiller(args, model, optimizer, compress_scheduler, device, dataloaders, dataset_sizes, loggers, epoch=1):

    """
    Training-with-compression loop for one epoch.
    IMPORTANT INFORMATION:

    For each training step in epoch:
        compression_scheduler.on_minibatch_begin(epoch)
        output = model(input)
        loss = criterion(output, target)
        compression_scheduler.before_backward_pass(epoch)
        loss.backward()
        compression_scheduler.before_parameter_optimization(epoch)
        optimizer.step()
        compression_scheduler.on_minibatch_end(epoch)
    """
    total_samples = dataset_sizes['train']
    batch_size = dataloaders["train"].batch_size

    steps_per_epoch = math.ceil(total_samples / batch_size)
    batch_time = tnt.AverageValueMeter()
    data_time = tnt.AverageValueMeter()

    OVERALL_LOSS_KEY = 'Overall Loss'
    #OBJECTIVE_LOSS_KEY = 'Objective Loss' # Only compute loss from the cost function, but we revise its name in Natural loss.
    NAT_LOSS_KEY = "Natural Loss"
    losses = OrderedDict([(OVERALL_LOSS_KEY, tnt.AverageValueMeter()),
                         (NAT_LOSS_KEY, tnt.AverageValueMeter())])

    model.train()
    end = time.time()
    for train_step, data in enumerate(dataloaders["train"], 0):
        inputs = Variable(data[0]).float().to(device)
        labels = Variable(data[1]).float().to(device)

        if compress_scheduler:
            compress_scheduler.on_minibatch_begin(epoch, train_step, steps_per_epoch, optimizer)

        nat_output = model(inputs, labels) # Tuple (loss, pred_tensor)
        losses[NAT_LOSS_KEY].add(nat_output[0].item())

        """
        ****
        Drop the early exist mode in this first version
        ****
        if not early_exit_mode(args):
        loss = criterion(output, target)
        # Measure accuracy
        classerr.add(output.detach(), target)
        acc_stats.append([classerr.value(1), classerr.value(5)])
        else:
        # Measure accuracy and record loss
        classerr.add(output[args.num_exits-1].detach(), target) # add the last exit (original exit)
        loss = earlyexit_loss(output, target, criterion, args)
        """

        if compress_scheduler:
            # Should be revised if using adversarial robustness training.
            agg_loss =  compress_scheduler.before_backward_pass(epoch, train_step, steps_per_epoch, nat_output[0],
                                                                optimizer=optimizer, return_loss_components=True)
            # Should be modified, this may be incorporated in the future.
            loss = agg_loss.overall_loss
            # if admm loss is zero, following line may raise error.
            losses[OVERALL_LOSS_KEY].add(loss.item())
            for lc in agg_loss.loss_components:
                if lc.name not in losses:
                    losses[lc.name] = tnt.AverageValueMeter()
                try:
                    losses[lc.name].add(lc.value.item())
                except:
                    # This is a constant case which may be raised by our ADMM implementation.
                    losses[lc.name].add(lc.value)
        else:
            losses[OVERALL_LOSS_KEY].add(nat_loss.item())
            loss = nat_loss

        optimizer.zero_grad()

        # ******************
        # Try apex AMP package:
        # ******************
        if args.apex:
            with amp.scale_loss(loss, optimizer) as scaled_loss:
                scaled_loss.backward()
        else:
            loss.backward()

        if compress_scheduler:
            # Applied zero gradient here.
            compress_scheduler.before_parameter_optimization(epoch, train_step, steps_per_epoch, optimizer)

        optimizer.step()
        if compress_scheduler:
            # Sometime this on "minibatch_end" function will not do anything.
            compress_scheduler.on_minibatch_end(epoch, train_step, steps_per_epoch, optimizer)

        batch_time.add(time.time() - end)
        steps_completed = (train_step + 1)

        if steps_completed % args.print_freq == 0 :
            # arguments for this function: losses, epoch, steps_completed, steps_per_epoch, batch_time, optimizer, loggers
            _log_training_progress(args, losses, epoch, steps_completed, steps_per_epoch, batch_time, optimizer, loggers)
        end = time.time()

    utl.log_weights_sparsity(model, epoch, loggers)
    return losses[NAT_LOSS_KEY], losses[OVERALL_LOSS_KEY]

def _log_valiation_progress(args, losses, epoch, steps_completed, steps_per_epoch, loggers):
    #if not _is_earlyexit(args):
    """
    Early exist model use following code:
    else:
        stats_dict = OrderedDict()
        for exitnum in range(args.num_exits):
            la_string = 'LossAvg' + str(exitnum)
            stats_dict[la_string] = args.losses_exits[exitnum].mean
            # Because of the nature of ClassErrorMeter, if an exit is never taken during the batch,
            # then accessing the value(k) will cause a divide by zero. So we'll build the OrderedDict
            # accordingly and we will not print for an exit error when that exit is never taken.
            if args.exit_taken[exitnum]:
                t1 = 'Top1_exit' + str(exitnum)
                t5 = 'Top5_exit' + str(exitnum)
                stats_dict[t1] = args.exiterrors[exitnum].value(1)
                stats_dict[t5] = args.exiterrors[exitnum].value(5)
    """

    stats_dict = OrderedDict(('Nat_Loss', losses['natural_loss'].mean))
    stats = ('Performance/Validation/', stats_dict)
    utl.log_training_progress(stats, None, epoch, steps_completed,
                                   steps_per_epoch, args.print_freq, loggers)

def _validate(args, dataloaders, data_group, model, device, loggers, epoch=-1, noise_factor=0):
    if epoch != -1:
        msglogger.info("----Validate (epoch=%d)----", epoch)

    losses = {'natural_loss': tnt.AverageValueMeter()}
    """
    Drop early exist model so far.
    if _is_earlyexit(args):
        # for Early Exit, we have a list of errors and losses for each of the exits.
        args.exiterrors = []
        args.losses_exits = []
        for exitnum in range(args.num_exits):
            args.exiterrors.append(tnt.ClassErrorMeter(accuracy=True, topk=(1, 5)))
            args.losses_exits.append(tnt.AverageValueMeter())
        args.exit_taken = [0] * args.num_exits
    """
    batch_time = tnt.AverageValueMeter()
    total_samples = len(dataloaders[data_group].sampler)
    batch_size = dataloaders[data_group].batch_size
    total_steps = total_samples / batch_size
    msglogger.info('%d samples (%d per mini-batch)', total_samples, batch_size)

    # For robustness testing, 20% of the testing data will be steralized.
    add_noise_steps =  int(total_steps * 0.2)
    end_range = int(total_steps) - add_noise_steps
    start_step = random.randint(0, end_range)
    start_step = 60
    end_step = start_step + add_noise_steps
    # Turn into evaluation mode.
    model.eval()
    end = time.time()
    # Starting primiary testing code here.
    with torch.no_grad():
        for validation_step, data in enumerate(dataloaders[data_group]):
            inputs = Variable(data[0]).float().to(device)
            labels = Variable(data[1]).float().to(device)

            if validation_step >= start_step and validation_step <= end_step and noise_factor:
                msglogger.info('%f is the factor multiplied in epoch %d', noise_factor, epoch)
                #print(validation_step)
                shape = inputs.shape
                # If using imagenet dataset:
                mean = np.array([0.0, 0.0, 0.0])
                std = np.array([1.0, 1.0, 1.0])
                min_val = (np.array([0,0,0]) - mean) / std
                max_val = (np.array([1,1,1]) - mean) / std
                noise = noise_factor * torch.randn(shape).to(device)

                """
                # for Plotting
                count = 0
                for fac in [0, 0.5, 1, 1.5, 2, 2.5, 3]:
                    temp_noise = fac * torch.randn(shape).to(device)
                    temp_inputs = inputs + temp_noise
                    for i in range(3):
                        temp_inputs[:, i, :, :] = torch.clamp(temp_inputs[:, i, :, :], min_val[i], max_val[i])
                    #temp_inputs = temp_inputs.numpy()
                    temp_inputs = temp_inputs[9, :, :, :].cpu().detach().numpy()

                    for i in range(3):
                        temp_inputs[i, :, :] = (temp_inputs[i, :, :] * std[i]) + mean[i]
                    temp_inputs = np.transpose(temp_inputs, (1, 2, 0))
                    def plot(img):
                        #x = x - np.min(x)
                        #x /= np.max(x)
                        img *= 255
                        img = img.astype(np.uint8)
                        img = img.reshape(224, 224, 3)
                        return img
                    plt.imsave(os.path.join(msglogger.logdir, str(count)+'.png'), plot(temp_inputs))
                    count+=1
                assert 1 == 2
                """

                inputs += noise
                for i in range(3):
                    inputs[:, i, :, :] = torch.clamp(inputs[:, i, :, :], min_val[i], max_val[i])

            nat_output = model(inputs, labels) # Tuple (loss, pred_tensor)

            # Early exist mode will incorporate in the near future.
            '''
            if not _is_earlyexit(args):
                # compute loss
                loss = criterion(output, target)
                # measure accuracy and record loss
                losses['objective_loss'].add(loss.item())
                classerr.add(output.detach(), target)
                if args.display_confusion:
                    confusion.add(output.detach(), target)
            else:
                earlyexit_validate_loss(output, target, criterion, args)
            '''

            losses['natural_loss'].add(nat_output[0].item())
            steps_completed = (validation_step + 1)
            batch_time.add(time.time() - end)
            end = time.time()
            steps_completed = (validation_step + 1)
            # "\033[0;37;40m\tExample\033[0m"
            if steps_completed % (args.print_freq) == 0 :
                _log_valiation_progress(args, losses, epoch, steps_completed, total_steps, [loggers[1]])

    stats_tmp = OrderedDict()
    stats_tmp['Nat_Loss'] = losses['natural_loss'].mean
    stats = ('Performance/Validation/', stats_tmp)

    utl.log_training_progress(stats, None, epoch, steps_completed=0,
                                    total_steps=1, log_freq=1, loggers=[loggers[0]])

    msglogger.info('==>  Nat_Loss: {:.5f} \n.'.format(losses['natural_loss'].mean))
    return losses['natural_loss'].mean

def trian_validate_with_scheduling(args, net, optimizer, compress_scheduler, device, dataloaders, dataset_sizes,
                                   loggers, tracker, epoch=1, validate=True, verbose=True):
    # Whtat's collectors_context
    # At first, we need to specify the model name, and its learning progress:
    #if not os.path.isdir(args.output_dir):
    #    os.mkdir(args.output_dir)
    #os.mkdir(args.output_dir, exist_ok=True)

    name = args.name
    if args.name == '':
        name = args.arch + "_" + args.dataset
    # Must exist pruning mode.
    # Reset learning rate and momentum buffer in the optimizer for next learning stage!
    # Should know whether the learning rate decay is based on epochs or steps
    # Or more, the meaning of last epoch argument indicates current epoch.
    #****
    # This line may raise the problems that the epoch doesn't exist any policy....
    #****
    if compress_scheduler:
        if compress_scheduler.prune_mechanism:
            if epoch == (compress_scheduler.pruner_info['max_epoch']):
                # Reset optimizer and learning rate in retrain phase.
                # NOTE: We should specify the true
                for index in range(len(compress_scheduler.policies[epoch])):
                    policy_name = compress_scheduler.policies[epoch][index].__class__.__name__.split("Policy")[0]
                    if policy_name == "LR":
                        compress_scheduler.policies[epoch][index].lr_scheduler.optimizer.param_groups[0]['lr'] = args.lr_retrain
                        compress_scheduler.policies[epoch][index].lr_scheduler.base_lrs = [args.lr_retrain]
                        compress_scheduler.policies[epoch][index].lr_scheduler.optimizer.param_groups[0]['momentum'] = 0.9
                        compress_scheduler.policies[epoch][index].lr_scheduler.optimizer.param_groups[0]['initial_lr'] = args.lr_retrain
                        for group in optimizer.param_groups:
                            for p in group['params']:
                                if 'momentum_buffer' in optimizer.state[p]:
                                    optimizer.state[p].pop('momentum_buffer', None)
                        break

            if epoch == (compress_scheduler.pruner_info['min_epoch']):
                # *****
                # NOTE If not using ADMM pruner, do we need to reset lr scheduler in this loop?
                # *****
                # Reset learning rate and momentum buffer for pruning stage!
                policy_name = compress_scheduler.policies[epoch][0].__class__.__name__.split("Policy")[0]
                #if policy_name != "ADMM":
                #    compress_scheduler.policies[epoch][0].lr_scheduler.optimizer.param_groups[0]['lr'] = args.lr_prune
                #    compress_scheduler.policies[epoch][0].lr_scheduler.base_lrs = [args.lr_prune]
                #    compress_scheduler.policies[epoch][0].lr_scheduler.optimizer.param_groups[0]['momentum'] = 0.9
                #    compress_scheduler.policies[epoch][0].lr_scheduler.optimizer.param_groups[0]['initial_lr'] = args.lr_prune
                for group in optimizer.param_groups:
                    group['lr'] = args.lr_prune
                    group['initial_lr'] = args.lr_prune
                    # for group in optimizer.param_groups:
                    for p in group['params']:
                        if 'momentum_buffer' in optimizer.state[p]:
                            optimizer.state[p].pop('momentum_buffer', None)

            if epoch >= compress_scheduler.pruner_info['max_epoch']:
                name  += "_retrain"

            elif epoch < compress_scheduler.pruner_info['min_epoch']:
                name += "_pretrain"

            else:
                name += "_prune"
    else:
        # Only proceed with pre-train or re-train phase model.
        name = name + "_" + args.stage

    if compress_scheduler:
        #dataset_name = 'val' if args.split_ratio != 0 else 'test'
        dataset_name = 'test'
        #data_group, model, criterion, device, num_classes, loggers, epoch=-1, noise_factor=0)

        # These two partial function is created for the channel pruning methods (Prof. Han):
        forward_fn = partial(_validate, args=args, dataloaders=dataloaders, data_group=dataset_name, device=device, loggers=loggers,   epoch=-1, noise_factor=0)

        #light_train_with_distiller(model, criterion, optimizer, compress_scheduler, device, num_classes,
        #                       dataset_sizes, loggers, epoch=1)

        train_fn = partial(light_train_with_distiller, args=args, optimizer=optimizer, compress_scheduler=compress_scheduler,
                               device=device, dataloaders =dataloaders, dataset_sizes=dataset_sizes, loggers=loggers, epoch=0)

        compress_scheduler.on_epoch_begin(epoch, optimizer, forward_fn=forward_fn, train_fn=train_fn)

    nat_loss, overall_loss = light_train_with_distiller(args, net, optimizer, compress_scheduler,
                                                          device, dataloaders, dataset_sizes, loggers, epoch)

    if validate:
        nat_loss = _validate(args, dataloaders, 'test', net, device, loggers, epoch=epoch)

    if compress_scheduler:
        # Or we can compute IoU here?
        loss = nat_loss
        #top1 = nat_loss
        compress_scheduler.on_epoch_end(epoch, optimizer, metrics={'min':loss}) #, 'max':top1})

    is_best, checkpoint_extras = _finalize_epoch(args, net, tracker, epoch, top1=nat_loss)
    # Check whether the out direcotry is already built.
    ckpt.save_checkpoint(epoch, args.arch, net, optimizer=optimizer,
                         scheduler=compress_scheduler, extras=checkpoint_extras,
                         is_best=is_best, name=name, dir=msglogger.logdir)

    #return top1, top5, loss, tracker
    return nat_loss, tracker

def _log_best_scores(args, performance_tracker, logger, how_many=-1):
    """
    Utility to log the best scores (minimum loss value).
    This function is currently written for pruning use-cases, but can be generalized.
    """
    assert isinstance(performance_tracker, (pt.SparsityAccuracyTracker))
    if how_many < 1:
        how_many = performance_tracker.max_len

    how_many = min(how_many, performance_tracker.max_len)
    best_scores = performance_tracker.best_scores(how_many)
    for score in best_scores:
        logger.info('==> Best [Nat_Loss: %.3f Sparsity:%.2f  NNZ-Params: %d on epoch: %d]',
                    -1*score.top1, score.sparsity, -score.params_nnz_cnt, score.epoch)

def _finalize_epoch(args, net, tracker, epoch, **kwargs):
    # ****
    # We mulitply -1 to the loss value so that the performance tracker can work well without any modifications.
    # ****
    loss_multiply = -1 * kwargs['top1']
    tracker.step(net, epoch, top1=loss_multiply, adv_train=False)
    _log_best_scores(args, tracker, msglogger)
    best_score = tracker.best_scores()[0]
    is_best = epoch == best_score.epoch
    checkpoint_extras = {'current_top1': kwargs['top1'],
                         'best_top1': -1 * best_score.top1,
                         'best_epoch': best_score.epoch}
    return is_best, checkpoint_extras


import random
import math

from state import State

class Annealing(object):
    """Class for the annealing algorithm"""

    def __init__(self, factor=20000):
        """
        Initializes random seed, state, and energy. Factor is controls the
        speed of annealing: lower values results faster, but imprecise results.
        """
        random.seed()
        self.state = State()
        self.iteration = 0
        self.energy = self.state.getEnergy()
        self.factor = factor

    def temperature(self):
        """
        Calculates the current temperature based on the current iteration count.
        """

        return 1.0 - math.tanh(float(self.iteration) / self.factor)

    def probability(self, neighbourEnergy):
        """
        Defines the probability of movement from the current state to a
        neighbour state. If the neighbour state is "better" (higher energy),
        definitely moves to it. Otherwise, probability depends on the current
        temperature
        """

        if neighbourEnergy > self.energy:
            return 1.0
        return self.temperature()

    def iterate(self):
        """
        Called from outside periodically. Expands a neighbour state, calculates
        its energy, and decides whether move there or not.
        """

        neighbour = self.state.genNeighbour()
        energy = neighbour.getEnergy()
        if self.probability(energy) > random.random():
            self.state = neighbour
            self.energy = energy

        # Increasing iteration counter
        self.iteration += 1


# project : baekjoon python algorithm practice
# user : marble
# date : 20. 3. 6.
# time : 오후 7:33
# problem : https://www.acmicpc.net/problem/1072
# problem type : Math

# 수학적 공식으로 계산해서 맞춤
# 이진 탐색으로 푸는 방법도 있음
import math

x, y = map(int, input().split())
n = int(100 * y // x)
if n >= 99:
    print(-1)
    exit()

result = math.ceil(((n+1) * x - 100 * y) / (99 - n))

print(result)


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

# In[1]:

import numpy as np
import pandas as pd
from scipy.stats import  binom
from scipy.stats import  poisson

# In[2]:

def combinations(n, k):
    return (np.math.factorial(n)/(np.math.factorial(k)*np.math.factorial(n-k)))

# In[3]:

p1 = binom.pmf(0,5000,0.0004)

# In[4]:

p2 = binom.pmf(2,5000,0.0004)

# In[5]:

lam = 5000*0.0004

# In[6]:

p3 = poisson.pmf(0,lam)

# In[7]:

p4 = poisson.pmf(2,lam)

# In[8]:

print('Вероятность, что ни одна из них не перегорит в первый день (binom) =',p1)

# In[9]:

print('Вероятность, что ни одна из них не перегорит в первый день (poisson) =',p3)

# In[10]:

print('Вероятность, что перегорят ровно две (binom) =',p2)

# In[11]:

print('Вероятность, что перегорят ровно две (poisson) =',p4)


from openerp import models, fields, api
from openerp.osv import osv

class Documentation(models.Model):
    _name = 'website.doc.toc'
    _description = 'Documentation ToC'
    _inherit = ['website.seo.metadata']
    _order = "sequence, parent_left"
    _parent_order = "sequence, name"
    _parent_store = True

    def name_get(self, cr, uid, ids, context=None):
        if isinstance(ids, (list, tuple)) and not len(ids):
            return []
        if isinstance(ids, (long, int)):
            ids = [ids]
        reads = self.read(cr, uid, ids, ['name', 'parent_id'], context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['parent_id']:
                name = record['parent_id'][1]+' / '+name
            res.append((record['id'], name))
        return res

    # TODO master remove me
    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)

    sequence = fields.Integer(
        'Sequence',
        default=10,
        )
    name = fields.Char(
        'Name',
        required=True,
        # to avoid complications we disable translation
        # translate=True,
        )
    parent_id = fields.Many2one(
        'website.doc.toc',
        'Parent Table Of Content',
        ondelete='cascade',
        domain=[('is_article', '=', False)],
        )
    child_ids = fields.One2many(
        'website.doc.toc',
        'parent_id',
        'Children Table Of Content'
        )
    parent_left = fields.Integer(
        'Left Parent',
        select=True
        )
    parent_right = fields.Integer(
        'Right Parent',
        select=True
        )
    is_article = fields.Boolean(
        'Is Article?'
        )
    article_toc_id = fields.Many2one(
        'website.doc.toc',
        'Documentation ToC',
        ondelete='set null',
        domain=[('is_article', '=', False)],
        )
    article_ids = fields.One2many(
        'website.doc.toc',
        'article_toc_id',
        'Articles',
        domain=[('is_article', '=', True)],
        context={'default_is_article': 1},
        )
    add_google_doc = fields.Boolean(
        'Add Google Doc?',
        help="Add Google Doc after Page Content?"
        )
    google_doc_link = fields.Char(
        'Google Document Code',
        )
    google_doc_code = fields.Char(
        'Google Document Code',
        )
    google_doc_height = fields.Char(
        'Google Document Height',
        default='1050px'
        )
    content = fields.Html(
        'Content',
        )
    google_doc = fields.Text(
        'Content',
        compute='get_google_doc',
        )
    group_ids = fields.Many2many(
        'res.groups',
        'website_doc_toc_group_rel',
        'website_toc_id', 'gid', 'Groups',
        help="If you have groups, the visibility of this TOC will be based on "
        "these groups. "
        # "If this field is empty, Odoo will compute visibility based on the "
        # related object's read access."
        )
    state = fields.Selection(
        [('private', 'Is Private'),
         ('published', 'Published')],
        'State',
        required=True,
        default='private',
        # default='private',
        help="If private, then it wont be accesible by portal or public users"
        )
    partner_id = fields.Many2one(
        'res.partner',
        'Partner',
        help='If partner is set, only this partner will be able\
        to see this item (except documentation managers)',
        )

    @api.one
    @api.depends('google_doc_code', 'google_doc_height')
    def get_google_doc(self):
        google_doc = False
        if self.google_doc_height and self.google_doc_code:
            google_doc = google_doc_template % (
                self.google_doc_height, self.google_doc_code)
        self.google_doc = google_doc

    _constraints = [
        (osv.osv._check_recursion,
            'Error ! You cannot create recursive categories.', ['parent_id'])
    ]

google_doc_template = """
 <div class="row">
    <iframe id="google-doc-iframe" srcdoc="" style="height: %s; margin: 0 auto; padding-left: 20px; padding-right: 20px" align="middle" frameborder="0" width="100%%" height="300" scrolling="no">
    </iframe>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
    $(function() {
        $.get("https://docs.google.com/document/d/%s/pub?", function(html) {
            $("#google-doc-iframe").attr("srcdoc", html);
            setTimeout(function() {
                $("#google-doc-iframe").contents().find('a[href^="http://"]').attr("target", "_blank");
                $("#google-doc-iframe").contents().find('a[href^="https://"]').attr("target", "_blank");
            }, 1000);
        });
    });
    </script>
</div>
"""


import random
from hm_guess import words
from hm_lives import game_name
from hm_lives import lives
guess_word=random.choice(words).lower()
word=len(guess_word)
game_over=False
tries=6
print(game_name)
result=[]
for i in range(word):
    result+='_'
while not game_over:
    user=input("Guess a letter: ")
    user=user.lower()
    for i in range(word):
        letter=guess_word[i]
        if letter==user:
            result[i]=letter
    if user not in guess_word:
        print("Oops, wrong guess")
        tries-=1
        if tries==0:
            game_over=True
            print("GAME OVER")
            print("U LOSE THE GAME")
    ans=' '.join(result)
    print(ans)
    if '_' not in result:
        game_over=True
        print("GAME OVER")
        print("U WON THE GAME")
    print(lives[tries])
print("the word is",guess_word)


import os  # to list directory
import re  # for regexp
import getopt  # for commands arguments
import sys  # for argv

def usage():
    """ print POD arg usage """
    print("""\
Usage: launchtests [OPTION...]

    -h, --help          give this help list
    -r, --reset         reset output checker

Report bugs to http://periphondemand.sourceforge.net/
""")

def diff(output, testname):
    tmpfile = open("tmp_chk", "w")
    tmpfile.write(output)
    tmpfile.close()
    out = os.popen("diff tmp_chk " + testname).read()
    out = out.strip()
    if out != "":
        return out
    else:
        return None

def main():
    reset = None
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   "hr", ["help", "reset"])
    except getopt.GetoptError as error:
        print(str(error))
        usage()
        sys.exit(2)
    options = [arg[0] for arg in opts]

    if "help" in options or "-h" in options:
        usage()
        sys.exit(2)

    if "reset" in options or "-r" in options:
        reset = 1

    # list files under tests/ directory
    dirlist = os.listdir(".")

    # keep testscript only
    testlist = [test for test in dirlist if re.match("\d\d*", test)]
    testlist.sort()
    number_of_tests = int(testlist[-1][0:2])

    for i in range(number_of_tests):
        print(" Test number " + str(i + 1) + " : " + testlist[i][3:]),
        out = os.popen("pod -s "+testlist[i]).read()
        # if -r, create output files
        if reset:
            file_chk = open("chk_" + testlist[i], "w")
            file_chk.write(out)
            file_chk.close()
            print("chk_" + testlist[i] + " written"),
        else:
            if not os.path.exists("chk_" + testlist[i]):
                print("[ERROR] chk_" + testlist[i] + " doesn't exist. " +
                      "Maybe you should use -r option to generate chk file ?")
                sys.exit(-1)
            testout = diff(out, "chk_" + testlist[i])
            if testout is None:
                print(" Check")
            else:
                print(" Not Check")
                print(testout)

if __name__ == "__main__":
    main()


import configargparse
import torch
import torchvision
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
import numpy as np
import json
import os
import matplotlib.pyplot as plt
import tqdm

device = torch.device(
    'cuda') if torch.cuda.is_available() else torch.device('cpu')

def config_parser():
    parser = configargparse.ArgumentParser()
    parser.add_argument('--data_path', default='data\spike\snn_spike.json')
    parser.add_argument('--hidden_layer_dim', type=int, default=512)
    parser.add_argument('--num_layers', type=int, default=8)
    parser.add_argument('--lr', type=float, default=1e-3)
    parser.add_argument('--batch_size', type=int, default=16)
    parser.add_argument('--epochs', type=int, default=100)
    parser.add_argument('--i_save', type=int, default=10)
    parser.add_argument('--output_path', default='./output/')
    return parser

def read_data(args):
    with open(args.data_path, 'r') as f:
        datas = json.load(f)
    signals, labels = [], []
    for key in datas.keys():
        data = datas[key]
        labels.append(data['label'])
        signal = np.zeros((30, 5))
        for i, channel in enumerate(list(data.keys())[:5]):
            for j in data[channel]:
                signal[int(j), i] += 1
        signals.append(signal)
    return signals, labels

class classifier(nn.Module):
    def __init__(self, args):
        super(classifier, self).__init__()
        self.encoder_layer = nn.TransformerEncoderLayer(
            d_model=args.hidden_layer_dim, nhead=8, dim_feedforward=args.hidden_layer_dim, batch_first=True)
        self.transformer_encoder = nn.TransformerEncoder(
            self.encoder_layer, num_layers=args.num_layers)
        self.embedding = nn.Sequential(
            nn.LayerNorm(5),
            nn.Linear(5, args.hidden_layer_dim),
            nn.ReLU()
        )
        self.classifier = nn.Sequential(
            nn.ReLU(),
            nn.Linear(args.hidden_layer_dim, 6)
        )

    def forward(self, x):
        x = self.embedding(x)
        x = self.transformer_encoder(x)
        y = self.classifier(x[:, 0])
        return y

class dataset(Dataset):
    def __init__(self, signals, labels):
        self.signals, self.labels = signals, labels

    def __getitem__(self, index):
        signal = self.signals[index].astype('float32')
        label = self.labels[index]
        return torch.tensor(signal).to(device), torch.tensor(label).to(device)

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

def test(net, loader):
    n = 0
    m = 0
    for index, (signal, label) in enumerate(loader):
        y = net(signal)
        if y.argmax() == label:
            m += 1
        n += 1
    return m/n

def main(args):
    signals, labels = read_data(args)
    signal_train, signal_test, label_train, label_test = train_test_split(
        signals, labels, test_size=0.2)
    print('train size:', len(label_train))
    print('test_size:', len(label_test))

    net = classifier(args).to(device)
    train_loader = DataLoader(
        dataset(signal_train, label_train), batch_size=args.batch_size, shuffle=True)
    train_sub_loader = DataLoader(
        dataset(signal_train, label_train), batch_size=1, shuffle=True)
    test_loader = DataLoader(
        dataset(signal_test, label_test), batch_size=1, shuffle=True)
    loss_fun = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(net.parameters(), lr=args.lr,momentum=0.1,weight_decay=0.01)
    lr_shedular = torch.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, args.epochs+30)

    train_loss = []
    train_acc = []
    test_acc = []
    epoch_n = []

    for epoch in tqdm.tqdm(range(args.epochs)):
        net.train()
        for index, (signal, label) in enumerate(train_loader):
            y = net(signal)
            loss = loss_fun(y, label)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
            train_loss.append(float(loss))
        lr_shedular.step()

        if ((epoch+1) % args.i_save == 0) or epoch == 0:
            epoch_n.append(epoch+1)
            path = args.output_path+'exp'+str(epoch+1)+'/'
            try:
                os.mkdir(path)
            except:
                pass
            net.eval()
            train_acc.append(test(net, train_sub_loader))
            test_acc.append(test(net, test_loader))
            plt.plot(train_loss)
            plt.savefig(path+'loss.png')
            with open(path+'acc.json', 'w') as f:
                json.dump(
                    {'train': train_acc, 'test': test_acc, 'time': epoch_n}, f)
            # torch.save(net,path+'mode.pt')

if __name__ == '__main__':
    args = config_parser().parse_args()
    main(args)


from const import RESOURCE_STATE_FORAGING

class PointOfInterest:
    def __init__(self, position, decay_time, t, value=None, index=None, is_visible=True):
        self.is_visible = is_visible
        self.decay_time = decay_time
        self.position = position
        self.value = value
        self.index = index
        self.type = t
        self.state = RESOURCE_STATE_FORAGING

    def encode(self):
        return {
            'position': self.position.__dict__,
            'type': self.type
        }


import os
from collections import OrderedDict
from configparser import RawConfigParser
from importlib.metadata import PackageNotFoundError, version

from django.core.checks import Error

from df_config.checks import missing_package, settings_check_results
from df_config.config.dynamic_settings import ExpandIterable
from df_config.guesses.social_providers import SOCIAL_PROVIDER_APPS
from df_config.utils import is_package_present

def allauth_provider_apps(settings_dict):
    parser = RawConfigParser()
    config = settings_dict["ALLAUTH_APPLICATIONS_CONFIG"]
    if not os.path.isfile(config):
        return []
    # noinspection PyBroadException
    try:
        parser.read([config])
    except Exception:  # nosec  # nosec
        settings_check_results.append(
            Error("Invalid config file. %s" % config, obj="configuration")
        )
        return []
    return [
        parser.get(section, "django_app")
        for section in parser.sections()
        if parser.has_option(section, "django_app")
    ]

allauth_provider_apps.required_settings = ["ALLAUTH_APPLICATIONS_CONFIG"]

class InstalledApps:
    """Provide a complete `INSTALLED_APPS` list, transparently adding common third-party packages.
    Specifically handle apps required by django-allauth (one by allowed method).

    """

    default_apps = [
        ExpandIterable("DF_INSTALLED_APPS"),
    ]
    base_django_apps = [
        "df_config",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.messages",
        "django.contrib.humanize",
        "django.contrib.sitemaps",
        "django.contrib.sites",
        "django.contrib.staticfiles",
        "django.contrib.admin",
    ]
    common_third_parties = OrderedDict(
        [
            ("USE_WEBSOCKETS", ["df_websockets", "channels"]),
            (
                "USE_SITE",
                [
                    "df_site",
                    "bootstrap4",
                    "channels",
                    "dal",
                    "dal_select2",
                    "fontawesome_5",
                    "smart_selects",
                ],
            ),
            ("USE_DEBUG_TOOLBAR", ["debug_toolbar.apps.DebugToolbarConfig"]),
            ("USE_PIPELINE", ["pipeline"]),
            ("USE_PAM_AUTHENTICATION", ["django_pam"]),
            ("USE_CORS_HEADER", ["corsheaders"]),
            ("USE_DAPHNE", ["daphne"]),
        ]
    )
    required_settings = [
        "ALLAUTH_PROVIDER_APPS",
        "DF_INSTALLED_APPS",
        "SESSION_ENGINE",
        "USE_ALL_AUTH",
    ] + list(common_third_parties)
    social_apps = SOCIAL_PROVIDER_APPS

    def __call__(self, settings_dict):
        apps = self.default_apps
        if settings_dict["SESSION_ENGINE"] == "django.contrib.sessions.backends.db":
            apps += ["django.contrib.sessions"]
        apps += self.process_django_allauth(settings_dict)
        apps += self.process_third_parties(settings_dict)
        apps += self.base_django_apps
        return apps

    def process_third_parties(self, settings_dict):
        result = []
        for k, v in self.common_third_parties.items():
            package_name = v[0].partition(".")[0]
            if not settings_dict[k]:
                continue
            elif not is_package_present(package_name):
                settings_check_results.append(missing_package(package_name, ""))
                continue
            result += v
        return result

    def process_django_allauth(self, settings_dict):
        if (
            not settings_dict["USE_ALL_AUTH"]
            and not settings_dict["ALLAUTH_PROVIDER_APPS"]
        ):
            return []
        try:
            version("django-allauth")
        except PackageNotFoundError:
            settings_check_results.append(
                missing_package(
                    "django-allauth", " to use OAuth2 or OpenID authentication"
                )
            )
            return []
        app = "django.contrib.sites"
        if app not in self.default_apps and app not in self.base_django_apps:
            settings_check_results.append(
                Error(
                    '"django.contrib.sites" app must be enabled.',
                    obj="configuration",
                    id="df_config.E001",
                )
            )
            return []
        result = [
            "allauth",
            "allauth.account",
            "allauth.socialaccount",
            "allauth.socialaccount.providers.openid",
        ]
        if settings_dict["ALLAUTH_PROVIDER_APPS"]:
            result += [
                k
                for k in settings_dict["ALLAUTH_PROVIDER_APPS"]
                if k in self.social_apps
            ]
        return result

    def __repr__(self):
        return "%s.%s" % (self.__module__, "installed_apps")

installed_apps = InstalledApps()

class Middlewares:
    use_cache_middleware = True
    base_django_middlewares = [
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.common.CommonMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.middleware.locale.LocaleMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django.middleware.clickjacking.XFrameOptionsMiddleware",
        "django.middleware.security.SecurityMiddleware",
        "df_config.apps.middleware.DFConfigMiddleware",
    ]
    common_third_parties = OrderedDict(
        [
            ("USE_WHITENOISE", "whitenoise.middleware.WhiteNoiseMiddleware"),
            ("USE_WEBSOCKETS", "df_websockets.middleware.WebsocketMiddleware"),
            ("USE_CSP", "csp.middleware.CSPMiddleware"),
            ("USE_CORS_HEADER", "corsheaders.middleware.CorsMiddleware"),
        ]
    )
    required_settings = ["DF_MIDDLEWARE"] + list(common_third_parties)
    social_apps = SOCIAL_PROVIDER_APPS

    def __call__(self, settings_dict):
        mw_list = []
        mw_list += self.base_django_middlewares
        mw_list.append(ExpandIterable("DF_MIDDLEWARE"))
        mw_list += self.process_third_parties(settings_dict)
        if settings_dict["USE_DEBUG_TOOLBAR"]:
            mw_list.insert(0, "debug_toolbar.middleware.DebugToolbarMiddleware")
        if self.use_cache_middleware:
            mw_list.insert(0, "django.middleware.cache.UpdateCacheMiddleware")
            mw_list.append("django.middleware.cache.FetchFromCacheMiddleware")
        return mw_list

    def process_third_parties(self, settings_dict):
        result = []
        for k, v in self.common_third_parties.items():
            package_name = v.partition(".")[0]
            if not settings_dict[k]:
                continue
            elif not is_package_present(package_name):
                settings_check_results.append(missing_package(package_name, ""))
                continue
            result.append(v)
        return result

    def __repr__(self):
        return "%s.%s" % (self.__module__, "middlewares")

middlewares = Middlewares()


'''
Created on Jan 24, 2019
@author: GANESHRAM KANAKASABAI
'''
from labs.common import ConfigUtil
from labs.common import ConfigConst
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
'''
creating a class smtpClientConnector
'''
class SmtpClientConnector(object):
    '''
    constructor of smtpClientConnector
    '''
    def __init__(self):
        self.config = ConfigUtil.ConfigUtil('../../../config/ConnectedDevicesConfig.props');
        print('Configuration data...\n' + str(self.config));
        self.config.loadConfig();
    '''
    PublishMessage function is used to build and construct message and is sent as a notification.
    @param topic: Subject to Email
    @param data : Sensor notification
    '''
    def publishMessage(self, topic, data):
        host = self.config.getProperty(ConfigConst.ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.ConfigConst.HOST_KEY);
        port = self.config.getProperty(ConfigConst.ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.ConfigConst.PORT_KEY);
        fromAddr = self.config.getProperty(ConfigConst.ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.ConfigConst.FROM_ADDRESS_KEY);
        toAddr = self.config.getProperty(ConfigConst.ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.ConfigConst.TO_ADDRESS_KEY);
        authToken = self.config.getProperty(ConfigConst.ConfigConst.SMTP_CLOUD_SECTION, ConfigConst.ConfigConst.USER_AUTH_TOKEN_KEY);
        msg = MIMEMultipart();
        msg['From'] = fromAddr;
        msg['To'] = toAddr;
        msg['Subject'] = topic;
        msgBody = str(data);
        msg.attach(MIMEText(msgBody));
        msgText = msg.as_string();# Here the email notification is sent .

        try:
            smtpServer = smtplib.SMTP_SSL(host, port);#Connecting SMTP server at given port number.
            smtpServer.ehlo();#method calling SMTP extended hello
            smtpServer.login(fromAddr, authToken);
            smtpServer.sendmail(fromAddr, toAddr, msgText);
            smtpServer.close();
        except:
            print("Error in Sending Mail");


#TC: O(n log n)
#SC: O(1)

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:

        n = len(nums)-1
        #sort the array
        nums.sort()

        result = [] #have a resultant array

        for i in range(n-1):
            if i>=1 and nums[i]==nums[i-1]: #just continue if you have duplicates
                continue

            j = i+1  #j pointer starts after i
            k = n #k stands at the end
            target = 0 - nums[i] #target will be the negative complement of the current element

            while j<k:
                if nums[j] + nums[k] == target:  #if j element and the k element gives the target, return all three indices
                    result.append([nums[i],nums[j],nums[k]])

                    while j<k and nums[j] == nums[j+1]: #adjust j pointer if you have duplicates
                        j+=1

                    while j<k and nums[k] == nums[k-1]: #adjust k pointer if you have duplicates
                        k-=1

                    #go to the next new element
                    j+=1
                    k-=1

                else:  #traverse k if target is lesser than the sum of current elements or else increment j
                    if target < (nums[j]+nums[k]):
                        k-=1
                    else:
                        j+=1

        return result #now return result


import numpy as np
import matplotlib.pyplot as plt
import glob
import os
import csv
from scipy.signal import savgol_filter
from numpy import mean

txtfiles=[]

def getFiles():
    for file in glob.glob("*.txt"):
        txtfiles.append(file)

def openFile():

    for i in range (txtfiles.__len__()):
        print("Press "+"{}".format(i+1)+" to open "+txtfiles[i])

    choice=int(input())
    f=open(txtfiles[choice-1])
    return f

def peakdetect(y_axis, x_axis = None, window = 50, delta = 0):
    """
    Wtitten based on a MATLAB script at http://billauer.co.il/peakdet.html

    Algorithm to detect local maximas and minmias in a signal.
    It detects peaks by searching for values which are surrounded by lower
    or larger values for maximas and minimas respectively

    keyword arguments:
    y_axis: List containg the signal over which to find peaks
    x_axis (optional): A x-axis whose values correspond to the y-axis and is used
        to obtain the x value at the maximas or minimas. (Default: 0 , return the
        index of the y-axis)

    window (optional): distance to look ahead from a peak candidate to
        determine if it is the actual peak (default: 50)

    delta (optional): specifies a minimum difference between a peak and
        the following points, before a peak may be considered a peak.
        Useful to allow for finer control over processing

    returns two lists [maxtab, mintab] containing the maximas and minimas
        respectively. Each cell of the lists contains a tupple of:
        (position, peak_value)
    """
    maxtab = []
    mintab = []
    dump = []   #Used to pop the first hit which always if false

    length = len(y_axis)

    # if x-axis isnt provided
    if x_axis is None:
        x_axis = range(length)

    #maxima and minima candidates are temporarily stored in mx and mn
    mn, mx = np.Inf, -np.Inf

    #Only detect peak if there is 'window' amount of points after it
    for index, (x, y) in enumerate(zip(x_axis[:-window], y_axis[:-window])):
        if y > mx:
            mx = y
            mxpos = x
        if y < mn:
            mn = y
            mnpos = x

        ####look for max####
        if y < mx-delta and mx != np.Inf:
            #Maxima peak candidate found
            #look ahead in signal to ensure that this is a peak and not jitter
            if y_axis[index:index+window].max() < mx:
                maxtab.append((mxpos, mx))
                dump.append(True)
                #set algorithm to only find minima now
                mx = np.Inf
                mn = np.Inf

        ####look for min####
        if y > mn+delta and mn != -np.Inf:
            #Minima peak candidate found
            #look ahead in signal to ensure that this is a peak and not jitter
            if y_axis[index:index+window].min() > mn:
                mintab.append((mnpos, mn))
                dump.append(False)
                #set algorithm to only find maxima now
                mn = -np.Inf
                mx = -np.Inf

    #Remove the false hit on the first value of the y_axis
    try:
        if dump[0]:
            maxtab.pop(0)
            #print "pop max"
        else:
            mintab.pop(0)
            #print "pop min"
        del dump
    except IndexError:
        #no peaks were found, should the function return empty lists?
        pass

    return maxtab, mintab

#fuction to filter signal
def filter(data_in,N,poly):

    filtered_sig= savgol_filter(data_in,N,poly)

    return filtered_sig

def outlierDeletion(data,N):
    mylist = data
    size = mylist.__len__()

    for i in range (size):
        if(mylist[i]>2*mean(mylist[i:i+N])):
            mylist[i]=mean(mylist[i:i+N])
        elif(mylist[i]<2*mean(mylist[i:i+20])):
            mylist[i]=mean(mylist[i:i+N])
        elif(mylist[i]<mean(mylist)):
            mylist[i]=mean(mylist[i:i+int(N/2)])
        elif(mylist[i]>mean(mylist)):
            mylist[i]=mean(mylist[i:i+int(N/2)])

if __name__=="__main__":

    voltage_current_pairs=[]
    voltage=[]
    current=[]

    #open file
    getFiles()

    for j in range(txtfiles.__len__()):
        file=open(txtfiles[j])

        #read file
        for line in file:
            csv_reader = csv.reader(file, delimiter=',')
            line_count = 0
            for row in csv_reader:
                voltage_current_pairs.append(row)

        #split current and voltage into seperate array
        i=0
        while i<voltage_current_pairs.__len__():
            voltage.append(voltage_current_pairs[i][0]) #store voltage only
            current.append(voltage_current_pairs[i][1]) #store current only
            i+=1

        #convert into numpy array
        y = np.asarray(current, dtype=np.float)
        x= np.asarray(voltage, dtype=np.float)

        #using algorithm to delete outliers
        window=3
        outlierDeletion(y,window)

        poly=2
        window=11
        y=filter(y,window,poly)

        _max, _min = peakdetect(y,x,10)
        xm = [p[0] for p in _max]
        ym = [p[1] for p in _max]
        xn = [p[0] for p in _min]
        yn = [p[1] for p in _min]

        # color=['r','g','b','k','m','r','r']
        # print(color[j])
        name=["blank calibration","150uM","50uM","250uM","blank","200uM","100uM","150uM"]

        plt.plot(x,y,label=name[j])
        plt.plot(xm,ym,'b+')
        plt.ticklabel_format(style='sci',scilimits=(0,0),axis='y')
        plt.xlabel('Voltage/V')
        plt.ylabel('Current/A')
        plt.title("P-aminophenol Calibration graph by square wave voltammetry")
        print(_max)

        voltage_current_pairs.clear()
        voltage.clear()
        current.clear()

    plt.legend(loc='best')
    plt.show()


recipes_list = []
ingredients_list = []

# function to take input from user on recipe

def take_recipe():
    name = str(input("Name of recipe: "))
    cooking_time = int(input("Cooking time (mins): "))
    ingredients = (input("Ingredients: ").split(", "))
    recipe = {'name': name, 'cooking_time': cooking_time,
              'ingredients': ingredients}
    return recipe

# Ask user how many recipes they would like to enter
n = int(input('How many recipes would you like to enter: '))

# Check if ingredient present else add into list
for i in range(n):
    recipe = take_recipe()
    for ingredient in recipe['ingredients']:
        if not ingredient in ingredients_list:
            ingredients_list.append(ingredient)
    recipes_list.append(recipe)

# Determine recipe difficulty level
for recipe in recipes_list:
    if recipe['cooking_time'] < 10 and len(recipe['ingredients']) < 4:
        recipe['difficulty'] = 'Easy'

    elif recipe['cooking_time'] < 10 and len(recipe['ingredients']) >= 4:
        recipe['difficulty'] = 'Medium'

    elif recipe['cooking_time'] >= 10 and len(recipe['ingredients']) < 4:
        recipe['difficulty'] = 'Intermediate'

    elif recipe['cooking_time'] >= 10 and len(recipe['ingredients']) >= 4:
        recipe['difficulty'] = 'Hard'

# Display recipe
for recipe in recipes_list:
    print()
    print("Recipe: ", recipe['name'])
    print("Cooking time (min): ", recipe['cooking_time'])
    print("Ingredients: ")
    for ingredient in recipe['ingredients']:
        print(ingredient)
    print("Difficulty level: ", recipe['difficulty'])

# Display all ingredients

def print_ingredients():
    print()
    ingredients_list.sort()
    print('Ingredients available across all recipes')
    print('--------------------------------------')
    for ingredient in recipe['ingredients']:
        print(ingredient)

print_ingredients()


from os import sep

# The data.
frqs = [600, 800]
fields = [50, 75, 100, 200, 300, 400, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500, 6000]
offsets = []
for i in range(21):
    offsets.append(i * 100.0 - 1000.0)

# Loop over the magnetic fields.
for frq in frqs:
    # Loop over the different spin-lock field strengths.
    for field in fields:
        # Open the output file.
        file_name = "%i_MHz_%i.res" % (frq, field)
        file = open('blank' + sep + file_name, 'w')

        # Loop over the offsets.
        for offset in offsets:
            # Write out the data.
            file.write("%20.12f %10.1f %10.1f\n" % (offset, 0.0, 0.5))


#   HTMLTestRunner是基于unittest框架的一个扩展，可以自己在网上自行下载
import os
import smtplib
import unittest
import time
from email.header import Header
from email.mime.text import MIMEText

from lib.HTMLTestRunner import HTMLTestRunner

def send_mail(path):
    f = open(path,'rb') # 要读的内容 二进制格式
    mail_body = f.read() # 读取html报告的内容，作为邮件的正文
    f.close()

    # 要想发邮件，要把二进制的内容转成MIME格式
    # MIME mulitpurseduo 多用途 Internate 互联网 Mail 邮件 Extension 扩展
    # MIME这种格式是对邮件协议的一个扩展，使邮件不仅支持文本格式，还支持多种格式，如：图片、音频、二进制文件等

    msg = MIMEText(mail_body, 'html', 'utf-8')  # 把二进制的内容转为MIME格式

    # 上面是邮件的正文，但是对于一个邮件来讲，除了正文，还需要主题、发件人、收件人
    # msg是字典的类型，字典类似于数组，区别是：1.字典是无序的；2.

    msg['Subject'] = Header("自动化测试报告","utf-8")  # 设置邮件主题

    # 如果想用客户端软件或者自己写代码登录邮箱，很多类型的邮箱需要单独设置一个客户端授权码，这个是为了邮箱安全着想
    # 因为自己邮箱没有设置授权码，所以发件箱统一用老师的
    msg['From'] = 'bwftest126@126.com' # 设置发件箱
    # msg['To'] = '15032683126@163.com'  # 设置收件箱
    msg['To'] = '18401569214@163.com'  # 设置收件箱

    # 现在邮件内容已经准备好了，下面开始发送邮件
    # 发邮件手动步骤：
    # 1.打开登录页面，即连接邮箱服务器
    # 要想连接服务器，首先必须搞清楚网络传输协议
    # http,https,ftp,socket
    # 发邮件的协议一般有三种，要先查看一下邮箱支持哪种协议
    # 126邮箱支持这三种协议：pom3，smtp,imap
    # 我们要选一种传输协议，用来发邮件，选smtp
    # smtp simple mail transfer protocol 简单邮件传输协议
    # 首先导入smtplib的代码库
    smtp = smtplib.SMTP()   # 实例化一个SMTP类的对象
    smtp.connect("smtp.126.com")  # 连接126邮箱的服务器地址

    # 2.登录邮箱
    smtp.login("bwftest126@126.com", "abc123asd654")

    # 3.发送邮件
    # 注意：msg是MIME类型，需要转成String类型再发送
    smtp.sendmail('bwftest126@126.com', '15032683126@163.com', msg.as_string())
    smtp.sendmail('bwftest126@126.com', '18401569214@163.com', msg.as_string())
    smtp.sendmail('bwftest126@126.com', '2410064039@qq.com', msg.as_string())
    smtp.sendmail('bwftest126@126.com', 'bszhangf@isoftstone.com', msg.as_string())

    # 4.退出邮箱
    smtp.quit()
    print("email has send out!")

if __name__ == '__main__':
    # 时间戳
    # strftime: str 是String，f是format格式
    # strftime()通过这个方法可以定义时间的格式
    # Y-year年，m-month月，d-day日，H-hour小时，M-minute分，S-second秒
    now = time.strftime("%Y-%m-%d_%H-%M-%S")

    suite = unittest.defaultTestLoader.discover("./day5", pattern="*Test.py")
    # suite = unittest.defaultTestLoader.discover(".", pattern="*Test.py")
    # unittest.TextTestRunner() 文本测试用例运行器
    # 现在用html的测试用例运行器
    # html的测试用例运行器最终会生成一个html格式的测试报告
    # 我们至少要指定测试报告的路径
    base_path = os.path.dirname(__file__)
    print(base_path)
    path = base_path + "/report/report" + now + ".html" # 给测试报告文件名加上时间戳命名
    file = open(path, "wb")
    # stream:要创建的文件
    # title:生成的测试报告的网页标签名
    # description:描述，正文，该变量的值可以为空，为空时会默认设置正文
    HTMLTestRunner(stream=file, title="海盗商城测试报告",
                   description="测试环境:Window Server 2008 + Chrome").run(suite)
    file.close()
    # 我们要把html报告作为邮件正文，发送邮件
    send_mail(path)

    # 这时生成的测试报告，只显示类名和方法名，只能给专业的人士看
    # 我们应该把相关的手动测试用例的标题加到我们的测试报告里
    # 我们自动化测试用例是从手动测试用例中挑出来的，手工测试用例怎么
    # 写，我们就怎么编写代码，所以我们的代码里应该体现手工测试用例的标题
    # 新的测试报告会覆盖原来的测试报告，如果想把所有的测试报告保存起来要怎么做
    # 加一个时间戳，按照当前时间计算一个数字，把数字作为文件名的一部分就避免了文件名重复的问题
    # 现在我们的html格式的测试报告生成了，当测试用例全部执行完成应该生成一封提醒邮件，通知所有关心测试结果的人


import sys
import os

import argparse
import time
import torch
import models.losses as ls
#import models.train as tr
from tqdm import tqdm
from typing import Callable, List, Optional, Iterator, Tuple, NamedTuple, Union
import random
from ithemal_utils import *
import training
import pandas as pd
#import utilities as ut

def main():
    # type: () -> None
    parser = argparse.ArgumentParser()

    # data arguments
    parser.add_argument('--data', required=True, help='The data file to load from')
    parser.add_argument('--embed-mode', help='The embedding mode to use (default: none)', default='none')
    parser.add_argument('--embed-size', help='The size of embedding to use (default: 256)', default=256, type=int)
    parser.add_argument('--hidden-size', help='The size of hidden layer to use (default: 256)', default=256, type=int)

    parser.add_argument('--use-rnn', action='store_true', default=False)
    rnn_type_group = parser.add_mutually_exclusive_group()
    rnn_type_group.add_argument('--rnn-normal', action='store_const', const=md.RnnType.RNN, dest='rnn_type')
    rnn_type_group.add_argument('--rnn-lstm', action='store_const', const=md.RnnType.LSTM, dest='rnn_type')
    rnn_type_group.add_argument('--rnn-gru', action='store_const', const=md.RnnType.GRU, dest='rnn_type')
    parser.set_defaults(rnn_type=md.RnnType.LSTM)

    rnn_hierarchy_type_group = parser.add_mutually_exclusive_group()
    rnn_hierarchy_type_group.add_argument('--rnn-token', action='store_const', const=md.RnnHierarchyType.NONE, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-dense', action='store_const', const=md.RnnHierarchyType.DENSE, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-multiscale', action='store_const', const=md.RnnHierarchyType.MULTISCALE, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-linear-model', action='store_const', const=md.RnnHierarchyType.LINEAR_MODEL, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-mop', action='store_const', const=md.RnnHierarchyType.MOP_MODEL, dest='rnn_hierarchy_type')
    parser.set_defaults(rnn_hierarchy_type=md.RnnHierarchyType.MULTISCALE)

    parser.add_argument('--rnn-skip-connections', action='store_true', default=False)
    parser.add_argument('--rnn-learn-init', action='store_true', default=False)
    parser.add_argument('--rnn-connect-tokens', action='store_true', default=False)

    sp = parser.add_subparsers(dest='subparser')

    train = sp.add_parser('train', help='Train an ithemal model')
    train.add_argument('--experiment-name', required=True, help='Name of the experiment to run')
    train.add_argument('--experiment-time', required=True, help='Time the experiment was started at')
    train.add_argument('--epochs', type=int, default=30, help='Number of epochs to run for')
    train.add_argument('--batch-size', type=int, default=32, help='The batch size to use in train')
    train.add_argument('--initial-lr', type=float, default=0.1, help='Initial learning rate')
    train.add_argument('--lr-decay-rate', default=1.2, help='LR division rate', type=float)

    cont = sp.add_parser('cont', help='Train an ithemal model')
    cont.add_argument('--experiment-name', required=True, help='Name of the experiment to run')
    cont.add_argument('--experiment-time', required=True, help='Time the experiment was started at')
    cont.add_argument('--epochs', type=int, default=30, help='Number of epochs to run for')
    cont.add_argument('--batch-size', type=int, default=32, help='The batch size to use in train')
    cont.add_argument('--initial-lr', type=float, default=0.1, help='Initial learning rate')
    cont.add_argument('--lr-decay-rate', default=1.2, help='LR division rate', type=float)
    cont.add_argument('--model',  help='Model architecture to use(dump file)', required=True)
    cont.add_argument('--model-data', help='Model data to use(mdl file)', required=True)

    args = parser.parse_args()

    base_params = BaseParameters(
        data=args.data,
        embed_mode=args.embed_mode,
        embed_size=args.embed_size,
        hidden_size=args.hidden_size,
        use_rnn=args.use_rnn,
        rnn_type=args.rnn_type,
        rnn_hierarchy_type=args.rnn_hierarchy_type,
        rnn_connect_tokens=args.rnn_connect_tokens,
        rnn_skip_connections=args.rnn_skip_connections,
        rnn_learn_init=args.rnn_learn_init,
    )

    if args.subparser == 'train':
        train_params = TrainParameters(
            experiment_name=args.experiment_name,
            experiment_time=args.experiment_time,
            epochs=args.epochs,
            batch_size=args.batch_size,
            initial_lr=args.initial_lr,
            lr_decay_rate=args.lr_decay_rate,
        )
        trainer = training.load_trainer(base_params,train_params)
        trainer.train()

    elif args.subparser == 'cont':
        train_params = TrainParameters(
            experiment_name=args.experiment_name,
            experiment_time=args.experiment_time,
            epochs=args.epochs,
            batch_size=args.batch_size,
            initial_lr=args.initial_lr,
            lr_decay_rate=args.lr_decay_rate,
        )
        trainer = training.load_continue(base_params,train_params, args.model, args.model_data)
        trainer.train()

    else:
        raise ValueError('Unknown mode "{}"'.format(args.subparser))

if __name__ == '__main__':
    main()


import random

def pickDices():
    diceList = ['d4','d6','d6', 'd8','d8','d8','d8','d10','d10','d12','d20','d20','d20']
    firstThreeDices = random.sample(diceList, 3)
    print("First three dices are: ", firstThreeDices)
    for dice in firstThreeDices:
        diceList.remove(dice)
    print("Remaining Dices to pick from: ", diceList)
    return random.sample(diceList, 2)

def rollDice(diceType):
    diceRange = int(diceType[1:])
    numRolled =  random.randint(1,diceRange)
    print("The dice and number rolled are: ", diceType, numRolled)
    return numRolled

def getSumOfDices():
    dicePicked = pickDices()
    print("The two dices picked are: ", dicePicked)
    sum = 0
    for dice in dicePicked:
        sum += rollDice(dice)
    print("The sum of number rolled in two dices is: ", sum)

getSumOfDices()


from datetime import datetime, timezone
from random import randint, shuffle

import config

daily_water_consumption_avg = 330

daily_water_consumption_in_percentage = (1.5, 0.5, 0.5, 0.5, 1.0, 2.0, 2.5, 4.0,
                                         6.0, 7.0, 6.0, 7.0, 6.0, 5.5, 4.0, 2.0, 6.0, 7.5, 8.0, 7.5, 5.5, 5.5, 2.5, 1.5)

def get_hourly_random_water_usage(current_hour_max):
    nb_of_step_per_hour = int(3600/config.delay)

    steps_per_hour = [0 for i in range(nb_of_step_per_hour)]

    total_hourly_random_water_usage = 0
    for step in range(nb_of_step_per_hour):
        random_value = randint(1, 3)
        res = random_value if (total_hourly_random_water_usage + random_value <=
                               current_hour_max) else 0
        total_hourly_random_water_usage += res
        steps_per_hour[step] = res

    shuffle(steps_per_hour)
    return steps_per_hour

def get_daily_random_water_usage():
    daily_water_usage = [-1 for i in range(24)]
    total_daily_random_water_usage = 0

    for hour in range(24):
        condition_for_more_water_usage = randint(0, 3) == 0
        delta = randint(1, 8) if condition_for_more_water_usage else 0
        hourly_percentage = daily_water_consumption_in_percentage[hour]
        current_hour_max = int(daily_water_consumption_avg *
                               hourly_percentage / 100 + delta)
        hourly_random_water_usage = get_hourly_random_water_usage(
            current_hour_max)
        daily_water_usage[hour] = hourly_random_water_usage
        total_daily_random_water_usage += current_hour_max

    return daily_water_usage

# def simulate_water_usage(time):
#     if ((time.hour > 21 and time.hour <= 23) or (time.hour >= 0 and time.hour < 7)):
#         return randint(0, 120) == 0

#     return randint(0, 25) == 0

def get_last_db_record(client, data_source: str):
    # return client.query('SELECT LAST(*) FROM {data_source}'.format(data_source=data_source.upper()))
    # return client.query('SELECT * FROM {data_source} GROUP BY * ORDER BY DESC LIMIT 1'.format(data_source=data_source.upper()))
    return client.query('SELECT * FROM {data_source} ORDER BY DESC LIMIT 1'.format(data_source=data_source.upper()))

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

daily_random_water_usage = None

def generate_random_entry(client, data_source: str, time: datetime):
    global daily_random_water_usage

    if(daily_random_water_usage is None or (time.hour == 0 and time.minute == 0)):
        print("Generating new daily water usage...")
        daily_random_water_usage = get_daily_random_water_usage()

    latest_record_query_res = get_last_db_record(client, data_source.upper())

    latest_record_list = list(latest_record_query_res.get_points())

    if(len(latest_record_list) == 0):
        return (0, 0)

    latest_record = latest_record_list[0]
    # latest_record = next(latest_record_query_res.get_points())

    latest_record_time_str = latest_record["time"]
    latest_record_time_date = utc_to_local(datetime.strptime(
        latest_record_time_str, "%Y-%m-%dT%H:%M:%S.%fZ")).day

    daily_consumption = latest_record["daily_consumption"] if latest_record_time_date == time.day else 0
    counter_index = latest_record["counter_index"]

    # new_value = randint(1, 10) if simulate_water_usage(time) else 0
    step = int((time.minute * 60 + time.second) / config.delay)
    new_value = daily_random_water_usage[time.hour][step]

    daily_consumption += new_value
    counter_index += new_value

    return (daily_consumption, counter_index)

if __name__ == "__main__":
    # now = datetime.now()
    # print(now.astimezone())
    fake_last_record_time_str = "2021-08-16T22:56:30.001017Z"
    fake_last_record_time_date = datetime.strptime(
        fake_last_record_time_str, "%Y-%m-%dT%H:%M:%S.%fZ")

    print(utc_to_local(fake_last_record_time_date))


# -*- coding: utf-8 -*-
import random
import sys
import numpy as np

# ----------- 蚂蚁算法 -----------

# 参数
# (ALPHA, BETA, RHO, Q) = (1.0, 1.0, 0.6, 30.0)
(alpha,beta,rho,smp_max,smp_min,srd,K,Q)=(1.0,1.0,0.6,4,1,0.3,5,3.0)
def change(array,i,n):
    temp = np.random.randint(0,n-2)

    if i != temp:
        p = array[temp]
        array[temp] = array[i];
        array[i] = p;
    return array

def seeking(city_num,distance_graph,Route_l,K,smp_min,smp_max):
    smp = np.zeros([K,city_num])
    for i in range(K):
        smp[i,:] = Route_l[:]
    smp = smp.astype(int)
    for i in range(K-1):
        srdnum = (smp_min + np.random.random()* (smp_max - smp_min))//1

        count = 0
        for j in range(city_num-2):
            if np.random.random() <=srd:
                smp[i,1:city_num-1] = change(smp[i,1:city_num-1],j,city_num)
                count = count +1
                if count >= srdnum:
                    break

    f = np.zeros([K])
    for i in range(K):
        for j in range(city_num-1):
            f[i] = f[i] + distance_graph[smp[i,j],smp[i,j+1]]
    mindex = np.argmin(f)

    Route = smp[mindex,:]

    return Route

class Ant_cso(object):
    # 初始化
    def __init__(self,cityNum,distance_graph,iter_max,ant_num,start_city,end_city):

        self.city_num=cityNum  # 城市数目
        self.distance_graph=np.array(distance_graph)  #距离矩阵
        self.iter_max = iter_max
        self.ant_num = ant_num
        self.start_city = start_city
        self.end_city = end_city

        self.pheromone_graph=np.ones([self.city_num,self.city_num])    #信息素矩阵
        self.Table = np.zeros([ant_num,cityNum])
        self.Length = np.zeros([self.ant_num,1])

        self.Route_best_l = np.zeros([iter_max,self.city_num])
        self.Length_best_l = np.zeros([iter_max,1])
        self.Length_ave = np.zeros([iter_max,1])
        self.citys_index = np.arange(cityNum)

    def _aco(self):     #一次蚁群算法的遍历
        start = np.zeros([self.ant_num,1])
        for i in range(self.ant_num):
            start[i] = int(self.start_city)

        self.Table[:,0] = start.ravel()
        for i in range(self.ant_num):
            for j in range(2,self.city_num+1):
                tabu = self.Table[i,0:(j-1)]

                allow_index =  np.array(list(set(self.citys_index).difference(set(tabu))))

                if allow_index.shape[0]>1:
                    allow_index=np.array(list(set(allow_index).difference([self.end_city])))
                P = np.array(allow_index).astype(float)
                for k in range(allow_index.shape[0]):
                    P[k]=pow(self.pheromone_graph[int(tabu[-1]),allow_index[k]],alpha)*pow((1/self.distance_graph[int(tabu[-1]),allow_index[k]]),beta)

                P = (1/np.sum(P))*P

                Pc = P.cumsum()

                target_index = np.where(Pc>np.random.random(1))

                target = allow_index[target_index][0]

                self.Table[i,j-1]=target

    def Route_length(self):
        self.Length = np.zeros([self.ant_num,1])
        for i in range(self.ant_num):
            Route = self.Table[i,:].astype(int)
            for j in range(self.city_num-1):
                self.Length[i] = self.Length[i]+self.distance_graph[Route[j],Route[j+1]]

    def _cso(self):
        L2 = np.sort(self.Length,axis=None)

        Route_l = np.zeros([1,self.city_num])
        for i in range(K):
            seeking_index = np.where(self.Length==L2[i])

            if seeking_index[0].shape != 1:
                seeking_index = seeking_index[0]

            Route_l = self.Table[seeking_index[0],:]
            Route_l = seeking(self.city_num,self.distance_graph,Route_l,K,smp_min,smp_max)
            self.Table[seeking_index,:] = Route_l

    def Clean_update(self):
        Delta_pheromone_graph = np.zeros([self.city_num,self.city_num])

        self.Table.astype(int)
        for i in range(self.ant_num):
            for j in range(self.city_num-1):
                Delta_pheromone_graph[int(self.Table[i,j]),int(self.Table[i,j+1])] = Delta_pheromone_graph[int(self.Table[i,j]),int(self.Table[i,j+1])]+Q/self.Length[i]
        self.pheromone_graph = (1-rho)*self.pheromone_graph+Delta_pheromone_graph
        self.Table = np.zeros([self.ant_num,self.city_num])

    # 搜索路径，外部接口
    def search_path(self):
        for iter in range(self.iter_max):
            self._aco()
            self.Route_length()
            self._cso()

            min_index = np.argmin(self.Length)
            min_Length = self.Length[min_index]
            self.Length_best_l[iter] = min_Length
            self.Length_ave[iter] = np.mean(self.Length)

            self.Route_best_l[iter,:] = self.Table[min_index,:]

            self.Clean_update()


from multiprocessing import Process, freeze_support
import time

import screen
import glob

def main():
    freeze_support()
    scr = screen.Screen()
    scr_t = Process(target=scr.start, args=('test.yaml',))
    scr_t.start()

    #Test
    glob.set_variable('venta', 0)
    while True:
        time.sleep(.1)
        glob.var_sum('venta', .1)
        if glob.get_variable('venta') >= 30:
            break
    return 0

if __name__ == '__main__':
    main()


from dataclasses import field
from rest_framework import serializers
from .models import Chat, Message
from django.contrib.auth.models import User
from django.db import transaction

class ChatViewSerializer(serializers.ModelSerializer):
    users = serializers.PrimaryKeyRelatedField(many=True,
                     queryset=User.objects.all())

    class Meta:
        model = Chat
        fields = ['id', 'name', 'users', 'chat_picture', 'type', 'messages']

class ChatViewPatchSerializer(serializers.ModelSerializer):
    users = serializers.PrimaryKeyRelatedField(many=True,
                     queryset=User.objects.all())

    class Meta:
        model = Chat
        fields = ['id', 'name', 'users', 'chat_picture', 'type', 'messages']

    @transaction.atomic
    def update(self, instance, validated_data):
        if 'users' in validated_data:
            users = validated_data.pop('users')[0]
            user = User.objects.get(id=users.id)
            instance.users.add(user)
            instance.save()

        return super().update(instance, validated_data)

# create serializer for sending message
class MessageSendSerializer(serializers.ModelSerializer):
    class Meta:
        model = Message
        fields = ['id', 'from_user', 'text', 'time', 'photo', 'file']

    @transaction.atomic
    def create(self, validated_data):
        # if 'chat_id' in validated_data:
        # print("I am here")
        request = self.context['request']
        from_user = validated_data['from_user']
        text = validated_data['text']
        message = Message.objects.create(from_user=from_user, text=text)
        chat = Chat.objects.get(id=request.data.get('chat_id'))
        chat.messages.add(message)

        # chat.messages.add(message)
        return message

class MessageViewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Message
        fields = ['id', 'from_user', 'text', 'time', 'photo', 'file']

    # def create(self, validated_data):
    #     if 'chat_id' in validated_data:
    #         requested_chat = validated_data.get('chat_id')
    #         chat = Chat.objects.get(id=requested_chat)
    #         print(chat)
    # def create(self, validated_data):
    #     # if 'chat_id' in validated_data:
    #     print(validated_data['chat_id'])
    #     from_user = validated_data['from_user']
    #     text = validated_data['text']
    #     message = Message.objects.create(from_user=from_user, text=text)
    #     # chat = Chat.objects.get(id=validated_data['chat_id'])

    #     # chat.messages.add(message)
    #     return message