# python sort 함수는 stable을 보장한다!
# cmp_to_key를 이용한 compare 함수가 동작하지 않는 이유는,,ㅠ => T,F 가 아니라 0, -1, 1 을 반환해야하는건가보다!! 완전 맞는말
# -1 :  현상 유지(앞에것이 앞으로)
from functools import cmp_to_key

def compare(x, y):
    nx = x[0].lower()
    ny = y[0].lower()

    if nx > ny:
        return 1
    elif nx < ny:
        return -1
    else:
        if int(x[1]) > int(y[1]):
            return 1
        elif int(x[1]) < int(y[1]):
            return -1
        else:
            return 0

def solution(files):
    answer = []

    v = []
    for file in files:
        header = ""
        number = ""
        tail = ""

        flag = 0

        for c in file:
            if(c.isdigit()):
                #  아  , , ,,,, digit이기만 하면 1로 바꿔서 문제였다
                if(flag ==0): flag = 1
            elif(flag == 1):
                flag = 2

            if len(number) == 5 : flag = 2

            if(flag == 0): header += c
            elif(flag == 1): number += c
            else: tail += c

        temp = [header, number, tail]
        v.append(temp)

    v = sorted(v, key=cmp_to_key(compare))

    for splits in v:
        s = ""
        for split in splits:
            s += split
        answer.append(s)
    return answer

# new version
# python sort 함수는 stable을 보장한다!
# sort key에 lambda 를 활용하자
def solution(files):
    answer = []

    for file in files:

        head, number, tail = "", "", ""
        flag = False

        for i in range(len(file)):
            # number에 추가
            if file[i].isdigit() and len(number) < 5:
                number += file[i]
                flag = True
            # 아직 number가 나오지 않았다면 header
            elif not flag:
                head += file[i]
            # 넘버가 나오고, 숫자도 아니면 나머지는 tail
            else:
                tail += file[i:]
                break

        # tuple로 저장
        answer.append((head, number, tail))

    # sort , header->number 순으로 와! 이러니까 cmp_to_key를 쓸 필요가 없구나
    answer.sort(key = lambda x : (x[0].upper(), int(x[1])))

    return [''.join(t) for t in answer]


from collections import deque
import sys

input = sys.stdin.readline

n = int(input())

num = []
base = deque([])
ans = []
sign = []

for i in range(n):
    base.append(int(input()))

i = 1
# print(base)

while True:

    if len(base) == 0 :
        print(*sign, sep='\n')
        break

    if len(num) > 0 :
        if base[0] == num[-1] :
            sign.append('-')
            ans.append(num.pop())
            base.popleft()
            continue
        if base[0] in num:
            print('NO')
            break

    if i not in num:
        sign.append('+')
        num.append(i)
        i += 1


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

"""

    #############################
    #                           #
    #   Autor: Equipo Enigma    #
    #                           #
    #############################

"""

try:
    from selenium import webdriver
except Exception as e:
    print("pip install selenium")
    exit(1)

try:
    from ipwhois import IPWhois
except Exception as e:
    print("pip install ipwhois")
    exit(1)

from sys import exit
from ipaddress import IPv4Address
from optparse import OptionParser
from sqlite3 import connect
from socket import socket, AF_INET, SOCK_STREAM, setdefaulttimeout,getfqdn
from random import randint
from dns import resolver, reversename
from os import path

def print_header():
    print("\n\t    MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM+ MMMMMMMMMMMMMMMMMMMMMMMMM. MMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM...MMMMMMMMMMMMMMMMMMMMMMM ...MMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ....MMMMMMMMMMMMMMMMMMMMM ....7MMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN .... MMMMMM7.    :DMMMMM.......MMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.......  ................ .......,MMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM..................................MMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM:..................................MMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ...................................MMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM................................... MMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.....  MMMM ............MMMMD ..... MMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM....,MMMMMMMM ........$MMMMMMMM.... MMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ....MMMMMMMMM .......MMMMMMMM.....MMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.....MMMMMMMM ......NMMMMMMM......MMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM= .... DMN+ .......... NMN.......MMMMM\n\
            MMMMMMMMMMMMMMMMN=..... .7MMMMMMMMMMMMMMMMM...............................MMMMMM\n\
            MMMMMMMMMMMMD.................:MMMMMMMMMMMMM:........................... MMMMMMM\n\
            MMMMMMMMMM ...................... DMMMMMMMMMMM ........................MMMMMMMMM\n\
            MMMMMMMN.............................NMMMMMMMMMM~ ................. ,MMMMMMMMMMM\n\
            MMMMMMO.   ,$$:   .............  . ....MMMMMMMMMMMMM...  ....   .MMMMMMMMMMMMMMM\n\
            MMMMM,.$NNNNNNNNNNO .... NNNNNNNNNNNN....OM?....MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMM?$NNNN:   .,NNNN8... NNN  ....NNNNN ............:MMMMMMMMMM8,....MMMMMMMMMMM\n\
            MMMMNNNN NNNNNNNN NNNN.. NNN.NNNNNN.ONNN............................. MMMMMMMMMM\n\
            MMMDNN8=NNNN~:DNNNIINN8. NNN.NN..DNN.DNN............................. MMMMMMMMMM\n\
            MMMNND,NNN .....ONN~NNN  NNN.NN . NNN?NN,.............................MMMMMMMMMM\n\
            MMMNN+NND....... NNN=NN. NNN.NN..ZNN:NNN..............................MMMMMMMMMM\n\
            MMMNN=NNN........NNN:NN. NNN.NNNNNNI~NNN..............................MMMMMMMMMM\n\
            MMMNNN.NND......7NN?NNN. NNN     .DNNNN ........,.....................MMMMMMMMMM\n\
            MMMNNN+DNNN=..~NNNM NNM. NNN.NNNNNNND ......$NN$IDNN.. NIN ..NZ7777N..MMMMMMMMMM\n\
            MMM.NNND.NNNNNNNM NNNN . NNN.NN   . .......NM?NNNNN...NONDN....NNN=.  MMMMMMMMMM\n\
            MMMM.DNNND..  ..NNNNN .. NNN.NN ...........N.N.......,NONZN ...NNN=...MMMMMMMMMM\n\
            MMMM~. NNNNNNNNNNNN .... NNNNNN............N+N ......N.N.N:N...NNN=...MMMMMMMMMM\n\
            MMMMM ... ~NNNN=.........       ...........DN NNNNN ONNNNNNN7..NNN=..MMMMMMMMMMM\n\
            MMMMMM .....................................,NNNNNNNNMNNNNNNN .NNN=. MMMMMMMMMMM\n\
            MMMMMMM ......                                  .                   ,MMMMMMMMMMM\n\
            MMMMMMMM.......MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMM.......DMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMM+........MMMMMMMMMMMMMMMMMMMN?  ...........ZMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMM ......... . :=,..............................MMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMM. ............................................ MMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMD....................  . ,+ONMMMMZ=............,MMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMI....  .. $MMMMMMMMMMMMMMMMMMMMMMMM ........7MMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM........MMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM.......MMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM ... MMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMENIGMAMMMMMMMM\n\
            MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM\n")

"""
Formatear whois

@whois -> String, Imprimimos data
@return -> result, Whois formateado

"""
def whoisFormatter(whois):
    result=''
    for x in whois:
        if(x is not 'nets'):
            result+='{0}: {1}
'.format(x,whois[x])
        else:
            result+='{0}:
'.format(x)
            for y in whois[x][0]:
                result += '    {0}: {1}
'.format(y,str(whois[x][0][y]).replace('
',''))
    return result

"""
Crea conexión a base de datos

@return -> Connection mysql
"""
def sqlite_open_connection():

    try:
        db_path = path.join(path.dirname(__file__), "db/opcat.db")
        db_path = path.join(db_path)
        connection = connect(db_path)
    except Exception as e:
        print(e)
        print("It has been an error establishing the connection with the database.")
        return None

    return connection

"""
Elimina tablas de la base de datos
@cursor -> Cursor de la conexión a base de datos

@return -> Connection mysql
"""
def sqlite_delete_table(cursor):
    cursor.execute("DROP TABLE IF EXISTS ip")
    cursor.execute("DROP TABLE IF EXISTS banner")
    cursor.execute("DROP TABLE IF EXISTS dns")
    cursor.execute("DROP TABLE IF EXISTS whois")
    cursor.execute("DROP TABLE IF EXISTS domainName")

"""
Crea las tablas en la base de datos
"""
def sqlite_create_table():

    connection = sqlite_open_connection()
    if( connection != None ):
        try:
            cursor = connection.cursor()
            cursor.execute("CREATE TABLE IF NOT EXISTS ip(iid INTEGER, ip VARCHAR(15), PRIMARY KEY (iid) )")
            cursor.execute("CREATE TABLE IF NOT EXISTS banner(bid INTEGER, iid INTEGER, port INTEGER(5), data VARCHAR(10000), screenshot LONGBLOB, PRIMARY KEY (bid), FOREIGN KEY (iid) REFERENCES ip(iid))")
            cursor.execute("CREATE TABLE IF NOT EXISTS dns(did INTEGER, iid INTEGER, data VARCHAR(10000), PRIMARY KEY (did), FOREIGN KEY (iid) REFERENCES ip(iid))")
            cursor.execute("CREATE TABLE IF NOT EXISTS whois(wid INTEGER, iid INTEGER, data VARCHAR(10000), PRIMARY KEY (wid), FOREIGN KEY (iid) REFERENCES ip(iid))")
            cursor.execute("CREATE TABLE IF NOT EXISTS domainName(dmid INTEGER, iid INTEGER, data VARCHAR(10000),PRIMARY KEY (dmid),FOREIGN KEY (iid) REFERENCES ip(iid))")
        except Exception as e:
            print(e)
            print("[Error] It has been an error creating the tables.")
        finally:
            cursor.close()
            connection.close()

"""
Inserta información de protocolos en base de datos

@ip     -> String, dirección IPv4
@port   -> Int, puerto TCP
@banner -> String, Banner del servicio
@dns    -> String, Información DNS
@whois  -> String, Información whois
@domainName -> String, Nombre de dominio
@screenshot -> Bytes, Imagen

@return -> Boolean, Estado de la inserción
"""
def sqlite_insert_data( ip, port, banner, dns, whois, domainName, screenshot ):
    # Obtenemos la conexión a BBDD
    connection = sqlite_open_connection()

    if connection != None:
        try:
            with connection:
                cursor = connection.cursor()

                sql = "INSERT INTO ip(ip) VALUES (?)"
                cursor.execute( sql, ( str(ip), ) )
                iid = cursor.lastrowid

                sql = "INSERT INTO banner(iid, port, data, screenshot) VALUES (?, ?, ?, ?)"
                cursor.execute( sql, ( int(iid), int(port), str(banner), screenshot, ) )

                sql = "INSERT INTO dns(iid, data) VALUES (?, ?)"
                cursor.execute( sql, (int(iid), str(dns),) )

                sql = "INSERT INTO whois(iid, data) VALUES (?, ?)"
                cursor.execute( sql, (int(iid), str(whois),) )

                sql = "INSERT INTO domainName(iid, data) VALUES (?, ?)"
                cursor.execute( sql, (int(iid),str(domainName), ) )

            # Realizamos commit para guardar los cambios
            connection.commit()
        except Exception as e:
            print(e)
            print("It has been an error during the insertion.")
        finally:
            # Cerramos conexion
            cursor.close()
            connection.close()

"""
Registramos en base de datos

@host -> IPv4Address, Dirección IPv4
@port -> Port, Número de puerto
@data -> Data,
"""
def generateInformationDB(host, port, banner, screenshot):

    #Obtenemos el Nombre de Dominio y realizamos un Whois para obtener más información
    domainName = getfqdn(host)
    whois      = whoisFormatter( IPWhois(host).lookup() )
    aux        = domainName.split('.')
    dnsQuery   = '{0}.{1}'.format(aux[-2],aux[-1])

    addr = reversename.from_address(host)
    dns = "
Nombre reverso
"
    dns += str(addr) + "
"

    try:

        ptrText = "

PTR
"
        for ptr in resolver.query( addr, "PTR" ):
            ptrText += str(ptr)+"
