#Grupo PHP
#Kevin Cevallos
#María Camila Navarro
#Joffre Ramírez

import ply.lex as lex
reserved = {
    'if': 'IF',
    'else': 'ELSE',
    'elseif': 'ELSEIF',
    #'boolean': 'BOOLEAN',
    #'float': 'FLOAT',
    #'string': 'STRING',
    'null': 'NULL',
    'array': 'ARRAY',
    #'object': 'OBJECT',
    'break': 'BREAK',
    'continue': 'CONTINUE',
    'return': 'RETURN',
    'for each': 'FOREACH',
    'echo': 'ECHO',
    'print': 'PRINT',
    'print_r': 'PRINT_R',
    'var_dump': 'VAR_DUMP',
    'fgets': 'FGETS',
    'fread': 'FREAD',
    'fscanf': 'FSCANF',
    'fpassthru': 'FPASSTHRU',
    'fgetcsv': 'FGETCSV',
    'fgetc': 'FGETC',
    'file_get_contents': 'FILE_GET_CONTENTS',
    'readfile': 'READFILE',
    'file': 'FILE',
    'parse_ini_file': 'PARSE_INI_FILE',
    'implode': 'IMPLODE',
    'explode': 'EXPLODE',
    'new':'NEW',
    'class':'CLASS',
    'count': 'COUNT',
    'sizeof': 'SIZEOF',
    'array_push': 'ARRAY_PUSH',
    'sort': 'SORT',
    'asort': 'ASORT',
    'ksort': 'KSORT',
    'unset': 'UNSET',
    'var_export': 'VAR_EXPORT',
    'shuffle': 'SHUFFLE',
    'array_merge': 'ARRAY_MERGE',
    'array_search': 'ARRAY_SEARCH',
    'array_rand': 'ARRAY_RAND',
    'array_chunk': 'ARRAY_CHUNK',
    'str_split': 'STR_SPLIT',
    'preg_split': 'PREG_SPLIT',
    'array_unique': 'ARRAY_UNIQUE',
    'function' : 'FUNCTION',
    'while' : 'WHILE',
    'as' : 'AS'
}

tokens =(
    [

    #Operadores Matemáticos
    'PLUS',
    'MINUS',
    'TIMES',
    'DIVIDE',
    'EQUALS',
    'MODULO',

    #Operadores Lógicos
    'AND',
    'OR',
    'XOR',
    'NOT',

    #Símbolos
    'LPAREN',
    'RPAREN',
    #'PEIROT',
    'RCORCHET',
    'LCORCHET',
    'OBJECT_OPERATOR',
    'COMA',
    'OPEN',
    'CLOSE',
    'END',
    'FLECHA',

    #Variable
    'ID',

    #Número
    'NUMBER',
    'DECIMAL',

    #Valor Boolean
    'TRUE',
    'FALSE',

    #Cadena de texto
    'TEXT',

     #Operadores Comparación
     'MAYORQUE',
     'MENORQUE',
     'IS_EQUAL',
     'IS_IDENTICAL',
     'IS_NOT_EQUAL',
     'IS_NOT_IDENTICAL',
     'IS_GREATER_OR_EQUAL',
     'IS_SMALLER_OR_EQUAL',
     'SPACESHIP',

     #Nombre de Funciones
     'FNOMBRE'
        ] + list(reserved.values()))

#Operadores Matemáticos
t_MODULO=r'%'
t_PLUS=r'\+'
t_MINUS=r'-'
t_TIMES=r'\*'
t_DIVIDE=r'/'
t_EQUALS = r'='

#Operadores Lógicos
t_AND = r'and'
t_OR = r'or'
t_XOR = r'xor'
t_NOT = r'!'

#Símbolos
t_OBJECT_OPERATOR=r'->'
t_LPAREN=r'\('
t_RPAREN=r'\)'
t_END = r';'
t_TEXT = r'".*"'
t_FLECHA = r'=>'

#t_PEIROT = r'\.'
t_OPEN = r'<\?php'
t_CLOSE = r'\?>'
t_RCORCHET=r'\}'
t_LCORCHET=r'\{'
t_COMA=r','

#Variable
t_ID = r'(\$([a-z]|[A-Z]))([a-zA-Z0-9]+)?'

#Valor Boolean
#t_TRUE = r'true'
#t_FALSE = r'false'

#Operadores Comparación
t_MAYORQUE = r'>'
t_MENORQUE = r'<'
t_IS_EQUAL = r'=='
t_IS_IDENTICAL = r'==='
t_IS_NOT_EQUAL= r'!='
t_IS_NOT_IDENTICAL= r'!=='
t_IS_GREATER_OR_EQUAL=r'>='
t_IS_SMALLER_OR_EQUAL=r'<='
t_SPACESHIP = r'<=>'

t_ignore = ' \t'

#Número
def t_DECIMAL(t):
    r'\d+\.\d+'
    t.value = float(t.value)
    return t
def t_NUMBER(t):
    r'\d+'
    t.value = int(t.value)
    return t

#Cadena de texto

#Palabras reservadas
def t_CLASS(t):
    r'class'
    return t
def t_ECHO(t):
    r'echo'
    return t
def t_NEW(t):
    r'new'
    return t
'''
def t_BOOLEAN(t):
    r'boolean'
    return t
def t_STRING(t):
    r'string'
    return t
'''
def t_TRUE(t):
    r'true'
    return t
def t_FALSE(t):
    r'false'
    return t
def t_NULL(t):
    r'null'
    return t
'''
def t_OBJECT(t):
    r'object'
    return t
'''
def t_BREAK(t):
    r'break'
    return t
def t_CONTINUE(t):
    r'continue'
    return t
def t_RETURN(t):
    r'return'
    return t
def t_FUNCTION(t):
    r'function'
    return t
def t_AS(t):
    r'as'
    return t
#Sentencia if
def t_IF(t):
    r'if'
    return t
def t_ELSE(t):
    r'else'
    return t
def t_ELSEIF(t):
    r'elseif'
    return t

#Lazo
def t_FOREACH(t):
    r'foreach'
    return t

def t_WHILE(t):
    r'while'
    return t

#Funciones print
def t_PRINT(t):
    r'print'
    return t
def t_PRINT_R(t):
    r'print_r'
    return t
def t_VAR_DUMP(t):
    r'var_dump'
    return t

#Funciones
def t_FGETS(t):
    r'fgets'
    return t
def t_FREAD(t):
    r'fread'
    return t
def t_FSCANF(t):
    r'fscanf'
    return t
def t_FPASSTHRU(t):
    r'fpassthru'
    return t
def t_FGETCSV(t):
    r'fgetcsv'
    return t
def t_FGETC(t):
    r'fgetc'
    return t
def t_FILE_GET_CONTENTS(t):
    r'file_get_contents'
    return t
def t_READFILE(t):
    r'readfile'
    return t
def t_FILE(t):
    r'file'
    return t
def t_PARSE_INI_FILE(t):
    r'parse_ini_file'
    return t
def t_IMPLODE(t):
    r'implode'
    return t
def t_EXPLODE(t):
    r'explode'
    return t
def t_ARRAY(t):
    r'array'
    return t
def t_COUNT(t):
    r'count'
    return t
def t_SIZEOF(t):
    r'sizeof'
    return t
def t_ARRAY_PUSH(t):
    r'array_push'
    return t
def t_SORT(t):
    r'sort'
    return t
def t_ASORT(t):
    r'asort'
    return t
def t_KSORT(t):
    r'ksort'
    return t
def t_UNSET(t):
    r'unset'
    return t
def t_VAR_EXPORT(t):
    r'var_export'
    return t
def t_SHUFFLE(t):
    r'shuffle'
    return t
def t_ARRAY_MERGE(t):
    r'array_merge'
    return t
def t_ARRAY_SEARCH(t):
    r'array_search'
    return t
def t_ARRAY_RAND(t):
    r'array_rand'
    return t
def t_ARRAY_CHUNK(t):
    r'array_chunk'
    return t
def t_STR_SPLIT(t):
    r'str_split'
    return t
def t_PREG_SPLIT(t):
    r'preg_split'
    return t
def t_ARRAY_UNIQUE(t):
    r'array_unique'
    return t

#Nombre de funciones
def t_FNOMBRE(t):
    r'(?!or|and|xor)([a-z]|[A-Z])([a-zA-Z0-9_]+)?'
    return t

def t_error(t):
    print("No es reconocido '%s'"%t.value[0])
    t.lexer.skip(1)

def t_newline(t):
    r'\n+'
    t.lexer.lineno += len(t.value)

lexer=lex.lex()

def analizar(dato):
    lexer.input(dato)
    while True:
        tok =lexer.token()
        if not tok:
            break
        print(tok)

archivo= open("archivo.txt")
for linea in archivo:
    #print(">>"+linea)
    #analizar(linea)
    if len(linea)==0:
        break
def ImprimirAnalizar(dato):
    texto= dato.split("\n")
    cadena=""
    for i in texto:
        cadena+= "-> "+i
        lexer.input(i)
        while True:
            tok = lexer.token()
            if not tok:
                break
            cadena+="\n"
            cadena+=str(tok)
        cadena+="\n"
    return cadena


import tkinter as tk
import tkFont
from tkinter import font

def list_fonts():
    font.families()
    for f in list(font.families()):
        print("Font: ", f)

root = tk.Tk()
btn = tk.Button(root, text="List families", command=list_fonts)
btn.grid(row=0, column=0)
root.mainloop()


def new_filter(lines, index, inverted):
    c = 0
    c_1 = 0
    for i in lines:
        c += 1
        if i[index] == "1":
            c_1 += 1

    if c_1 + c_1 >= c:
        print("get 1")
        if inverted:
            f_v = "0"
        else:
            f_v = "1"

    else:
        if inverted:
            f_v = "1"
        else:
            f_v = "0"

    n_l = []
    for i in lines:
        if i[index] == f_v:
            n_l.append(i)

    return n_l

if __name__ == '__main__':

    l = []
    filename = "input.txt"

    lines = []
    for line in open(filename, "r").readlines():
        line = line[:-1]
        lines.append(line)

    a_l = [i for i in lines]
    b_l = [i for i in lines]
    i  = 0
    while True:
        a_l = new_filter(a_l, i, False)
        i += 1
        if len(a_l) == 1:
            break
    i  = 0

    while True:
        b_l = new_filter(b_l, i, True)
        i += 1
        if len(b_l) == 1:
            break

    print(int(a_l[0], 2) * int(b_l[0], 2))


import csv
import datetime
import pathlib
from typing import Generator

import click

from case_rate._types import Cases, CaseTesting, PathLike
from case_rate.sources._utilities import download_file
from case_rate.storage import InputSource

def _to_date(date: str) -> datetime.date:
    '''Converts a date string into a date object.

    Parameters
    ----------
    date : str
        input date string of the form "DD-MM-YYYY"

    Returns
    -------
    datetime.date
        output ``date`` object
    '''
    dt = datetime.datetime.strptime(date, '%d-%m-%Y')
    return dt.date()

def _to_int(number: str) -> int:
    '''Converts a numerical string into an integer.

    This performs an extra check to see if the input string is ``''``.  This is
    then treated as a zero.  Anything else will result in a ``ValueError``.

    Parameters
    ----------
    number : str
        input string as a number

    Returns
    -------
    int
        the string's integer value

    Throws
    ------
    :exc:`ValueError`
        if the string is not actually a number
    '''
    if len(number) == 0:
        return 0

    if number == 'N/A':
        return 0

    try:
        count = int(number)
    except ValueError:
        count = int(float(number))

    return count

