import subprocess as sp
import sys
import ctypes
import os
import random
import json
import base64
import pathlib
import tempfile
import functools
import operator
import time
import numpy
import pylibsort
import libff.invoke

# ol-install: numpy

# from memory_profiler import profile
import cProfile
import pstats
import io

doProfile = False

def printCSV(pr, path):
    path = pathlib.Path(path)

    result = io.StringIO()
    # pstats.Stats(pr,stream=result).print_stats()
    pstats.Stats(pr,stream=result).sort_stats(pstats.SortKey.CUMULATIVE).print_stats()
    result=result.getvalue()
    # chop the string into a csv-like buffer
    result='ncalls'+result.split('ncalls')[-1]
    result='\n'.join([','.join(line.rstrip().split(None,5)) for line in result.split('\n')])

    with open(path, 'w') as f:
        f.write(result)

def sortPartial(event, ctx):
    # Temporary limitation for testing
    # if event['arrType'] != 'file':
    #     return { "error" : "Function currently only supports file distributed arrays" }
    pylibsort.ConfigureBackend('file', ctx)

    refs = pylibsort.getPartRefs(event)
    rawBytes = pylibsort.readPartRefs(refs)

    try:
        boundaries = pylibsort.sortPartial(rawBytes, event['offset'], event['width'])
    except Exception as e:
        return { "error" : str(e) }

    pylibsort.writeOutput(event, rawBytes, boundaries)

    return { "error" : None }

def selfTest():
    """Main only used for testing purposes"""

    import numpy as np

    # nElem = 256
    # nElem = 256*(1024*1024)
    nElem = 1024*1024
    nbyte = nElem*4
    offset = 0
    width = 8
    # width = 16
    narr = 2
    npart = 2
    bytesPerPart = int(nbyte / (narr * npart))

    inBuf = pylibsort.generateInputs(nElem)

    with tempfile.TemporaryDirectory() as tDir:
        tDir = pathlib.Path(tDir)
        libffCtx = libff.invoke.RemoteCtx(libff.array.ArrayStore('file', tDir), None)
        pylibsort.ConfigureBackend('file', libffCtx)

        inArrName = "faasSortTestIn"
        outArrName = "faasSortTestOut"

        # Write source arrays
        inShape = pylibsort.ArrayShape.fromUniform(bytesPerPart, npart)
        refs = []
        for arrX in range(narr):
            arrName = inArrName + str(arrX)
            inArr = pylibsort.DistribArray.Create(arrName, inShape)

            start = (arrX*npart)*bytesPerPart
            end = start + (bytesPerPart*npart)
            inArr.WriteAll(inBuf[start:end])
            for partX in range(npart):
                refs.append({
                    'arrayName': arrName,
                    'partID' : partX,
                    'start' : 0,
                    'nbyte' : -1
                })
            inArr.Close()

        req = {
                "offset" : offset,
                "width" : width,
                "arrType" : "file",
                "input" : refs,
                "output" : outArrName
        }

        if doProfile:
            pr = cProfile.Profile()
            pr.enable()
            resp = sortPartial(req, libffCtx)
            pr.disable()
            printCSV(pr, "./faas{}b.csv".format(width))
            pr.dump_stats("./faas{}b.prof".format(width))
        else:
            start = time.time()
            resp = sortPartial(req, libffCtx)
            print(time.time() - start)

        if resp['error'] is not None:
            print("FAILURE: Function returned error: " + resp['error'])
            exit(1)

        outArr = pylibsort.DistribArray.Open(outArrName)
        outBuf = outArr.ReadAll()
        boundaries = outArr.shape.starts

        outArr.Destroy()

    # byte capacities to int boundaries
    caps = np.array(outArr.shape.caps) // 4
    boundaries = np.cumsum(caps)
    boundaries = np.roll(boundaries, 1)
    boundaries[0] = 0

    pylibsort.checkPartial(inBuf, outBuf, boundaries, offset, width)

    print("PASS")

def libffProcessInvoke():
    """Use this as main when you are using libff.invoke to invoke the sort as a
    remote process (ProcessRemoteFunc).  See libff.invoke documentation for how
    this works"""
    libff.invoke.RemoteProcessServer({"sortPartial" : sortPartial}, sys.argv[1:])

def LibffInvokeRegister():
    return {"sortPartial" : sortPartial}

if __name__ == "__main__":
    # selfTest()
    libffProcessInvoke()


import sys
sys.stdin = open('input.txt', 'r')

T = int(input())
for test_case in range(1, T+1):
    N = int(input())
    result = 0

    print('#{} {} : {}'.format(test_case, N, result))

# def pow(a, n):
#     if n == 0:
#         return 1
#     else:
#         return a * pow(a, n - 1)

# T = int(input())
# ans = []
# for test_case in range(T):
#     N = int(input())
#     M, cnt = N, 0
#
#     while N >= 1:
#         if N % 2:
#             cnt += 1
#         N //= 2
#     ans.append(M + 1 - int(pow(2, cnt)))
# for i in range(T):
#     print("#{} {}".format(i + 1, ans[i]))


"""
This file
"""
from textblob import TextBlob
import sys

user_input = sys.argv
if len(user_input) != 2:
    print("Need a txt file to read")
    exit()

with open(user_input[1], 'r') as f:
    text = f.read()

blob = TextBlob(text)
sentiment = blob.sentiment.polarity
print(sentiment)


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        dummy = ListNode(0)
        cur = head
        offset = dummy

        # find offset
        for _ in xrange(m - 1):
            offset.next = cur
            offset = offset.next
            cur = cur.next

        # reverse selected range
        end, tmp, start = None, None, cur
        for _ in xrange(m, n + 1):
            tmp = start.next
            start.next = end # init to None
            end = start      # final value is 4 subject to [1,2,3,4,5] with param (2, 4)
            start = tmp      # final value is 5 subject to [1,2,3,4,5] with param (2, 4)

        # combine range
        offset.next = end # 1 -> 4 -> 3 -> 2,  5
        cur.next = start  # 1 -> 4 -> 3 -> 2 -> 5

        return dummy.next


#!/usr/bin/python3
"""
This module contains a Square class
"""

from models.rectangle import Rectangle
from models.base import Base

class Square(Rectangle):
    """
    Square class
    """
    def __init__(self, size, x=0, y=0, id=None):
        """
        Initializes a square class that inherits from rectangle
        Args:
        size (int): size of the square
        x (int): position in x axis of the square
        y (int): position in y axis of the square
        """
        super().__init__(size, size, x, y, id)

    def __str__(self):
        """
        Prints information of a square
        """
        return "[Square] ({:d}) {:d}/{:d} - {:d}".format(self.id, self.x,
                                                         self.y, self.size)

    @property
    def size(self):
        """
        Returns size of the square
        """
        return self.width

    @size.setter
    def size(self, value):
        """
        Assings and validates the value of size
        """
        if type(value) is not int:
            raise TypeError("width must be an integer")
        elif value < 0:
            raise ValueError("width must be > 0")
        else:
            self.width = value

    def area(self):
        """
        Returns the area of a square
        """
        return self.size * self.size

    def display(self):
        """
        Prints str rep of a square
        """
        for y_skip in range(self.y):
            print()
        spaces = " " * self.x
        for row in range(self.size):
            print(spaces, end="")
            for col in range(self.size):
                print("#", end="")
            print()

    def update(self, *args, **kwargs):
        """
        Updates the value of the square using args
        """
        if len(args):
            for key, arg in enumerate(args):
                if arg == 0:
                    self.id = arg
                elif arg == 1:
                    self.size = arg
                elif arg == 2:
                    self.x = arg
                elif arg == 3:
                    self.y = arg
        else:
            if "id" in kwargs:
                self.id = kwargs["id"]
            if "size" in kwargs:
                self.size = kwargs["size"]
            if "x" in kwargs:
                self.x = kwargs["x"]
            if "y" in kwargs:
                self.y = kwargs["y"]

    def to_dictionary(self):
        """
        Return dict representation of a class
        """
        square = Square(self.id, self.size, self.x, self.y)
        return dict(square.__dict__)


"""
----------SANTIAGO RIOS GUIRAL--------------------------------------------------
----------santiago.riosg@udea.edu.co--------------------------------------------
--------------------------------------------------------------------------------
----------EMMANUEL GOMEZ OSPINA-------------------------------------------------
----------emmanuel.gomezo@udea.edu.co-------------------------------------------
--------------------------------------------------------------------------------
----------Curso Básico de Procesamiento de Imágenes y Visión Artificial---------
--------------------------------------------------------------------------------
"""

import time

def start_read(source_file):
	"""Obtiene el historial de movimientos de la partida de ajedrez y lo guarda en una cadena de caracteres.
	"""
	with open(source_file,"r") as f:
		record = f.read()
		return record

def move(m):
	"""Pasa cada movimiento de una ficha al formato PGN.
	"""
	M = ""  #Guarda la jugada en formato PGN
	capture = 0
	# Caracteriza el movimiento, sí se mueve una ficha o dos en el caso del movimiento Castle
	if(m.lower() == "ooo" or m.lower() == "oo"):
		M = '-'.join(m.upper()) #https://stackoverflow.com/a/3258612/8235105
		return M
	else:
		# Organiza la jugada en formato PGN
		if(m[0].lower() != "x"): # Jugadas cuando solo se movio una ficha
			past = m[0:2]
			present = m[-2:len(m)]
			piece = m[2:-2]
		else:	# Jugadas cuando se presenta la captura de una ficha
			past = m[1:3]
			present = m[-2:len(m)]
			piece = m[3:-2]
			capture = 1
		#rendering the move:
		pt = piece[0] #piece type
		if(pt.lower() == "p"):
			M = f"{past[0]}x{present}" if(capture) else f"{present}"
		else:
			M = f"{pt.upper()}{past}x{present}" if(capture) else f"{pt.upper()}{past}{present}" #remove upper() if needed
		return M

def decode_stringhistory(record):
	""" Cambia el formato del historial de jugadas y lo pasa a PGN. para esto recibe una cadena de caracteres con los movimientos
	de las fichas y para cada una formatea la jugada de acuerdo al estandar PGN.
	"""
	record_listed = record.split(" - ") # Separa las jugadas
	record_listed[-1] = record_listed[-1][:-1] # Elimina el espacio al inicio y final de la cadena de caracteres
	if(record_listed[-1] == ""):
		record_listed.pop()
	record_ordered = "" # Cadena de caracteres que guarda las jugadas PGN
	# Itera sobre cada jugada para pasarla a PGN
	for i,m in enumerate(record_listed):
		iteration = i//2+1
		Blackstate = i%2
		if(not Blackstate):
			record_ordered += f"{iteration}. "
		processed_move = move(m) # Organiza la jugada en formato PGN
		record_ordered += f"{processed_move} " # Agrega la jugada a la cadena de caracteres
	return record_ordered

def to_pgn():
	"""Convierte el historial de jugadas en la partida de ajedrez en formato PGN.
	"""
	#moves source file
	source = "chess-pgn.txt" # Archivo con el historial de jugadas
	#record
	record = start_read(source) # Cadena de caracteres con el historial de jugadas

	# Formato de inicio del archivo PGN de salida
	PGNrecord = """[Event "PDI Final project"]
	[Site "Universidad de Antioquia"]
	[Date "2022.04.06"]
	[EventDate "2022.04.06"]
	[Round "1"]
	[Result "1-0"]
	[White "Garry Kasparov"]
	[Black "Veselin Topalov"]
	[ECO "B01"]
	[WhiteElo "3000"]
	[BlackElo "3000"]
	[PlyCount "18"]

	"""

	result = decode_stringhistory(record) # Decodifica el historial de jugadas a formato PGN
	PGNrecord += result # Genera una cadena de caracteres con el historial en PGN
	timestr = time.strftime("%H:%M:%S-%d+%m+%y")
	fname = f"PGN{timestr}.txt"
	# Crea el archivo con la partida de ajedrez en formato PGN
	with open(fname, "w+") as f:
		f.write(PGNrecord)
	return 0