"

        dns += ptrText

    except Exception as e:
        pass

    try:

        nsText = "

Servidores de nombre
"
        for server in resolver.query(dnsQuery, 'NS'):
            nsText += str(server).rstrip('.')+'
'

        dns += nsText

    except Exception as e:
        pass

    sqlite_insert_data( host, port, banner, dns, whois, domainName, screenshot )

    return True

"""

"""
def takeScreenshot(host, port):

    # Realizamos una captura del servicio web
    setdefaulttimeout(200)

    try:
        browser = webdriver.Firefox(timeout=200)
        browser.implicitly_wait(200) # Segundos
        browser.set_page_load_timeout(200)
        browser.get('http://{0}'.format(host))
        screenshot = browser.get_screenshot_as_png()
        state = True
        browser.quit()

    except selenium.common.exception.WebDriverException as e:
        print("ERROR: Do you have Firefox installed?")
        exit(1)

    except Exception as e:
        state = False
        print("[Error] takeScreenShot: {0}".format(e))
        browser.quit()

    if state:
        return screenshot
    else:
        return None

"""
Determinamos si la dirección IP generada aleatoriamente es una página web
@host -> String, Dirección IPv4.
@port -> Int, Número de puerto.

@return -> Boolean, estado de la operación.
"""
def isOpenPort( host, port, timeout ):

    setdefaulttimeout(timeout)
    template = "{0:16}{1:3}{2:40}"
    #Intentamos establecer una conexión a un puerto, en caso positivo realizamos las funciones pertinentes
    try:
        # Definimos conexión
        #   AF_INET: Representa conjunto (host, port)
        #   SOCK_STREAM: Establece protocolo de la conexión TCP
        connection = socket(AF_INET, SOCK_STREAM)
        # Establecemos par de dirección IP y puerto
        connection.connect((host, port))
        # Obtenemos el banner y lo parseamos
        connection.send(b'HEAD / HTTP/1.0\r\n\r\n')
        banner = connection.recv(1024)
        # Imprimimos mensaje Puerto abierto junto a la dirección IPv4
        print(template.format(host, '->', 'Open Port'))
        # Adaptamos salto de línea a HTML
        aux = str(banner).replace('\\r\\n','
')
        # Obtenemos banner eliminando carácteres especiales del principio
        # y del final
        banner = aux[2:len(aux)-3]
        # Cerramos la conexión
        connection.close()

        #Intenamos realizar la captura de la página web,
        #si se realiza con éxito generamos el fichero de información.
        screenshot = takeScreenshot(host, str(port))

        if generateInformationDB( host, port, banner, screenshot ) :
            return True

    except Exception as e:
        print(template.format(host, '->', 'Closed Port: ('+str(e)+')'))
        connection.close()
        return False

"""
Generamos una dirección IP aleatoria.

@return -> IPv4Address, Dirección ipv4 válida.
"""
def ipFactory():
    ip = IPv4Address('{0}.{1}.{2}.{3}'.format(randint(0,255),randint(0,255),randint(0,255),randint(0,255)))

    if(ip.is_multicast or ip.is_private or ip.is_unspecified or ip.is_reserved or ip.is_loopback or ip.is_link_local):
        return ipFactory()

    return ip

"""
Función principal,

Establece a partir de dos parametros de entarada el número de puerto
y el número de iteraciones. Obtiene una dirección IPv4 válida y comprueba
si el puerto está abierto.

@Port -> Número de puerto
@Iterations-> Número de iteraciones

"""
if __name__ == "__main__":
    try:
        sqlite_create_table()
        # Imprimimos sintaxis para inserción de valores
        parser = OptionParser("Usage: %prog [-i] <iterations [default:1]> [-a] <IP address [default:random]> [-t] <timeout [default:2]>")
        parser.add_option("-t", dest="timeout", default="2", type="float", help="Specify the timeout (seconds).")
        parser.add_option("-a", dest="ip", default="0.0.0.0", type="string", help="Specify the IP for scan.")
        parser.add_option("-i", dest="iterations", default="1", type="string", help="Specify the number of iterations.")
        (options, args) = parser.parse_args()
        # Asignamos parámaetros de entrada
        numberOfIteration = int(options.iterations)
        ip = str(options.ip)
        timeout = options.timeout
        port = 80

        # Imprimir imagen de header
        print_header()

        # Imprimimos mensaje de escaneo activo
        print( 'Scanning...' )

        if(ip == "0.0.0.0"):
            # Contador para comprobar el número de iteración actual
            count = 0
            # Realizamos búsqueda de 'N' servidores con número de puerto abierto
            while(count < numberOfIteration):
                # Comprobamos si el puerto está abierto
                if( isOpenPort( str( ipFactory() ), port, timeout ) ):
                    count += 1
        else:
            if(numberOfIteration != '1'):
                print('\n[+] The following IP address will be scanned: {0}, the -i parameter will not be used.\n'.format(ip))
            isOpenPort( ip, port, timeout )

    except KeyboardInterrupt as e:
        print("[+] Bye!")


from graphics.meshes.mesh import Mesh
from graphics.vertex_buffer import Types
from glm import translate, rotate, scale, radians, mat4, vec3

class Grid(Mesh):
    def __init__(self, position, slices, size, rotation=0.0, rotationVector=(1.0, 1.0, 1.0)):
        vertices = []
        indices = []

        for j in range (slices + 1):
            for i in range (slices + 1):
                x = i / slices - 0.5
                y = 0.0
                z = j / slices - 0.5
                vertices.append(x)
                vertices.append(y)
                vertices.append(z)

        for j in range (slices):
            for i in range (slices):
                row1 =  j      * (slices + 1)
                row2 = (j + 1) * (slices + 1)
                indices.append(row1 + i)
                indices.append(row1 + i + 1)
                indices.append(row1 + i + 1)
                indices.append(row2 + i + 1)
                indices.append(row2 + i + 1)
                indices.append(row2 + i)
                indices.append(row2 + i)
                indices.append(row1 + i)

        super().__init__(position, vertices, indices, [Types.FLOAT3])

        self.slices = slices
        self.size = size
        self.rotation = rotation
        self.rotationVector = rotationVector
        self.modelMatrix = translate(mat4(1.0), vec3(self.position)) * \
                           rotate(mat4(1.0), radians(self.rotation), vec3(self.rotationVector)) * \
                           scale(mat4(1.0), vec3(self.size))


import numpy as np
from collections import Counter
from nltk.tokenize import RegexpTokenizer
import os, pickle

class Book:
    def __init__(self, file_name='10.txt.utf-8'):
        pickle_name = 'book_text.pckl'
        if os.path.exists(pickle_name):
            with open(pickle_name, 'rb') as f:
                self._book_text = pickle.load(f)
        else:
            with open(file_name) as f:
                book = f.read()
                book = book.lower()
                tokenizer = RegexpTokenizer(r'\w+')
                book = [w.lower() for w in tokenizer.tokenize(book)]
                self._book_text = book
            with open(pickle_name, 'wb') as f:
                pickle.dump(book, f)

        print("Unique words: " + str(len(Counter(self._book_text))))

    def create_dictionaries(self, vocabulary_size):
        '''Create a dict mapping words to word ids. It works by finding the
        `vocabulary_size` most common words and assigning ids based on the
        frequency. The most common word will have id 1, the second most common
        one id 2, and so forth. All other words (with the key "UNKNOWN") will
        have id 0.

        Parameters
        ----------
        vocabulary_size :   int
                            Number of most common words to create ids for
        '''
        words_and_count = Counter(self._book_text).most_common(vocabulary_size - 1)

        word2id = {word.lower(): word_id for word_id, (word, _) in enumerate(words_and_count, 1)}
        word2id["UNKNOWN"] = 0

        id2word = dict(zip(word2id.values(), word2id.keys()))

        # Map words to ids
        self._book = [word2id.get(word, 0) for word in self._book_text]

        self._word2id = word2id
        self._id2word = id2word

    def words2ids(self, words):
        if type(words) == list or type(words) == range or type(words) == np.ndarray:
            return [self._word2id.get(word.lower(), 0) for word in words]
        else:
            return self._word2id.get(words, 0)

    def ids2words(self, ids):
        if type(ids) == list or type(ids) == range or type(ids) == np.ndarray:
            return [self._id2word.get(wordid, "UNKNOWN") for wordid in ids]
        else:
            return self._id2word.get(ids, 0)

    def get_training_batch(self, batch_size, skip_window):
        valid_indices = range(skip_window, len(self._book) - (skip_window + 1))
        context_range = [x for x in range(-skip_window, skip_window + 1) if x != 0]
        wordid_contextid_pairs = [(word_id, word_id + shift) for word_id in
                valid_indices for shift in context_range]

        np.random.shuffle(wordid_contextid_pairs)

        counter = 0
        words = np.zeros((batch_size), dtype = np.int32)
        contexts = np.zeros((batch_size, 1), dtype = np.int32)

        for word_index, context_index in wordid_contextid_pairs:
            words[counter] = self._book[word_index]
            contexts[counter, 0] = self._book[context_index]
            counter += 1

            if counter == batch_size:
                yield words, contexts
                counter = 0


import numpy as np
import xlrd
import matplotlib.pyplot as plt

loss=np.load('loss.npy')
x=range(0,100)
plt.plot(x,loss,label='Train loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
#plt.ylim(0,1.2)
plt.grid()
plt.legend()
plt.show()


name={8259:['Apoorv',20932.45,2001],1845:['Aparna',76896.89,1979],1122:['Atoull',45553.67,1971],6048:['Gargi',678568.78,1998]}

ac=int(input("Enter your account number: "))
if ac in name.keys():
    bal=name[ac]
    print("Welcome!", bal[0])
    pin = int(input("Please Enter your PIN "))
    if(pin==bal[2]):
        ch = int(input("1.Display Balance\n2.Deposit Money\n3.Withdraw Money\n0.EXIT\nChoose an operation "))
        while(ch!=0):
            if(ch==1):

                print("Your Account Balance is: ",bal[1])
                print("***************")
            elif(ch==2):
                add=int(input("Enter the amount to deposit: "))
                bal[1]+=add
                name[ac]=bal
                print('New balance: ', bal[1])
                print("**************")
            elif(ch==3):
                sub=int(input("Enter the amount to withdraw: "))
                if(sub>bal[1]):
                    print("ERROR! Insufficient Funds")
                    print('Balance: ',bal[1])
                    print("**************")
                else:
                    bal[1]=bal[1]-sub
                    name[ac]=bal
                    print('New balance: ',bal[1])
                    print("**************")
            ch = int(input("1.Display Balance\n2.Deposit Money\n3.Withdraw Money\n0.EXIT\nChoose an operation "))
    else:
        print("Invalid PIN ")
else:
    print("The A/C Number you entered does not exist ")


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

import cv2

import keras
from keras.datasets import mnist
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D

#veri setinin yüklenmesi
(x_train, y_train),(x_test, y_test) = mnist.load_data()

#veri ön işleme
img_rows = 28
img_cols = 28
x_train = x_train.reshape( x_train.shape[0],img_rows,img_cols,1)
x_test = x_test.reshape( x_test.shape[0],img_rows,img_cols,1)
input_shape = (img_rows,img_cols,1)

#normalizasyon
x_train = x_train.astype("float32")
x_test = x_test.astype("float32")

x_train /= 255
x_test /= 255

#One Hot Encoding işlemi
num_classes = 10
y_train = keras.utils.to_categorical(y_train,num_classes)
y_test = keras.utils.to_categorical(y_test,num_classes)

#CNN yapısı
model_list = []
score_list = []

batch_size = 128
epochs = 30

filter_numbers = np.array([[16,32,64], [32,64,128], [64,128,256]])

for i in range(3):

    print(filter_numbers[i])
    model = Sequential()
    model.add(Conv2D(filter_numbers[i,0], kernel_size = (3,3),activation = "relu",input_shape = input_shape))
    model.add(MaxPooling2D())
    model.add(Conv2D(filter_numbers[i,1], kernel_size = (3,3),activation = "relu"))
    model.add(MaxPooling2D())
    model.add(Dropout(0.25))

    model.add(Flatten())
    model.add(Dense(filter_numbers[i,2],activation = "relu"))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes,activation = "softmax"))

    model.compile(loss = keras.losses.categorical_crossentropy,
                  optimizer="adam",
                  metrics = ["accuracy"])

    history = model.fit(x_train, y_train,
                        batch_size = batch_size,
                        epochs = epochs, verbose = 1,
                        validation_data = (x_test,y_test))

    score = model.evaluate(x_test, y_test, verbose = 0)
    print("Model {} Test Loss: {}".format(i+1, score[0]))
    print("Model {} Test Accuracy: {}".format(i+1, score[1]))
    model_list.append(model)
    score_list.append(score)

    model.save("modelCNN"+str(i+1)+".h5")