class PublicHealthAgencyCanadaSource(InputSource):
    '''Uses reporting data published by the PHAC.

    This input source uses a CSV file that's regularly updated by the Public
    Health Agency of Canada (PHAC).  The default source is
    https://health-infobase.canada.ca/src/data/covidLive/covid19.csv.  The
    data source will link back to the original PHAC site rather than to the
    file.
    '''
    def __init__(self, path: PathLike, url: str, info: str,
                 update: bool = True):
        '''
        Parameters
        ----------
        path : path-like object
            the path (on disk) where the CSV file is located
        url : str
            the URL to the Government of Canada's COVID-19 report
        info : str optional
            the URL to the main information path (not the CSV file)
        update : bool, optional
            if ``True`` then updates an existing CSV file to the latest version
        '''
        path = pathlib.Path(path) / 'covid19.csv'
        if path.exists():
            if update:
                click.echo('Updating PHAC COVID-19 report.')
                download_file(url, path)
        else:
            click.echo('Accessing PHAC COVID-19 report.')
            download_file(url, path)

        self._info = info
        self._path = path

    @classmethod
    def name(cls) -> str:
        return 'public-health-agency-canada'

    @classmethod
    def details(cls) -> str:
        return 'Public Health Agency of Canada - Current Situation'

    def url(self) -> str:
        return self._info

    def cases(self) -> Generator[Cases, None, None]:
        with self._path.open() as f:
            contents = csv.DictReader(f)
            for entry in contents:
                if entry['prname'] == 'Canada':
                    continue

                # NOTE: PHAC doesn't report resolved cases as of 2022-08-26
                yield Cases(
                    date=_to_date(entry['date']),
                    province=entry['prname'],
                    country='Canada',
                    confirmed=_to_int(entry['totalcases']),
                    resolved=-1,
                    deceased=_to_int(entry['numdeaths'])
                )

    def testing(self) -> Generator[CaseTesting, None, None]:
        with self._path.open() as f:
            contents = csv.DictReader(f)
            for entry in contents:
                if entry['prname'] == 'Canada':
                    continue

                # NOTE: PHAC doesn't report testing counts as of 2022-08-26
                yield CaseTesting(
                    date=_to_date(entry['date']),
                    province=entry['prname'],
                    country='Canada',
                    tested=-1,
                    under_investigation=-1
                )


# import the argmax function from numpy to get the index of the maximum value in an array
from numpy import argmax
# import the mnist dataset from keras, which contains 60,000 images of handwritten digits for training and 10,000 images for testing
from keras.datasets import mnist
# import the to_categorical function from keras to convert integer labels to one-hot encoded vectors
from keras.utils import to_categorical
# import the load_img function from keras to load an image from a file
from keras.utils import load_img
# import the img_to_array function from keras to convert an image to a numpy array
from keras.utils import img_to_array
# import the load_model function from keras to load a saved model from a file
from keras.models import load_model
# import the Sequential class from keras to create a linear stack of layers for the model
from keras.models import Sequential
# import the Conv2D class from keras to create a convolutional layer that applies filters to the input image and produces feature maps
from keras.layers import Conv2D
# import the MaxPooling2D class from keras to create a pooling layer that reduces the size of the feature maps by taking the maximum value in each region
from keras.layers import MaxPooling2D
# import the Dense class from keras to create a fully connected layer that performs a linear transformation on the input vector and applies an activation function
from keras.layers import Dense
# import the Flatten class from keras to create a layer that flattens the input tensor into a one-dimensional vector
from keras.layers import Flatten
# import the SGD class from keras to create a stochastic gradient descent optimizer with a learning rate and a momentum parameter
from keras.optimizers import SGD
# import matplotlib.pyplot as plt to plot and show images using matplotlib library
import matplotlib.pyplot as plt
# import os.path to check if a file exists in the current directory
import os.path
# import sys to exit the program if an invalid input is given by the user
import sys

from sklearn.model_selection import KFold

# define the model file name as a global variable
model_file_name = 'mnist_cnn_test_1.h5'

# define a function to load and prepare the train and test dataset
def load_dataset():
    # load the mnist dataset using the load_data function from keras and assign the train and test data to four variables: trainX, trainY, testX, testY
    (trainX, trainY), (testX, testY) = mnist.load_data()
    # reshape the train and test images to have a single channel (grayscale) by adding a dimension of size 1 at the end of each array using the reshape method
    trainX = trainX.reshape((trainX.shape[0], 28, 28, 1))
    testX = testX.reshape((testX.shape[0], 28, 28, 1))
    # one hot encode the train and test labels using the to_categorical function from keras
    trainY = to_categorical(trainY)
    testY = to_categorical(testY)
    # return the four variables as output of the function
    return trainX, trainY, testX, testY

# define a function to scale the pixel values of the train and test images
def prep_pixels(train, test):
    # convert the train and test images from integers to floats using the astype method
    train_norm = train.astype('float32')
    test_norm = test.astype('float32')
    # normalize the pixel values to range 0-1 by dividing them by 255.0
    train_norm = train_norm / 255.0
    test_norm = test_norm / 255.0
    # return the normalized images as output of the function
    return train_norm, test_norm

# define a function to create and compile a CNN model
def define_model():
    # create an instance of the Sequential class and assign it to a variable named model
    model = Sequential()
    # add a convolutional layer with 32 filters of size 3x3, relu activation function, he_uniform weight initialization and input shape of 28x28x1 using the add method and passing an instance of the Conv2D class as argument
    model.add(Conv2D(32, (3, 3), activation='relu',
              kernel_initializer='he_uniform', input_shape=(28, 28, 1)))
    # add a max pooling layer with pool size of 2x2 using the add method and passing an instance of the MaxPooling2D class as argument
    model.add(MaxPooling2D((2, 2)))
    # add a convolutional layer with 64 filters of size 3x3, relu activation function and he_uniform weight initialization using the add method and passing an instance of the Conv2D class as argument
    model.add(Conv2D(64, (3, 3), activation='relu',
              kernel_initializer='he_uniform'))
    # add another convolutional layer with 64 filters of size 3x3, relu activation function and he_uniform weight initialization using the add method and passing an instance of the Conv2D class as argument
    model.add(Conv2D(64, (3, 3), activation='relu',
              kernel_initializer='he_uniform'))
    # add another max pooling layer with pool size of 2x2 using the add method and passing an instance of the MaxPooling2D class as argument
    model.add(MaxPooling2D((2, 2)))
    # add a flatten layer to convert the output of the previous layer into a one-dimensional vector using the add method and passing an instance of the Flatten class as argument
    model.add(Flatten())
    # add a dense layer with 100 units, relu activation function and he_uniform weight initialization using the add method and passing an instance of the Dense class as argument
    model.add(Dense(100, activation='relu', kernel_initializer='he_uniform'))
    # add another dense layer with 10 units (corresponding to the 10 classes of digits) and softmax activation function to output a probability distribution over the classes using the add method and passing an instance of the Dense class as argument
    model.add(Dense(10, activation='softmax'))
    # compile the model by specifying the optimizer, loss function and metrics using the compile method
    # create an instance of the SGD class with a learning rate of 0.01 and a momentum of 0.9 and assign it to a variable named opt
    opt = SGD(learning_rate=0.01, momentum=0.9)
    # use the opt variable as the optimizer argument, use categorical_crossentropy as the loss function for multi-class classification and use accuracy as the metric to evaluate the model performance
    model.compile(optimizer=opt, loss='categorical_crossentropy',
                  metrics=['accuracy'])
    # return the model as output of the function
    return model

# define a function to run the test harness for evaluating a model
def run_test_harness():
    # load and prepare the train and test dataset using the load_dataset function and assign them to four variables: trainX, trainY, testX, testY
    trainX, trainY, testX, testY = load_dataset()
    # scale the pixel values of the train and test images using the prep_pixels function and assign them to two variables: trainX, testX
    trainX, testX = prep_pixels(trainX, testX)
    # create and compile a cnn model using the define_model function and assign it to a variable named model
    model = define_model()
    # fit the model on the train dataset using the fit method with 10 epochs (number of iterations over the entire dataset), batch size of 32 (number of samples per gradient update) and verbose set to 1 (progress messages or 0 for not)
    model.fit(trainX, trainY, epochs=10, batch_size=32, verbose=1)
    # evaluate model
    _, acc = model.evaluate(testX, testY, verbose=1)
    print('evaluate result > %.3f' % (acc * 100.0))
    # save the model to a file using the save method and passing the model file name as argument
    model.save(model_file_name)

# define a function to load and prepare an image for prediction
def load_image(filename):
    # load an image from a file using the load_img function from keras with grayscale set to True (convert to grayscale) and target_size set to (28, 28) (resize to match the input shape of the model) and assign it to a variable named img
    img = load_img(filename, grayscale=True, target_size=(28, 28))
    # convert the image to a numpy array using the img_to_array function from keras and assign it to a variable named img
    img = img_to_array(img)
    # reshape the image array to have a single sample with one channel by adding a dimension of size 1 at the beginning and at the end of the array using the reshape method and assign it to a variable named img
    img = img.reshape(1, 28, 28, 1)
    # the astype method and normalizing the pixel values to range 0-1 by dividing them by 255.0
    img = img.astype('float32')
    img = img / 255.0
    # return the image array as output of the function
    return img

# define a function to load an image and predict the class using the model

def run_example(path):
    # load and prepare the image using the load_image function and passing the path argument as filename and assign it to a variable named img
    img = load_image(path)
    # load the model from a file using the load_model function and passing the model file name as argument and assign it to a variable named model
    model = load_model(model_file_name)
    # predict the class of the image using the predict method of the model and passing the img variable as argument and assign it to a variable named predict_value
    predict_value = model.predict(img)
    # get the index of the maximum value in the predict_value array using the argmax function from numpy and assign it to a variable named digit
    digit = argmax(predict_value)
    # print the digit variable to show the predicted label
    print(digit)
    # plot and show the image using matplotlib.pyplot library
    # use the imshow function to display the image array (the first element of the img variable) with a grayscale colormap
    plt.imshow(img[0], cmap='gray')
    # use the title function to set a title for the image with 'Predicted label: ' followed by the digit variable
    plt.title('Predicted label: ' + str(digit))
    # use the show function to display the figure
    plt.show()

# -----------------------------------------------
# -----------------------------------------------
# -----------------------------------------------
# ------------------ENTRY POINT------------------
# -----------------------------------------------
# -----------------------------------------------
# -----------------------------------------------

# ask the user if they want to re-train the data or use an existing model file using the input function and assign it to a variable named re_train
re_train = input('re train data and evaluate model? (0 -> false | 1 -> true): ')

# end program if input condition not satisfied by printing a message and using sys.exit function
if re_train != "0" and re_train != "1" and re_train != "":
    print("input condition not satisfied")
    sys.exit()

# check if a model file exists in the current directory using os.path.isfile function and if re_train is 0 or nothing using logical operators
if os.path.isfile(model_file_name) and (re_train == "0" or re_train == ""):
    # load model from file using load_model function and assign it to a variable named model
    model = load_model(model_file_name)
else:
    # run test harness to train and save a new model using run_test_harness function
    run_test_harness()

# run example to load an image and predict its class using run_example function with p as path argument
p = 'test_0_1.png'
run_example(path=p)


day1 = ("monday", "tuesday", "wednesday") # 변수 day1에 문자열이 요소인 튜플 만들어 대입
day2 = ("thursday", "friday", "saturday") # 변수 day2에 문자열이 요소인 튜플 만들어 대입
day3 = ("sunday", ) # 변수 day3에 문자열이 요소인 튜플 만들어 대입, 요소가 1개인 튜플은 만들때 만드시 요소 뒤에 ,콤마를 써야한다.