import shutil
import os
import glob2
from tqdm import tqdm

train_path = '../data/train/'
test_path = '../data/test/'

if not os.path.exists(train_path):
    os.makedirs(train_path)

if not os.path.exists(test_path):
    os.makedirs(test_path)

test_num = 0
for filename in tqdm(glob2.glob('../data/dicom-images-test/**/*.dcm')):
    fname = str(filename).split('/')[-1]
    shutil.copy(str(filename), os.path.join(test_path, fname))
    test_num += 1

print('Moved ' + str(test_num) + ' files!' )

train_num = 0
for filename in tqdm(glob2.glob('../data/dicom-images-train/**/*.dcm')):
    fname = str(filename).split('/')[-1]
    shutil.copy(str(filename), os.path.join(train_path, fname))
    train_num += 1

print('Moved ' + str(train_num) + ' files!' )


import os
from pdfRecognition import pdfRecognition
import fitz

class pdfToPic():
    def __init__(self,filepath,folderPath):
        self.filepath  = filepath
        self.folderPath = folderPath

    def pdfToPic(self):
        pdfDoc = fitz.open(self.filepath)
        for pg in range(pdfDoc.page_count):
            page = pdfDoc[pg]
            rotate = int(0)
            zoom_x = 1.33333333
            zoom_y = 1.33333333
            mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
            pix = page.get_pixmap(matrix=mat, alpha=False)

            if not os.path.exists(self.folderPath):
                os.makedirs(self.folderPath)

            fileName = self.folderPath + '/' + '%s.png' % pg

            pix.save(fileName)

            pdfNewName = pdfRecognition(fileName,self.folderPath).BarodeIdentification()

            os.rename(self.folderPath + '/' + '%s.pdf' % pg, self.folderPath + '/' + pdfNewName + ".pdf")

            os.remove(fileName)


import subprocess
from sys import exit
from itertools import combinations, permutations
from math import floor, ceil

# Facer lista de nxn coas reglas, para obter as filas e as columnas das regras
# Logo, con esto facemos as permutacions de 4 para a segunda regra
def filasColumnas(lista):
    """
    :param lista: Lista de formato nxn coas regras do problema
    :return: as filas e columnas da lista
    """
    totalVerticais = []
    for i in range(0, n):
        totalVerticais.append([row[i] for row in lista])
    return totalVerticais, lista

def list_to_nxn(lista):
    """
    Convirte a lista de regras nunha lista nxn
    :param lista: lista de regras do problema
    :return: lista das regras no formato nxn
    """
    result = []
    for i in range(0, n ):
        row = []
        for j in range(0, n ):
            row.append(lista[celda(i, j)] + 1)
        result.append(row)
    return result

def empty_list():
    """
    :return: Lista vacia en formato nxn
    """
    result = []
    for i in range(0, n):
        row = []
        for j in range(0, n):
            row.append(0)
        result.append(row)
    return result

def line_prepender(filename, line):
    """
    Engade liña ao comezo do ficheiro co numero de regras e predicados
    :param filename: Ficheiro no que escribir
    :param line: Liña co numero de regras e predicados
    """
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)

def celda(i, j):
    c = i * n + j
    return c

def fila(v):
    i = floor(v/n)
    return i

def columna(v):
    j = (v) % n
    return j

# Abrimos o ficheiro de entrada en modo lectura
f = open ('input.txt' , 'r')

# Gardamos nunha lista de listas os valores do input
l = [[elem for elem in line] for line in f]

# Quitamos da lista os saltos de liña. E INEFICIENTE porque facemos unha copia
# da lista
s = []
for elem in l:
    try:
        elem.remove("\n")
        s.append(elem)
    except:
        s.append(elem)
#################

# Tamaño fila ou columna do problema. Primeiro xuntamos os numeros da primeira
# lista (numero de filas/columnas) nun string e logo pasamolo a int
tFila = ''.join(s[0])
n = int(tFila)

# Eliminamos o numero fila/columna porque non o necesitaremos mais
s.remove(s[0])

# Imprimimos o problema inicial
for elem in s:
    print(*elem)

# Numero variables:
nvars = n*n

# Numero de predicados
npreds = 0

# Abrimos o ficheiro de saida
text_file = open("Output.txt", "w")

# Asignamos os valores booleanos as fichas que xa estan colocadas e
# gardamos as posibles regras (celdas) nunha lista
rulesList = []
for i in range(0, n):
    for j in range(0, n):
        var = celda(i, j)
        rulesList.append(var)
        if s[i][j] == '1':
            text_file.write("{0} 0\n".format(var + 1))
            npreds += 1
        elif s[i][j] == '0':
            text_file.write("-{0} 0\n".format(var + 1))
            npreds += 1

# Pasamos a lista de regras a unha lista de listas nxn
rulesList_nxn = list_to_nxn(rulesList)

##############################################################################
########################## Regras do xogo ####################################
##############################################################################

# REGRA No 1 => Non pode haber 3 da mesma cor seguidas
#  ¬(p ^ q ^ r)
#     ==
#  ¬p ∨ ¬q ∨ ¬r
for i in range(0, n):
    for j in range(0, n):
        var = celda(i, j)
        # Comprobamos os dous veciños da fila pola dereita
        if j + 2 < n:
            varY2 = celda(i, j + 1)
            varY3 = celda(i, j + 2)
            text_file.write("{0} {1} {2} 0\n".format(
                var + 1, varY2 + 1, varY3 + 1))
            text_file.write("-{0} -{1} -{2} 0\n".format(
                var + 1, varY2 + 1, varY3 + 1))
            npreds +=  2
        # Comprobamos os dous veciños da columna por abaixo
        if i + 2 < n:
            varX2 = celda(i + 1, j)
            varX3 = celda(i + 2, j)
            text_file.write("{0} {1} {2} 0\n".format(
                var + 1, varX2 + 1, varX3 + 1))
            text_file.write("-{0} -{1} -{2} 0\n".format(
                var + 1, varX2 + 1, varX3 + 1))
            npreds += 2

# REGRA 2 => Ten que haber as mesmas de cada cor en cada fila e columna
# p ^ q ^ r --> ¬s
#        ==
# ¬p ∨ ¬q ∨ ¬r ∨ ¬sº

# Obtemos as filas e columnas da lista de regras
verticais, laterais = filasColumnas(rulesList_nxn)

# En cada fila facemos as combinacions de (n/2 + 1) elementos
for lat in laterais:
    for row in combinations(lat, int(n/2 + 1)):
        regraBlancas = ""
        regraNegras = ""
        for item in row:
            regraBlancas += str(item) + " "
            regraNegras+= "-"+ str(item) + " "
        regraBlancas += "0\n"
        regraNegras += "0\n"
        text_file.write(regraBlancas)
        text_file.write(regraNegras)
        npreds += 2
for ver in verticais:
    for column in combinations(ver, int(n/2 + 1)):
        regraBlancas = ""
        regraNegras = ""
        for item2 in column:
            regraBlancas += str(item2) + " "
            regraNegras+= "-"+ str(item2) + " "
        regraBlancas += "0\n"
        regraNegras += "0\n"
        text_file.write(regraBlancas)
        text_file.write(regraNegras)
        npreds += 2

# REGRA 3 => Non pode haber filas/columnas repetidas
for fila1 in laterais:
    for fila2 in laterais:
        listaPs = []
        regraP = ""
        if fila1 != fila2:
            if fila1 != fila2:
                for i in range(0, len(fila1)):
                    nvars += 1
                    text_file.write("-{0} {1} {2} 0\n".format(nvars, fila1[i], fila2[i]))
                    text_file.write("-{0} -{1} -{2} 0\n".format(nvars, fila1[i], fila2[i]))
                    text_file.write("-{0} {1} {2} 0\n".format(fila1[i], fila2[i], nvars))
                    text_file.write("{0} -{1} {2} 0\n".format(fila1[i], fila2[i], nvars))
                    npreds += 4
                    listaPs.append(nvars)
                for elem in listaPs:
                    regraP += str(elem) + " "
                regraP += " 0\n"
                text_file.write(regraP)
                npreds += 1

for col1 in verticais:
    for col2 in verticais:
        listaPs = []
        regraP = ""
        if col1 != col2:
            for i in range(0, len(col1)):
                nvars += 1
                text_file.write("-{0} {1} {2} 0\n".format(nvars, col1[i], col2[i]))
                text_file.write("-{0} -{1} -{2} 0\n".format(nvars, col1[i], col2[i]))
                text_file.write("-{0} {1} {2} 0\n".format(col1[i], col2[i], nvars))
                text_file.write("{0} -{1} {2} 0\n".format(col1[i], col2[i], nvars))
                npreds += 4
                listaPs.append(nvars)
            for elem in listaPs:
                regraP += str(elem) + " "
            regraP += " 0\n"
            text_file.write(regraP)
            npreds += 1

######################################################################
######################################################################
######################################################################

text_file.close()

# Engadimos ao comezo do ficheiro a liña inicial de SAT
line_prepender("Output.txt", "p cnf {0} {1}\n".format(nvars, npreds))

# Chamada a Clasp
out = subprocess.Popen(['clasp', '--verbose=0', 'Output.txt'],
           stdout=subprocess.PIPE,
           stderr=subprocess.STDOUT)

# Procesamos a saida do Clasp
claspOutput = out.communicate()
claspError = claspOutput[1]
claspPrint = str(claspOutput[0])
claspPrint = claspPrint.split(" ")

# Elimina caracteres indesexados da saida
claspPrint.pop()
claspPrint.pop()
try:
    del claspPrint[0]
except:
    print("UNSATISFIABLE\n")
    exit(0)

# Transforma a saida de clasp de String a matriz de numeros
output = []
for elem in claspPrint:
    try:
        output.append(int(elem))
    except:
        # Se hai un salto de liña, eliminase aqui
        try:
            output.append(int(elem[:-3]))
        except:
            # Imprime o erro nun caso inesperado
            print(claspOutput[0])

print("\n")

# Convirte o resultado de clasp na matriz de 1's e 0's
visitados = []
result = empty_list()
for pos in output:
        if abs(pos) <= n*n:
            num = rulesList[abs(pos) - 1]
            x = fila(num)
            y = columna(num)
            if (x, y) not in visitados:
                visitados.append((x, y))
                visitados.append((x, y))
                if pos > 0:
                    result[x][y] = 1
                elif pos < 0:
                    result[x][y] = 0

for elem in result:
    print(*elem, sep="")
# Imprimime a matriz tal e como se pide
with open('result.txt', 'w') as f:
    for elem in result:
        print(*elem, sep="", file=f)


import sys, os

sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),
                "../datasets/"))
from mass_spring import get_dataset
import torch
import torch.nn as nn
import pytorch_lightning as pl
import numpy as np
import torch.utils.data as data
from TorchSnippet.energy import HNN
from TorchSnippet.dyna import odeint
import matplotlib.pyplot as plt

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