#modellerin yüklenmesi
modelCNN1 = load_model("modelCNN1.h5")
modelCNN2 = load_model("modelCNN2.h5")
modelCNN3 = load_model("modelCNN3.h5")


if __name__ == "__main__":
    questions = []
    count_questions = []
    with open('./input.txt', 'r') as f:
        lines = f.readlines()

    for i, line in enumerate(lines):
        if line != '\n':
            for question in range(0, len(line.strip())):
                if line[question] not in questions:
                    questions.append(line[question])

        if len(line.strip()) == 0 or i+1 >= len(lines):
            count_questions.append(len(questions))
            questions = []

    print(sum(count_questions))


L = float(input('Largura da parede em metros:'))
Al = float(input('Altura da parede em metros'))
a = L * Al
p = a/2

print('Sua parede tem dimensão de {}x{} e sua área é de {}m²'.format(L, Al, a))
#A CADA 2m² DE PAREDE PRECISA DE 1L DE TINTA
print('Para pintar essa parede você precisará de {}L de tinta'.format(p))


# These warnings are not useful in unit tests.
# pylint: disable=missing-class-docstring,missing-function-docstring,missing-module-docstring

__copyright__ = "Copyright 2023 the Pacemaker project contributors"
__license__ = "GPLv2+"

import unittest

from pacemaker._cts.network import next_ip

# next_ip makes a bunch of assumptions that we are not going to test here:
#
# * The env argument actually contains an "IPBase" key with a string in it
# * The string is a properly formatted IPv4 or IPv6 address, with no extra
#   leading or trailing whitespace

class NextIPTestCase(unittest.TestCase):
    def test_ipv4(self):
        # The first time next_ip is called, it will read the IPBase out of
        # the environment.  After that, it just goes off whatever it
        # previously returned, so the environment value doesn't matter.
        self.assertEqual(next_ip("1.1.1.1"), "1.1.1.2")
        self.assertEqual(next_ip(), "1.1.1.3")

        # Passing reset=True will force it to re-read the environment.  Here,
        # we use that to ask it for a value outside of the available range.
        self.assertRaises(ValueError, next_ip, "1.1.1.255", reset=True)

    def test_ipv6(self):
        # Same comments as for the test_ipv4 function, plus we need to reset
        # here because otherwise it will remember what happened in that function.
        self.assertEqual(next_ip("fe80::fc54:ff:fe09:101", reset=True),
                         "fe80::fc54:ff:fe09:102")
        self.assertEqual(next_ip(),
                         "fe80::fc54:ff:fe09:103")

        self.assertRaises(ValueError, next_ip, "fe80::fc54:ff:fe09:ffff", reset=True)


"""
   ---------------------------------------------------------------------------------------------------------
    PYTHON PROJECT 2A
                      Air Pollution Forecasting using LSTM in KERAS
                                                                                submitted by,
                                                                                Justin Joseph.
                                                                                18201354
   ---------------------------------------------------------------------------------------------------------
   ---------------------------------------------------------------------------------------------------------
    Import the necessary packages.
   ---------------------------------------------------------------------------------------------------------
"""
import warnings
import numpy as np
import math as mt
import datetime as dt
import pandas as pd
import sklearn.preprocessing as skp
import sklearn.metrics as skm
import keras.layers as kl
import keras.models as km
import bokeh.plotting as bp

warnings.filterwarnings("ignore")
"""
   ---------------------------------------------------------------------------------------------------------
    Function definitions.
   ---------------------------------------------------------------------------------------------------------
"""
def date_reformat(x): #Function to merge the individual date entries into a single column
    return dt.datetime.strptime(x,'%Y %m %d %H')

def timeseries_to_supervised(d,input=1,output=1): #Function to convert timeseries to supervised structure
    vars=1 if type(d) is list else d.shape[1]
    df=pd.DataFrame(d)
    cols,names=list(),list()
    #
    for i in range(input,0,-1):
        cols.append(df.shift(i))
        names += [('var%d(t-%d)' % (j+1, i)) for j in range(vars)]
    #
    for i in range(0,output):
        cols.append(df.shift(-i))
        if i==0:
            names += [('var%d(t)' % (j+1)) for j in range(vars)]
        else:
            names += [('var%d(t+%d)' % (j+1,i)) for j in range(vars)]
    aggregate=pd.concat(cols,axis=1)
    aggregate.columns=names
    return aggregate

def drop_na(d): #Function to remove NA values
    d.dropna(inplace=True)
    return d

def create_lstm_model(data): #Function to create the LSTM model
    a = km.Sequential()
    a.add(kl.LSTM(100, input_shape=(data.shape[1], data.shape[2])))
    a.add(kl.Dense(1))
    a.compile(loss='mae', optimizer='adam')
    return a

def invert_scaling(a,b): #Function to perform inverse scaling
    c = np.concatenate((b, a[:, 1:]), axis=1)
    c = scale.inverse_transform(c)
    c = c[:, 0]
    return c
"""
   ---------------------------------------------------------------------------------------------------------
    Main Paragraph.
   ---------------------------------------------------------------------------------------------------------
"""
# Load the data with reformatted date and date column as the index
data=pd.read_csv('C:/Users/HP/Downloads/Study/Python/Assignment/Project 2/raw.csv',parse_dates=[['year','month','day',
                  'hour']],index_col=0,date_parser=date_reformat)
data.drop('No',axis=1,inplace=True) #Drop the column "No" as it has no significance in prediction
data.columns=['Pollution','Dew','Temperature','Pressure','Wind Direction','Wind Speed','Snow','Rain'] #Rename the columns
data.index.name='Date' #Rename the index
data=data[24:] #Drop the first 24 hours of data as it has NA values
data['Pollution'].fillna(0,inplace=True) #Replace all the other NA values with 0
val=data.values
"""
   ---------------------------------------------------------------------------------------------------------
    Bokeh plots to show the changes in the attributes with time.
   ---------------------------------------------------------------------------------------------------------
"""
bp.output_file("Pollution.html")
p=bp.figure(title='Pollution in Beijing during 2010-2014',x_axis_label='Year',y_axis_label='Pollution',
            x_axis_type='datetime',plot_width=1100)
p.line(data.index,val[:,0],legend=data.columns[0],line_width=2)
bp.show(p)

bp.output_file("Dew.html")
p=bp.figure(title='Dew in Beijing during 2010-2014',x_axis_label='Year',y_axis_label='Dew',
            x_axis_type='datetime',plot_width=1100)
p.line(data.index,val[:,1],legend=data.columns[1],line_width=2)
bp.show(p)

bp.output_file("Temperature.html")
p=bp.figure(title='Temperature in Beijing during 2010-2014',x_axis_label='Year',y_axis_label='Temperature',
            x_axis_type='datetime',plot_width=1100)
p.line(data.index,val[:,2],legend=data.columns[2],line_width=2)
bp.show(p)

bp.output_file("Pressure.html")
p=bp.figure(title='Pressure in Beijing during 2010-2014',x_axis_label='Year',y_axis_label='Pressure',
            x_axis_type='datetime',plot_width=1100)
p.line(data.index,val[:,3],legend=data.columns[3],line_width=2)
bp.show(p)

bp.output_file("Wind Speed.html")
p=bp.figure(title='Wind Speed in Beijing during 2010-2014',x_axis_label='Year',y_axis_label='Wind Speed',
            x_axis_type='datetime',plot_width=1100)
p.line(data.index,val[:,5],legend=data.columns[5],line_width=2)
bp.show(p)

bp.output_file("Snow.html")
p=bp.figure(title='Snow in Beijing during 2010-2014',x_axis_label='Year',y_axis_label='Snow',
            x_axis_type='datetime',plot_width=1100)
p.line(data.index,val[:,6],legend=data.columns[6],line_width=2)
bp.show(p)

bp.output_file("Rain.html")
p=bp.figure(title='Rain in Beijing during 2010-2014',x_axis_label='Year',y_axis_label='Rain',
            x_axis_type='datetime',plot_width=1100)
p.line(data.index,val[:,7],legend=data.columns[7],line_width=2)
bp.show(p)
"""
   ---------------------------------------------------------------------------------------------------------
    Prepare data for modelling.
   ---------------------------------------------------------------------------------------------------------
"""
# Convert categorical data (Wind Speed) into numbers
encode=skp.LabelEncoder()
val[:,4]=encode.fit_transform(val[:,4])

# Makes all data as float type
val=val.astype('float32')

# Normalize the data
scale=skp.MinMaxScaler(feature_range=(0,1))
scaled_val=scale.fit_transform(val)

# Reformat to supervised learning
reformatted=timeseries_to_supervised(scaled_val,1,1)

# Drop any NA values present after the shift operation is done
reformatted=drop_na(reformatted)

# Drop columns that aren't used to predict
reformatted.drop(reformatted.columns[[9,10,11,12,13,14,15]],axis=1,inplace=True)

# Split dataset into train and test datasets
val_reformat=reformatted.values
train_hours=(365*24)*4 # Train with Four years of data
train=val_reformat[:train_hours, :]
test=val_reformat[train_hours:, :]

# Split into input and output
train_X,train_Y=train[:, :-1],train[:, -1]
test_X,test_Y=test[:, :-1],test[:, -1]

# Reshape into a 3D array suitable for the LSTM model
train_X=train_X.reshape((train_X.shape[0],1,train_X.shape[1]))
test_X=test_X.reshape((test_X.shape[0],1,test_X.shape[1]))
print(train_X.shape,train_Y.shape,test_X.shape,test_Y.shape)
"""
   ---------------------------------------------------------------------------------------------------------
    Design a neural network using LSTM .
   ---------------------------------------------------------------------------------------------------------
"""
model=create_lstm_model(train_X)

# Fit network
history=model.fit(train_X,train_Y,epochs=50,batch_size=72,validation_data=(test_X,test_Y),verbose=2,shuffle=False)
"""
   ---------------------------------------------------------------------------------------------------------
    Bokeh plot.
   ---------------------------------------------------------------------------------------------------------
"""
bp.output_file("Loss.html")
p=bp.figure(title='Loss',x_axis_label='Epoch',y_axis_label='Loss Value')
p.line(list(range(len(history.history['loss']))),history.history['loss'],legend='Train',line_color='firebrick',line_width=2)
p.line(list(range(len(history.history['val_loss']))),history.history['val_loss'],legend='Test',line_color='navy',line_width=2)
bp.show(p)
"""
   ---------------------------------------------------------------------------------------------------------
    Predict using the model generated above.
   ---------------------------------------------------------------------------------------------------------
"""
y_hat=model.predict(test_X)
test_X=test_X.reshape((test_X.shape[0],test_X.shape[2]))
test_Y=test_Y.reshape((len(test_Y),1))

# Invert scaling for actual
inv_Y=invert_scaling(test_X,test_Y)

# Invert scaling for forecast
inv_Y_hat=invert_scaling(test_X,y_hat)

# Calculate RMSE
RMSE=mt.sqrt(skm.mean_squared_error(inv_Y,inv_Y_hat))
print('The RMSE value is : ',RMSE)


#!/usr/bin/env python3

import sys
import collections

from src.PiskvorkParsing import PiskvorkParser

def main():
  piskvorkParser = PiskvorkParser()

  while True:
    line = sys.stdin.readline()
    if not piskvorkParser.parseAndExecuteCommand(line):
      break
  return 0

if __name__ == "__main__":
  main()