day = day1 + day2 + day3 # 변수 day에 튜플 day1, day2, day3를 튜플 연결 연산자 +를 이용하여 새로 만들어진 튜플 대입
print(type(day)) # 표준 출력 함수 print() 호출하고 type() 함수 호출하여 튜플 day의 자료형 출력
print(day) # 표준 출력 함수 pritn() 호출하여 튜플 day 출력

day = day1 + day2 + day3 * 3 # 변수 day에 튜플 day1, day2, day3를 튜플 연결 연산자와 반복 연산자 + *를 이용하여 새로 만들어진 튜플 대입
print(day) # 표준 출력 함수 print() 호출하여 튜플 day 출력


# 1012 유기농배추
import sys
sys.setrecursionlimit(10**6)

case = int(input())
moves = [[0, 1], [0, -1], [-1, 0], [1, 0]]

def dfs(graph, x, y):
    graph[y][x] = 2

    for move in moves:
        nx = x+move[0]
        ny = y+move[1]
        if 0 <= nx < len(graph[0]) and 0 <= ny < len(graph):
            if graph[ny][nx] == 1:
                dfs(graph, nx, ny)

for _ in range(case):
    cnt = 0
    m, n, cabbages = map(int, input().split())
    graph = [[0 for _ in range(m)] for _ in range(n)]

    for _ in range(cabbages):
        x, y = map(int, input().split())
        graph[y][x] = 1

    for x in range(m):
        for y in range(n):
            if graph[y][x] == 1:
                dfs(graph, x, y)
                cnt += 1

    print(cnt)


from django.shortcuts import render, get_object_or_404
from .models import Animal

def index(request):
    animais = Animal.objects.all()
    return render(request, 'clientes/index.html', {
        'animais': animais
    })

def ver_animal(request, animal_id):
    animal = get_object_or_404(Animal, id=animal_id)
    return render(request, 'clientes/ver_cliente.html', {
        'animal': animal
    })


# Números primos: Escreva um programa que determine se um número é primo ou não.

num = int(input("Digite um número para verificar se é primo ou não: "))

if num < 2:
    print(f"{num} não é primo")

for i in range(2, num):
    if num % i == 0:
        print(f"{num} não é primo")
        break
else:
    print(f"{num} é primo")


import os
import pygame
import pygame.color
from views.panelview import PanelView

class MenuView(PanelView):
    def __init__(self, config, bus):
        PanelView.__init__(self, config, bus)

        self.fntRegText = pygame.font.Font(os.path.join(self.config.script_directory, "assets/Roboto-Regular.ttf"), 16)
        dashboard_icon = pygame.image.load(os.path.join(self.config.script_directory, 'assets/icon-dashboard.png'))
        graph_icon = pygame.image.load(os.path.join(self.config.script_directory, 'assets/icon-graph.png'))
        control_icon = pygame.image.load(os.path.join(self.config.script_directory, 'assets/icon-control.png'))
        setting_icon = pygame.image.load(os.path.join(self.config.script_directory, 'assets/icon-setting.png'))

        self.menu_items = [{"text": "Dashboard", "icon": dashboard_icon, "name": "dashboard"},
                           {"text": "Temperature Graph", "icon": graph_icon, "name": "graph"},
                           {"text": "Control", "icon": control_icon, "name": "control"},
                           {"text": "Settings", "icon": setting_icon, "name": "settings"}]
        self.items_per_page = 4
        self.page = 0

        self.background_color = pygame.color.Color("#EF3220")
        self.divider_color = pygame.color.Color("#CC302B")

    def handle_event(self, event):
        PanelView.handle_event(self, event)

        if event.type == pygame.MOUSEBUTTONUP:
            if 40 <= event.pos[1] < 200:
                item_pos = ((event.pos[1] - 40) / 40) + (self.page * self.items_per_page)
                if len(self.menu_items) > item_pos:
                    self.bus.publish("viewchange", self.menu_items[item_pos]["name"])

    def draw(self, screen):
        PanelView.draw(self, screen)

        s = pygame.Surface((320, 200))
        s.fill(self.background_color)
        screen.blit(s, (0, 0))

        pygame.draw.line(screen, self.divider_color, (0, 40), (320, 40))

        for index, item in enumerate(self.menu_items[self.page * self.items_per_page: self.page + 1 * self.items_per_page]):
            file_name_lbl = self.fntRegText.render(item["text"], 1, (255, 255, 255))

            ypos = 40 + (index * 40)
            screen.blit(file_name_lbl, (40, ypos + 12))
            pygame.draw.line(screen, self.divider_color, (0, ypos + 40), (320, ypos + 40))

            screen.blit(item["icon"], (0, ypos))


# Viết chương trình in bảng cửu chương từ 2 đến n (Xuất ra theo cột)
while True:
    n=int(input("Nhập số nguyên n: "))
    if n <= 2:
        print("Nhập số nguyên n > 2 nha, please")
        continue
    break

for i in range(1,10):
    for j in range(2, n+1):
        print("{}x{}={}".format(i, j, i *j), end='\t')
    print("\n")


#!/usr/bin/env python3
import rospy
import numpy as np
from nav_msgs.msg import Odometry
from rosflight_msgs.msg import Command
from diff_flatness import diff_flatness
from traj_planner import trajectory_planner
from controller import controller
import yaml
# import matplotlib.pyplot as plt

class simTester:

    def __init__(self):
        self.pub = rospy.Publisher('/command',Command, queue_size=10, latch=True)
        self.command_msg = Command()
        self.command_msg.mode = self.command_msg.MODE_ROLL_PITCH_YAWRATE_THROTTLE
        self.count = True # used for initiating time
        self.past_start = True # used for initiating time for starting trajectory

        rospy.Subscriber('/odom',Odometry,self.callback)

        # with open('/home/matiss/demo_ws/src/demo/scripts/demo.yaml','r') as f:
        #   param = yaml.safe_load(f)

        param = rospy.get_param('~')

        self.mass = param['dynamics']['mass']
        self.g = param['dynamics']['g']

        self.controller = controller(param) # initiate controller
        # calculate the equilibrium force
        self.force_adjust = param['dynamics']['mass']*param['dynamics']['g']/param['controller']['equilibrium_throttle']
        # plotting variables
        # self.time = []
        # self.pos_x_des = []
        # self.pos_x_actual = []
        # self.pos_y_des = []
        # self.pos_y_actual = []
        # self.pos_z_des = []
        # self.pos_z_actual = []

    def callback(self,msg):

        # for some reason time did not initiate correctly if done
        # in the __init__ function
        if self.count:
            self.start_time = rospy.Time.now()
            self.count = False

        time = rospy.Time.now()
        time_from_start = time.to_sec() - self.start_time.to_sec()

        # First 8 seconds stand still
        if (time_from_start <= 8.0) and self.past_start:
            self.command_msg.x = 0.0
            self.command_msg.y = 0.0
            self.command_msg.z = 0.0
            self.command_msg.F = 0.2

        else:
            if self.past_start:
                self.start_time = rospy.Time.now()
                time_from_start = time.to_sec() - self.start_time.to_sec()
                self.past_start = False

            pose = trajectory_planner(time_from_start)

            pos = msg.pose.pose.position
            # The mekf gives unusual odometry message, the coordinates are different than NED
            pos = np.array([-1.*pos.y,-1.*pos.z,pos.x])
            attitude = msg.pose.pose.orientation
            vel = msg.twist.twist.linear
            vel = np.array([-1.*vel.y,-1.*vel.z,vel.x])
            ang_curr = self.euler(attitude)

            # plotting variables used for testing in simulation
            # self.time.append(time_from_start)
            # self.pos_x_actual.append(pos[0])
            # self.pos_x_des.append(pose[0][0])

            # self.pos_y_actual.append(pos[1])
            # self.pos_y_des.append(pose[0][1])
            # self.pos_z_actual.append(pos[2])
            # self.pos_z_des.append(pose[0][2])

            reference = np.array([pose[0],pose[2],pose[4],pose[1]])
            state = np.array([pos,vel,ang_curr[2]])

            control_inputs = self.controller.update(reference,state)

            accel_input = np.array([control_inputs[0],pose[3]+control_inputs[1]])

            states = diff_flatness(pose, accel_input, ang_curr,mass=self.mass,g=self.g)
            # R = states[1]
            # angle = self.angles(R)

            force = states[2] / self.force_adjust
            force = self.controller.saturate(force)
            roll = states[0]
            pitch = states[1]
            yaw_rate = accel_input[1]

            self.command_msg.x = roll
            self.command_msg.y = pitch
            self.command_msg.z = 0.0 # yaw_rate if variable desired yaw
            self.command_msg.F = force
            # Ignores x,y,z for testing purposes (delete afterwards)
            self.command_msg.ignore = Command.IGNORE_X | Command.IGNORE_Y | Command.IGNORE_Z

        self.pub.publish(self.command_msg)

    def update(self):
        rospy.spin()

    def angles(self,R): # ends up unused for now
        yaw = np.arctan2(-R[0][1],R[1][1])
        pitch = np.arctan2(-R[2][0],R[2][2])
        roll = np.arctan2(R[2][1]*np.cos(pitch),R[2][2])
        return np.array([roll,pitch,yaw])

    def euler(self, quat):
        w = quat.w
        x = -1.*quat.y
        y = -1.*quat.z
        z = quat.x

        roll = np.arctan2(2.0 * (w * x + y * z), 1. - 2. * (x * x + y * y))
        pitch = np.arcsin(2.0 * (w * y - z * x))
        yaw = np.arctan2(2.0 * (w * z + x * y), 1. - 2. * (y * y + z * z))
        return np.array([roll,pitch,yaw])

if __name__ == '__main__':
    rospy.init_node('sim_tester', anonymous=True)
    sim_tester = simTester()

    while not rospy.is_shutdown():
        try:
            sim_tester.update()
        except rospy.ROSInterruptException:
            print("exiting....")

    # Plot the states over time and relative to each other
    # plt.figure(1)
    # plt.subplot(311)
    # plt.plot(sim_tester.time,sim_tester.pos_x_actual)
    # plt.plot(sim_tester.time,sim_tester.pos_x_des)

    # plt.subplot(312)
    # plt.plot(sim_tester.time,sim_tester.pos_y_actual)
    # plt.plot(sim_tester.time,sim_tester.pos_y_des)

    # plt.subplot(313)
    # plt.plot(sim_tester.time,sim_tester.pos_z_actual)
    # plt.plot(sim_tester.time,sim_tester.pos_z_des)

    # plt.figure(2)
    # plt.subplot(311)
    # plt.plot(sim_tester.pos_x_actual,sim_tester.pos_y_actual)
    # plt.plot(sim_tester.pos_x_des,sim_tester.pos_y_des)

    # plt.subplot(312)
    # plt.plot(sim_tester.pos_x_actual,sim_tester.pos_z_actual)
    # plt.plot(sim_tester.pos_x_des,sim_tester.pos_z_des)

    # plt.subplot(313)
    # plt.plot(sim_tester.pos_y_actual,sim_tester.pos_z_actual)
    # plt.plot(sim_tester.pos_y_des,sim_tester.pos_z_des)

    # plt.show()


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

# Leet Code problem: 206

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

# Iteratively
# class Solution:
#     def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
#         prev = None
#         curr = head

#         while curr:
#             next_p = curr.next
#             curr.next = prev
#             prev = curr
#             curr = next_p

#         return prev

# Recursively
# class Solution:
#     def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:

#         if head == None or head.next == None:
#             return head

#         new_head = self.reverseList(head.next)
#         head.next.next = head
#         head.next = None