t = torch.linspace(0,1, 100).reshape(-1,1)
X = torch.cat([
    torch.sin(2*np.pi*t),
    torch.cos(2*np.pi*t)
],1).to(device)

y = torch.cat([
    torch.cos(2*np.pi*t),
    -torch.sin(2*np.pi*t)
],1).to(device)
# data1 = get_dataset(samples=50)
# X, y = torch.tensor(data1['x'], dtype=torch.float32).to(device), torch.tensor(data1['dx'], dtype=torch.float32).to(device)
# print(X.shape, y.shape)
train = data.TensorDataset(X, y)
dataloader = data.DataLoader(train, batch_size=15, shuffle=False)

class Learner(pl.LightningModule):
    def __init__(self, model:nn.Module):
        super().__init__()
        self.model = model
        self.c = 0

    def forward(self, x):
        return self.model(x)

    def loss(self, y, y_hat):
        return ((y-y_hat)**2).sum()

    def training_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self.model(x)
        loss = self.loss(y_hat, y)
        logs = {'train_loss': loss}
        return {'loss': loss, 'log': logs}

    def configure_optimizers(self):
        return torch.optim.Adam(self.model.parameters(), lr=0.01)

    def train_dataloader(self):
        return dataloader

func = HNN(nn.Sequential(
            nn.Linear(2,64),
            nn.Tanh(),
            nn.Linear(64,1))).to(device)

learner = Learner(func)
trainer = pl.Trainer(min_epochs=500, max_epochs=1000)
trainer.fit(learner)

func1 = lambda t, x: func(x)

# x_t = torch.randn(1000, 2).to(device)
x_t = X[:1, :]
print(x_t.shape)
s_span = torch.linspace(0, 2*np.pi, 618)
trajectory = odeint(func1, x_t, s_span).detach().cpu().numpy()
for i in range(len(x_t)):
    plt.plot(trajectory[:, i, 0], trajectory[:, i, 1], 'b')
plt.plot(X[:, 0], X[:, 1], '+')
plt.show()


import os
import secrets
from PIL import Image
from flask import render_template, url_for, flash, redirect, request, abort, jsonify, make_response
from app import app, db, bcrypt, mail
from forms import *
from models import *
from flask_login import login_user, current_user, logout_user, login_required
from datetime import datetime,timedelta

@app.route("/notification", methods=['GET','POST'])
def notification():

    page = request.args.get('page', 1, type=int)
    current_time = datetime.utcnow()
    four_weeks_ago = current_time - timedelta(weeks=4)
    posts = Post.query.filter(Post.date_posted>four_weeks_ago).order_by(Post.date_posted.desc()).paginate(page=page, per_page=6)

    stocktakeAll = Verify_Product_Storage.query.distinct(Verify_Product_Storage.verify_id).all()
    stocktakeAll.extend(Order_Product.query.distinct(Order_Product.verify_id).all())
    allUpdatebooking=Verify_Listing_Booking.query.distinct(Verify_Listing_Booking.verify_id).all()
    allUpdatebooking_verfiyid=[(v.verify_id) for v in allUpdatebooking]
    if current_user.role=="Manager":
        validStorageId = [user.user_id for user in User_Storage.query.filter_by(user_id=current_user.id).all()]
        stocktake=[s for s in stocktakeAll if s.storage_id in validStorageId]
        validVerify = [(v.id) for v in Verify.query.filter(Verify.id.in_(allUpdatebooking_verfiyid),(Verify.user_id==current_user.id)).distinct(Verify.id).all()]
        stocktake.extend([s for s in allUpdatebooking if s.verify_id in validVerify])
    else:
        stocktakeAll.extend(allUpdatebooking)
        stocktake=stocktakeAll

    notificationVerify=[]
    for stock in stocktake:
        temp=[]
        st = Verify.query.filter_by(id=stock.verify_id, user_id_confirm = None, date_verified = None).first()
        if(st!=None):
            temp={}
            temp["title"]=st.title
            temp["date"]=st.date_posted.strftime('%Y-%m-%d at %H:%M')
            temp["verify_id"]=st.id
            temp["username"]=User.query.filter_by(id=st.user_id).first().username
            if(st.title=="Update Booking"):
                temp["id"]=stock.listing_id
                temp["name"]=stock.listing.name+' - '+stock.listing.location.suburb
            else:
                temp["id"]=stock.storage_id
                temp["name"]=stock.storage.name+' - '+stock.storage.location.suburb
            if(st.title=="Stocktake"):
                temp["url"]="verifyStocktake"
            elif(st.title=="Transfer"):
                temp["url"]="verifyTransfer"
            elif(st.title=="Shopping"):
                temp["url"]="verifyShopping"
            elif(st.title=="Update Booking"):
                temp["url"]="verifyUpdateBooking"
            notificationVerify.append(temp)

    form = PostForm()

    return render_template('notification/notification.html', posts=posts,notificationVerify=notificationVerify, form=form)

@app.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
    if (request.json!=None):
        if request.json.get('submit')=='post':
            post = Post(title=request.json.get('title'), content=request.json.get('content'), author=current_user)
            db.session.add(post)
            db.session.commit()
            return jsonify({'status':'success'})
    return jsonify({'status':'fail'})

@app.route("/user/<string:username>")
def user_posts(username):
    page = request.args.get('page', 1, type=int)
    user = User.query.filter_by(username=username).first_or_404()
    posts = Post.query.filter_by(author=user)\
        .order_by(Post.date_posted.desc())\
        .paginate(page=page, per_page=5)
    return render_template('user/user_posts.html', posts=posts, user=user)

@app.route("/post/<int:post_id>")
def post(post_id):
    post = Post.query.get_or_404(post_id)
    userPost = User.query.filter_by(id=post.user_id).first()
    image_file = url_for('static', filename='pictures/profile/' + userPost.image_file)
    return render_template('notification/post.html', post=post, role=current_user.role,image_file=image_file)

'''
@app.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.title = form.title.data
        post.content = form.content.data
        db.session.commit()
        flash('Your post has been updated!', 'success')
        return redirect(url_for('post', post_id=post.id))
    elif request.method == 'GET':
        form.title.data = post.title
        form.content.data = post.content
    return render_template('notification/create_post.html',
                           form=form, legend='Update Post')
'''

@app.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    db.session.delete(post)
    db.session.commit()
    flash('Your post has been deleted!', 'success')
    return redirect(url_for('notification'))


import os
import hashlib

def getBigFileMD5(filename):
    '''
    获取文件的MD5值，适用于较大的文件
    '''
    if not os.path.isfile(filename):
        return
    myhash = hashlib.md5()
    f = open(filename, 'rb')
    while True:
        b = f.read(8096)
        if not b:
            break
        myhash.update(b)
    f.close()
    return myhash.hexdigest()

def printDiff(dirPath1, dirPath2):
    dirPath1 = dirPath1.replace(
        '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.', '').replace('-170410/tjtjs-ecstore', '')
    dirPath2 = dirPath2.replace(
        '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.', '').replace('-170410/tjtjs-ecstore', '')
    print(dirPath1 + ',' + dirPath2)
    pass

def getDirTree(dirPath1, dirPath2):
    ignoreList = ['.git', '.gitignore', 'public170327', 'publicbak170317', 'data/backup', 'data/cache/secache.php',
                  'themesbak170327', 'wap_themesbak0327', 'data/logs', 'data/kvstore', 'data/miscbak', 'data/retry.log', 'data/retry_result.log', 'wap_themes', 'themes']
    for igStr in ignoreList:
        if dirPath1.endswith(igStr) or dirPath2.endswith(igStr):
            return

    if os.path.isdir(dirPath1):
        files1 = os.listdir(dirPath1)
        files2 = os.listdir(dirPath2)
        for file in files1:
            fileFullPath = dirPath1 + '/' + file
            isIgnore = 0
            for igStr in ignoreList:
                if fileFullPath.endswith(igStr):
                    isIgnore = 1
                    break
            if isIgnore:
                continue

            if file in files2:
                getDirTree(dirPath1 + '/' + file, dirPath2 + '/' + file)
            else:
                printDiff(dirPath1 + '/' + file, '-')

        for file in files2:
            fileFullPath = dirPath2 + '/' + file
            isIgnore = 0
            for igStr in ignoreList:
                if fileFullPath.endswith(igStr):
                    isIgnore = 1
                    break
            if isIgnore:
                continue

            if file in files1:
                continue
            else:
                printDiff('-', dirPath2 + '/' + file)
    else:
        if getBigFileMD5(dirPath1) == getBigFileMD5(dirPath2):
            pass
        else:
            printDiff(dirPath1, dirPath2)

if __name__ == '__main__':
    # print('/home/tangbq/d/code/tjtjs-ecstore.172.16.226.163-170410/tjtjs-ecstore',
    #       '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.165-170410/tjtjs-ecstore')
    getDirTree(
        '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.163-170410/tjtjs-ecstore', '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.165-170410/tjtjs-ecstore')
    # print('---------')
    # print(
    #     '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.163-170410/tjtjs-ecstore', '/home/tangbq/d/code/tjtjs-ecstore')
    # getDirTree(
    #     '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.163-170410/tjtjs-ecstore', '/home/tangbq/d/code/tjtjs-ecstore')
    # print('---------')
    # print(
    #     '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.165-170410/tjtjs-ecstore', '/home/tangbq/d/code/tjtjs-ecstore')
    # getDirTree(
    #     '/home/tangbq/d/code/tjtjs-ecstore.172.16.226.165-170410/tjtjs-ecstore', '/home/tangbq/d/code/tjtjs-ecstore')


import torch
import numpy as np
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.utils.data._utils.collate import default_collate
from .datasets import IuxrayMultiImageDataset, MimiccxrSingleImageDataset, KnowledgeDataset

class ToPILImage(object):
    def __init__(self):
        self.to_pil = transforms.ToPILImage(mode="F")

    def __call__(self, x):
        return (self.to_pil(x[0]))