from ReplayBuffer import IndividualBuffers, makeOUNoise
from ActorCritic import ActorCritic
import matplotlib.pyplot as plt
import gym
import pybullet_envs
import numpy as np
from training import train, testing

if __name__=="__main__":

    activation_name='relu'
    save_name='PackNet_TESTS'

    DR = False # Turn Distributional Regularizers on and off.
    PACK = False # Turn PackNet on and off.
    CPACK = False # Turn PackNet on and off for critic net specifically.
    USE_PER = True # Prioritized Experience Replay buffer

    # Obtain pertinent environment information.
    env_names = ['Pendulum-v0']
    # env_names = ['HalfCheetahBulletEnv-v0','HalfCheetahBulletEnv-v0']

    # Obtain pertinent environment information.
    env_names = ['HalfCheetahBulletEnv-v0']
    seeds = [4444, 5021, 1580]

    env = gym.make(env_names[0])

    state_dim = env.observation_space.shape[0]
    action_dim = env.action_space.shape[0]
    action_max = env.action_space.high[0]

    ac_dict = {'state_shape':state_dim,
               'action_shape':action_dim,
               'action_scale':action_max,
               'tau':1e-3}

    actor_dict = {'layer_sizes':[480,360],
                  'activation':activation_name,
                  'pool_size':2,
                  'dropout_rate':0.5,
                  'use_bn':False,
                  'use_do':True,
                  'DR':DR,
                  'total_tasks':len(env_names),
                  'cpack':False}

    # Create actor and critic objects based on environment information.
    ActorObj = ActorCritic(actor_type=True,**ac_dict, lr=1e-3, **actor_dict)

    # Critic object has a simpler version if not using PackNet on it.
    # Which is only needed for multi-task PackNet.
    if not CPACK:
        CriticObj = ActorCritic(actor_type=False,**ac_dict, lr=1e-3, cpack=CPACK)
    else:
        critic_dict = {'layer_sizes':[480,360],
                  'activation':activation_name,
                  'pool_size':2,
                  'dropout_rate':0.5,
                  'use_bn':False,
                  'use_do':False,
                  'DR':DR,
                  'total_tasks':len(env_names),
                  'cpack':CPACK}

        CriticObj = ActorCritic(actor_type=False,**ac_dict, lr=1e-3, **critic_dict)

    Total_R_e_list = []

    for t,name in enumerate(env_names):
        envmt = gym.make(name)
        envmt.seed(seeds[t])
        envmt.reset()

        state_dim = envmt.observation_space.shape[0]
        action_dim = envmt.action_space.shape[0]
        action_max = envmt.action_space.high[0]

        # Make experience buffer and noise.
        buffer_size = int(5e4)
        BufferObj = IndividualBuffers(buffer_size, state_dim, action_dim)
        NoiseObj = makeOUNoise(noise_type='normal',mu=np.zeros(action_dim),sigma=np.full(action_dim,0.2))

        # Training arguments.
        arg_dict = {'ActorObj':ActorObj,
                    'CriticObj':CriticObj,
                    'buffer':BufferObj,
                    'noise':NoiseObj,
                    'episode_num':150,
                    'step_num':1000,
                    'batch_size':64,
                    'gamma':0.99,
                    'envmt':envmt,
                    'task':t,
                    'PACK':PACK,
                    'CPACK':CPACK,
                    'DR':DR,
                    'USE_PER': USE_PER}

        # Run training procedure and save results.
        Total_R_e, TrainedActorObj, TrainedCriticObj, zero_store = train(**arg_dict)
        Total_R_e_list.append(Total_R_e)

        if PACK:
            if t<len(env_names)-1:
                ActorObj.packPruning(task=t,T=len(env_names))
                if CPACK: CriticObj.packPruning(task=t,T=len(env_names))

            # Reinitialize parameters with original values.
            ActorObj.layerSave(False)
            ActorObj.softTargetNetUpdate()

            if CPACK:
                CriticObj.layerSave(False)
                CriticObj.softTargetNetUpdate()

        '''
        # Show zero activation percent over training
        fig, ax = plt.subplots(figsize=(12,7))
        plt.plot(list(range(len(zero_store))), zero_store)
        plt.xlabel('Episode')
        plt.ylabel('Pct Zero Activations')
        plt.show()
        '''

    model_name = save_name+'_'+activation_name

    #TrainedActorObj.net.save_weights('./saved_models/'+model_name+'_actor')
    #TrainedCriticObj.net.save_weights('./saved_models/'+model_name+'_critic')

    for i, R_e in enumerate(Total_R_e_list):
        fig, ax = plt.subplots(figsize=(12,7))
        plt.plot(list(range(len(R_e))), R_e)
        plt.xlabel('Episode')
        plt.ylabel('Total Reward')
        plt.title('Task #'+str(i+1))
        plt.show()

        rew_str = ''
        for r in R_e:
            rew_str = rew_str+str(r)+'\n'
        rew_str = rew_str[:-1]
        with open('./results/'+model_name+'.txt','a') as write_file:
            write_file.write(rew_str)

    testing(ActorObj,env,state_dim,model_name,'new_seed')

    ActorObj.setTask(0)
    env.seed(seeds[0])
    testing(ActorObj,env,state_dim,model_name,'first_seed')

    ActorObj.setTask(1)
    env.seed(seeds[1])
    testing(ActorObj,env,state_dim,model_name,'second_seed')


from django.db import models

class Faculty(models.Model):
    # Properties:
    title = models.CharField(max_length=150, null=False)
    about = models.TextField(max_length=300, null=False)
    content = models.TextField(max_length=1024, null=False)
    photo = models.FileField(upload_to='photo/', null=True)
    logo = models.FileField(upload_to='logo/', null=True)
    url = models.URLField(null=True)
    # Repr:
    def __str__(self) -> str:
        return str(self.title)


# Definition for singly-linked list.

class Node:
    def __init__(self,x):
        self.val = x
        self.next = None

class printList:
    def solve(self,A):
        curr = A
        while curr != None:
            print(curr.val, end='')
            curr = curr.next
        print('')


import sys

from PyQt5 import QtWidgets

class Pencere (QtWidgets.QWidget):
    def __init__(self):

        super().__init__() #yukarıda yazdıgımız QWİDGET sınıfını cagırdık

        self.init_ui() #ekstra özellikler eklemek içinde init_ui tanımladım

    def init_ui(self):

        self.yazı_alanı = QtWidgets.QLineEdit() #QLineEdit ile input olusturduk ve artık yazı yazabilecegimiz bir alan var
        self.temizle = QtWidgets.QPushButton("Temizle")
        self.yazdır = QtWidgets.QPushButton("Yazdır!")

        v_box = QtWidgets.QVBoxLayout()

        v_box.addWidget(self.yazı_alanı)
        v_box.addWidget(self.temizle)
        v_box.addWidget(self.yazdır)
        v_box.addStretch()  # boşluk bırakmak için yazdık

        self.setLayout(v_box) #v_boxu kendi penceremize ekledik

        self.temizle.clicked.connect(self.click)
        self.yazdır.clicked.connect(self.click)

        self.show()

    def click(self): #hangi butona basıldıgını anlamam için qwidgets içindeki bir fonk. kullanalım

        sender = self.sender() #eger temizle butonuna basılırsa üzerindeki yazı bana gelicek ve altta olusturacagımız if ile bunu anlayabilecegiz
        # 2 tane buton olusturduk (temizle ve yazdır) hangisine basıldıgını anlamamız için sender fonk. kullanıp if else ile komutunu belirledik

        if sender.text() == "Temizle":

            self.yazı_alanı.clear()

        else:

            print(self.yazı_alanı.text())

app = QtWidgets.QApplication(sys.argv)

pencere = Pencere()
sys.exit(app.exec_())

PyQt5/Qline Edit Olusturma Ve İnput Alanları.py


from dataclasses import dataclass
from typing import Union

from bling.helpscout.mailboxes import Mailbox
from bling.mc.client import MobileCommonsClient
from bling.phone import Phone
from twilio.rest import TwilioClient

TWILIO_TRANSPORT_TYPE = "twilio"
MOBILECOMMONS_TRANSPORT_TYPE = "mobilecommons"

@dataclass
class IncomingMesage:
    mailbox: Mailbox
    from_phone: Phone
    body: str

@dataclass
class OutgoingMessage:
    mailbox: Mailbox
    to_phone: Phone
    body: str

class Transport:
    def get_client(self) -> Union[MobileCommonsClient, TwilioClient]:
        raise NotImplementedError("'get_client' is not implemented on this transport")

    def send_response(self, message: OutgoingMessage):
        raise NotImplementedError(
            "'send_response' is not implemented on this transport"
        )

class TwilioTransport(Transport):
    def __init__(self, client: TwilioClient):
        self.client = client

    def get_client(self) -> TwilioClient:
        return self.client

    def send_response(self, message: OutgoingMessage):
        return self.client.messages.create(
            to=message.to_phone.twilio_format,
            from_=message.mailbox.phone.twilio_format,
            body=message.body,
        )

class MobileCommonsTransport(Transport):
    def __init__(self, client: MobileCommonsClient):
        self.client = client

    def get_client(self) -> MobileCommonsClient:
        return self.client

    def send_response(self, message: OutgoingMessage):
        return self.client.send_sms(
            message.mailbox.mc_campaign_id, message.to_phone.twilio_format, message.body
        )


#Group 1  Xikang Zhang, Yajie Zhang, Yacong Wang
# system initialization
# set the desired state and  upload it to the AWS IoT shadow

from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import logging
import time
import json
import threading
from sense_hat import SenseHat

# aws iot shadow schema
#
# {
#     "state: {
#         "desired": {
#             "temperature":"38.5",
#               "humidity":"60"
#         }
#         "reported": {
#             "timestamp":"2020-04-13 10:07:43",
#               "temperature":"37",
#               "humidity":"30",
#               "level":"yes|no"
#         }
#     }
# }

deviceShadowHandler = None
# Initialize Sense Hat
sense = SenseHat()

# get all values from sensors
def getDeviceStatus():
    temp = sense.get_temperature()
    humidity = sense.get_humidity()
    temp = round(temp, 1)
    humidity = round(humidity, 1)
    # level
    raw = sense.accel_raw
    x, y, z = raw["x"], raw["y"], raw["z"]
    level_str = "x: " + str(x) + ", y: " + str(y) + ", z: " + str(z)
    level_state = "no"
    if (-0.05 < x < 0.05) and (-0.05 < y < 0.05) and (0.95 < z < 1.05):
        level_state = "yes"
    # format the current time
    currenttime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
    return {"temperature":temp, "humidity":humidity, "level":level_state, "time":currenttime}

def customShadowCallback_upate(payload, responseStatus, token):
    # payload is a JSON string which will be parsed by jason lib
    if responseStatus == "timeout":
        print("Update request with " + token + " time out!")
    if responseStatus == "accepted":
        playloadDict = json.loads(payload)
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        print(payload)
        print("Update request with token: " + token + " accepted!")
        print("Temperature: " + str(playloadDict["state"]["desired"]["temperature"]))
        print("humidity: " + str(playloadDict["state"]["desired"]["humidity"]))
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n")
    if responseStatus == "rejected":
        print("Update request " + token + " rejected!")

def customShadowCallback_delete(payload, responseStatus, token):
    if responseStatus == "timeout":
        print("Delete request " + token + " time out!")
    if responseStatus == "accepted":
        print("Delete request with token " + token + " accepted!")
    if responseStatus == "rejected":
        print("Delete request with token " + token + " rejected!")

# aws iot info
awsiotHost = "a1eeyktzyeh5hs-ats.iot.us-east-1.amazonaws.com"
awsiotPort = 443;
rootCAPath = "/home/pi/Scripts/lab3/crt/root-ca-cert.pem"
privateKeyPath = "/home/pi/Scripts/lab3/crt/ac354bff74-private.pem.key"
certificatePath = "/home/pi/Scripts/lab3/crt/ac354bff74-certificate.pem.crt"

myAWSIoTMQTTShadowClient = None;
myAWSIoTMQTTShadowClient = AWSIoTMQTTShadowClient("Status Initialization")
myAWSIoTMQTTShadowClient.configureEndpoint(awsiotHost, awsiotPort)
myAWSIoTMQTTShadowClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

myAWSIoTMQTTShadowClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTShadowClient.configureConnectDisconnectTimeout(60) # 10sec
myAWSIoTMQTTShadowClient.configureMQTTOperationTimeout(50) #5sec

#connect to AWS IoT
myAWSIoTMQTTShadowClient.connect()

#create a devcie Shadow with persistent subscription
thingName = "my-iot-thing"
deviceShadowHandler = myAWSIoTMQTTShadowClient.createShadowHandlerWithName(thingName, True)

#Delete shadow JSON doc
deviceShadowHandler.shadowDelete(customShadowCallback_delete, 50)

#start a thread to get device status
statusLoopThread = threading.Thread(target=getDeviceStatus)
statusLoopThread.start()

# initialize the light and water sprinkler status
b = [0, 0, 255]
o = [255, 165, 0]
w = [255,255,255]
z = [0, 0, 0]

initImage = [
o,o,o,o,o,o,o,o,
z,z,z,z,z,z,z,z,
z,z,z,z,z,z,z,z,
z,z,z,z,z,z,z,z,
z,z,z,z,z,z,z,z,
z,z,z,z,z,z,z,z,
z,z,z,z,z,z,z,z,
z,z,z,z,z,z,z,z,
]
sense.set_pixels(initImage)

#set the ideal temperature and humidity for incubation
deisredTemp = str(35)
desiredHum = str(60)
print("To set desired temperature to " + deisredTemp + "and desired humidity to " + desiredHum+ "\n")
jsonPayload = {"state":{"desired":{"temperature":deisredTemp, "humidity":desiredHum}}}
print("payload is: " + str(jsonPayload) + "\n")
deviceShadowHandler.shadowUpdate(json.dumps(jsonPayload), customShadowCallback_upate, 60)


from local_apps.tps.models import TPForm, TrabajoPractico, AlumnoForm, ValorControl, ValorControlForm,\
    ValidacionControlesForm
from django.template import Context, loader
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
import re
from django.db.models.aggregates import Count
from django.conf import settings

@login_required
def index(request):
    #Muestra index principal especifico dependiendo si es del grupo profesores o alumnos
    isProfesor = validateGroupProfesores(request.user)

    if isProfesor:
        listaAlumnos = User.objects.filter(groups__name__contains='alumnos', is_active='True').order_by('-first_name')[:5]
        listaTPs = TrabajoPractico.objects.all().order_by('codigo', 'tema').annotate(dcount=Count('codigo'))
        t = loader.get_template('tps/indexProfesores.html')
    else:
        #Si es alumno
        listaAlumnos = (User.objects.get(username=request.user.username),)
        nroLegajoAsignacion = getNroLegajoAsignacion(request.user.username)
        listaTPs = TrabajoPractico.objects.filter(nrosLegajosAsignados__contains=nroLegajoAsignacion).order_by('codigo', 'tema').annotate(dcount=Count('codigo'))
        t = loader.get_template('tps/indexAlumnos.html')

    c = Context ({
                  'user': request.user,
                  'listaAlumnos':listaAlumnos,
                  'listaTPs':listaTPs,
    })
    return HttpResponse(t.render(c))

#prueba de pagina de error
def error(request):
    t = loader.get_template('404.html')
    c = Context ({
                  'listaAlumnos':'',
    })
    return HttpResponse(t.render(c))

@login_required
def trabajosPracticos(request, tp_codigo, tp_tema):
    #si es profesor devuelve formulario de modificacion de TP
    if validateGroupProfesores(request.user):
        try:
            tp = TrabajoPractico.objects.get(codigo=tp_codigo, tema=tp_tema)
            form = TPForm(instance=tp)
            form.fields['codigo'].widget.attrs['readonly'] = 'True'
            form.fields['tema'].widget.attrs['readonly'] = 'True'
        except TrabajoPractico.DoesNotExist:
            raise Http404
        try:
            valoresCtrl = ValorControl.objects.filter(trabajoPractico=tp)
        except ValorControl.DoesNotExist:
            valoresCtrl = [ValorControl(),]
        return render_to_response('tps/forms.html',
                                  {'formTP': form,
                                   'codigoTP': str(tp.codigo) + '_' + tp.tema,
                                   'valoresCtrl': valoresCtrl,},
                                  context_instance=RequestContext(request))
    else:
        #devuelve formulario de autoevaluacion para el alumno
        try:
            tp = TrabajoPractico.objects.get(codigo=tp_codigo, tema=tp_tema)
        except TrabajoPractico.DoesNotExist:
            raise Http404
        try:
            valoresCtrl = ValorControl.objects.filter(trabajoPractico=tp)
            form = ValidacionControlesForm(request.POST or None, valoresCtrl)#ELIMINAR
        except ValorControl.DoesNotExist:
            valoresCtrl = [ValorControl(),]
        return render_to_response('tps/autoevaluacionValoresCtrl.html',
                                  {'user': request.user,
                                   'codigoTP': str(tp.codigo) + '_' + tp.tema,
                                   'tp': tp,
                                   'formValCtrl': form,#ELIMINAR
                                   'valoresCtrl': valoresCtrl,},
                                   context_instance=RequestContext(request))

@login_required
def alumnos(request, legajo_id):
    try:
        alumno = User.objects.get(username=legajo_id)
        form = AlumnoForm(instance=alumno)
        form.fields['username'].widget.attrs['readonly'] = 'True'
    except User.DoesNotExist:
        raise Http404
    return render_to_response('tps/alumnos.html',
                              {'alumno': alumno,
                               'formAlumno': form,
                               'nroLegajoAsignacion': getNroLegajoAsignacion(alumno.username),
                               },
                               context_instance=RequestContext(request))

@login_required
def valorControl(request, tp_codigo, tp_tema, id_ValCtrl):
    try:
        valCtrl = ValorControl.objects.get(pk=id_ValCtrl)
        form = ValorControlForm(instance=valCtrl)
    except ValorControl.DoesNotExist:
        raise Http404
    return render_to_response('tps/forms.html',
                              {'formValCtrl': form,
                               },
                              context_instance=RequestContext(request))

@login_required
def agregarTP(request):
    #Valida permisos
    if not request.user.has_perm('tps.change_trabajopractico'):
        return HttpResponseForbidden()

    if request.method == 'POST':
        try:
            tp = TrabajoPractico.objects.get(codigo = request.POST['codigo'], tema=request.POST['tema'])
        except TrabajoPractico.DoesNotExist:
            tp = TrabajoPractico()
        form = TPForm(request.POST, request.FILES, instance=tp)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(settings.FACULTAD_PRINCIPAL_PAGE)
    else:
        form = TPForm()
    return render_to_response('tps/forms.html',
                              {'formTP': form,},
                              context_instance=RequestContext(request))

@login_required
def agregarValorCtrl(request, tp_codigo, tp_tema):
    #Alta de los Valores de control para los trabajos practicos
    #Valida permisos
    if not request.user.has_perms(['tps.change_trabajopractico','tps.change_valorcontrol']):
        return HttpResponseForbidden()

    form = ValorControlForm(request.POST or None)
    #si el request viene por POST se da de alta, sino devuelve un formulario vacio
    if request.method == 'POST':
        if form.is_valid():
            valCtrl = form.save(commit=False)
            tp = TrabajoPractico.objects.get(codigo=tp_codigo, tema=tp_tema)
            valCtrl.trabajoPractico = tp
            valCtrl.save()
            return HttpResponseRedirect('/facultad/tps/'+tp_codigo+'_'+tp_tema)

    return render_to_response('tps/forms.html',
                              {'formValCtrl': form,},
                              context_instance=RequestContext(request))

@login_required
def validarValoresControl(request, tp_codigo, tp_tema):
    try:
        tp = TrabajoPractico.objects.get(codigo=tp_codigo, tema=tp_tema)
    except TrabajoPractico.DoesNotExist:
        raise Http404
    valoresCorrectos = ValorControl.objects.filter(trabajoPractico=tp)
    form = ValidacionControlesForm(request.POST or None, valoresCorrectos)
    if request.method == 'POST':
        for valorCorrecto in valoresCorrectos:
            valorMin = valorCorrecto.valor*0.97
            valorMax = valorCorrecto.valor*1.03
            value = request.POST["valCtrl_"+str(valorCorrecto.id)]
            valorFormateado = re.sub(',','.',value)
            try:
                if valorFormateado != "" and float(valorFormateado) < valorMax and float(valorFormateado) > valorMin:
                    form.fields["valCtrl_"+str(valorCorrecto.id)].widget.attrs['style'] = 'background-color: #99FF99'
                else:
                    form.fields["valCtrl_"+str(valorCorrecto.id)].widget.attrs['style'] = 'background-color: #FF9999'
            except ValueError:
                form.fields["valCtrl_"+str(valorCorrecto.id)].widget.attrs['style'] = 'background-color: #FF9999'
            form.fields["valCtrl_"+str(valorCorrecto.id)].widget.attrs['value'] = request.POST["valCtrl_"+str(valorCorrecto.id)]

    return render_to_response('tps/autoevaluacionValoresCtrl.html',
                              {'formValCtrl': form,
                               'valoresCorrectos': valoresCorrectos,
                               'tp': tp,
                               },
                              context_instance=RequestContext(request))

@login_required
def agregarAlumno(request):
    #Valida permisos
    if not request.user.has_perm('auth.change_user'):
        return HttpResponseForbidden()

    if request.method == 'POST':
        try:
            alumno = User.objects.get(username=request.POST['username'])
            alumnoInstance = alumno
        except User.DoesNotExist:
            alumnoInstance = User()

        form = AlumnoForm(request.POST, instance=alumnoInstance)
        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(settings.FACULTAD_PRINCIPAL_PAGE)
    else:
        form = AlumnoForm()
    return render_to_response('tps/forms.html',
                              {'formAlumno': form,},
                              context_instance=RequestContext(request))

def formatLegajoToString(legajo_id):
    legajo_id_str = re.sub('-|\/','',legajo_id)
    return legajo_id_str

def getNroLegajoAsignacion(legajo):
    return re.sub('^\w-{0,1}\d{3}|\/{0,1}\d{1}$', '', legajo)

def validateGroupProfesores(user):
    isProfesor = False
    for group in user.groups.all():
        if group.name == 'profesores':
            isProfesor = True
            break
    return isProfesor


import json

import faker
import pytest

from .utils import get_template, load_data_from_file, get_random_imgur_id

class ResponseFixture:
    FIXTURE_DIR = "tests/fixtures/"

    def __init__(self, status=200, reason="OK", content=b""):
        self.status = status
        self.reason = reason
        self.content = content

    def read(self):
        return self.content

    def json(self):
        return json.loads(self.content.decode("utf-8"))

@pytest.fixture
def imgur_common_200_response():
    content = load_data_from_file("common_200_response.json").encode("utf-8")
    return ResponseFixture(status=200, reason="OK", content=content)

@pytest.fixture
def imgur_image_get_200_response():
    template = get_template("imgur_image_get_200.json.j2")
    content = template.render(id=get_random_imgur_id()).encode("utf-8")
    return ResponseFixture(status=200, reason="OK", content=content)

@pytest.fixture
def imgur_image_post_200_response():
    template = get_template("imgur_image_post_200.json.j2")
    content = template.render(id=get_random_imgur_id()).encode("utf-8")
    return ResponseFixture(status=200, reason="OK", content=content)

@pytest.fixture
def imgur_comment_get_200_response():
    template = get_template("imgur_comment_get_200.json.j2")
    content = template.render(
        album_cover_id=get_random_imgur_id(), image_id=get_random_imgur_id()
    ).encode("utf-8")
    return ResponseFixture(status=200, reason="OK", content=content)

@pytest.fixture
def imgur_comment_post_200_response():
    template = get_template("imgur_comment_post_200.json.j2")
    content = template.render().encode("utf-8")
    return ResponseFixture(status=200, reason="OK", content=content)

@pytest.fixture
def imgur_comment_delete_200_response():
    template = get_template("imgur_comment_delete_200.json.j2")
    content = template.render().encode("utf-8")
    return ResponseFixture(status=200, reason="OK", content=content)