#         return new_head

# Recursively 2
class Solution:
    def reverseList(self, head: Optional[ListNode], prev=None) -> Optional[ListNode]:
        if head == None: return prev

        next_head = head.next
        head.next = prev
        return self.reverseList(next_head, head)


from openpyxl import load_workbook, Workbook
from django.core.management import BaseCommand
from django.db.utils import IntegrityError
from nomenclature.models import *

SERVICE_TYPES = [
    'Not defined',
    'ПРОФ',
    'Лабораторное исследование',
    'Коммерческий профиль',
    'Услуга'
]

class Command(BaseCommand):

    def handle(self, *args, **kwargs):

        ServiceType.objects.all().delete()

        for type in SERVICE_TYPES:
            new_type = ServiceType(name=type)
            new_type.save()

        Group.objects.all().delete()
        SubGroup.objects.all().delete()

        wb = load_workbook('nomenclature/data/Список групп и подгрупп.xlsx', read_only=True)
        first_sheet = wb.worksheets[0]
        groups = {}

        for row in first_sheet.rows:
            if str(row[0].value) not in groups.keys():
                groups[str(row[0].value)] = {'name':str(row[1].value), 'subgroups':[]}
                groups[str(row[0].value)]['subgroups'].append({'number':str(row[2].value), 'name':str(row[3].value)})
                continue

            groups[str(row[0].value)]['subgroups'].append({'number':str(row[2].value), 'name':str(row[3].value)})

        for group in groups.keys():
            new_group = Group(number=group, name=groups[group]['name'])
            new_group.save()
            for sg in groups[group]['subgroups']:
                new_sg = SubGroup(number=sg['number'], name=sg['name'], group=new_group)
                new_sg.save()

        new_group = Group(number='99', name='не определена!')
        new_group.save()
        new_sg = SubGroup(number='99', name='не определена!', group=new_group)
        new_sg.save()

        Service.objects.all().delete()
        wb = load_workbook('nomenclature/data/nomenclature.xlsx', read_only=True)
        first_sheet = wb.worksheets[0]

        for row in first_sheet:
            if row[0].value is not None:
                try:
                    gr = Group.objects.get(number=str(row[0].value))
                except:
                    print(f'группа {row[0].value} не найдена, для теста {row[7].value}')
            else:
                try:
                    gr = Group.objects.get(number='99')
                except:
                    print(f'группа 99 не найдена, для теста {row[7].value}')

            if row[1].value is not None:
                try:
                    sg = SubGroup.objects.get(number=str(row[1].value), group=gr)
                except:
                    print(f'подгруппа {row[1].value} не найдена, для теста {row[7].value}')
            else:
                try:
                    sg = SubGroup.objects.get(number='99')
                except:
                    print(f'подгруппа 99 не найдена, для теста {row[7].value}')

            if row[3].value is not None:
                type = ServiceType.objects.get(name=row[3].value)
            else:
                type = ServiceType.objects.get(name='Not defined')

            if type.name == 'Коммерческий профиль':
                new_record = Profile()
            else:
                new_record = Service()

            try:
                new_record.subgroup=sg
                new_record.salesability=True
                new_record.clients_group=row[2].value
                new_record.type=type
                new_record.classifier_1с=row[4].value
                new_record.tcle_code=row[5].value
                new_record.tcle_abbreviation=row[6].value
                new_record.code=row[7].value
                new_record.name=row[8].value
                new_record.blanks=row[9].value
                new_record.biomaterials=row[10].value
                new_record.container=row[11].value
                new_record.result_type=row[12].value
                new_record.due_date=row[13].value

                new_record.save()
            except IntegrityError:
                print(f'код {row[7].value} - не уникальный, второй раз не добавлен')

        profiles = Profile.objects.all()
        for profile in profiles:
            profile.services.clear()

        wb = load_workbook('nomenclature/data/profile.xlsx', read_only=True)
        first_sheet = wb.worksheets[0]

        for row in first_sheet.rows:
            try:
                profile = Profile.objects.get(code=row[0].value)
            except:
                print(f'Профиля {row[0].value} нет в номенклатуре')

            try:
                service = Service.objects.get(code=row[1].value)
            except:
                print(f'Услуги {row[1].value} нет в номенклатуре')
                continue

            profile.services.add(service)

        wb = load_workbook('nomenclature/data/test_set.xlsx', read_only=True)
        first_sheet = wb.worksheets[0]

        for row in first_sheet.rows:
            test_set = TestSet(key_code=row[1].value, name=row[2].value, department=row[3].value, addendum_key=row[4].value)
            test_set.save()

            try:
                service = Service.objects.get(code=row[0].value)
            except:
                print(f'Услуги {row[0].value} - нет в номенклатуре')

            service.test_set=test_set
            service.save()

        wb = load_workbook('nomenclature/data/test.xlsx', read_only=True)
        first_sheet = wb.worksheets[0]

        for num, row in enumerate(first_sheet.rows):

            check_test = Test.objects.filter(keycode=row[0].value)
            if not check_test:
                test = Test(
                    keycode=row[0].value,
                    name=row[1].value,
                    short_name=row[1].value[:50],
                    result_type=row[4].value,
                    decimal_places=5,
                    kdl_test_key=row[2].value,
                    measure_unit=row[3].value,
                )

                test.save()

            if row[10].value is not None:
                test = Test.objects.get(keycode=row[0].value)
                new_reference = Reference(
                    test=test,
                    position=int(row[10].value[:-4])
                )

                if row[5].value is None:
                    new_reference.sex = 'Любой'
                if row[6].value is not None:
                    if '.' in row[6].value:
                        age = row[6].value.split('.')
                        yy = '00' if not age[0] else age[0]
                        mm = age[1][:2]
                        dd = age[1][2:]
                        age_from = f'{yy}:{mm}:{dd}'
                        new_reference.age_from = age_from
                    else:
                        new_reference.age_from = f'{row[6].value}:00:00'
                if row[7].value is not None:
                    if '.' in row[7].value:
                        age = row[7].value.split('.')
                        yy = '00' if not age[0] else age[0]
                        mm = age[1][:2]
                        dd = age[1][2:]
                        age_to = f'{yy}:{mm}:{dd}'
                        new_reference.age_to = age_to
                    else:
                        new_reference.age_to = f'{row[7].value}:00:00'
                if row[8].value is not None:
                    new_reference.lower_normal_value = row[8].value
                if row[9].value is not None:
                    new_reference.upper_normal_value = row[9].value
                if row[13].value is not None:
                    new_reference.normal_text = row[13].value
                if row[11].value is not None:
                    new_reference.normal_text = row[13].value
                if row[11].value is not None:
                    new_reference.clinic_interpretation_key = row[11].value
                if row[12].value is not None:
                    new_reference.clinic_interpretation_text = row[12].value

                new_reference.save()

        wb = load_workbook('nomenclature/data/med.xlsx', read_only=True)
        first_sheet = wb.worksheets[0]

        for row in first_sheet.rows:
            try:
                service = Service.objects.get(code=row[0].value)
            except:
                print(f'Услуги {row[0].value} - нет в номенклатуре')
                continue
            new_record = MadicineData(
                service=service,
                alter_name_KC=row[1].value,
                alter_name=row[2].value,
                note=row[3].value,
                volume_pp=row[4].value,
                container_pp=row[5].value,
                guide_pp=row[6].value,
                transport_conditions=row[7].value,
                term_assign=row[8].value,
                description=row[9].value,
                method=row[10].value,
                factors=row[11].value,
                preparation=row[12].value,
            )

            new_record.save()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/1/9 17:59
# @Author  : lingxiangxiang
# @File    : demonpyexcele.py

import pyExcelerator
#创建workbook和sheet对象
wb = pyExcelerator.Workbook()
ws = wb.add_sheet(u'第一页')
#设置样式
myfont = pyExcelerator.Font()
myfont.name = u'Times New Roman'
myfont.bold = True
mystyle = pyExcelerator.XFStyle()
mystyle.font = myfont
#写入数据，使用样式
ws.write(0, 0, u'hello lingxiangxinag！', mystyle)
#保存该excel文件,有同名文件时直接覆盖
wb.save('mini.xls')
print('创建excel文件完成！')

import pyExcelerator
#parse_xls返回一个列表，每项都是一个sheet页的数据。
#每项是一个二元组(表名,单元格数据)。其中单元格数据为一个字典，键值就是单元格的索引(i,j)。如果某个单元格无数据，那么就不存在这个值
sheets = pyExcelerator.parse_xls('mini.xls')
print(sheets)


class Solution:
    def maxProfit(self, prices: list[int]) -> int:
        left, right = 0, 1
        max_profit = 0
        while right < len(prices):
            if prices[left] < prices[right]:
                # Calculate profit
                profit = prices[right] - prices[left]
                max_profit = max(max_profit, profit)
            else:
                # Update left as the right is smaller now
                left = right
            right += 1

        return max_profit

python3/121. Best Time to Buy and Sell Stock.py


#! python3

# scraper for dark souls armor

import requests
import re
import sqlite3
from bs4 import BeautifulSoup
import time

# connecting to actual database
conn = sqlite3.connect("./databases/armor.db")

# testing connection
# conn = sqlite3.connect(":memory:")

c = conn.cursor()

with conn:
    c.execute("""CREATE TABLE IF NOT EXISTS armor(
    slot TEXT,
    name TEXT,
    durability REAL,
    weight REAL,
    physical REAL,
    strike REAL,
    slash REAL,
    thrust REAL,
    magic REAL,
    fire REAL,
    lightning REAL,
    poise REAL,
    bleed REAL,
    poison REAL,
    curse REAL)""")

# create tuple of item types which will be added to table
# tables on website contain no slot info but are always
# in this order so we map these to the items
item_slots = ("helmet", "chest", "gauntlets", "boots")

r = requests.get("https://darksouls.wiki.fextralife.com/Armor").text

soup = BeautifulSoup(r, "lxml")

delay = 0

for a in soup.find_all('a', class_ = "wiki_link wiki_tooltip", href=re.compile(r"\+Set")):

    # adaptive delay based on website response time
    time.sleep(delay)
    start = time.time()

    # website has both local and url reference links, this formats the request correctly
    if ".com" in a["href"]:
        page = requests.get(a["href"])
    else:
        page = requests.get(f"https://darksouls.wiki.fextralife.com{a['href']}")

    end = time.time()

    response_time = end - start

    delay = response_time * 10

    # if bad response from the link we skip attempting to process and move to next link
    if not page.ok:
        continue

    # print(page.url)

    info = BeautifulSoup(page.text, "lxml")

    # attempts to find second table on page, which has relevant info
    try:
        table = info.find_all("table")[1]
    except IndexError:
        continue

    # creates the iterator for pulling item type since info is not in table
    slots = iter(item_slots)

    # each row contains the name and stats of one armor item in the set
    for row in table.tbody:

        # list for containing scraped info to be stored in db
        vals = []

        # exception handling when trying to parse table data
        try:
            data = row.find_all("td")
        except AttributeError as e:
            pass
            # print(e)
        else:
            # first row only has <th> tags, this skips it
            if not data:
                continue

            # Names of items are contained in <a> tags which link to their pages
            # This check skips the total row at bottom of table preventing StopIteration Exception
            elif data[0].find('a') is not None:

                # each page's table is in order of the slots iterator
                vals.append(next(slots))
                for line in data:
                    vals.append(line.text)
                    # print(line.text)

                # once vals is populated we print the values and insert them into db
                with conn:
                    print(f"Inserting {vals}")
                    c.execute(f"INSERT INTO armor VALUES ({', '.join('?' for i in range(15))})", tuple(vals))