class LADataLoader(DataLoader):
    def __init__(self, args, tokenizer, split, shuffle):
        self.args = args
        self.dataset_name = args.dataset_name
        self.batch_size = args.batch_size
        self.shuffle = shuffle
        self.num_workers = args.num_workers
        self.tokenizer = tokenizer
        self.split = split

        normalize = transforms.Normalize(mean=[0.500, 0.500, 0.500],
                                         std=[0.275, 0.275, 0.275])
        if split == 'train':
            self.transform = transforms.Compose([
                transforms.Resize(args.image_size),
                transforms.RandomCrop(args.crop_size),
                transforms.RandomHorizontalFlip(),
                transforms.RandomAffine(degrees=10, translate=(0.2, 0.2), scale=(0.8, 1.2), fillcolor=(0, 0, 0)),
                transforms.ToTensor(),
                normalize])
        else:
            self.transform = transforms.Compose([
                transforms.Resize(args.image_size),
                transforms.CenterCrop(args.crop_size),
                transforms.ToTensor(),
                normalize])

        if self.dataset_name == 'iu_xray':
            self.dataset = IuxrayMultiImageDataset(self.args, self.tokenizer, self.split, transform=self.transform)
        elif self.dataset_name == 'mimic_cxr':
            self.dataset = MimiccxrSingleImageDataset(self.args, self.tokenizer, self.split, transform=self.transform)
        else:
            raise NotImplementedError

        self.init_kwargs = {
            'dataset': self.dataset,
            'batch_size': self.batch_size,
            'shuffle': self.shuffle,
            'collate_fn': self.collate_fn,
            'num_workers': self.num_workers,
            'pin_memory': False
        }
        super().__init__(**self.init_kwargs)

    @staticmethod
    def collate_fn(data):
        # image采用默认的batch方式，多进程的情况下可以减少额外的内存拷贝
        images = default_collate([d['image'] for d in data])

        images_id = [d['idx'] for d in data]
        reports_ids = [d['report_ids'] for d in data]
        reports_masks = [d['report_mask'] for d in data]
        seq_lengths = [d['seq_length'] for d in data]
        knowledges_ids = [d['knowledge_ids'] for d in data]
        # knowledges_masks = [d['knowledge_mask'] for d in data]

        max_seq_length = max(seq_lengths)

        targets = np.zeros((len(reports_ids), max_seq_length), dtype=int)
        targets_masks = np.zeros((len(reports_ids), max_seq_length), dtype=int)

        for i, report_ids in enumerate(reports_ids):
            targets[i, :len(report_ids)] = report_ids

        for i, report_masks in enumerate(reports_masks):
            targets_masks[i, :len(report_masks)] = report_masks

        b_knowledges = np.zeros((len(knowledges_ids), 64), dtype=int)
        # b_knowledges_masks = np.zeros((len(reports_ids), 64), dtype=int)

        for i, knowledge_ids in enumerate(knowledges_ids):
            knowledge_ids = knowledge_ids[:64]
            b_knowledges[i, :len(knowledge_ids)] = knowledge_ids

        # for i, knowledge_mask in enumerate(knowledges_masks):
        #     knowledge_mask = knowledge_mask[:64]
        #     b_knowledges_masks[i, :len(knowledge_mask)] = knowledge_mask

        batch = {'images_id': images_id,
                 'images': images,
                 'targets': torch.LongTensor(targets),
                 'reports_mask': torch.FloatTensor(targets_masks),
                 'knowledges': torch.LongTensor(b_knowledges),
                 # 'knowledges_mask': torch.FloatTensor(b_knowledges_masks)
                 }
        return batch

def get_bert_dataloader(args, tokenizer):
    dataset = KnowledgeDataset(args, tokenizer)
    dataloader = DataLoader(dataset,
                            batch_size=args.batch_size,
                            shuffle=False,
                            num_workers=0,
                            pin_memory=True)
    return dataset, dataloader


"""A number-guessing game."""
from random import randint

def getNum(prompt, start=None, end=None):
    try:
        num=int(input(prompt))
    except ValueError:
        print("Invalid number.")
        num = None

    if start is not None:
        if num < start:
            print ("Number must be greater than {}".format(start))
            num = None

    if end is not None:
        if num > end:
            print ("Number must be less than {}".format(end))
            num = None
    return num

def playGame(maxTries, start, end):
    print("{}, I'm thinking of a number between {} and {}.".format(name, start, end))
    print("Try to guess my number.")

    num = randint(start,end)
    tries = 0

    while tries < maxTries:
        guess = getNum("Your guess? ", start, end)
        if guess is None:
            print("Try again. Enter a number between {} and {}".format(start, end))
            continue
        '''
        try:
            guess = int(input("Your guess? "))
        except ValueError:
            print("That wasn't a valid number. Try again")
            continue
        '''

        # check for valid input
        '''
        if guess < start or guess > end:
            print("You have committed a crime. Please enter a number between {} and {}".format(start, end))
            continue
        '''

        tries += 1
        if num == guess:
            break
        elif num > guess:
            print("Your guess is too low, try again.")
        else:
            print("Your guess in too high, try again.")

    if tries >= maxTries:
        print("Too many tries.  The number was {}.   :-( ".format(num))
        return None
    else:
        print("Well done, {}! You found my number in {} tries!".format(name, tries))
        return tries

def scoreGame(tries, start, end):
    if tries is None:
        score = 0
    else:
        rangeSize = end - start
        score = rangeSize // tries
    print("Your score is {}".format(score))
    return score

# Put your code here
print("Howdy, what's your name?")
name = input("(type in your name) ")

# Get the range of valid guesses
'''
try:
    start = int(input("What's the start of the range? (enter starting number): "))
    end = int(input("What's the end of the range? (enter ending number): "))
except ValueError:
    print("Invalid range numbers. We'll use 1 to 100.")
'''
start = getNum("What's the start of the range? (enter starting number): ")
end = getNum("What's the end of the range? (enter ending number): ")
if start is None or end is None or start > end:
    print("Invalid range. We'll use 1 to 100")
    start = 1
    end = 100

try:
    maxTries = int(input("What\'s the maximum number of guesses you need per round? "))
except ValueError:
    print("That wasn't a valid number.  You get 20 tries.")
    maxTries=20

if maxTries < 1:
    print("Need a positive number.  You get 20 tries.")
    maxTries=20

playAgain = True
bestScore = 0

while playAgain:
    tries = playGame(maxTries, start, end)
    score = scoreGame(tries, start, end)
    if score > bestScore:
        bestScore = score
        # print ("bestScore so far is {}".format(bestScore))

    playAgainAnswer = input("Would you like to play again? (enter Yes to play again):  ")
    if playAgainAnswer.lower() != 'yes':
        playAgain = False

if bestScore == 0:
    print("Thanks for playing! You didn't win any games today.")
else:
    print("Thanks for playing! Your best score today was {}. Bye.".format(bestScore))


#!/root/nsd1905/bin/python
'''script for directory and file backup

by means of md5
Mon full backup
Tue-Sun incremental backup
计划任务,非交互式程序
1.星期几
2.备份方案（增量备和完全备）
完全备：
1.打包压缩目录下所有文件
2.os walk遍历所有文件并得到文件完整路径
3.计算每个文件的md5值
4.写入字典 -key: 路径 value md5
5.将字典pickle.dump到md5file里面

增量备
#压缩包的绝对路径： security_incr_back_20200904.tar.gz
#tar包生成并使用gz压缩
#将md5.data的值读出该字典
#os walk检查src的md5放进另一本字典中

#检查src中的每个key,是否在md5文件中有，如果没有，则是新增的文件。
#1.记录新增的key value，添加到md5文件中
#2.key文件路径加入tar包，作备份

# 检查src中的每个key是否在md5文件中有,如有，则看返回的value是否和生成的md5相同，如果不同，则
#1. 更新相应key的value在md5文件中
#2. key文件路径加入tar包，作备份
#关闭tar包
#把md5字典写入文件
'''

import tarfile
import time
import os
import pickle
import hashlib

def full_backup(src,dst,md5file):
    #压缩包的绝对路径： security_full_back_20200904.tar.gz
    fname='%s_full_backup_%s.tar.gz' % (os.path.basename(src),time.strftime('%Y%m%d'))
    fullpath=os.path.join(dst,fname)
    #打包并gz压缩
    tar=tarfile.open(fullpath,'w:gz')
    tar.add(src)
    tar.close()

    #计算每个文件的md5值

    #os.walk 得到每个文件完整路径
    md5dict={}
    for path,folders,files in os.walk(src):
        for file in files:
            key=os.path.join(path,file)
            #字典key=路径 value=md5
            md5dict[key] = check_md5(key)

    #把md5字典写入文件
    with open(md5file,'wb') as fobj:
        pickle.dump(md5dict,fobj)

def incr_backup(src,dst,md5file):
    #压缩包的绝对路径： security_incr_back_20200904.tar.gz
    fname='%s_incr_backup_%s.tar.gz' % (os.path.basename(src),time.strftime('%Y%m%d'))
    fullpath=os.path.join(dst,fname)
    #tar包生成并使用gz压缩
    tar=tarfile.open(fullpath,'w:gz')

    #将md5.data的值读出字典
    md5dict={}
    md5file_dict={}
    with open(md5file,'rb') as fobj:
        md5file_dict=pickle.load(fobj)
    #os walk检查src的md5放进另一本字典中
    for path,folders,files in os.walk(src):
        for file in files:
            key = os.path.join(path, file)
            md5dict[key]=check_md5(key)
            #检查src中的每个key,是否在md5文件中有，如果没有，则是新增的文件。
            #1.记录新增的key value，添加到md5文件中
            #2.key文件路径加入tar包，作备份
            if md5file_dict.get(key)==None:
                md5file_dict[key]=md5dict[key]
                tar.add(key)
            # 检查src中的每个key是否在md5文件中有,如有，则看返回的value是否和生成的md5相同，如果不同，则
            #1. 更新相应key的value在md5文件中
            #2. key文件路径加入tar包，作备份
            elif md5file_dict.get(key)!=md5dict[key]:
                md5file_dict[key]=md5dict[key]
                tar.add(key)
    tar.close()
    #把md5字典写入文件
    with open(md5file,'wb') as fobj:
        pickle.dump(md5file_dict,fobj)

def check_md5(fname):   #文件名路径 ==》md5值
    m=hashlib.md5()
    with open(fname,'rb') as fobj:
        while 1:
            data=fobj.read(4096)
            if not data:
                break
            m.update(data)
    return m.hexdigest()

if __name__ == '__main__':
    src = '/tmp/demo/security'   #需要备份的目录
    dst = '/tmp/demo/backup'     #备份的目标目录
    md5file = '/tmp/demo/backup/md5.data'    #md5记录文件
    weekd = time.localtime()
    #校验是不是星期一？
    if weekd.tm_wday == 0:
        full_backup(src,dst,md5file)
    else:
        incr_backup(src,dst,md5file)


import copy
import mmcv
import re
import torch
import torch.nn as nn
import warnings
from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
                      kaiming_init)
from mmcv.cnn.bricks.registry import NORM_LAYERS
from mmcv.runner import load_checkpoint
from numpy.random import rand
from operator import pos
from torch.nn import functional as F

from mmcls.models.builder import build_backbone, build_neck
from mmcls.models.classifiers.base import BaseClassifier

from ..builder import (CLASSIFIERS, build_distill_losses,
                         build_classifier, build_head)

ADAPTATION = "adaptation_layer_{}"
NORM_LAYER = "adaptation_norm_layer_{}"