@pytest.fixture
def imgur_replies_get_200_response():
    fake = faker.Faker()
    template = get_template("imgur_comment_replies_get.json.j2")
    content = template.render(
        album_cover=get_random_imgur_id(),
        username=fake.user_name(),
        image_id=get_random_imgur_id(),
    ).encode("utf-8")
    return ResponseFixture(status=200, reason="OK", content=content)

@pytest.fixture
def general_json_dict():
    data = load_data_from_file("general_valid_json.json")
    return json.loads(data)

@pytest.fixture
def test_image():
    with open("tests/fixtures/assets/cat1.jpg", "rb") as image:
        return image.read()

@pytest.fixture
def title_fixture():
    fake = faker.Faker()
    return " ".join(fake.words(2)).capitalize()

@pytest.fixture
def description_fixture():
    fake = faker.Faker()
    return fake.text()


#! /usr/bin/env python3
import math
import numpy as np
import pylab as pl
from mpl_toolkits.mplot3d import Axes3D
#Defino la función
def z(x,y):
  return x**2-y**2

fig = pl.figure()
fig.suptitle('$z=x^2-y^2$')
#Datos del  primer gráfico
ax = fig.add_subplot(2, 1, 1, projection='3d')
x = np.linspace(-5,5,50)
y = np.linspace(-5,5,50)
x, y = np.meshgrid(x, y)
ax.plot_surface(x, y, z(x,y), rstride=1, cstride=1, cmap=pl.cm.hot)
ax.set_zlim(-25,25)

#Ahora veré las curvas de nivel
ax = fig.add_subplot(2, 1, 2)
ax.contourf(x, y, z(x,y), 8, alpha=.75, cmap=pl.cm.hot)
Numcurvas = 6
#Las curvas de nivel aparecerán en negro
C = ax.contour(x, y, z(x,y), Numcurvas, colors='black')
ax.clabel(C, inline=1, fontsize=10)

fig.savefig('Ejercicio8')
pl.show()


class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        i = 0
        while n !=0:
            if nums[i] ==0 :
                nums.append(0)
                del(nums[i])
            else: i+=1

            n-=1


from ...utils.function import parse_f
from ...utils.math import haveSameSign

@parse_f()
def secant(fx, epsilon=0.1, x0=-10, x1=10):
  while True:
    y0 = fx(x0)
    y1 = fx(x1)

    x2 = (x0 - (((x1-x0)/(y1 - y0)) * y0))
    y2 = fx(x2)

    if (y2 == 0):
      return x2

    if abs(x0 - x2) <= epsilon:
      return x2

    if haveSameSign(y0, y2):
      x0 = x2
    else:
      x1 = x2


import numpy as np
import seaborn as sns
import pandas
import matplotlib.pyplot as plt
import mcmc_tools
from scipy.stats import norm

# 回帰分析の各種テクニックを学んでいく

# 7.1 交互作用の解釈をしっかりしていく
# 積をとる場合、線形結合の項を変形することによって、
# モデリングの解釈が可能となる。
data_rental = pandas.read_csv('data-rental.txt')
print(data_rental.head())
print(data_rental.describe())

# データの図示
sns.scatterplot(
    x='Area',
    y='Y',
    data=data_rental
)
plt.show()
plt.close()

# AreaをもとにYを推定するモデリング
# Yは正規分布を仮定する Area をもとに平均を推定し、分散をノイズとして扱う。
Y = data_rental['Y']
Area = data_rental['Area']
N = len(Y)
Area_new = np.arange(10, 120, 1)
N_new = len(Area_new)

stan_data = {
    'Y': Y,
    'Area': Area,
    'N': N,
    'Area_new': Area_new,
    'N_new': N_new
}

# コンパイル
filename = '../model/model7-1'
mcmc_result = mcmc_tools.sampling(filename, stan_data, n_jobs=4)
mcmc_sample = mcmc_result.extract()

# 予測分布のプロット
df = pandas.DataFrame(mcmc_sample['Y_new'])
df.columns = Area_new
print(df)
qua = [0.025, 0.25, 0.50, 0.75, 0.975]
d_est = pandas.DataFrame()
for i in np.arange(len(df.columns)):
    for qu in qua:
        d_est[qu] = df.quantile(qu)

x = d_est.index
y1 = d_est[0.025].values
y2 = d_est[0.25].values
y3 = d_est[0.5].values
y4 = d_est[0.75].values
y5 = d_est[0.975].values

plt.fill_between(x,y1,y5,facecolor='blue',alpha=0.1)
plt.fill_between(x,y2,y4,facecolor='blue',alpha=0.5)
plt.plot(x,y3,'k-')
plt.scatter(data_rental["Area"],data_rental["Y"],c='b')
plt.show()
plt.close()

# 予測値と実績値のプロット
quantile = [10, 50, 90]
colname = ['p' + str(x) for x in quantile]
print(np.percentile(mcmc_result['Y_pred'], q=quantile, axis=0))
data_rental_pred = pandas.DataFrame(np.percentile(mcmc_result['Y_pred'], q=quantile, axis=0).T, columns=colname)
d = pandas.concat([data_rental, data_rental_pred], axis=1)

plt.plot([0,1800], [0,1800], 'k--', alpha=0.7)
plt.errorbar(d.Y, d.p50, yerr=[d.p50 - d.p10, d.p90 - d.p50],
    fmt='o', ecolor='gray', ms=10, alpha=0.8, marker='o', mfc='blue', capsize=3)
ax = plt.axes()
ax.set_aspect('equal')
plt.legend()
plt.xlabel('Observed', fontsize=12)
plt.ylabel('Predicted', fontsize=12)
plt.show()
plt.close()

# 分散の確認
# 実測値と中央値の差分でMAP推定、カーネル密度推定を行う
data_rental_mu = pandas.DataFrame(np.percentile(mcmc_result['mu'], q=quantile, axis=0).T, columns=colname)
d_mu = pandas.concat([data_rental, data_rental_mu], axis=1)
def ip_diff(d_mu):
    return d_mu.loc['Y'] - d_mu.loc['p50']
d_mu['ip'] = d_mu.apply(ip_diff, axis=1)
# MAP推定、カーネル密度推定seabornで実施
# 内部はscipyのnorm
sns.distplot(d_mu['ip'], bins=13, color='#123456', label='data',
             kde_kws={'label': 'kde', 'color': 'k'},
             fit=norm, fit_kws={'label': 'norm', 'color': 'red'},
             rug=False)
plt.legend()
plt.show()
plt.close()
# この予測では、カーネル密度推定の結果から、多峰性のノイズ分布となっていることがわかる。
# この理由は、応答変数の大きさとノイズの大きさを等しくあつかっているため、10倍のYに対する10倍のノイズは、推定結果に対して、
# 10倍の価値をもつようになるからである。


class Tree():
    def __init__(self, value):
        self.value = value
        self.right = None
        self.left = None

def sameBT(root1,root2):
    if root1 is None and root2 is None:
        return True
    if root1 is None or root2 is None:
        return False
    return root1.value == root2.value and \
    sameBT(root1.left, root2.left) and \
    sameBT(root1.right, root2.right)

root = Tree(10)
node1 = Tree(9)
node2 = Tree(8)
root.left = node1
root.right = node2

root2 = Tree(10)
node3 = Tree(90)
node4 = Tree(8)
root2.left = node3
root2.right = node4

a = sameBT(root,root)
print(a)

4. Trees and Graphs/PracticePrograms/sameBT.py


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.views import View
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView

from .models import Employee, Position
from .forms import EmployeeForm, PositionForm

def index(request):
    context = {
        'employees': Employee.objects.all(),
        'position_count': Position.objects.all().count()
    }
    return render(request, 'employee_list.html', context)

class Form(CreateView):
    template_name='form.html'
    model = Employee
    fields = '__all__'
    success_url = reverse_lazy('home')

def empUpdate(request, pk):
    employee = Employee.objects.get(id=pk)
    form = EmployeeForm(instance=employee)
    if request.method == 'POST':
        form = EmployeeForm(request.POST, instance=employee)
        if form.is_valid():
            form.save()
        return redirect('home')
    context = {'form': form}
    return render(request, 'employee_update.html', context)

def empDelete(request, pk):
    emp = Employee.objects.get(id=pk)
    if request.method == 'POST':
        emp.delete()
        return redirect('home')
    context = {'emp': emp}
    return render(request, 'employee_delete.html', context)

def positonList(request):
    position=Position.objects.all()
    context={'positions':position}
    return render(request, 'position_list.html', context)

def positionUpdate(request, pk):
    position=Position.objects.get(id=pk)
    form=PositionForm(instance=position)
    if request.method == 'POST':
        form=PositionForm(request.POST, instance=position)
        if form.is_valid():
            form.save()
        return redirect('position-list')
    context={'form':form}
    return render(request, 'position_update.html', context)

def positionDelete(request, pk):
    position=Position.objects.get(id=pk)
    if request.method == 'POST':
        position.delete()
        return redirect('position-list')
    context={'position':position}
    return render(request, 'position_delete.html', context)


import bpy

lang = {}
lang_en = {}
lang_fr = {}

lang_en['ERR001'] = "It's a syntax error"
lang_fr['ERR001'] = "C'est une erreur de syntaxe"

lang_en['ERR002'] = 'Unknow file'
lang_fr['ERR002'] = 'Fichier inconnu'

lang_en['ERR003'] = 'Armature information is missing'
lang_fr['ERR003'] = "Informations manquantes pour l'armature"

lang_en['ERR004'] = 'Keyframes are already saved'
lang_fr['ERR004'] = 'Les keyframes sont déjà sauvegardées'

lang_en['ERR005'] = 'Armatures are already freezed'
lang_fr['ERR005'] = 'Les armatures sont déjà gelées'

lang_en['ERR006'] = "Can't found keyframes"
lang_fr['ERR006'] = 'Aucune keyframe trouvée'

lang_en['ERR007'] = 'Mesh without ac file assignement'
lang_fr['ERR007'] = 'Mesh sans assignation de fichier AC3D'

lang_en['ERR008'] = 'Invalide keyframe'
lang_fr['ERR008'] = 'Keyframe invalide'

#----------------------------------------------------------------------------------------------------------------------------------
lang_en['MENTIT'] = 'Flightgear Tools Menu'
lang_fr['MENTIT'] = 'Flightgear boîte à outils'

#----------------------------------------------------------------------------------------------------------------------------------
lang_en['MEN000'] = 'Insert Keyframe Rotate'
lang_fr['MEN000'] = 'Insérer une keyframe de rotation'

lang_en['MEN001'] = 'Insert Keyframe Translate'
lang_fr['MEN001'] = 'Insérer une keyframe de translation'

lang_en['MEN002'] = 'Import (.xml)'
lang_fr['MEN002'] = 'Importer (.xml)'

lang_en['MEN003'] = 'Create animations'
lang_fr['MEN003'] = 'Créer les animations'

lang_en['MEN004'] = 'Apply edge-split'
lang_fr['MEN004'] = 'Exécute edge-split'

lang_en['MEN005'] = 'Select objects by property'
lang_fr['MEN005'] = 'Séléctionne objets par propriété'

lang_en['MEN006'] = 'Increase speed animation'
lang_fr['MEN006'] = 'Augmente la vitesse d\'animation'

lang_en['MEN007'] = 'Decrease speed animation'
lang_fr['MEN007'] = 'Diminue la vitesse d\'animation'

lang_en['MEN008'] = 'Assign object name'
lang_fr['MEN008'] = 'Initialise le nom ac3d'

lang_en['MEN009'] = 'Copy AC3D filename'
lang_fr['MEN009'] = 'Recopie le nom de fichier AC3D'

lang_en['MEN010'] = 'Armatures'
lang_fr['MEN010'] = 'Armatures'

lang_en['MEN011'] = 'Unwrap'
lang_fr['MEN011'] = 'Dépliage UV'

#----------------------------------------------------------------------------------------------------------------------------------
lang_en['MEN020'] = 'Along X'
lang_fr['MEN020'] = 'Le long de X'