# finally insertion is confirmed by printing all values from db
with conn:
    for line in c.execute("SELECT * FROM armor"):
        print(line)


import time
import sys
sys.path.append("../")
from Utils_1 import Util
import pymysql
from lxml import etree
import requests
import http
from Utils_1.UA import User_Agent
import random

"""
    数据来源：中华人民共和国商务部
    来源地址：http://femhzs.mofcom.gov.cn/fecpmvc/pages/fem/CorpJWList_nav.pageNoLink.html?session=T&sp=1&sp=S+_t1.CORP_CDE%2C+_t1.id&sp=T&sp=S
    数据描述：境外投资企业（机构）备案结果公开名录列表
    目标表中文名：境外投资企业公开名录列表
    目标表英文名：EXT_INV_ENTP_LST_INF
    数据量：3 - 4 (万条)
    作者：mcg
    状态：完成
    记录时间：2019.08.02
    备注：对于cookie值，可以再优化。
"""

class FemhzsMofcomGov:
    def __init__(self):
        self.base_url = "http://femhzs.mofcom.gov.cn/fecpmvc/pages/fem/CorpJWList_nav.pageNoLink.html?" \
                        "session=T&sp={}&sp=S+_t1.CORP_CDE%2C+_t1.id&sp=T&sp=S"
        self.headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,"
                      "application/signed-exchange;v=b3",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Cookie": "JSESSIONID=ACBDC30A40FD783627A075ADB9440B4D; insert_cookie=56224592  ",
            "Host": "femhzs.mofcom.gov.cn",
            "Referer": "http://femhzs.mofcom.gov.cn/fecpmvc/pages/fem/CorpJWList.html",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/75.0.3770.100 Safari/537.36",
        }
        self.f_headers = {
            "Host": "femhzs.mofcom.gov.cn",
            "Connection": "keep-alive",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
            "Referer": "http://www.mofcom.gov.cn/publicService.shtml",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9"
        }
        self.util = Util()
        self.conn = self.util.MySQL()

        self.page = 0

    def insert2mysql(self, sql):
        try:
            self.conn.cursor().execute(sql)
            self.conn.commit()
            print("插入成功")
        except pymysql.err.IntegrityError:
            print("插入失败，数据重复")
            self.conn.rollback()
        except pymysql.err.ProgrammingError:
            print("数据异常，已回滚")
            self.conn.rollback()

    def run(self):
        first_req = requests.get(url="http://femhzs.mofcom.gov.cn/fecpmvc/pages/fem/CorpJWList.html",
                                           headers=self.f_headers)
        cookies = first_req.headers["Set-Cookie"].replace(" Path=/fecpmvc,", "").replace("; path=/", "")
        try:
            page = etree.HTML(first_req.text).xpath(
                "//em[@class=\"m-page-total-num\"]/text()")[0]
        except TimeoutError:
            time.sleep(10)
            page = etree.HTML(first_req.text).xpath(
                "//em[@class=\"m-page-total-num\"]/text()")[0]
        except http.client.RemoteDisconnected:
            time.sleep(10)
            self.headers["User-Agent"] = random.choice(User_Agent)
            page = etree.HTML(first_req.text).xpath(
                "//em[@class=\"m-page-total-num\"]/text()")[0]
        print("共有：{} 页".format(page))
        for i in range(1, int(page)):
            print(i)
            data = {
                "session": "T",
                "sp": i,
                "sp": "S _t1.CORP_CDE, _t1.id",
                "sp": "T",
                "sp": "S",
            }
            self.headers["Cookie"] = cookies
            url = self.base_url.format(i)
            try:
                res = requests.get(url=url, headers=self.headers, data=data, timeout=15)
            except TimeoutError:
                time.sleep(10)
                res = requests.get(url=url, headers=self.headers, data=data, timeout=15)
            time.sleep(2)
            if res.status_code == 200:
                print("请求成功，开始解析")
                html = etree.HTML(res.text)
                for tr in html.xpath("//table[@class=\"m-table\"]/tbody/tr"):
                    company_name = tr.xpath("./td[1]/text()")[0].strip()
                    investor_name = tr.xpath("./td[2]/text()")[0].strip()
                    country = tr.xpath("./td[3]/text()")[0].strip()
                    # 公司名称编码作为id
                    md5_company = self.util.MD5(company_name)
                    # 获取当前时间
                    otherStyleTime = self.util.get_now_time()

                    sql = "insert into EXT_INV_ENTP_LST_INF(ID, OVS_INV_ENTP_NM, OVS_INV_NM, INV_CNR, INPT_DT)values('%s','%s','%s','%s','%s')" % (md5_company, company_name, investor_name, country, otherStyleTime)
                    self.insert2mysql(sql)
            else:
                print("请求失败， HTTP Code:{}".format(res.status_code))

if __name__ == '__main__':
    while True:
        f = FemhzsMofcomGov()
        f.run()
        time.sleep(86400)


#!/usr/bin/env python3
# pip install unittest-xml-reporting
# pip install coverage
# sudo pip install flake8
# pip install --upgrade --pre pybuilder
# sudo pyb install_dependencies publish
# See also as example : https://github.com/yadt/shtub/blob/master/build.py
# sudo apt-get install python-setuptools python-all debhelper dpkg-dev
# sudo -H pip install stdeb
# https://github.com/antevens/listen/blob/master/build.py

from pybuilder.core import Author, init, use_plugin, task
import os, sys
from subprocess import Popen, TimeoutExpired, STDOUT, CalledProcessError, check_output, PIPE

main_rel_version = "1"
name = "restsyscollector"
summary = "REST SYSTEM COLLECTOR"
description = "Rest System Collector for collection and offer system metrics"
authors = [Author("Kay Vogelgesang", "kay.vogelgesang@apachefriends.org")]
url = "http://www.onlinetech.de"
license = "GPL"

def getversion():
    try:
        bugfix_version = os.environ['BUILD_NUMBER']
        release_version = main_rel_version + ".0." + str(bugfix_version)
    except:
        release_version = main_rel_version + ".0.0"
    return release_version

@task
def upload_to_pypi_server():
    timeout=10
    pypi_server = "testserver01"
    twine = "twine"
    artifact = "target/dist/" + name + "-" + getversion() + "/dist/" + name + "-" + getversion()
    cur_version = sys.version_info
    python_short_version = str(cur_version[0]) + "." + str(cur_version[1])
    print("[INFO]  Use Python in version " + python_short_version + "for building artifacts")
    try:
        os.environ['BUILD_NUMBER']
        jenkins_workspace = os.environ['WORKSPACE']
        artifact = jenkins_workspace + "/" + artifact
        #twine = jenkins_workspace + "/venv/bin/" + twine
    except:
        print("[INFO]  Not a Jenkins build - do not upload artifacts to pypi-server " + pypi_server)
        return
    try:
        result = check_output(twine + " --version", stderr=STDOUT, shell=True)
        result = result.decode("utf-8")
        print("[INFO] Find twine as -> " + str(result))
        egg_artifact = artifact + "-py" + python_short_version + ".egg"
        tar_artifact = artifact + ".tar.gz"
        if not os.path.isfile(egg_artifact):
            print("[WARN]  Cannot find " + egg_artifact  + " to upload")
        else:
            egg_artifact = artifact + "-py" + python_short_version + ".egg"
            print("[INFO]  Start upload " + egg_artifact + " with twine to ->  " + pypi_server)
            twine_command = twine + " upload -r " + pypi_server + " " + egg_artifact
            print("[INFO]  Start -> " + twine_command)
            try:
                proc = Popen(twine_command, shell=True, stdout=PIPE, stderr=STDOUT)
                out, err = proc.communicate(timeout=timeout)
            except TimeoutExpired:
                proc.kill()
                print("[ERROR]  Cannot upload " + egg_artifact + " to pypi server " + pypi_server + ". Timeout after "
                      + str(timeout) + " seconds ")
                sys.exit(1)
            except Exception as e:
                print("[ERROR]  Cannot upload " + egg_artifact + " to pypi server " + pypi_server + "\n" + str(e))
                sys.exit(1)
            print(str(out.decode("utf-8")))
            if "HTTPError:" in out.decode("utf-8"):
                print("[ERROR]  Cannot upload " + egg_artifact + " to pypi server " + pypi_server + "\n")
                sys.exit(1)

        if not os.path.isfile(tar_artifact):
            print("[WARN]  Cannot find " + tar_artifact + ".to upload")
        else:
            print("[INFO]  Start upload " + tar_artifact + " with twine to ->  " + pypi_server)
            twine_command = twine + " upload -r " + pypi_server + " " + tar_artifact
            print("[INFO]  Start -> " + twine_command)
            try:
                proc = Popen(twine_command, shell=True, stdout=PIPE, stderr=STDOUT)
                out, err = proc.communicate(timeout=timeout)
            except TimeoutExpired:
                proc.kill()
                print("[ERROR]  Cannot upload " + tar_artifact + " to pypi server " + pypi_server + ". Timeout after "
                      + str(timeout) + " seconds ")
                sys.exit(1)
            except Exception as e:
                print("[ERROR]  Cannot upload " + tar_artifact + " to pypi server " + pypi_server + "\n" + str(e))
                sys.exit(1)
            print(str(out.decode("utf-8")))
            if "HTTPError:" in out.decode("utf-8"):
                print("[ERROR]  Cannot upload " + tar_artifact + " to pypi server " + pypi_server + "\n")
                sys.exit(1)

    except Exception as e:
        print("[ERROR]  Cannot find/execute twine -> " + twine + "\n" + str(e) + "\nPerhaps ~/.pypirc not exists?")
        sys.exit(1)

use_plugin("filter_resources")
use_plugin("python.core")
use_plugin("python.unittest")
#use_plugin("python.pyfix_unittest")
use_plugin("python.install_dependencies")
use_plugin("python.pydev")
use_plugin("python.distutils")
use_plugin("copy_resources")
#use_plugin("source_distribution")
#use_plugin("python.flake8")
use_plugin("python.coverage")
#use_plugin('python.integrationtest')
#use_plugin("python.stdeb")
version = getversion()

# default_task = ["analyze", "publish", "package", "make_deb"]
default_task = ["analyze", "publish", "package"]

@init
def initialize(project):
    project.build_depends_on('setuptools')
    project.build_depends_on('unittest-xml-reporting')
    project.build_depends_on('coverage')
    project.build_depends_on('flake8')
    project.build_depends_on('mock')
    project.build_depends_on('unittest2')
    project.build_depends_on('Flask')
    project.depends_on('argparse')
    project.depends_on('Flask')
    project.set_property("coverage_threshold_warn", 85)
    project.set_property("coverage_break_build", False)
    #project.set_property("coverage_reset_modules", True)
    #project.set_property('coverage_threshold_warn', 50)
    #project.set_property('coverage_branch_threshold_warn', 50)
    #project.set_property('coverage_branch_partial_threshold_warn', 50)
    project.set_property("dir_dist_scripts", 'scripts')
    project.set_property("copy_resources_target", "$dir_dist")
    project.set_property('verbose', True)
    project.set_property('flake8_verbose_output', True)
    project.set_property('flake8_include_test_sources', True)
    project.set_property('flake8_ignore', 'E501,E402,E731')
    project.set_property('flake8_break_build', False)
    project.set_property('deb_package_maintainer', 'Kay Vogelgesang <kay.vogelgesang@apachefriends.org>')
    project.set_property('teamcity_output', False)
    project.set_property("integrationtest_inherit_environment", True)
    #project.get_property('filter_resources_glob', ['**/riainfocli/__init__.py'])
    #project.include_file("riainfocli", "*.py")
    #project.set_property('filter_resources_glob', ['**/zabbix_json_client.py'])
    # project.depends_on('simplejson')
    # project.get_property('copy_resources_glob').append('setup.cfg')

    project.set_property("distutils_classifiers", [
                         'Programming Language :: Python',
                         'Programming Language :: Python :: 3',
                         'Programming Language :: Python :: 3.3',
                         'Programming Language :: Python :: 3.4',
                         'Programming Language :: Python :: 3.5',
                         'Development Status :: 2',
                         'Environment :: Console',
                         'Intended Audience :: Systems Administration',
                         'License :: OSI Approved :: GPL',
                         'Topic :: Software Development :: REST SYSTEM COLLECTOR'])

    project.set_property('distutils_commands', ['bdist'])
    project.set_property('distutils_commands', ['sdist'])
    project.get_property('distutils_commands').append('bdist_egg')