@CLASSIFIERS.register_module()
class KnowledgeDistillationImageClassifier(BaseClassifier):

    def __init__(self,
                 backbone,
                 teacher_config,
                 distill_losses,
                 adaptation=None,
                 neck=None,
                 head=None,
                 teacher_ckpt=None,
                 eval_teacher=True,
                 adaptive=False,
                 pretrained=None,
                 init_cfg=None,
                 add_layer_loss=True,
                 alpha_distill=1.0):
        super(KnowledgeDistillationImageClassifier, self).__init__(init_cfg)
        """
            backbone (dict): student backbone configuration.
            teacher_config (str): path to teacher configuration.add()
            distillation_losses (list): list of distillation losses
            adaptation (dict): configuration for adaptation layers
            neck (dict): student neck configuration. Default:None
            head (dict): student prediciton head configuration. Default:None
            teacher_ckpt (str): path to teacher checkpoint file
            eval_teacher (bool): flag to change teacher mode. Default:True
            adaptive (bool): flag to specify whether to use adaptive distillation. Default:False
            pretrained (str): path to pretrained checkpoint for student model.add(). Default:None
            init_cfg (dict): student model initialization configuration. Default:None
            add_layer_loss (bool): flag to switch between adaptive or adaptive-layerwise methods.add()
            alpha_distill (float): relative importance between distillation loss and empirical loss.
        """

        if pretrained is not None:
            warnings.warn('DeprecationWarning: pretrained is a deprecated \
                key, please consider using init_cfg')
            self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)

        self.backbone = build_backbone(backbone)  # build student backbone
        self.eval_teacher = eval_teacher
        self.adaptive = adaptive
        self.distill_losses = {}
        self.distill_paths = []
        self.add_layer_loss = add_layer_loss
        self.adaptation = adaptation
        self.alpha_distill = alpha_distill

        # Build adaptation layers
        if adaptation:
            for i, (in_c, out_c) in enumerate(zip(adaptation['in_channels'], adaptation['out_channels'])):
                conv = build_conv_layer(backbone.get('conv_cfg', None), in_c, out_c,
                                        kernel_size=1,
                                        stride=1, bias=False)
                _, norm = build_norm_layer(backbone.get('norm_cfg', 'BN'), out_c, postfix=i)
                kaiming_init(conv)
                constant_init(norm, 1)
                self.add_module(ADAPTATION.format(i), conv)
                self.add_module(NORM_LAYER.format(i), norm)

        # Build teacher model and load from checkpoint
        if isinstance(teacher_config, str):
            teacher_config = mmcv.Config.fromfile(teacher_config)
        self.teacher_model = build_classifier(teacher_config['model'])
        if teacher_ckpt is not None:
            load_checkpoint(self.teacher_model, teacher_ckpt)

        # Build distillation losses
        for distill_loss_cfg in distill_losses:
            distill_loss = build_distill_losses(distill_loss_cfg)
            self.distill_losses[distill_loss.loss_name] = distill_loss
            if not add_layer_loss and distill_loss.mode == 'feature':
                for ii in self.backbone.out_indices:
                    self.distill_paths.append(distill_loss.loss_name + ":" + str(ii))
            else:
                self.distill_paths.append(distill_loss.loss_name)

        # Build loss scale for adaptive disitllation
        self.loss_scaler = AdaptiveLossScaler(
            list(self.distill_paths)) if self.adaptive else None

        if neck is not None:
            self.neck = build_neck(neck)

        if head is not None:
            self.head = build_head(head)

    def cuda(self, device=None):
        """Since teacher_model is registered as a plain object, it is necessary
        to put the teacher model to devices when calling cuda function."""
        self.teacher_model.cuda(device=device)
        for dl_name in self.distill_losses:
            self.distill_losses[dl_name].cuda(device=device)
        if self.loss_scaler:
            self.loss_scaler.cuda(device=device)
        return super().cuda(device=device)

    def extract_feat(self, img, with_neck=True):
        """Directly extract features from the backbone + neck."""
        x = self.backbone(img)
        if self.with_neck and with_neck:
            x = self.neck(x)
        return x

    def forward_train(self, img, gt_label, **kwargs):
        """Forward computation during training.

        Args:
            img (Tensor): of shape (N, C, H, W) encoding input images.
                Typically these should be mean centered and std scaled.
            gt_label (Tensor): It should be of shape (N, 1) encoding the
                ground-truth label of input images for single label task. It
                shoulf be of shape (N, C) encoding the ground-truth label
                of input images for multi-labels task.
        Returns:
            dict[str, Tensor]: a dictionary of loss components
        """
        losses = dict()

        # ----Extract student outputs------
        # x is tuple of student backbone output layers
        # gap_x is global average pooled output from last layer of student backbone
        # out is the output logit from student
        x = self.extract_feat(img, with_neck=False)
        gap_x = self.neck(x[-1])
        out = self.head.forward_train(gap_x, gt_label=None, return_loss=False)
        loss = self.head.loss(out, gt_label)
        losses['loss_cls'] = loss['loss']

        # Transform student features to teacher using adaptation layers
        if self.adaptation:
            feats = []
            for i, feat in enumerate(x):
                feat = getattr(self, ADAPTATION.format(i))(x[i])
                feat = getattr(self, NORM_LAYER.format(i))(feat)
                feats.append(feat)

        # ----Extract teacher outputs------
        # teacher_x is tuple of teacher backbone output layers
        # teacher_gap_x is global average pooled output from last layer of teacher backbone
        # out_teacher is the output logit from teacher
        with torch.no_grad():
            teacher_x = self.teacher_model.extract_feat(img, with_neck=False)
            teacher_gap_x = self.teacher_model.neck(teacher_x[-1])
            out_teacher = self.teacher_model.head.forward_train(
                teacher_gap_x, gt_label=None, return_loss=False)

        # Compute different distillation losses using features or logits
        for dl_name in self.distill_losses:
            distill_loss = self.distill_losses[dl_name]
            if distill_loss.mode == 'feature':
                s_feats = x if 'attention_transfer' in distill_loss.loss_name else feats
                if isinstance(s_feats, tuple) or isinstance(s_feats, list):
                    if self.add_layer_loss:
                        loss = sum([distill_loss(s_x, t_x)
                                    for s_x, t_x in zip(s_feats, teacher_x)])
                        losses[dl_name] = loss*distill_loss.loss_weight
                    else:
                        for ii, (s_x, t_x) in enumerate(zip(s_feats, teacher_x)):
                            dl_name = distill_loss.loss_name + ":" + str(ii)
                            losses[dl_name] = distill_loss(s_x, t_x)*distill_loss.loss_weight
                else:
                    loss = distill_loss(x, teacher_x)
            elif distill_loss.mode == 'logits':
                loss = distill_loss(out, out_teacher, gt_label)
                losses[dl_name] = loss*distill_loss.loss_weight
            elif distill_loss.mode == 'softmax_regression':
                adapted_student_gap_x = self.neck(feats[-1])
                out_cross_student = self.teacher_model.head.forward_train(
                    adapted_student_gap_x, gt_label=None, return_loss=False)
                loss = distill_loss(out_teacher, out_cross_student)
                losses[dl_name] = loss*distill_loss.loss_weight

        # scale distillation losses using adaptive distillation loss scaler
        if self.loss_scaler:
            losses.update(self.loss_scaler(losses))

        # change the relative importance of distillation loss using alpha distill
        for key, loss in losses.items():
            if 'loss_kd' in key or 'loss_alphas' in key:
                losses[key] = loss*self.alpha_distill

        return losses

    def simple_test(self, img, img_metas):
        """Test without augmentation."""
        x = self.extract_feat(img, with_neck=False)
        x = self.neck(x[-1])
        out = self.head.simple_test(x)
        teacher_x = self.teacher_model.extract_feat(img, with_neck=False)
        teacher_x = self.teacher_model.neck(teacher_x[-1])
        teacher_out = self.teacher_model.head.simple_test(teacher_x)
        return torch.tensor([out, teacher_out])

    def train(self, mode=True):
        """Set the same train mode for teacher and student model."""
        if self.eval_teacher:
            self.teacher_model.train(False)
        else:
            self.teacher_model.train(mode)
        super().train(mode)

    def __setattr__(self, name, value):
        """Set attribute, i.e. self.name = value
        This reloading prevent the teacher model from being registered as a
        nn.Module. The teacher module is registered as a plain object, so that
        the teacher parameters will not show up when calling
        ``self.parameters``, ``self.modules``, ``self.children`` methods.
        """
        if name == 'teacher_model':
            object.__setattr__(self, name, value)
        else:
            super().__setattr__(name, value)

class AdaptiveLossScaler(nn.Module):
    def __init__(self, positions):
        super().__init__()
        self.positions = positions
        self.alphas = nn.Parameter(torch.zeros(len(positions)))

    def forward(self, losses):
        loss_cls = losses.pop('loss_cls')
        scaled_losses = self.get_scaled_losses(losses, torch.exp(-self.alphas))
        scaled_losses.update(dict(loss_alphas=self.alphas.sum()))
        scaled_losses.update(dict(loss_cls=loss_cls))
        return scaled_losses

    def get_scaled_losses(self, losses, alphas):
        if len(list(losses.keys())) != len(self.positions):
            raise ValueError('Check distillation positions. Losses: {}, Positions: {}'.format(
                list(losses.keys()), self.positions))
        scaled_losses = {}
        for index, position in enumerate(self.positions):
            scaled_losses.update(self.scale_losses(losses.pop(position), alphas[index], position))
            scaled_losses.update({'alpha_{}'.format(position.strip("loss_")): alphas[index]})
        return scaled_losses

    def scale_losses(self, losses, alpha, position=None):
        # Scale losses with alpha.
        if isinstance(losses, dict):
            for task, loss in losses.items():
                if isinstance(loss, list):
                    losses[task] = [l*alpha for l in loss]
                else:
                    losses[task] = loss*alpha
        elif isinstance(losses, list):
            losses = {'{}'.format(position): [l*alpha for l in losses]}
        elif isinstance(losses, torch.Tensor):
            losses = {'{}'.format(position): losses*alpha}

        return losses


import sys
import os
import re
import numpy as np
import pandas as pd
from stock.utils.symbol_util import get_stock_symbols, get_archived_trading_dates, exsymbol_to_symbol
from stock.marketdata.storefactory import get_store
from stock.lib.finance import get_lrb_data
from sklearn import linear_model
import matplotlib.pyplot as plt
from config import store_type
from stock.lib.finance import load_stock_basics

def get_slope(array):
    x = range(len(array))
    reg = linear_model.LinearRegression()
    X = np.array(x).reshape(-1,1)
    reg.fit(X=X, y=array)
    return reg.coef_[0]

def get_quarter_profit(df):
    for i in range(len(df)):
        date = df.index[i]
        if i == 0:
            df.loc[date, "profit"] = np.nan

        dt = date.to_pydatetime()
        if dt.month > 3:
            df.loc[date, "profit"] = df.iloc[i].yylr - df.iloc[i-1].yylr
        else:
            df.loc[date, "profit"] = df.iloc[i].yylr

    return df

def plot_profit(exsymbol):
    df_lrb = get_lrb_data(exsymbol)
    get_quarter_profit(df_lrb)
    plt.plot(df_lrb.index, df_lrb["profit"])
    plt.show()

def generate_middle():
    store = get_store(store_type)
    exsymbols = store.get_stock_exsymbols()

    date = "2017-04-28"
    df_res = pd.DataFrame(columns=["exsymbol", "incr_ratio", "pe", "mcap", "past_profit", "future_profit"])
    for exsymbol in exsymbols:
        try:
            df_lrb = get_lrb_data(exsymbol).loc[:date]
            get_quarter_profit(df_lrb)
            if len(df_lrb) < 16:
                continue
            profits_q1 = df_lrb[df_lrb.quarter=="Q1"].profit.iloc[-3:]
            profits_q2 = df_lrb[df_lrb.quarter=="Q2"].profit.iloc[-3:]
            profits_q3 = df_lrb[df_lrb.quarter=="Q3"].profit.iloc[-3:]
            profits_q4 = df_lrb[df_lrb.quarter=="Q4"].profit.iloc[-3:]
            year_profits = df_lrb[df_lrb.quarter=="Q4"].yylr
            if len(profits_q1) < 3 or \
                len(profits_q2) < 3 or \
                len(profits_q3) < 3 or \
                len(profits_q4) < 3:
                continue
            if df_lrb.iloc[-16:].profit.isnull().any():
                continue
            if np.sum(df_lrb.iloc[-16:].profit <= 0) > 0:
                continue
            low1 = df_lrb.loc["2014-01-01":"2014-12-31"].profit.min()
            low2 = df_lrb.loc["2015-01-01":"2015-12-31"].profit.min()
            low3 = df_lrb.loc["2016-01-01":"2016-12-31"].profit.min()
            if low3 < low2 or low2 < low1:
                continue
            #if profits_q1[-1] < profits_q1[-2] or profits_q1[-2] < profits_q1[-3] or profits_q1[-3] < profits_q1[-4]:
            #    continue
            #if profits_q2[-1] < profits_q2[-2] or profits_q2[-2] < profits_q2[-3] or profits_q2[-3] < profits_q2[-4]:
            #    continue
            #if profits_q3[-1] < profits_q3[-2] or profits_q3[-2] < profits_q3[-3] or profits_q3[-3] < profits_q3[-4]:
            #    continue
            #if profits_q4[-1] < profits_q4[-2] or profits_q4[-2] < profits_q4[-3] or profits_q4[-3] < profits_q4[-4]:
            #    continue

            df = store.get(exsymbol)
            if date not in df.index:
                continue
            if year_profits[-1] > year_profits[-2] and year_profits[-2] > year_profits[-3]:
                price = df.loc[date].close
                df_basics = load_stock_basics()
                total_shares = df_basics.loc[exsymbol, "totals"]
                mcap = total_shares * price
                slope = get_slope(np.log(df_lrb.profit[-16:]))
                pe = mcap / year_profits[-1] * 10000
                future_profit = df.iloc[-1].close / price - 1
                past_profit = price / df.loc["2017-01-01":].iloc[0].close - 1
                df_res.loc[len(df_res)] = [exsymbol, slope, pe, mcap, past_profit, future_profit]
        except Exception as e:
            print(str(e))

    df_res.to_csv("/tmp/pe.csv")