lang_en['MEN021'] = 'Along Y'
lang_fr['MEN021'] = 'Le long de Y'

lang_en['MEN022'] = 'Along Z'
lang_fr['MEN022'] = 'Le long de Z'

#----------------------------------------------------------------------------------------------------------------------------------
lang_en['MEN040'] = 'Create rotate'
lang_fr['MEN040'] = 'Créer rotation'

lang_en['MEN041'] = 'Create translate'
lang_fr['MEN041'] = 'Créer translation'

lang_en['MEN042'] = 'Create spin'
lang_fr['MEN042'] = 'Créer spin'

lang_en['MEN043'] = 'Convert to rotate'
lang_fr['MEN043'] = 'Convertir en rotation'

lang_en['MEN044'] = 'Convert to translate'
lang_fr['MEN044'] = 'Convertir en translation'

lang_en['MEN045'] = 'Convert to spin'
lang_fr['MEN045'] = 'Convertir en spin'

lang_en['MEN046'] = 'Select related armatures'
lang_fr['MEN046'] = "Séléction relié à l'armature"

lang_en['MEN047'] = 'Select armature(s) by property'
lang_fr['MEN047'] = 'Séléctionne l(es) armature(s) par propriété'

lang_en['MEN048'] = 'Select object(s) by armature(s)'
lang_fr['MEN048'] = "Séléctionne le(s) objet(s) par armature(s)"

lang_en['MEN049'] = 'Copy xml file (active->selects)'
lang_fr['MEN049'] = 'Copie xml file (active->selects)'

lang_en['MEN050'] = 'Copy property (active->selects)'
lang_fr['MEN050'] = 'Copie propriété (active->selects)'

lang_en['MEN051'] = 'Reset Rotate'
lang_fr['MEN051'] = 'Reset'

lang_en['MEN052'] = 'Init Rotate'
lang_fr['MEN052'] = 'Initialise'

lang_en['MEN053'] = 'Freeze selected armature'
lang_fr['MEN053'] = 'Geler armature'

lang_en['MEN054'] = 'Save Keyframes and Reset'
lang_fr['MEN054'] = 'Sauver keyframes et reset'

lang_en['MEN055'] = 'Unfreeze'
lang_fr['MEN055'] = 'Dégeler'

lang_en['MEN056'] = 'Save Parent and Reset'
lang_fr['MEN056'] = 'Sauve parenté et reset'

lang_en['MEN057'] = 'Restore Parent '
lang_fr['MEN057'] = 'Restaurer parenté'

lang_en['MEN058'] = 'Select by file'
lang_fr['MEN058'] = 'Séléction par fichier'

lang_en['MEN059'] = 'Reset all armatures'
lang_fr['MEN059'] = 'Raz toutes les armatures'

lang_en['MEN060'] = 'Insert Keyframe Rotate AT'
lang_fr['MEN060'] = 'Insérer une keyframe de rotation à'

lang_en['MEN061'] = 'Insert Keyframe Translate AT'
lang_fr['MEN061'] = 'Insérer une keyframe de translation à'

#----------------------------------------------------------------------------------------------------------------------------------
lang_en['MEN070'] = 'Along X'
lang_fr['MEN070'] = 'Axe X'

lang_en['MEN071'] = 'Along Y'
lang_fr['MEN071'] = 'Axe Y'

lang_en['MEN072'] = 'Along Z'
lang_fr['MEN072'] = 'Axe Z'

lang_en['MEN073'] = 'Along -X'
lang_fr['MEN073'] = 'Axe -X'

lang_en['MEN074'] = 'Along -Y'
lang_fr['MEN074'] = 'Axe -Y'

lang_en['MEN075'] = 'Along -Z'
lang_fr['MEN075'] = 'Axe -Z'

lang_en['MEN076'] = 'Along  XY'
lang_fr['MEN076'] = 'Axe XY'

lang_en['MEN077'] = 'Along XZ'
lang_fr['MEN077'] = 'Axe XZ'

lang_en['MEN078'] = 'Along YZ'
lang_fr['MEN078'] = 'Axe YZ'

lang_en['MEN079'] = 'Along XYZ '
lang_fr['MEN079'] = 'Axe XYZ'

#----------------------------------------------------------------------------------------------------------------------------------

lang_en['UI001'] = 'Save AC3D file'
lang_fr['UI001'] = 'Sauvegarde le fichier AC3D'

lang_en['UI002'] = 'Save XML file'
lang_fr['UI002'] = 'Sauvegarde le fichier XML'

lang_en['UI003'] = 'Show objects related to selected object'
lang_fr['UI003'] = 'Afficher les objets liés à l\'objet séléctionné'

lang_en['UI004'] = 'Show all objects'
lang_fr['UI004'] = 'Afficher tous les objets'

lang_en['UI005'] = 'AC3D File'
lang_fr['UI005'] = 'Fichier AC3D'

lang_en['UI006'] = 'JSBSim File'
lang_fr['UI006'] = 'Fichier JSBSim'

lang_en['UI007'] = 'Camera File'
lang_fr['UI007'] = 'Fichier caméra'

lang_en['UI008'] = 'Property'
lang_fr['UI008'] = 'Propriété'

lang_en['UI009'] = 'Property:'
lang_fr['UI009'] = 'Propriété:'

lang_en['UI010'] = 'XML File'
lang_fr['UI010'] = 'Fichier XML'

lang_en['UI011'] = 'Show objects related to selected animation'
lang_fr['UI011'] = 'Afficher tous les objets liés à l\'animation séléctionné'

lang_en['UI012'] = 'Parent(s):'
lang_fr['UI012'] = 'Parent(s):'

lang_en['UI013'] = 'Child object(s):'
lang_fr['UI013'] = 'Objet(s) enfant:'

lang_en['UI014'] = 'Filename'
lang_fr['UI014'] = 'Fichier'

lang_en['UI015'] = 'Mesh Name'
lang_fr['UI015'] = 'Nom d\'objet'

lang_en['UI016'] = 'Attribute'
lang_fr['UI016'] = 'Attribue'

lang_en['UI017'] = 'Family'
lang_fr['UI017'] = 'Famille'

lang_en['UI018'] = 'Value'
lang_fr['UI018'] = 'Valeur'

lang_en['UI019'] = 'Index'
lang_fr['UI019'] = 'Index'

lang_en['UI020'] = 'Factor'
lang_fr['UI020'] = 'Facteur'

lang_en['UI021'] = 'Type'
lang_fr['UI021'] = 'Type'

lang_en['UI022'] = 'Min'
lang_fr['UI022'] = 'Min'

lang_en['UI023'] = 'Max'
lang_fr['UI023'] = 'Max'

lang_en['UI024'] = 'Duration'
lang_fr['UI024'] = 'Durée'

lang_en['UI025'] = 'Include manual write'
lang_fr['UI025'] = 'Inclure les modifivations manuelles'

lang_en['UI026'] = 'To disk'
lang_fr['UI026'] = 'Vers le disque'

lang_en['UI027'] = '??'
lang_fr['UI027'] = '??'

lang_en['UI028'] = '??'
lang_fr['UI028'] = '??'

lang_en['UI029'] = '??'
lang_fr['UI029'] = '??'

lang_en['UI030'] = '??'
lang_fr['UI030'] = '??'

lang_en['UI031'] = 'Insert keyframe between [%0.2f,%0.2f]'
lang_fr['UI031'] = 'Insérer keyframe entre [%0.2f,%0.2f]'

lang_en['UI032'] = 'Insert keyframe between [%0.2f,%0.2f]'
lang_fr['UI032'] = 'Insérer keyframe entre [%0.2f,%0.2f]'

#----------------------------------------------------------------------------------------------------------------------------------

lang_en['DOC001'] = 'Assign AC3D filename from active object to selected object(s)'
lang_fr['DOC001'] = 'Assigne le nom du fichier AC3D de l\'objet actif a(ux) objet(s) séléctionné(s)'

lang_en['DOC002'] = 'Select AC3D file destination'
lang_fr['DOC002'] = 'Sélection du fichier AC3D de destination'

lang_en['DOC003'] = 'Assign object name to Mesh Name for selected objects'
lang_fr['DOC003'] = 'Assigne les noms d\'objets dans Nom d\'objet pour le(s) objet(s) séléctionné(s)'

lang_en['DOC004'] = 'Save AC3D file (create it automatically if doesn\'t exist)'
lang_fr['DOC004'] = 'Sauvegarde le fichier AC3D (créer automatiquement si inexistant)'

lang_en['DOC005'] = 'Assign XML filename from active armature to selected armature(s)'
lang_fr['DOC005'] = 'Assigne le nom du fichier XML de l\'armature active pour le(s) armature(s) séléctionné(s)'

lang_en['DOC006'] = 'Select XML file destination'
lang_fr['DOC006'] = 'Sélection du fichier XML de destination'

lang_en['DOC007'] = 'Select JSBSim (XML) file destination'
lang_fr['DOC007'] = 'Sélection du fichier JSBSim (XML) de destination'

lang_en['DOC008'] = 'Save XML file (create it automatically if doesn\'t exist)'
lang_fr['DOC008'] = 'Sauvegarde le fichier XML (créer automatiquement si inexistant)'

lang_en['DOC009'] = 'Unwrap selected object for 4 faces'
lang_fr['DOC009'] = 'Dépliage de l\'objet séléctionné en 4 faces'

lang_en['DOC010'] = 'Apply edge split to selected object(s)'
lang_fr['DOC010'] = 'Applique un edge split a(ux) objet(s) séléctionné(s)'

lang_en['DOC011'] = 'Increase speed animation x2'
lang_fr['DOC011'] = 'Augmente la vitesse d\'animation x2'

lang_en['DOC012'] = 'Decrease speed animation x2'
lang_fr['DOC012'] = 'Diminue la vitesse d\'animation x2'

lang_en['DOC013'] = 'Create armature type "translate" on selected axis'
lang_fr['DOC013'] = 'Crée une armature de type "translate" pour l\'axe donné'

lang_en['DOC014'] = 'Create armature type "rotate" on selected axis'
lang_fr['DOC014'] = 'Crée une armature de type "rotate" pour l\'axe donné'

lang_en['DOC015'] = 'Create armature type "spin" on selected axis'
lang_fr['DOC015'] = 'Crée une armature de type "spin" pour l\'axe donné'

lang_en['DOC016'] = 'Compute XML animations loaded from the XML import, press Alt+a to run animations'
lang_fr['DOC016'] = 'Calcul les animations XML chargées depuis l\'import XML, pressez Alt+a pour démarrer les animations'

lang_en['DOC017'] = 'Insert first and last keyframe'
lang_fr['DOC017'] = 'Insere la première et dernière keyframe'

lang_en['DOC018'] = '?????????'
lang_fr['DOC018'] = '?????????'

lang_en['DOC019'] = 'Convert selected armature(s) as armature type "rotate"'
lang_fr['DOC019'] = 'Converti la(es) armature(s) séléctionné(s) en armature de type "rotate"'

lang_en['DOC020'] = 'Convert selected armature(s) as armature type "translate"'
lang_fr['DOC020'] = 'Converti la(es) armature(s) séléctionné(s) en armature de type "translate"'

lang_en['DOC021'] = 'Convert selected armature(s) as armature type "spin"'
lang_fr['DOC021'] = 'Converti la(es) armature(s) séléctionné(s) en armature de type "spin"'

lang_en['DOC022'] = 'Freeze selected armature(s)'
lang_fr['DOC022'] = 'Geler la(es) armature(s) sélectionné(s)'

lang_en['DOC023'] = 'Unfreeze selected armature(s)'
lang_fr['DOC023'] = 'Dégeler la(es) armature(s) séléctionné(s)'

lang_en['DOC024'] = 'Select objects and armatures by file'
lang_fr['DOC024'] = 'Séléctionne les objets et armatures d\'un fichier'

lang_en['DOC025'] = '?????????'
lang_fr['DOC025'] = '?????????'

lang_en['DOC026'] = '?????????'
lang_fr['DOC026'] = '?????????'

lang_en['DOC027'] = '?????????'
lang_fr['DOC027'] = '?????????'