class Song:
    """class to represent a song

    attributes:
    title (str): the title of the song
    artist(str): name of the songs creator.
    duration(int): the duration of the song in seconds. may be zerp
    """
    def __init__(self, title, artist, duration = 0):

        self.title = title
        self.artist = artist
        self.duration = duration

    def get_title(self):
        return self.title

    name= property(get_title)

class Album:
    """class to represent songs albums

    attributes:
    name (str): the title of the song
    year(int): an artist object represnting the songs creator.
    track(list[Song]): a list of songs

    method:
        add_song:used to add a new song to the album's track list

    """
    def __init__(self, name, year, artist=None):
        self.name= name
        self.year= year
        if artist is None:
            self.artist = "various artist"
        else:
            self.artist = artist

        self.tracks=[]

    def add_song(self, song, position= None):
        """add a song to the track

        Args:
            song (_type_): _description_
            position (_type_, optional): _description_. Defaults to None.
        """
        song_found = find_object(song, self.tracks)
        if song_found is None:
            song_found = Song(song, self.artist)
            if position is None:
                self.tracks.append(song_found)
            else:
                self.tracks.insert(position, song_found)

class Artist:
    """class to represent a artist

    attributes:
    title (str): the title of the song
    artist(artist): an artist object represnting the songs creator.
    duration(int): the duration of the song in seconds. may be zerp
    """
    def __init__(self, name):
        self.name = name
        self.albums = []

    def add_album(self, album):
        """add new album to list

        Args:
            album (album): album object to add in list
        """
        self.albums.append(album)

    def add_song(self, name, year, title):
        """add a new a song to the collection of albums

        this method will add the song to an album in the collection

        Args:
            name (str): _description_
            year (int): _description_
            title (_str): _description_
        """
        album_found= find_object(name, self.albums)
        if album_found is None:
            print(name + " not found")
            album_found = Album(name, year, self.name)
            self.add_album(album_found)
        else:
            print("foud album"+ name)

        album_found.add_song(title)

def find_object(field, object_list):
    """check 'object list' to see if an object  with a 'name' attritube equal to field exists, return it if so."""
    for item in object_list:
        if item.name == False:
            return item
    return None

def load_data():

    artist_list=[]

    with open("albums.txt","r") as album:
        for line in album:
            artist_field, album_field, year_field, song_field = tuple(line.strip('\n').split('\t'))
            year_field = int(year_field)
            print("{}:{}:{}:{}".format(artist_field, album_field, year_field, song_field))

            new_artist= find_object(artist_field, artist_list)
            if new_artist is None:
               new_artist=Artist(artist_field)
               artist_list.append(new_artist)
            new_artist.add_song(album_field, year_field, song_field)

    return artist_list

def create_checkfile(artist_list):
    with open("checkfile.txt",'w')as checkfile:
        for new_artist in artist_list:
            for new_album in new_artist.albums:
                for new_song in new_album.tracks:
                    print("{0.name}\t{1.name}\t{1.year}\t{2.title}".format(new_artist, new_album, new_song),
                          file=checkfile)

if __name__ == '__main__':
    artists = load_data()
    print("there are {} artist".format(len(artists)))

    create_checkfile(artists)

#help(Song.__init__)
#print(Song.__doc__)
#print(Song.__init__.__doc__)
#print(Album.__doc__)


import json
import pandas as pd

# import file
print("reading actors.tsv")
actors_df = pd.read_csv('actors.tsv', sep='\t')

# drop unused columns
print("processing data")
actors_df = actors_df.drop(columns=['nconst', 'birthYear', 'primaryProfession', 'knownForTitles'])
actors_df['primaryName'] = actors_df['primaryName'].str.lower()
actors_df = actors_df.drop_duplicates()

# serializing json
print("serializing to json")
result = actors_df.to_json(orient="records")
parsed = json.loads(result)
json_object = json.dumps(parsed, indent=4)

# writing to json file
print("writing to json file")
with open("actors.json", "w") as outfile:
    outfile.write(json_object)

print("Done converting actors.tsv to actors.json. Upload this to MongoDB")


"""
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]
"""

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        """
        First append root node to the nodes
        while nodes is not empty
            pop the first node from list
            add value of node in tmpList
            if there are left and right child of the node, then append childs to nodes
            continue till all elements at this level are traversed

        """

        final = [] #this list will contain final list containing one list for each level
        queue = []
        if root:
            queue.append(root) #append root element
        while queue:
            qSize = len(queue) #number of nodes at this level
            level = [] #list to store elements at this level
            for elem in range(qSize):
                node = queue.pop(0)
                level.append(node.val)
                #append any left or right childs to the nodes, these will be nodes for next level
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            final.append(level)
        return final


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from django.utils.translation import ugettext_lazy as _

USERNAME_FIELD_HELP_TEXT = _(
    'Required field. Length must not exceed 30 characters. Only letters, digits and symbols @/./+/-/_ are accepted.'
)
USERNAME_LENGTH_VALIDATION_TEXT = _('Username length must not exceed 30 characters.')

# ==============================================================================
# CustomerCreationForm
# ==============================================================================
class CustomerCreationForm(UserCreationForm):
    class Meta(UserChangeForm.Meta):
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        super(UserCreationForm, self).__init__(*args, **kwargs)
        self.fields['username'].help_text = USERNAME_FIELD_HELP_TEXT

    def clean(self):
        if 'username' in self.cleaned_data:
            username = self.cleaned_data['username']
            if username and len(username) > 30:
                raise forms.ValidationError(USERNAME_LENGTH_VALIDATION_TEXT)

    def save(self, commit=True):
        self.instance.is_staff = True
        return super(CustomerCreationForm, self).save(commit=False)

# ==============================================================================
# CustomerChangeForm
# ==============================================================================
class CustomerChangeForm(UserChangeForm):
    email = forms.EmailField(required=False)

    class Meta(UserChangeForm.Meta):
        model = get_user_model()

    def __init__(self, *args, **kwargs):
        initial = kwargs.get('initial', {})
        instance = kwargs.get('instance')
        initial['email'] = instance.email or ''
        super(CustomerChangeForm, self).__init__(initial=initial, *args, **kwargs)
        self.fields['username'].help_text = USERNAME_FIELD_HELP_TEXT

    def clean(self):
        if 'username' in self.cleaned_data:
            username = self.cleaned_data['username']
            if username and len(username) > 30:
                raise forms.ValidationError(USERNAME_LENGTH_VALIDATION_TEXT)

    def clean_email(self):
        email = self.cleaned_data.get('email').strip()
        if not email:
            # nullify empty email field in order to prevent unique index collisions
            return None
        customers = get_user_model().objects.filter(email=email)
        if len(customers) and (len(customers) > 1 or self.instance != customers[0]):
            msg = _("A customer with the e-mail address ‘{email}’ already exists.")
            raise forms.ValidationError(msg.format(email=email))

        return email

    def save(self, commit=False):
        self.instance.email = self.cleaned_data['email']
        return super(CustomerChangeForm, self).save(commit)


#!/usr/bin/env python3
# coding=utf-8

'''MDMForm 系统配置主窗口'''

import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPalette, QPixmap, QIcon
from PyQt5.QtWidgets import QMainWindow,QMessageBox,QTableWidgetItem,QFileDialog

from PyQt5 import QtSql
from PyQt5.QtSql import QSqlQuery

from openpyxl import load_workbook,Workbook

import warnings
warnings.filterwarnings('ignore')

BASE_DIR= os.path.dirname(os.path.dirname(os.path.abspath(__file__) ) )
sys.path.append( BASE_DIR  )
from ui.Ui_MDMForm import Ui_MDMForm