def parse_middle(filepath="/tmp/pe.csv"):
    df= pd.read_csv(filepath, encoding="utf-8")
    df["score"] = df.incr_ratio/ df.pe
    print(df[df.mcap > 300].sort_values(["incr_ratio"]))

if __name__ == "__main__":
    #generate_middle()
    #parse_middle()
    PLOT = True
    if PLOT:
        df_lrb = get_lrb_data(sys.argv[1])
        get_quarter_profit(df_lrb)
        print(df_lrb["yylr"])
        plt.plot(df_lrb.index[-16:], df_lrb.profit[-16:])
        #plt.axhline(y=0.0, c='r')
        plt.show()


from __future__ import annotations

import json
from pathlib import Path
from typing import TYPE_CHECKING

import pytest

from pyk.kore.parser import KoreParser
from pyk.kore.syntax import And, App, Kore, Or, Pattern, SortVar, kore_term

if TYPE_CHECKING:
    from collections.abc import Mapping
    from typing import Any, Final

TEST_DATA_DIR: Final = Path(__file__).parent / 'test-data'

DEFINITION_PASS_KORE_FILES: Final = tuple((TEST_DATA_DIR / 'definitions/pass').iterdir())
DEFINITION_FAIL_KORE_FILES: Final = tuple(
    test_file for test_file in (TEST_DATA_DIR / 'definitions/fail').iterdir() if test_file.suffix == '.kore'
)

PATTERN_FILES: Final = tuple((TEST_DATA_DIR / 'patterns').iterdir())

JSON_FILES: Final = tuple((TEST_DATA_DIR / 'json').iterdir())
JSON_TEST_DATA: Final = tuple(
    (json_file, i, dct) for json_file in JSON_FILES for i, dct in enumerate(json.loads(json_file.read_text()))
)

@pytest.mark.parametrize(
    'kore_file', DEFINITION_PASS_KORE_FILES, ids=lambda path: path.name
)  # mypy complains on Path.name.fget
def test_parse_definition_pass(kore_file: Path) -> None:
    # Given
    text = kore_file.read_text()

    # When
    parser1 = KoreParser(text)
    definition1 = parser1.definition()
    parser2 = KoreParser(definition1.text)
    definition2 = parser2.definition()

    # Then
    assert parser1.eof
    assert parser2.eof
    assert definition1 == definition2

@pytest.mark.parametrize('kore_file', DEFINITION_FAIL_KORE_FILES, ids=lambda path: path.name)
def test_parse_definition_fail(kore_file: Path) -> None:
    # Given
    text = kore_file.read_text()
    parser = KoreParser(text)

    # Then
    with pytest.raises(ValueError):
        # When
        parser.definition()

@pytest.mark.parametrize('kore_file', PATTERN_FILES, ids=lambda path: path.name)
def test_parse_pattern(kore_file: Path) -> None:
    # Given
    text = kore_file.read_text()

    # When
    parser1 = KoreParser(text)
    pattern1 = parser1.pattern()
    parser2 = KoreParser(pattern1.text)
    pattern2 = parser2.pattern()
    pattern3 = Pattern.from_dict(pattern1.dict)

    # Then
    assert parser1.eof
    assert parser2.eof
    assert pattern1 == pattern2
    assert pattern1 == pattern3

@pytest.mark.parametrize(
    'json_file,i,dct', JSON_TEST_DATA, ids=[f'{json_file.name}-{i}' for json_file, i, _ in JSON_TEST_DATA]
)
def test_parse_json(json_file: Path, i: int, dct: Mapping[str, Any]) -> None:
    # When
    kore1: Kore = kore_term(dct)  # TODO type hint should be unnecessary
    parser = KoreParser(kore1.text)
    kore2 = parser.pattern()
    kore3 = Kore.from_json(kore1.json)

    # Then
    assert parser.eof
    assert kore1 == kore2
    assert kore1 == kore3

x, y, z = (App(name) for name in ['x', 'y', 'z'])
MULTI_OR_TEST_DATA: Final[tuple[tuple[str, str, list[Pattern]], ...]] = (
    ('nullary', r'\left-assoc{}(\or{S}())', []),
    ('unary', r'\left-assoc{}(\or{S}(x{}()))', [x]),
    ('binary', r'\left-assoc{}(\or{S}(x{}(), y{}()))', [x, y]),
    ('multiary', r'\left-assoc{}(\or{S}(x{}(), y{}(), z{}()))', [x, y, z]),
)

@pytest.mark.parametrize(
    'test_id,text,expected',
    MULTI_OR_TEST_DATA,
    ids=[test_id for test_id, *_ in MULTI_OR_TEST_DATA],
)
def test_multi_or(test_id: str, text: str, expected: list[Pattern]) -> None:
    # Given
    parser = KoreParser(text)

    # When
    actual = parser.multi_or()

    # Then
    assert parser.eof
    assert actual == expected

S = SortVar('S')
a, b, c, d = (App(name) for name in ['a', 'b', 'c', 'd'])
MULTIARY_TEST_DATA: Final = (
    ('nullary-and', r'\and{S}()', And(S, ())),
    ('unary-and', r'\and{S}(a{}())', And(S, (a,))),
    ('binary-and', r'\and{S}(a{}(), b{}())', And(S, (a, b))),
    ('ternary-and', r'\and{S}(a{}(), b{}(), c{}())', And(S, (a, b, c))),
    ('quaternary-and', r'\and{S}(a{}(), b{}(), c{}(), d{}())', And(S, (a, b, c, d))),
    ('nullary-or', r'\or{S}()', Or(S, ())),
    ('unary-or', r'\or{S}(a{}())', Or(S, (a,))),
    ('binary-or', r'\or{S}(a{}(), b{}())', Or(S, (a, b))),
    ('ternary-or', r'\or{S}(a{}(), b{}(), c{}())', Or(S, (a, b, c))),
    ('quaternary-or', r'\or{S}(a{}(), b{}(), c{}(), d{}())', Or(S, (a, b, c, d))),
)

@pytest.mark.parametrize(
    'test_id,text,expected',
    MULTIARY_TEST_DATA,
    ids=[test_id for test_id, *_ in MULTIARY_TEST_DATA],
)
def test_multiary(test_id: str, text: str, expected: list[Pattern]) -> None:
    # Given
    parser = KoreParser(text)

    # When
    actual = parser.pattern()

    # Then
    assert parser.eof
    assert actual == expected


import random
import string
import cv2
import os
import argparse

BASE_DIR = os.getcwd()