lang_en['DOC028'] = 'Assign FG property from active armature to selected armature(s)'
lang_fr['DOC028'] = 'Assigne la propriété FG de l\'armature active a(ux) armature(s) séléctionné(s)'

lang_en['DOC029'] = 'Select all objects and armatures with same property than active object/armature'
lang_fr['DOC029'] = 'Séléctionne tous les objets et armatures utilisant la même propriété que l\'objet/armature actif'

lang_en['DOC030'] = 'Show all objects with the same property than active object/armature and hide other'
lang_fr['DOC030'] = 'Affiche tous les objets utilisant la même propriété que l\'objet/l\'armature active et cache les autres'

lang_en['DOC031'] = 'Show all objects/armatures'
lang_fr['DOC031'] = 'Affiche tous les objets/armatures'

lang_en['DOC032'] = 'Insert keyframe type "rotate" with linear interpolation'
lang_fr['DOC032'] = 'Insère une keyframe de type "rotate" avec une interpolation linéaire'

lang_en['DOC033'] = 'Insert keyframe type "translate" with linear interpolation'
lang_fr['DOC033'] = 'Insère une keyframe de type "translate" avec une interpolation linéaire'

lang_en['DOC034'] = 'Select all armatures with same FG property'
lang_fr['DOC034'] = 'Séléctionne toutes les armatures utilisant la propriété FG'

lang_en['DOC035'] = 'Select all objects related to selected armature(s)'
lang_fr['DOC035'] = 'Séléctionne tous les objets relié a(ux) armature(s) séléctionné(s)'

lang_en['DOC036'] = 'Path of the AC3D file (.ac)'
lang_fr['DOC036'] = 'Chemin du fichier AC3D (.ac)'

lang_en['DOC037'] = 'Mesh name in the AC3D file'
lang_fr['DOC037'] = 'Nom de l\'objet dans le fichier AC3D'

lang_en['DOC038'] = 'Path of the JSBSim file (.xml)'
lang_fr['DOC038'] = 'Chemin du fichier JSBSim (.xml)'

lang_en['DOC039'] = 'JSBSim attribute'
lang_fr['DOC039'] = 'Attribue JSBSim'

lang_en['DOC040'] = 'Path of the Camera file (.xml)'
lang_fr['DOC040'] = 'Chemin du fichier Camera (.xml)'

lang_en['DOC041'] = 'Name of view'
lang_fr['DOC041'] = 'Nom de la vue'

lang_en['DOC043'] = 'Property family'
lang_fr['DOC043'] = 'Famille de propriété'

lang_en['DOC044'] = 'Family value'
lang_fr['DOC044'] = 'Valeur de la famille'

lang_en['DOC045'] = 'Value used for XML file'
lang_fr['DOC045'] = 'Valeur utiliser pour le fichier XML'

lang_en['DOC046'] = 'Write file to disk'
lang_fr['DOC046'] = 'Écrit le fichier sur le disque'

lang_en['DOC047'] = 'Duration of animation'
lang_fr['DOC047'] = 'Durée de l\'animation'

lang_en['DOC048'] = 'Index X of the property "/engines/engine[X]/throttle"'
lang_fr['DOC048'] = 'Indice X de la propriété "/engines/engine[X]/throttle"'

lang_en['DOC049'] = 'Minimum value of the property'
lang_fr['DOC049'] = 'Valeur minimum de la propriété'

lang_en['DOC050'] = 'Maximum value of the property'
lang_fr['DOC050'] = 'Valeur maximum de la propriété'

lang_en['DOC051'] = 'Value of <factor> tags'
lang_fr['DOC051'] = 'Valeur de la balise <factor>'

lang_en['DOC052'] = 'Path of the XML file (.xml)'
lang_fr['DOC052'] = 'Chemin du fichier XML (.xml)'

lang_en['DOC053'] = '??'
lang_fr['DOC053'] = '??'

lang_en['DOC054'] = '??'
lang_fr['DOC054'] = '??'

lang_en['DOC055'] = '??'
lang_fr['DOC055'] = '??'

lang_en['DOC056'] = '??'
lang_fr['DOC056'] = '??'

lang_en['DOC057'] = '??'
lang_fr['DOC057'] = '??'

lang_en['DOC059'] = 'Set transform to 0 (no destructive operation)'
lang_fr['DOC059'] = 'Remet à zero toutes les armatures (operation non destructive)'

#----------------------------------------------------------------------------------------------------------------------------------

user_lang = bpy.context.user_preferences.system.language

if user_lang == 'DEFAULT':
	lang = lang_en
elif user_lang == 'en_EN':
	lang = lang_en
elif user_lang == 'fr_FR':
	lang = lang_fr
else:
	lang = lang_en


# -- coding: utf-8 --
# @Time : 2022/8/25
# @Author : ykk648
# @Project : https://github.com/ykk648/AI_power
import cv2
from cv2box import CVImage, CVVideoLoader
from cv2box.cv_gears import Linker, Consumer, CVVideoThread, Queue

from face_lib.face_restore import GFPGAN
from face_lib.face_detect_and_align import FaceDetect5Landmarks
from face_lib.face_parsing import FaceParsing

class FaceDetectThread(Linker):
    def __init__(self, queue_list: list):
        super().__init__(queue_list, fps_counter=True)
        self.fd = FaceDetect5Landmarks(mode='scrfd_500m')

    def forward_func(self, something_in):
        frame = something_in[0]
        bboxes_scrfd, kpss_scrfd = self.fd.get_bboxes(frame, min_bbox_size=64)
        # self.fd.draw_face()
        face_image_, mat_rev_, roi_box_ = self.fd.get_single_face(crop_size=512, mode='mtcnn_512',
                                                                  apply_roi=True)  # mtcnn_512 arcface_512 arcface
        return [frame, face_image_, mat_rev_, roi_box_]

class FaceRestoreThread(Linker):
    def __init__(self, queue_list: list):
        super().__init__(queue_list, fps_counter=True)
        self.gfp = GFPGAN(model_type='GFPGANv1.4', provider='gpu')

    def forward_func(self, something_in):
        src_face_image_ = something_in[1]
        face_restore_out_ = self.gfp.forward(src_face_image_)
        return [face_restore_out_] + something_in

class FaceParseThread(Linker):
    def __init__(self, queue_list: list):
        super().__init__(queue_list, fps_counter=True)
        self.fpt = FaceParsing(model_name='face_parse_onnx', provider='gpu')

    def forward_func(self, something_in):
        face_parse_in_ = something_in[0] * 255
        face_parse_out_ = self.fpt.forward(face_parse_in_)
        face_mask_ = self.fpt.get_face_mask(mask_shape=(512, 512))
        return something_in + [face_mask_]

class FaceReverseThread(Consumer):
    def __init__(self, queue_list: list, video_writer):
        super().__init__(queue_list, fps_counter=True)
        self.gfp = GFPGAN(model_type='GFPGANv1.4', provider='gpu')
        self.video_writer = video_writer

    def forward_func(self, something_in):
        face_restore_out = something_in[0]
        src_img_in = something_in[1]
        mat_rev = something_in[3]
        roi_box = something_in[4]
        face_mask_ = something_in[5]
        restore_roi = CVImage(None).recover_from_reverse_matrix(face_restore_out,
                                                                src_img_in[roi_box[1]:roi_box[3],
                                                                roi_box[0]:roi_box[2]],
                                                                mat_rev, img_fg_mask=face_mask_)
        src_img_in[roi_box[1]:roi_box[3], roi_box[0]:roi_box[2]] = restore_roi

        # CVImage(src_img_in).show(1)
        self.video_writer.write(src_img_in)

if __name__ == '__main__':
    video_in_p = ''
    video_out_p = ''

    with CVVideoLoader(video_in_p) as cvvl_dummy:
        videoWriter = cv2.VideoWriter(video_out_p, cv2.VideoWriter_fourcc(*'mp4v'), cvvl_dummy.fps, cvvl_dummy.size)

    q0 = Queue(2)
    q1 = Queue(2)
    q2 = Queue(2)
    q3 = Queue(2)

    cvvl = CVVideoThread(video_in_p, [q0])
    fdt = FaceDetectThread([q0, q1])
    frt = FaceRestoreThread([q1, q2])
    fpt = FaceParseThread([q2, q3])
    fret = FaceReverseThread([q3], videoWriter)

    threads_list = [cvvl, fdt, frt, fpt, fret]

    for thread_ in threads_list:
        thread_.start()

    for thread_ in threads_list:
        thread_.join()

    videoWriter.release()


def solution(s):
    answer = []

    lists = []
    sets = s[2:-2].split('},{')

    for st in sets:
        lists.append(list(map(int, st.split(','))))

    lists = sorted(lists, key=lambda x: len(x))

    for lst in lists:
        for item in lst:
            if not item in answer:
                answer.append(item)

    return answer


from collections import Counter
from collections import defaultdict
class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        # set up columns to for validity checks
        row, column, square = {}, {}, {}
        # set up helper Arrays
        rowHelperArray, colHelperArray, squareHelperArray = [], [], []

        # count numbers in row and column
        for i in range(len(board)):
            for j in range (len(board)):
                if board[i][j] != '.':
                     rowHelperArray.append(board[i][j])
                if board[j][i] != '.':
                    colHelperArray.append(board[j][i])
            column[str(i)], row[str(i)] = Counter(colHelperArray), Counter(rowHelperArray)
            rowHelperArray, colHelperArray = [], []

        # count numbers in 3x3 square
        for k in range(9):
            if k % 3 == 0:
                for l in range(9):
                    if (board[k + 0][l] != '.'):
                        squareHelperArray.append(board[k + 0][l])
                    if (board[k + 1][l] != '.'):
                        squareHelperArray.append(board[k + 1][l])
                    if (board[k + 2][l] != '.'):
                        squareHelperArray.append(board[k + 2][l])
                    if (l == 2 or l == 5 or l == 8):
                        square[str(int(k + ((l+1)/3) - 1))] = Counter(squareHelperArray)
                        squareHelperArray = []
        # divide the sum of counter dictionary by length of counter dicitionary to determine
        # if each requirement is met
        for c in range(9):
            rowCounterSum, rowCounterLength  = sum(row[str(c)].values()), len(row[str(c)].values())
            columnCounterSum, columnCounterLength = sum(column[str(c)].values()), len(column[str(c)].values())
            squareCounterSum, squareCounterLength = sum(square[str(c)].values()), len(square[str(c)].values())

            if (rowCounterLength != 0 and (rowCounterSum/rowCounterLength != 1)):
                return False
            if (columnCounterLength != 0 and (columnCounterSum/columnCounterLength != 1)):
                return False
            if (squareCounterLength != 0 and (squareCounterSum/squareCounterLength != 1)):
                return False
            elif (c == 8):
                return True


from urllib.request import urlopen
from bs4 import BeautifulSoup
import pyexcel
from collections import OrderedDict

# 1. Connection
url = "https://dantri.com.vn"
conn = urlopen(url)
raw_data = conn.read()
html_content = raw_data.decode('utf8')

with open("dantri.html","wb") as f:
    f.write(raw_data)

# 2. Find ROI (region of interest)
soup = BeautifulSoup(html_content,"html.parser")
ul = soup.find('ul','ul1 ulnew') # attribute "class" ko can type ra

# 3.Extract ROI
li_list = ul.find_all('li')
Result =[]
for li in li_list:
    h4 = li.h4
    a = h4.a
    title = a.string.strip()
    link  = url + a['href']
    phantu = OrderedDict({"Title":title,"Link":link})
    Result.append(phantu)

# pyexcel.save_as(records=Result, dest_file_name="test.xlsx")


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

while True:

    ch = list(input().split())

    repeat = {}

    if ch[0] == 'END':
        break

    # 반복 횟수 체크 하기
    for i in range(len(ch)):
        if ch[i] not in repeat:
            repeat[ch[i]] = 1
        else:
            repeat[ch[i]] += 1

    result = []

    # sort 함수 사용하기 위해 리스트로 바꾸기
    for k, v in repeat.items():
        result.append((k, v))

    result.sort() # 알파벳 순 정렬

    # 출력
    for k, v in result:
        print('{} : {}'.format(k, v))