class MDMForm(QMainWindow,Ui_MDMForm):

    def __tablesql(self):
        """返回所有配置表的信息,用来对照Excel模板文件信息

        Returns:
            string: 查询表SQL语句
        """
        sql= 'SELECT object_id, \
                object_name, \
                object_name_cn, \
                object_desc, \
                template_file, \
                template_sheet, \
                start_row, \
                end_row \
                FROM xt_objects \
                where object_type=\'T\' \
                order by object_id ASC'
        return sql

    def __columnsql(self,id):
        """指定表的列及对应excel内汉字名称

        Args:
            id (int): 配置的表ID

        Returns:
            string: SQL查询列信息
        """
        sql= 'SELECT \
            object_name, \
            object_name_cn, \
            object_desc, \
            column_mapping \
            FROM xt_objects \
            where object_type=\'C\' \
            and parent_object_id= '
        sql += str(id)

        #sql += ' and rim(column_mapping) !=\'\' '
        sql += ' order by column_mapping asc'

        return sql

    def __columns(self,id):
        """指定表的列及对应excel内汉字名称

        Args:
            id (int): 配置的表ID

        Returns:
            dict: 回指定表的列及对应excel内汉字名称字典
        """
        cols = dict()
        if not self.db.isOpen():
            if not self.db.open():
                QMessageBox.critical(self, 'MDM', self.db.lastError().text())
                return
        query = QSqlQuery()
        if not query.exec(self.__columnsql(str(id))):
            QMessageBox.critical(self,'MDM', query.lastError().text())
        else:
            while query.next():
                cols[query.value('object_name')] = query.value('object_name_cn')
        return cols

    def __columnmap(self,id):
        """指定表的列及对应excel内对应列

        Args:
            id (int): 配置的表ID

        Returns:
            dict:  回指定表的列及对应excel内对应excel的列
        """
        cols = dict()
        if not self.db.isOpen():
            if not self.db.open():
                QMessageBox.critical(self, 'MDM', self.db.lastError().text())
                return
        query = QSqlQuery()
        if not query.exec(self.__columnsql(str(id))):
            QMessageBox.critical(self,'MDM', query.lastError().text())
        else:
            while query.next():
                cols[query.value('object_name')] = query.value('column_mapping')
        return cols

    def __insertsql(self,columnmap,tbname):
        """插入配置表语句

        Args:
            columnmap (dict): 配置表字段与Excel对应列
            tbname (string): 配置表名

        Returns:
            string: 带参数的sql insert语句
        """
        sqlk = ''
        sqlv = ''
        for k,v in columnmap.items():
            if len(str(v))>0:
                if len(sqlk) > 0:
                    sqlk +=','
                    sqlv +=','
                sqlk += str(k)
                sqlv += '?'
        sql = 'insert into '
        sql += tbname
        sql += ' ('
        sql += sqlk
        sql += ') values ('
        sql += sqlv
        sql +=')'
        return sql

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setupUiEx()
        self.addConnect()
        self.db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
        self.db.setDatabaseName(os.path.join(BASE_DIR,'db\\mdm.db'))
        self.initData()
        if self.MDMListWidget.count()>0:
            self.MDMListWidget.setCurrentItem(self.MDMListWidget.item(0))
            self.mdmListClick()

    def closeEvent(self, QCloseEvent):
        if self.db.isOpen:
            self.db.close()

    def setupUiEx(self):
        palette = QPalette()
        icon = QIcon()
        appPath=os.path.join(BASE_DIR,u'res\\icon\\mdmconf.ico')
        icon.addPixmap(QPixmap(appPath))
        self.setWindowIcon(icon)

    def addConnect(self):
        self.MDMListWidget.clicked.connect(self.mdmListClick)
        self.btnTemplate.clicked.connect(self.templateClick)
        self.btnImport.clicked.connect(self.importClick)
        self.btnExport.clicked.connect(self.exportClick)
        self.btnUpdate.clicked.connect(self.updateClick)

    def initData(self):
        self.MDMListWidget.clear()
        if not self.db.isOpen():
            if not self.db.open():
                QMessageBox.critical(self, 'MDM', self.db.lastError().text())
                return
        query = QSqlQuery()
        if query.exec(self.__tablesql()):
            while query.next():
                qItem = QtWidgets.QListWidgetItem()
                cols = dict()
                cols['object_id'] = query.value('object_id')
                cols['object_name'] = query.value('object_name')
                cols['object_name_cn'] = query.value('object_name_cn')
                cols['object_desc'] = query.value('object_desc')
                cols['template_file'] = query.value('template_file')
                cols['template_sheet'] = query.value('template_sheet')
                cols['start_row'] = query.value('start_row')
                cols['end_row'] = query.value('end_row')
                qItem.setData(QtCore.Qt.ItemDataRole.UserRole,cols)
                qItem.setText(query.value('object_name_cn'))

                self.MDMListWidget.addItem(qItem)
        else:
             QMessageBox.critical(self,'MDM', query.lastError().text())

    def showData(self,id,name):
        """绑定配置数据到界面

        Args:
            id (int): 配置表ID
            name (string): 配置表名
        """
        cols = self.__columns(str(id))
        self.dataTableWidget.clear()
        self.dataTableWidget.setRowCount(0)
        self.dataTableWidget.setColumnCount(len(cols))
        self.dataTableWidget.setHorizontalHeaderLabels(cols.values())

        sql = ''
        for col in cols.keys():
            if(len(sql))>0:
                sql += ','
            sql += str(col)
        sql = 'select ' + sql
        sql +=' from '
        sql += str(name)
        if not self.db.isOpen():
            if not self.db.open():
                QMessageBox.critical(self, 'MDM', self.db.lastError().text())
                return
        query = QSqlQuery()
        if not query.exec(sql):
            QMessageBox.critical(self,'MDM', query.lastError().text())
        else:
            while query.next():
                rows=self.dataTableWidget.rowCount()
                self.dataTableWidget.insertRow(rows)
                for i in range(len(cols)):
                    qtitem=QTableWidgetItem(str(query.value(list(cols.keys())[i])))
                    self.dataTableWidget.setItem(rows,i,qtitem)

    def mdmListClick(self):
        qItem=self.MDMListWidget.currentItem()
        tconfs = dict(qItem.data(QtCore.Qt.ItemDataRole.UserRole))

        self.dataLabel.setText(str(tconfs['object_name_cn']) + ' : ' + str(tconfs['object_desc']))
        self.temFile.setText(str(tconfs['template_file']))
        self.temSheet.setText(str(tconfs['template_sheet']))
        self.temStart.setText(str(tconfs['start_row']))
        self.temEnd.setText(str(tconfs['end_row']))
        self.showData(str(tconfs['object_id']),str(tconfs['object_name']))

    def templateClick(self):
        if self.MDMListWidget.count()<=0:
            QMessageBox.information(self,'MDM', '请先选择要打开配置文件对应的基础数据配置表')
            return
        qItem=self.MDMListWidget.currentItem()
        tconfs = dict(qItem.data(QtCore.Qt.ItemDataRole.UserRole))

        if str(tconfs['template_file']) =='':
            QMessageBox.information(self,'MDM', '当前基础数据表尚未配置对应的配置文件')
            return
        appPath=os.path.join(BASE_DIR,str(tconfs['template_file']))
        #subprocess.run(appPath)
        os.system('start ' + appPath)
        #os.startfile(appPath)
        return

    def importClick(self):
        if self.MDMListWidget.count()<=0:
            QMessageBox.information(self,'MDM', '请先选择要重新导入数据的基础数据配置表')
            return
        fNames= QFileDialog.getOpenFileName(self,'导入基础数据', '/','Excel File (*.xlsx)')
        if not fNames[0]:
            return

        qItem=self.MDMListWidget.currentItem()
        tconfs = dict(qItem.data(QtCore.Qt.ItemDataRole.UserRole))
        sheetName = str(tconfs['template_sheet'])
        if QMessageBox.question(self, 'MDM', '确认更新模板配置表[' +sheetName + ']的数据?',QMessageBox.Yes|QMessageBox.No) == QMessageBox.No:
            return

        startRow = 2  #默认没有设置起始值，则默认从第二行开始（第一行为标题）
        if str(tconfs['start_row']).isdigit():
            startRow=int(str(tconfs['start_row']))
        endRow = 0   #没有设置结束行，默认后面数据行全部加载
        if str(tconfs['end_row']).isdigit():
            endRow=int(str(tconfs['end_row']))
        columnMap =dict()
        columnMap = self.__columnmap(str(tconfs['object_id']))

        try:
            wb= load_workbook(filename=fNames[0],read_only=True,data_only=True)
            if not (wb.sheetnames.index(sheetName) >= 0):
                QMessageBox.warning(self,'MDM', '选择的文件:' + fNames[0] + ',未包含配置指定的Sheet[' +sheetName + ']')
                wb.close()
                return

            ws=wb[sheetName]

            if endRow == 0:
                endRow = ws.max_row   # type: ignore
            sql = 'delete from ' + str(tconfs['object_name'])
            if not self.db.isOpen():
                if not self.db.open():
                    QMessageBox.critical(self, 'MDM', self.db.lastError().text())
                    return
            query = QSqlQuery()
            if not query.exec_(sql):
                QMessageBox.warning(self,'MDM', '清空数据表[' + str(tconfs['object_name_cn'] + ':' + query.lastQuery() + ']失败' + query.lastError().text()))
                wb.close()
                return
            sql = self.__insertsql(columnMap,str(tconfs['object_name']) )
            query.prepare(sql)
            for iRow in (range(startRow,endRow+1)):
                bAllEmptyflag = True
                for k,v in columnMap.items():
                    if len(str(v))<=0:
                        continue
                    if ws[str(v)+str(iRow)].value is None:
                        qvalue =''
                    else:
                        qvalue = str(ws[str(v)+str(iRow)].value)# type: ignore

                    if not(len(qvalue)==0 or qvalue.isspace()):
                        bAllEmptyflag = False
                    query.addBindValue(qvalue)

                if bAllEmptyflag:
                    continue
                elif not query.exec():
                        QMessageBox.warning(self,'MDM', '执行语句[' + query.lastQuery() + ']失败,' + query.lastError().text())
                        wb.close()
                        return
            wb.close()
            self.showData(str(tconfs['object_id']),str(tconfs['object_name']))
            QMessageBox.information(self,'MDM', '导入数据[' + str(tconfs['object_name_cn'])+ ']完成')
        except (NameError,ZeroDivisionError):
            QMessageBox.critical(self, '动力电缆计算', '变量名错误或除数为0')
        except OSError as reason:
            QMessageBox.critical(self, '动力电缆计算', str(reason))
        except TypeError as reason:
            QMessageBox.critical(self, '动力电缆计算', str(reason))
        except :
            QMessageBox.information(self,'动力电缆计算','导出数据文件失败')

    def exportClick(self):
        if self.MDMListWidget.count()<=0:
            QMessageBox.information(self,'MDM', '请先选择要重新导入数据的基础数据配置表')
            return
        fNames= QFileDialog.getSaveFileName(self,'下载基础数据', '/','Excel File (*.xlsx)')
        if not fNames[0]:
            return
        qItem=self.MDMListWidget.currentItem()
        tconfs = dict(qItem.data(QtCore.Qt.ItemDataRole.UserRole))
        sheetName = str(tconfs['template_sheet'])
        startRow = 2  #默认没有设置起始值，则默认从第二行开始（第一行为标题）
        if str(tconfs['start_row']).isdigit():
            startRow=int(str(tconfs['start_row']))

        columnMap = dict()
        column = dict()
        columnMap = self.__columnmap(str(tconfs['object_id']))
        column = self.__columns(str(tconfs['object_id']))

        try:
            wb = Workbook()
            ws = wb.active
            ws.title = sheetName
            for k,v in columnMap.items():
                if len(str(v))<=0:
                    continue
                ws[str(v)+str(startRow-1)] = column[k]   # type: ignore
            sql = ''
            for col in columnMap.keys():
                if(len(sql))>0:
                    sql += ','
                sql += str(col)
            sql = 'select ' + sql
            sql +=' from '
            sql += str(tconfs['object_name'])
            if not self.db.isOpen():
                if not self.db.open():
                    QMessageBox.critical(self, 'MDM', self.db.lastError().text())
                    return
            query = QSqlQuery()
            if not query.exec(sql):
                QMessageBox.critical(self,'MDM', query.lastError().text())
                return
            iRow = startRow
            while query.next():
                for k,v in columnMap.items():
                    if len(str(v))<=0:
                        continue
                    ws[str(v)+str(iRow)] = str(query.value(str(k))) # type: ignore
                iRow += 1
            wb.save(fNames[0])
            wb.close
            QMessageBox.information(self,'MDM','导出数据完成，文件名：' + fNames[0])
        except (NameError,ZeroDivisionError):
            QMessageBox.critical(self, '动力电缆计算', '变量名错误或除数为0')
        except OSError as reason:
            QMessageBox.critical(self, '动力电缆计算', str(reason))
        except TypeError as reason:
            QMessageBox.critical(self, '动力电缆计算', str(reason))
        except :
            QMessageBox.information(self,'动力电缆计算','导出数据文件失败')
        return

    def updateClick(self):
        if self.MDMListWidget.count()<=0:
            QMessageBox.information(self,'MDM', '请先选择要更新模板文件数据的基础数据配置表')
            return

        qItem=self.MDMListWidget.currentItem()
        tconfs = dict(qItem.data(QtCore.Qt.ItemDataRole.UserRole))
        if str(tconfs['template_file']) =='':
            QMessageBox.information(self,'MDM', '当前基础数据表尚未配置对应的配置文件')
            return
        tempfile=os.path.join(BASE_DIR,str(tconfs['template_file']))

        sheetName = str(tconfs['template_sheet'])

        if QMessageBox.question(self, 'MDM', '确认更新本地模板文件:' + tempfile + ',配置表[' + sheetName + ']的数据?',QMessageBox.Yes|QMessageBox.No) == QMessageBox.No:
            return

        startRow = 2  #默认没有设置起始值，则默认从第二行开始（第一行为标题）
        if str(tconfs['start_row']).isdigit():
            startRow=int(str(tconfs['start_row']))
        try:
            columnMap = dict()
            column = dict()
            columnMap = self.__columnmap(str(tconfs['object_id']))
            column = self.__columns(str(tconfs['object_id']))
            wb = load_workbook(tempfile,False)
            if not (wb.sheetnames.index(sheetName) >= 0):
                QMessageBox.warning(self,'MDM', '选择的文件:' + tempfile + ',未包含配置指定的Sheet[' + sheetName + ']')
                wb.close()
                return
            ws=wb[sheetName]
            #maxRow = ws.max_row # type: ignore
            # #暂未实现清除文档中老数据（考虑有附加列未导入数据库，如图片等）
            '''
            if startRow >1:
                for k,v in columnMap.items():
                    if len(str(v))<=0:
                        continue
                    QMessageBox.information(self,'MDM', str(column[k]))
                    ws[str(v)+str(startRow-1)] = str(column[k])   # type: ignore
                    #更新标题暂未实现
            '''
            sql = ''
            for col in columnMap.keys():
                if(len(sql))>0:
                    sql += ','
                sql += str(col)
            sql = 'select ' + sql
            sql +=' from '
            sql += str(tconfs['object_name'])
            if not self.db.isOpen():
                if not self.db.open():
                    QMessageBox.critical(self, 'MDM', self.db.lastError().text())
                    return
            query = QSqlQuery()
            if not query.exec(sql):
                QMessageBox.critical(self,'MDM', query.lastError().text())
                return
            iRow = startRow
            while query.next():
                for k,v in columnMap.items():
                    if len(str(v))<=0:
                        continue
                    ws[str(v)+str(iRow)] = str(query.value(str(k))) # type: ignore
                iRow += 1
            wb.save(tempfile)
            wb.close
            QMessageBox.information(self,'MDM','更新模板文件数据:' + tempfile + '完成')
        except (NameError,ZeroDivisionError):
            QMessageBox.critical(self, '动力电缆计算', '变量名错误或除数为0')
        except OSError as reason:
            QMessageBox.critical(self, '动力电缆计算', str(reason))
        except TypeError as reason:
            QMessageBox.critical(self, '动力电缆计算', str(reason))
        except :
            QMessageBox.information(self,'动力电缆计算','导出数据文件失败')
        return