def cut_img(image, column_num, row_num, prefix_name):
    """
    image: 이미지 경로
    column_num: 가로로 자를 갯수
    row_num: 세로로 자를 갯수
    prefix_name: 고정된 이름
    """
    if os.path.isdir(os.path.join(BASE_DIR, 'cuted_img')):
        for file in os.scandir(os.path.join(BASE_DIR, 'cuted_img')):
            os.remove(file.path)
    else:
        os.mkdir(os.path.join(BASE_DIR, 'cuted_img'))

    h, w, _ = image.shape
    if h % row_num != 0 or w % column_num != 0:
        image = image[:h-(h % row_num), :w-(w % column_num)]

    for i in range(row_num):
        for j in range(column_num):
            cut_img = image[i*int(h//row_num):(i+1)*int(h//row_num), j*int(w//column_num):(j+1)*int(w//column_num)]

            # random 수정
            rand = random.uniform(0,1)
            if rand > 0.5:
                cut_img = cv2.flip(cut_img,1) # 좌우 반전

            rand = random.uniform(0,1)
            if rand > 0.5:
                cut_img = cv2.flip(cut_img,0) # 상하 반전

            rand = random.uniform(0,1)
            if rand > 0.5:
                cut_img = cv2.rotate(cut_img, cv2.ROTATE_90_COUNTERCLOCKWISE)

            random_name_len = 10
            random_name = ""
            for _ in range(random_name_len):
                random_name += str(random.choice(string.ascii_lowercase))

            cv2.imwrite(f'cuted_img/{prefix_name}-{random_name}.png', cut_img)

if __name__=="__main__":
    parser = argparse.ArgumentParser(description="Divide image into patches")

    parser.add_argument("image_file_name", type=str)
    parser.add_argument("column_num", type=int)
    parser.add_argument("row_num", type=int)
    parser.add_argument("prefix_output_filename", type=str)

    configs = parser.parse_args()

    img = cv2.imread(configs.image_file_name, cv2.IMREAD_COLOR)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    cut_img(img, configs.column_num, configs.row_num, configs.prefix_output_filename)


from test_tools.example_stubber import ExampleStubber

class ConfigStubber(ExampleStubber):
    """
    A class that implements stub functions used by AWS Config unit tests.

    The stubbed functions expect certain parameters to be passed to them as
    part of the tests, and raise errors if the parameters are not as expected.
    """

    def __init__(self, client, use_stubs=True):
        """
        Initializes the object with a specific client and configures it for
        stubbing or AWS passthrough.

        :param client: A Boto3 AWS Config client.
        :param use_stubs: When True, use stubs to intercept requests. Otherwise,
                          pass requests through to AWS.
        """
        super().__init__(client, use_stubs)

    def stub_put_config_rule(self, rule, error_code=None):
        expected_params = {"ConfigRule": rule}
        response = {}
        self._stub_bifurcator(
            "put_config_rule", expected_params, response, error_code=error_code
        )

    def stub_describe_config_rules(self, rule_names, source_ids=None, error_code=None):
        expected_params = {"ConfigRuleNames": rule_names}
        response = {
            "ConfigRules": [
                {
                    "ConfigRuleName": name,
                    "Source": {"Owner": "Test", "SourceIdentifier": "TestID"},
                }
                for name in rule_names
            ]
        }
        if source_ids is not None:
            for rule, source_id in zip(response["ConfigRules"], source_ids):
                rule["Source"]["SourceIdentifier"] = source_id
        self._stub_bifurcator(
            "describe_config_rules", expected_params, response, error_code=error_code
        )

    def stub_delete_config_rule(self, rule_name, error_code=None):
        expected_params = {"ConfigRuleName": rule_name}
        response = {}
        self._stub_bifurcator(
            "delete_config_rule", expected_params, response, error_code=error_code
        )

    def stub_describe_conformance_packs(self, packs, error_code=None):
        expected_params = {}
        response = {
            "ConformancePackDetails": [
                {
                    "ConformancePackName": pack,
                    "ConformancePackArn": f"arn:{pack}",
                    "ConformancePackId": f"{pack}-id",
                }
                for pack in packs
            ]
        }
        self._stub_bifurcator(
            "describe_conformance_packs",
            expected_params,
            response,
            error_code=error_code,
        )

    def stub_describe_conformance_pack_compliance(
        self, pack_name, rule_names, error_code=None
    ):
        expected_params = {"ConformancePackName": pack_name}
        response = {
            "ConformancePackName": pack_name,
            "ConformancePackRuleComplianceList": [
                {"ConfigRuleName": rule_name} for rule_name in rule_names
            ],
        }
        self._stub_bifurcator(
            "describe_conformance_pack_compliance",
            expected_params,
            response,
            error_code=error_code,
        )


"""
Reverse a 3-digit integer.
Example 1:

Input: number = 123
Output: 321
Example 2:

Input: number = 900
Output: 9
"""
class Solution:
    """
    @param number: A 3-digit number.
    @return: Reversed number.
    """
    def reverseInteger(self, number):
        numberStr = list(str(number))
        tmp = numberStr[2]
        numberStr[2] = numberStr[0]
        numberStr[0] = tmp
        return int('_'.join(numberStr))

if __name__ == '__main__':

    A = Solution()
    print(A.reverseInteger(123))


import matplotlib.animation as animation

from pyparticles.utils.pypart_global import *

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib
import numpy as np

import pyparticles.pset.particles_set as ps
import pyparticles.pset.logger as log

import pyparticles.animation.animated_scatter as anim

import pyparticles.animation as pan

import pyparticles.animation.test_animation as test

import pyparticles.pset.rand_cluster as clu
import pyparticles.forces.gravity as gr

import pyparticles.ode.euler_solver as els
import pyparticles.ode.leapfrog_solver as lps
import pyparticles.ode.runge_kutta_solver as rks
import pyparticles.ode.stormer_verlet_solver as svs

import matplotlib.animation as animation

import pyparticles.pset.periodic_boundary as pb
import pyparticles.pset.rebound_boundary as rb
import pyparticles.forces.const_force as cf
import pyparticles.forces.vector_field_force as vf
import pyparticles.forces.linear_spring as ls
import pyparticles.pset.file_cluster as fc

import pyparticles.demo.solar_system as sol
import pyparticles.demo.springs as spr
import pyparticles.demo.gas_lennard_jones as lj
import pyparticles.demo.bubble as bu
import pyparticles.demo.springs_constr as spc
import pyparticles.demo.test as tst
import pyparticles.demo.electrostatic_demo as eld
import pyparticles.demo.electromagnetic_demo as emd
import pyparticles.demo.fountain as fou
import pyparticles.demo.gravity_clusters as grav

import pyparticles.utils.parse_args as arg

import pyparticles.utils.problem_config as pc
import pyparticles.pset.octree as ot

from pyparticles.geometry.dist import distance

import pyparticles.pset.constrained_x as ct
import pyparticles.pset.constrained_force_interactions as cfi

import pyparticles.geometry.transformations as tr

import time

import sys

import pyparticles.animation.animated_ogl as aogl

def main():

    #my_test()

    np.seterr(all='ignore')

    options = arg.parse_args()

    cfg = pc.ParticlesConfig()

    if options.version :
        print( py_particle_version() )
        return

    if options.about :
        about()
        return

    if options.test :
        print("")
        print("Start a test simulation:")
        print(" It compares the simulated solution with the analytical solution in a specific problem")
        tst.test( options.test )
        return

    if options.config_model :
        file_name = "example_pyparticles_config.cfg"
        cfg.write_example_config_file("example_pyparticles_config.cfg")
        print( "A file named: %s has been written in the current directory" % file_name )
        print( "" )
        return

    if options.demo == "fountain" :
        print("")
        print("Start the simulation example:")
        print(" 250K Particles fountain")
        fou.fountain()
        return

    if options.demo == "springs" :
        print("")
        print("Start the simulation example:")
        print(" 3 body springs")
        spr.springs()
        return

    if options.demo == "cat_spri" :
        print("")
        print("Start the simulation example:")
        print(" catenary springs (constraints demo)")
        spc.spring_constr()
        return

    if options.demo == "gas_lj" :
        print("")
        print("Start the simulation example:")
        print(" Pseudo gas with Lennard Jones potential")
        lj.gas_lj()
        return

    if options.demo == "bubble" :
        print("")
        print("Start the simulation example:")
        print(" Pseudo bubble demo")
        bu.bubble()
        return

    if options.demo == "el_static" :
        print("")
        print("Start the simulation example:")
        print(" electrostatic")
        eld.electro()
        return

    if options.demo == "elmag_field" :
        print("")
        print("Start the simulation example:")
        print(" electromagnetic fields")
        emd.electromag_field()
        return

    if options.demo == "galaxy" :
        print("")
        print("Start the simulation example:")
        print(" Gravitational clusters")
        grav.gravity_cluster()
        return

    if options.path_name == None or options.demo == "solar_system":

        print("")
        print("Start the simulation example:")
        print(" Solar system")
        print(" -- Try to watch the Moon ... around the Earth ")
        print("")
        print(" Use your mouse for rotating, zooming and tranlating the scene.")
        print("")
        print("For more details type:")
        print(" pyparticles --help")
        print("")

        sol.solar_system()
        return

    if options.path_name != None :

        cfg.read_config( options.path_name )
        ( an , pset , force , ode_solver ) = cfg.build_problem()

        an.build_animation()

        print("")
        print("Start the simulation described in: %s ... " % options.path_name )

        an.start()
        return

    print("Ops ... ")
    return

####################################################################
####################################################################
####################################################################
####################################################################
####################################################################
####################################################################
#### Old test code .....and tests ....
####################################################################

class MyField( vf.VectorFieldForce ):
    def __init__(self,size,dim):
        super(MyField,self).__init__(size)
        self.v = np.zeros((dim,size))

    def vect_fun( self , X ):
        self.v[:] = ( X**2 ).T
        return ( self.v * -X.T/np.sqrt( np.sum(self.v,0) ) ).T

def my_test() :

    pset = ps.ParticlesSet( 10 )

    lo = log.Logger( pset , 10 )

    for i in range( 105 ) :
        pset.X[:] =  float(i)
        lo.log()

        print( lo.get_particles_log( 3 ) )

    exit()

    t = tr.Transformations()

    t.set_points_tuple_size(1)

    t.rotate( np.radians(90) , 1 , 0 , 0 )
    #t.rotX( np.radians(90) )

    t.append_point( list( [1,0,0] ) )
    t.append_point( np.array( [1,1,0] ) )
    t.append_point( np.array( [1,1,1] ) )
    t.append_point( np.array( [0,1,1] ) )

    t.push_matrix()
    t.identity()
    t.translation( 10 , 2 , 2 )
    #t.rotate( np.radians(20) , 1 , 1 , 1 )

    t.append_point( [1,1,1] )
    t.append_point( np.matrix( [0,1,1] ).T )

    t.pop_matrix()

    t.append_point( np.array( [1,0,0] ) )
    t.append_point( [1,1,0] )
    t.append_point( np.array( [1,1,1] ) )
    t.append_point( [0,1,1] )

    #print( t.transform(pt[0] , pt[1] , pt[2] ) )

    print("")

    for (p) in t :
        print( p )

    exit()

    n = 10
    dt = 0.005
    #dt = 0.0023453

    steps = 1000000

    G = 0.001
    #G = 6.67384e-11

    FLOOR = -10
    CEILING = 10

    #ff = fc.FileCluster()
    #ff.open( options.path_name )

    pset = ps.ParticlesSet( n , label=True )

    pset.label[8] = "tttt"
    pset.label[9] = "tzzzttt"

    pset.add_property_by_name("ciao",dim=1 , model="list")

    pset.get_by_name("ciao")[3] = 100
    pset.get_by_name("X")[3,:] = 101

    sz = 15
    pset.resize( sz )

    tree = ot.OcTree()

    pset.get_by_name("X")[:] = np.random.rand(sz,3)
    pset.get_by_name("M")[:] = 1.0

    pset.update_centre_of_mass()

    print(" C O M pset")
    print( pset.centre_of_mass() )
    print("")

    csrt = ct.ConstrainedX( pset )

    cfit = cfi.ConstrainedForceInteractions( pset )

    cfit.add_connections( [[12,3],[4,4],[6,8],[1,1]] )
    cfit.remove_connections( [[12,3]] )

    print( cfit.dense )
    print( cfit.sparse )
    print( cfit.items )

    cc = np.array( [[1,2,3],[3,3,3]] )
    cc = np.array( [[1,2,3],[3,3,5]] )

    csrt.add_x_constraint( [2,5] , cc )
    csrt.add_x_constraint( [7,10] , cc )

    print( csrt.get_cx_indicies() )
    print( csrt.cX )

    csrt.remove_x_constraint( [2,10] )

    print( csrt.get_cx_indicies() )
    print( csrt.cX )

    exit()

    tree.set_global_boundary()

    a = time.time()
    tree.build_tree( pset )
    b = time.time()

    print( "Tot time: % f" %(b-a) )

    C = np.array([0.5,0.4,0.3])
    R = 0.05

    a = time.time()
    for ix in range( pset.size ):
        nl = tree.search_neighbour( pset.X[ix,:] , R )
    b = time.time()

    print( "Tot time octree : % f" %(b-a) )

    nl = np.sort( nl )

    print("")
    print("nl:")
    print( nl )

    print("")
    print("dd:")

    a = time.time()
    for ix in range( pset.size ):
        dd = np.sqrt(  np.sum( (pset.X[ix,:] - pset.X)**2 , 1 ) )
        din, = np.where( dd <= R )
    b = time.time()

    print( "Tot time numpy : % f" %(b-a) )

    print( din )

    print(" C O M")
    print( tree.centre_of_mass )
    print("")

    print ( np.all( nl == din ) )

    #tree.print_tree()

    #print( pset.get_by_name( "ciao" ) )
    #print( pset.get_by_name( "X" ) )
    #print("")
    #print( pset.X )
    #print( pset.label )

    exit()
    return

    #ff.insert3( pset )
    #ff.close()

    #pset.unit = 149597870700.0
    #pset.mass_unit = 5.9736e24

    cs = clu.RandCluster()

    cs.insert3( pset.X , M=pset.M , V=pset.V ,
                n = n/2 , centre=(-1.5,1,0.5) , mass_rng=(0.5,5.0) ,
                vel_rng=(0,0) , vel_mdl="bomb" )

    cs.insert3( pset.X , M=pset.M , V=pset.V ,
                start_indx=int(n/2) , n = int(n/2) , centre=(1.5,-0.5,0.5) ,
                vel_rng=(0.2,0.4) , vel_mdl="const" , vel_dir=[-1.0,0.0,0.0] )
    #

    grav = gr.Gravity( pset.size , Consts=G )
    #grav = cf.ConstForce(n , u_force=[0,0,-1.0] )
    #grav = MyField( pset.size , dim=3 )
    #grav = ls.LinearSpring( pset.size , Consts=10e8 )

    grav.set_masses( pset.M )

    bound = None
    #bound = pb.PeriodicBoundary( (-50.0 , 50.0) )
    #bound = rb.ReboundBoundary(  (-10.0 , 10.0)  )

    pset.set_boundary( bound )
    grav.update_force( pset )

    solver = els.EulerSolver( grav , pset , dt )
    #solver = lps.LeapfrogSolver( grav , pset , dt )
    #solver = svs.StormerVerletSolver( grav , pset , dt )
    #solver = rks.RungeKuttaSolver( grav , pset , dt )

    a = aogl.AnimatedGl()
    # a = anim.AnimatedScatter()

    a.xlim = ( FLOOR , CEILING )
    a.ylim = ( FLOOR , CEILING )
    a.zlim = ( FLOOR , CEILING )

    a.ode_solver = solver
    a.pset = pset
    a.steps = steps

    a.build_animation()

    a.start()

    return

if __name__ == '__main__':
    main()


# n = 10
# a = [4, 5, 7, 2, 7, 4, 8, 3, 9, 3]

n = int(input())
a = [int(i) for i in input().split(" ")]

a.sort()
m = n % 2

alice = 0
bob = 0

while n > 0:
    if n % 2 == m:
        alice += a[-1]
    else:
        bob += a[-1]
    a.pop()
    n -= 1

print(alice - bob)


from db import DB
from crawl import Crawl
from goods import Goods
from mail import Mail
import time
import sched

class Monitor:
    def __init__(self, email='1656704949@qq.com', rate=60, note=60 * 60):
        self.scheduler = sched.scheduler(time.time, time.sleep)
        self.goods_dict = {}
        self.db = DB()
        self.crawl = Crawl()
        self.mail = Mail()
        self.email = [email]  # 电子邮箱
        self.rate = rate  # 刷新频率
        self.note = note  # 通知频率

        # 加载数据
        result = self.db.query()
        print('----------加载数据----------')
        for id, item in result.items():
            self.goods_dict[id] = Goods(item['id'], item['want'], item['status'])
            print(self.goods_dict[id].__dict__)
        print('----------加载完成----------')

    # 添加商品
    def add(self, id, want, status=True):
        if id not in self.goods_dict.keys():
            self.db.add(id, want, status)
            goods = Goods(id, want, status)
            name, price, date = self.crawl.get(id)
            goods.update(name, price, date)
            self.goods_dict[id] = goods
            print(self.goods_dict[id].__dict__)
            return True
        else:
            return False

    # 删除商品
    def remove(self, id):
        if id in self.goods_dict.keys():
            self.goods_dict.pop(id)
            self.db.delete(id)
            return True
        else:
            return False

    # 更新期望价格
    def update_want(self, id, want):
        if id in self.goods_dict.keys():
            self.goods_dict[id].update_want(want)
            self.goods_dict[id].update_note(0)  # 刷新通知时间
            self.db.update_want(id, want)
            return True
        else:
            return False

    # 更新运行状态
    def update_status(self, id, status):
        if id in self.goods_dict.keys():
            self.goods_dict[id].update_status(status)
            self.goods_dict[id].update_note(0)  # 刷新通知时间
            self.db.update_status(id, status)
            return True
        else:
            return False

    # 获取历史价格
    def history(self, id):
        if id in self.goods_dict.keys():
            return self.crawl.get_history(id)
        else:
            return ''

    # 定时任务
    def task(self):
        ids = list(self.goods_dict.keys())
        for id in ids:
            goods = self.goods_dict[id]
            if goods.status:
                name, price, date = self.crawl.get(id)
                if id not in self.goods_dict.keys(): continue  # 防止商品已经删除
                goods.update(name, price, date)

                ########## 检查是否符合发送条件 ##########
                # 满足通知间隔时间 & 当前价格小于期望价格
                if (date - goods.note >= self.note) and (price <= goods.want):
                    self.mail.send(self.email, name, price, goods.want, goods.url)
                    goods.update_note(date)
        print('----------刷新数据----------')
        for goods in self.goods_dict.values():
            print(goods.__dict__)
        print('----------刷新完成----------')

    # 定时器
    def _run(self):
        self.scheduler.enter(self.rate, 0, self._run, ())  # delay, priority, action, argument=()
        self.task()

    # 定时器
    def run(self):
        self.scheduler.enter(0, 0, self._run, ())  # delay, priority, action, argument=()
        self.scheduler.run()

if __name__ == '__main__':
    ids = ['4311178', '4311182', '100002795959', '100004751037', '8797490']
    wants = [219.00, 339.00, 4900.00, 5600.00, 8998.00]

    monitor = Monitor(rate=10)
    monitor.run()


import boto3
from botocore.exceptions import ClientError
import json
from botocore.vendored import requests

dynamodb = boto3.resource('dynamodb', region_name='us-east-1', endpoint_url="https://dynamodb.us-east-1.amazonaws.com")
subscriptions_table = dynamodb.Table('test')

AWS_REGION = "us-east-1"
SUBJECT = "newsApp - newsletter"
CHARSET = "UTF-8"

def handler(json_input, context):
    #get all subscribers
    subscribers = subscriptions_table.scan(
        AttributesToGet=['email']
    )
    # get news
    news = get_news()
    #send a newsletter to each subscriber
    print(len(subscribers['Items']))
    for subscriber in subscribers['Items']:
        send_newsletter_report_to_address(subscriber['email'], news)

def send_newsletter_report_to_address(email_address, news):
    global AWS_REGION, SUBJECT, CHARSET
    body_html, body_text = compose_report_body(news)
    client = boto3.client('ses', region_name=AWS_REGION)
    try:
        response = client.send_email(
            Destination={
                'ToAddresses': [
                    email_address,
                ],
            },
            Message={
                'Body': {
                    'Html': {
                        'Charset': CHARSET,
                        'Data': body_html,
                    },
                    'Text': {
                        'Charset': CHARSET,
                        'Data': body_text,
                    },
                },
                'Subject': {
                    'Charset': CHARSET,
                    'Data': SUBJECT,
                },
            },
            Source="allexandra.gadioi@gmail.com",
        )
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        print("Email sent! Message ID:"),
        print(response['ResponseMetadata']['RequestId'])

#receives news, returns the html body of the email message to be sent (and the text body, for non-HTML email clients)
def compose_report_body(news):
    text_body = "text"
    html_body = """

newsApp - newsletter

Most recent news:

      """
    for article in news:
        html_body += "
" + article['title'] + "
Publish date: " + \
        article['publishedDate'] + "
go to article
" + article['summary'] + \
            "

" + article['content'] + "
"
    html_body += ""
    return html_body, text_body

def get_news():
    url = 'http://newsapp.syvh7ndmiz.eu-central-1.elasticbeanstalk.com/news'
    r = requests.get(url)
    return json.loads(r.text)


import re
class Solution:
    def myAtoi(self, s: str) -> int:
        s_array = s.split()
        if s_array:
            s_f = s_array[0]
            if re.match(r'^\+-',s_f):
                return 0
        else:
            return 0

        if re.match(r'\+?(\-?\d+)',s_f):
            s_fu = re.match(r'\+?(\-?\d+)',s_f)
            s_f = s_fu.group(1)
            if re.match(r'(\+?\-?)0+',s_f):
                if re.match(r'.?0+$',s_f):
                    return 0
                s_fu = re.match(r'(.?)0+(\d+)',s_f)
                s_f = s_fu.group(2)
                if s_fu.group(2):
                    if s_fu.group(1) == '-':
                        s_f = s_fu.group(1) + s_fu.group(2)
                    else:
                        s_f = s_fu.group(2)

            if int(s_f) < -2**31:
                return -2**31
            elif int(s_f) > 2**31 - 1:
                return 2**31 - 1
            else:
                return(s_f)

        else:
            return 0


from os import name
from django.shortcuts import render
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
from subprocess import run, PIPE
import sys ,os
import detect
from webs.controller import count,data_label
from webs.controller import banana_ripe_or_raw,guava_ripe_or_raw,papaya_ripe_or_raw

# Create your views here.
def index(request):
    return render(request, 'home.html')

def home(request):
    return render(request, 'home.html')

def upimg(request):
    return render(request, 'upload.html')

def profile(request):
    return render(request, 'profile.html')

def upload(request):
    if  len(request.FILES) != 0:
        request.method == 'POST'
        image = request.FILES['image'] or None
        fs = FileSystemStorage()
        filename = fs.save(image.name, image)
        fileurl = fs.open(filename)
        templateurl = fs.url(filename)
        print("file raw url:", filename)
        print("file full url:", fileurl)
        print("template url:", templateurl)
        image = run([sys.executable,'detect.py',str(fileurl)],shell=False,stdout=PIPE)
        file_count = count.countimage()
        classes_label = data_label.all_label()
        processdata = []
        allsend = []
        classes = []
        classes_label = []
        if os.stat("webs/text/data_label.txt").st_size == 0:
                send = 'Not'
                allsend.append(send)
        with open("webs/text/data_label.txt", "r") as f:
            classes = [line.strip() for line in f.readlines()]
            for x in classes:
                if x not in classes_label:
                    classes_label.append(x)
        for i in classes_label:
            if i == 'Banana':
                send = 'Banana'
                allsend.append(send)
                data = banana_ripe_or_raw.banana_find_ripe_raw()
                processdata.append(data)
            elif i == 'Guava':
                send = 'Guava'
                allsend.append(send)
                data = guava_ripe_or_raw.guava_find_ripe_raw()
                processdata.append(data)
            elif i == 'Papaya':
                send = 'Papaya'
                allsend.append(send)
                data = papaya_ripe_or_raw.papaya_find_ripe_raw()
                processdata.append(data)

        fruit = processdata

        return render(request, 'process.html', {'raw_url': templateurl,
                                                'file_count':file_count,
                                                'allsend': allsend,
                                                'fruit':fruit})
    else:
        return render(request, 'process.html')


import os.path
import random
import urllib.request
from duckduckgo_images_api import search

def image_download(request, target_dir, max_trials=10):
    results = search(request)
    count = len(results['results'])
    if count == 0:
        return None
    for i in range(min(max_trials, count)):
        #index = random.randint(0, count - 1)
        try:
            address = results['results'][i]['image']
            filename = address.split('/')[-1]
            target_path = os.path.join(target_dir, filename)
            urllib.request.urlretrieve(address, target_path)
            return target_path
        except Exception as e:
            print(e)
            continue
    return None


# main source file

import os
from .utils import update_poe_env, check_config
import poe

class Poe:
    def __init__(self, bot: str = "capybara"):
        self.poe_token = check_config()
        self.poe_proxy = os.getenv('POE_PROXY')
        self.poe_client = poe.Client(self.poe_token, proxy=self.poe_proxy)
        self.message_queue = []
        self.bot_name = bot;
    def single_chat(self, msg: str, with_chat_break=True):
        for chunk in self.poe_client.send_message(self.bot_name, msg, with_chat_break=with_chat_break):
            print(chunk['text_new'], end="", flush=True)

    def continus_chat(self):
        while True:
            question = ""
            print('🍄> ', end='')
            while True:
                tmp = input("")
                tmp = tmp.strip()
                if tmp == '':
                    break
                question += tmp
            if question == "":
                break
            print("\n😊> ", end='')
            try:
                self.single_chat(question, with_chat_break=False)
            except:
                print("好像网络出了点问题，重新发一下吧~🙌", end='', flush=True)
            print("\n")
        print(f"Hope this journey with {self.bot_name} can help you!")
        return