'''import random
countries = ['gt', 'nic', 'cr']

population = {country: random.randint(1, 100)
for country in countries}
print(population)

result2 = {country: population for (country, population) in population.items() if population > 50}
print(result2)

text = 'Hola, si soy una mierda'
unique = {c: text.count(c) for c in text if c in 'aeiou'}
print(unique)'''

def message_creator(text):
   # Escribe tu soluciÃ³n ðŸ‘‡

   respuestas = {'computadora' : "Con mi computadora puedo programar usando Python",
                    'celular' : "En mi celular puedo aprender usando la app de Platzi",
                    'cable' : "Â¡Hay un cable en mi bota!"}

   if text in respuestas.keys():
      print(respuestas['cable'])
      return respuestas[text]
   else:
      return 'ArtÃculo no encontrado'

text = 'celular'
response = message_creator(text)
print(response)


from casinos_manager import CasinosManager
from player import EmptyPlayer, HumanPlayer, MLPlayer, RuleBasePlayer, RandomPlayer

class PlayersManager:
    def __init__(self, print_game: bool = True):
        self._player_slots = [EmptyPlayer(index=i + 1) for i in range(5)]
        self._print_game = print_game

    def __len__(self):
        cnt = 0
        for _ in self._get_exist_players():
            cnt += 1
        return cnt

    def __str__(self):
        string = "[PLAYERS]"
        for player in self._player_slots:
            if isinstance(player, EmptyPlayer):
                continue
            string += '\n' + str(player)
        return string

    def reset_game(self):
        self.set_num_white_dice()
        for player in self._player_slots:
            player.reset_game()

    def reset_round(self):
        for player in self._player_slots:
            player.reset_round()

    def set_num_white_dice(self, num_white_dice: int = None):
        if num_white_dice is None:
            empty_cnt = 0
            for player in self._player_slots:
                if isinstance(player, EmptyPlayer):
                    empty_cnt += 1
            if empty_cnt == 0:
                num_white_dice = 0
            elif empty_cnt == 1 or empty_cnt == 2:
                num_white_dice = 2
            elif empty_cnt == 3:
                num_white_dice = 4
            else:
                num_white_dice = 8

        for player in self._player_slots:
            player.set_num_white_dice(num_white_dice)

    def add_player(self, slot_index: int, player_type: str = "Human"):
        if isinstance(self._player_slots[slot_index - 1], EmptyPlayer):
            if player_type == 'Human':
                self._player_slots[slot_index - 1] = HumanPlayer(index=slot_index, print_game=self._print_game)
                return True
            elif player_type == 'MLPlayer':
                self._player_slots[slot_index - 1] = MLPlayer(index=slot_index, print_game=self._print_game)
                return True
            elif player_type == 'MLPlayerTraining':
                self._player_slots[slot_index - 1] = MLPlayer(index=slot_index, print_game=self._print_game, train=True)
                return True
            elif player_type == 'RuleBase':
                self._player_slots[slot_index - 1] = RuleBasePlayer(index=slot_index, print_game=self._print_game)
                return True
            elif player_type == 'Random':
                self._player_slots[slot_index - 1] = RandomPlayer(index=slot_index, print_game=self._print_game)
                return True
            else:
                print("Player type {} not yet implemented".format(player_type))
                return False
        else:
            print("Slot {} is not empty".format(slot_index)) if self._print_game else None
            return False

    def del_player(self, slot_index: int):
        self._player_slots[slot_index - 1] = EmptyPlayer(index=slot_index)

    def _get_exist_players(self):
        for player in self._player_slots:
            if not isinstance(player, EmptyPlayer):
                yield player

    def get_num_players(self):
        return len(self)

    def get_players_info(self):
        players_info = {}
        for player in self._get_exist_players():
            num_dice, num_dice_white = player.get_num_dice()
            players_info[player.index] = {'num_dice': num_dice, 'num_dice_white': num_dice_white, 'money': player.get_money()}
        return players_info

    def get_ranking(self):
        players_money = {}
        for player_i, player in enumerate(self._player_slots):
            if not isinstance(player, EmptyPlayer):
                players_money[player_i + 1] = player.get_money()

        ranking = []
        for player_index, player_money in sorted(players_money.items(), key=lambda x: x[1], reverse=True):
            ranking.append(player_index)
        return ranking

    def add_banknotes(self, players_win: dict):
        for player_index, banknotes in players_win.items():
            if player_index == 0:
                continue
            self._player_slots[player_index - 1].add_banknotes(banknotes)

    def run_turn(self, casinos_manager: CasinosManager, game_info=None):
        all_done = True

        for player in self._get_exist_players():
            casino_index, dice = player.run_turn(game_info=game_info)
            if not casino_index:
                continue
            casinos_manager.add_dice(casino_index=casino_index, dice=dice)
            game_info['casinos'] = casinos_manager.get_casinos_info()
            all_done = False

        return all_done


from re import L
from flask import Flask
from flask import jsonify
from flask import request
from flask_restful import Api, Resource, reqparse
import json
import sys
from get_details import get_name
from process_swipe import process_swipe
import requests
import random
from eventlet import wsgi
import eventlet
from redis_instance import get_instance
from RecommendationEngine import get_swipe_stack
from mysql_connection import get_cursor
import traceback
import pymongo

mongod = pymongo.MongoClient("")
db = mongod["tat"]
collection = db["sessions"]
r = get_instance()

# 1 day
EXPIRATION_TIME = 86400

like_post_args = reqparse.RequestParser()
like_post_args.add_argument(
    "foodid", type=int, help="The ID of the food item swiped on")
like_post_args.add_argument("userid", type=str, help="Your UserID")
like_post_args.add_argument("restuarantid", type=int, help="The restaurants ID UserID")
like_post_args.add_argument("authtoken", type=str, help="Authorisation token")
like_post_args.add_argument(
    "islike", type=bool, help="If the like was like / dislike")
like_post_args.add_argument(
    "isfavourite", type=bool, help="If it was a super like")
like_post_args.add_argument("isGroup", type=bool, help="If the swipe stack you're getting is for a group")

swipestack_args = reqparse.RequestParser()
swipestack_args.add_argument(
    "lat", type=float, help="Lattitude of where to search recommendations"
)
swipestack_args.add_argument(
    "lng", type=float, help="Longitude of where to search recommendations"
)
swipestack_args.add_argument(
    "userid", type=str, help="The userID"
)
swipestack_args.add_argument("authtoken", type=str, help="Authorisation token")
swipestack_args.add_argument("code", type=int, help="Room code")
swipestack_args.add_argument("isGroup", help="If the swipe stack you're getting is for a group")
swipestack_args.add_argument(
    "distance", type=float, help="Radius of the circle to search within"
)

app = Flask(__name__)
api = Api(app)

class RecommenderController(Resource):
    #get [/swipestack]
    def post(self):
        args = swipestack_args.parse_args()
        print(args)
        payload = {"authtoken": args.authtoken, "userid": args.userid}
        r = requests.post(
            'http://devapi.trackandtaste.com/user/authcheck', json=payload)
        if r.status_code != 200:
            return '', r.status_code
        try:
            data = get_swipe_stack(args.lat, args.lng, args.userid, args.distance, args.isGroup == "True", str(args.code))
        except Exception as e :
            print(e)
            print(traceback.format_exc())
            return '', 404 # We couldn't find any restaurants
        return json.loads(data), 200

class SwipeController(Resource):
    # post [/swipe]
    def post(self):
        args = like_post_args.parse_args()
        payload = {"authtoken": args.authtoken, "userid": args.userid}
        res = requests.post(
            'http://devapi.trackandtaste.com/user/authcheck', json=payload)
        if res.status_code != 200:
            return '', r.status_code
        try:
            process_swipe(args.userid, args.foodid,
                            args.islike, args.isfavourite)
            # If the swipe doesn't come from the group page, cache it
            # Else caching is handled by the websocket server and is saved in mongo
            if not args.isGroup:
                print(args)
                r.lpush(f"Recommendations-{args.userid}", args.foodid)
                r.expire(f"Recommendations-{args.userid}", 7200)
                if args.islike or args.isfavourite:
                    r.lpush(f"Likes-{args.userid}", f"{args.foodid},{args.restuarantid}")
                    r.expire(f"Likes-{args.userid}", 7200)
        except Exception as e:
            print(e)
            print(traceback.format_exc())
            # Food item not found
            return '', 404
        return '', 201

class ItemController(Resource):
    #get [/likeditems]
    def get(self):
        args = request.args
        # If we're dealing with a group
        filtered = []

        if(args["isGroup"] == "true"):
            print("is group")
            room = collection.find_one({"code" : args["room"]}, {"restaurantsLiked": 1})
            userid = str(args["userID"])
            restaurantid = int(args["restaurantID"])
            for restaurant in room["restaurantsLiked"]:
                if restaurant["restaurantID"] == restaurantid:
                    for user in restaurant["likes"]:
                        if user["userID"] == userid:
                            for item in user["items"]:
                                filtered.append(str(item))
        else:
            print("Nota group")
            # We're dealing with individual swipe
            likedItems = [i.decode("UTF-8") for i in r.lrange(f"Likes-{args['userID']}", 0, -1)]
            for item in likedItems:
                if item.split(',')[1] == str(args["restaurantID"]):
                    filtered.append(item.split(',')[0])

        if len(filtered) == 0:
            return '', 404
        cursor = get_cursor()
        cursor.execute(f"SELECT Price, FoodNameShort, FoodID FROM FoodItem WHERE FoodID IN({','.join(filtered)});")
        result = cursor.fetchall()
        items = []
        for item in result:
            items.append({"price": str(item[0]),"name": item[1], "id": item[2]})
        print(items)
        return items, 200

api.add_resource(SwipeController, "/swipe")
api.add_resource(RecommenderController, "/swipestack")
api.add_resource(ItemController, "/likeditems")
if __name__ == "__main__":
    wsgi.server(eventlet.listen(('', 8000)), app)