from joblib import dump, load
from sklearn.ensemble import RandomForestRegressor
from sklearn.kernel_ridge import KernelRidge
from sklearn.gaussian_process import GaussianProcessRegressor
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from itertools import chain, combinations
from sklearn.gaussian_process.kernels import RationalQuadratic, RBF, DotProduct, WhiteKernel, Matern
from sklearn.metrics import mean_absolute_error, mean_absolute_percentage_error, mean_squared_error
import tensorflow as tf
import os
from preprocessed import data_preprocess
import pickle

def random_forest_model(num_trees=400, max_depth=20, model_name = 'rf', data_dir = 'VN_housing_dataset.csv'):
    model = RandomForestRegressor(n_estimators=num_trees, max_depth=max_depth, min_samples_leaf=2, max_features='sqrt')
    X_train, X_test, y_train, y_test = data_preprocess(data_dir)
    model.fit(X_train, y_train)
    print("Model MAE on training set", mean_absolute_error(y_train, model.predict(X_train)))
    print("Model MAE on test set", mean_absolute_error(y_test, model.predict(X_test)))
    print("Model MSE on training set", mean_squared_error(y_train, model.predict(X_train)))
    print("Model MSE on test set", mean_squared_error(y_test, model.predict(X_test)))
    print("Model MAPE on training set", mean_absolute_percentage_error(y_train, model.predict(X_train)))
    print("Model MAPE on test set", mean_absolute_percentage_error(y_test, model.predict(X_test)))
    dump(model, os.path.join('saved_model', model_name + '.joblib'))
    print("Saved the model at " + os.path.join('saved_model', model_name + '.joblib'))

def kernel_ridge_regression(kernel='linear', alpha=1, model_name = 'kr', data_dir = 'VN_housing_dataset.csv'):
    model = KernelRidge(alpha=alpha, kernel=kernel, gamma=0.1)
    X_train, X_test, y_train, y_test = data_preprocess(data_dir)
    model.fit(X_train, y_train)
    print("Model MAE on training set", mean_absolute_error(y_train, model.predict(X_train)))
    print("Model MAE on test set", mean_absolute_error(y_test, model.predict(X_test)))
    print("Model MSE on training set", mean_squared_error(y_train, model.predict(X_train)))
    print("Model MSE on test set", mean_squared_error(y_test, model.predict(X_test)))
    print("Model MAPE on training set", mean_absolute_percentage_error(y_train, model.predict(X_train)))
    print("Model MAPE on test set", mean_absolute_percentage_error(y_test, model.predict(X_test)))
    dump(model, os.path.join('saved_model', model_name + '.joblib'))
    print("Saved the model at " + os.path.join('saved_model', model_name + '.joblib'))

def gaussian_process_regression(kernel='Matern', alpha=1, model_name = 'gp', data_dir = 'VN_housing_dataset.csv'):
    if kernel == 'RBF':
        model = GaussianProcessRegressor(kernel = RBF() + WhiteKernel(alpha), normalize_y = True)
    elif kernel == 'Matern':
        model = GaussianProcessRegressor(kernel = Matern() + WhiteKernel(alpha), normalize_y = True)
    elif kernel == "DotProduct":
        model = GaussianProcessRegressor(kernel = DotProduct() + WhiteKernel(alpha), normalize_y = True)
    elif kernel == "RationalQuadratic":
        model = GaussianProcessRegressor(kernel = RationalQuadratic() + WhiteKernel(alpha), normalize_y = True)
    else:
        print("Invalid kernel")
        return
    X_train, X_test, y_train, y_test = data_preprocess(data_dir)
    model.fit(X_train, y_train)
    print("Model MAE on training set", mean_absolute_error(y_train, model.predict(X_train)))
    print("Model MAE on test set", mean_absolute_error(y_test, model.predict(X_test)))
    print("Model MSE on training set", mean_squared_error(y_train, model.predict(X_train)))
    print("Model MSE on test set", mean_squared_error(y_test, model.predict(X_test)))
    print("Model MAPE on training set", mean_absolute_percentage_error(y_train, model.predict(X_train)))
    print("Model MAPE on test set", mean_absolute_percentage_error(y_test, model.predict(X_test)))
    dump(model, os.path.join('saved_model', model_name + '.joblib'))
    print("Saved the model at " + os.path.join('saved_model', model_name + '.joblib'))

def ensemble_neural_network(neurons=25, model_name = 'enn', data_dir = 'VN_housing_dataset.csv'):
    X_train, X_test, y_train, y_test = data_preprocess(data_dir)
    X_train = tf.convert_to_tensor(X_train, dtype=tf.float64)
    X_test = tf.convert_to_tensor(X_test, dtype=tf.float64)
    y_train = tf.convert_to_tensor(y_train, dtype=tf.float64)
    y_test = tf.convert_to_tensor(y_test, dtype=tf.float64)
    list_of_layers =[]
    Layer_0 = Dense(units=neurons, input_dim=X_train.shape[1], kernel_initializer='normal', activation='relu')
    for i in range(3):
      list_of_layers.append(Dense(units=neurons, kernel_initializer = 'normal', activation = 'relu'))
    final_layer = Dense(1, kernel_initializer='normal')
    def powerset(iterable):
        "powerset([1,2,3]) → () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
        s = list(iterable)
        return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
    for x in powerset(list_of_layers):
        temp_list_of_layers =list(x)
        ANN_temp = Sequential()

        ANN_temp.add(Layer_0)
        for layer in temp_list_of_layers:
            ANN_temp.add(layer)

        ANN_temp.add(final_layer)
        ANN_temp.compile(loss='mean_squared_error', optimizer='adam')
        ANN_temp.fit(x = X_train, y = y_train, batch_size = X_train.shape[0], epochs=3000, verbose=0)
    print("Model MAE on training set", mean_absolute_error(y_train.numpy(), ANN_temp.predict(X_train)))
    print("Model MAE on test set", mean_absolute_error(y_test.numpy(), ANN_temp.predict(X_test)))
    print("Model MSE on training set", mean_squared_error(y_train.numpy(), ANN_temp.predict(X_train)))
    print("Model MSE on test set", mean_squared_error(y_test.numpy(), ANN_temp.predict(X_test)))
    print("Model MAPE on training set", mean_absolute_percentage_error(y_train.numpy(), ANN_temp.predict(X_train)))
    print("Model MAPE on test set", mean_absolute_percentage_error(y_test.numpy(), ANN_temp.predict(X_test)))
    ANN_temp.save(os.path.join('saved_model', model_name + '.h5'))

def load_model(model_dir, input_data_dir="VN_housing_dataset.csv"):
    model = load(model_dir)
    X = data_preprocess(input_data_dir, "encoder.pkl")
    print("The prediction output:")
    print(model.predict(X))

def load_keras_model(model_dir, input_data_dir="VN_housing_dataset.csv"):
    model = tf.keras.models.load_model(model_dir)
    X = data_preprocess(input_data_dir, "encoder.pkl")
    X = tf.convert_to_tensor(X, dtype=tf.float64)
    print("The prediction output:")
    print(model.predict(X))


import chess
import chess.pgn

class Game:
    def __init__(self, model, model_format="lan", human_start=True, start_position=None):
        if start_position == None:
            self.board = chess.Board()
        else: # Play from any position
            self.board = chess.Board(fen=start_position)
        self.model = model
        self.model_format = model_format
        self.human_turn = human_start # True if human has first move, False if AI starts

        if model_format == "san" or "pgn": # python-chess requires an empty board to parse the move stack
            self.empty_board = chess.Board()

    def play(self):
        display(self.board) # Display the board position in a nice way
        print("Board position: ", self.get_board_position(self.model_format)) # Print board position in notation (this is what the model sees)

        move = self.get_move(self.human_turn)

        if move in self.board.legal_moves:
            self.board.push(move) # MAKE THE MOVE (most important line of code)
            self.human_turn = not self.human_turn # Switch turns

            if not self.board.is_game_over(): # Check if the game is over, if not play the next round
                self.play()
            else:
                display(self.board)
                print("Game over!")

        else:
            display(self.board)
            print("An invalid move was made and the game has ended.")

    def get_move(self, human_turn):
        # Get move from human
        if human_turn:
            try:
                move_text = str(input("Your move: "))
                move = self.board.parse_san(move_text)
            except:
                print("Invalid move text! Please try again.")
                move_text = str(input("Your move: "))
                move = self.board.parse_san(move_text)
            return move
        # Get move from AI
        else:
            board_position = self.get_board_position(self.model_format)
            if self.model_format == "pgn" or self.model_format == "san":
                moves = self.model.generate(board_position, 6, 5) # Generate top 5 strings of 6 tokens (the maximum length of a move in SAN notation)
                for move in moves:
                    move = move.replace(board_position+" ", "") # Keep only the newly generated string
                    move = move.split(" ")[0] # The first move in the string is the new move
                    try:
                        move = self.board.parse_san(move)
                    except:
                        continue
                    if move in self.board.legal_moves:
                        return move
            elif self.model_format == "lan" or self.model_format == "uci":
                moves = self.model.generate(board_position, 1, 5) # Generate top 5 strings of 1 token (each move is one token)
                for move in moves:
                    move = move.split(" ")[-1] # Take the last token, which is the new move
                    move = self.board.parse_san(move)
                    if move in self.board.legal_moves:
                        return move
            # No legal move found
            if self.model_format == "lan" or self.model_format == "uci": # If model uses UCI/LAN format, we can force a legal move with constrained beam search
                move = self.model.generate_legal_move(board_position, self.board)
                move = self.board.parse_san(move)
                return move
            else: # If model uses PGN/SAN format, we cannot use constrained beam search, as moves consist of multiple tokens
                #yprint("The model was not able to find a legal move. It will now resign.")
                raise(ValueError("The model was not able to find a legal move."))

    def get_board_position(self, format):
        if format == "uci" or format == "lan": # Return the board position in LAN notation
            # Found no way to get LAN notation directly in documentation, so it has to be created manually
            text = ""
            for index, move in enumerate(self.board.move_stack):
                if index % 2 == 0:
                    text += str(int(index/2)+1) + ". "
                text += str(move) + " "
            return text
        elif format == "pgn" or format == "san": # Return the board position in SAN notation
            return self.empty_board.variation_san(self.board.move_stack)
        elif format == "fen": # Return the board position in FEN notation
            return self.board.fen()
        else:
            raise ValueError("Invalid format. Please use 'lan' or 'pgn'.")


#-*- coding: utf-8 -*-

import wx.grid as grid

class FileListGridTable(grid.GridTableBase):
	def __init__(self, datas):
		grid.GridTableBase.__init__(self)

		self.datas = datas

		self.colLabels = [u'File Name', u'File Path', u'Page Num']

		self.odd = grid.GridCellAttr()
		self.odd.SetReadOnly(True)
		self.odd.SetBackgroundColour('white')

		self.even = grid.GridCellAttr()
		self.even.SetReadOnly(True)

		pass

	def GetAttr(self, row, col, kind):
		attr = [self.even, self.odd][row % 2]
		attr.IncRef()
		return attr

	def GetNumberRows(self):
		return len(self.datas)

	def GetNumberCols(self):
		return len(self.colLabels)

	def GetColLabelValue(self, col):
		return self.colLabels[col]

	def GetRowLabelValue(self, row):
		return str(row)

	def GetValue(self, row, col):
		return self.datas[row][col]

	def ClearRows(self):
		self.DeleteRows(0, self.GetNumberRows())

	def RowMoveUp(self, row):
		if row > 0:
			temp = self.datas[row - 1]
			self.datas[row - 1] = self.datas[row]
			self.datas[row] = temp

			self.isModified = True

	def RowMoveDown(self, row):
		if row < self.GetNumberRows():
			temp = self.datas[row + 1]
			self.datas[row + 1] = self.datas[row]
			self.datas[row] = temp

			self.isModified = True

	def AppendRows(self, newData=None):
		self.datas.append(newData)
		self.isModified = True
		gridView = self.GetView()
		gridView.BeginBatch()
		appendMsg = grid.GridTableMessage(self, grid.GRIDTABLE_NOTIFY_ROWS_APPENDED, 1)
		gridView.ProcessTableMessage(appendMsg)
		gridView.EndBatch()
		getValueMsg = grid.GridTableMessage(self, grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
		gridView.ProcessTableMessage(getValueMsg)

		return True

	def SetValue(self, row, col, value):
		try:
			self.datas[row][col] = value
		except IndexError:
			# add a new row
			self.datas.append([''] * self.GetNumberCols())
			innerSetValue(row, col, value)

			# tell the grid we've added a row
			msg = grid.GridTableMessage(self,  # The table
										grid.GRIDTABLE_NOTIFY_ROWS_APPENDED,  # what we did to it
										1  # how many
										)

			self.GetView().ProcessTableMessage(msg)

	def DeleteRows(self, pos=0, numRows=0):
		if self.datas is None or len(self.datas) == 0 or numRows == 0:
			return False

		del self.datas[pos:numRows]

		gridView = self.GetView()
		gridView.BeginBatch()
		deleteMsg = grid.GridTableMessage(self, grid.GRIDTABLE_NOTIFY_ROWS_DELETED, pos, numRows)
		gridView.ProcessTableMessage(deleteMsg)
		gridView.EndBatch()
		getValueMsg = grid.GridTableMessage(self, grid.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
		gridView.ProcessTableMessage(getValueMsg)

		self.isModified = True

		return True


#!/usr/bin/env python3
import sys
import math
from itertools import permutations
def doMachine(inp,s,pos):
	output= []
	inpptr=0
	skip= 0
	#print("Position",pos, inp)
	while(True):
		instr=s[pos]%100
		mode1= (int(s[pos]/100))%10
		mode2= (int(s[pos]/1000))%10
		mode3= (int(s[pos]/10000))%10
		#print(pos,s[pos],instr,mode1,mode2,mode3)
		if (instr == 99):
			#print("terminate")
			return(inp+output,-1)
		elif (instr == 1):
			if mode1 == 0:
				x= s[s[pos+1]]
			else:
				x= s[pos+1]
			if mode2 == 0:
				y= s[s[pos+2]]
			else:
				y= s[pos+2]

			res= x + y
			s[s[pos+3]]= res
			#print("Add",res)
			pos+=4
		elif (instr == 2):
			if mode1 == 0:
				x= s[s[pos+1]]
			else:
				x= s[pos+1]
			if mode2 == 0:
				y= s[s[pos+2]]
			else:
				y= s[pos+2]
			res= x * y
			s[s[pos+3]]= res
			pos+=4
			#print("Mult",res)
		elif (instr == 3):
			#print(inp)
			if len(inp) == 0:
				return (output,pos)
			x=inp.pop(0)
			if mode1 == 0:
				s[s[pos+1]]= x
			else:
				s[pos+1]= x
			pos+=2

		elif (instr == 4):
			if (mode1 == 0):
				x=s[s[pos+1]]
			else:
				x= s[pos+1]
			#print(x)
			output.append(x)
			pos+= 2
		elif (instr == 5):
			if mode1 == 0:
				x= s[s[pos+1]]
			else:
				x= s[pos+1]
			if mode2 == 0:
				y= s[s[pos+2]]
			else:
				y= s[pos+2]
			if (x != 0):
				pos= y
			else:
				pos+=3
		elif (instr == 6):
			if mode1 == 0:
				x= s[s[pos+1]]
			else:
				x= s[pos+1]
			if mode2 == 0:
				y= s[s[pos+2]]
			else:
				y= s[pos+2]
			if (x == 0):
				pos= y
			else:
				pos+=3
		elif (instr == 7):
			if mode1 == 0:
				x= s[s[pos+1]]
			else:
				x= s[pos+1]
			if mode2 == 0:
				y= s[s[pos+2]]
			else:
				y= s[pos+2]
			if mode3 == 0:
				store= s[pos+3]
			else:
				store= pos+3
				#print("Weird8")
			if (x < y):
				s[store]= 1
			else:
				s[store]= 0
			pos+=4
		elif (instr == 8):
			if mode1 == 0:
				x= s[s[pos+1]]
			else:
				x= s[pos+1]
			if mode2 == 0:
				y= s[s[pos+2]]
			else:
				y= s[pos+2]
			if mode3 == 0:
				store= s[pos+3]
			else:
				#print("Weird7")
				store= pos+3
			if (x == y):
				#print ("Storing 1 at position",store)
				s[store]= 1
			else:
				s[store]= 0
			pos+=4
		else:
			print("Did not expect ",s[pos])
			sys.exit()
	#print(s)
	#print("Part 1",s[0])

fp= open("rgcinput.txt","r")
l= fp.readline()
fp.close()
s= l.split(",")
pos= 0
for i in s:
	s[pos]= int(i)
	pos+= 1
inputs=permutations([0,1,2,3,4])
best=0
for inp in inputs:
	scopy=s.copy()
	ampa= doMachine([inp[0],0],scopy,0)[0][0]
	scopy=s.copy()
	ampb= doMachine([inp[1],ampa],scopy,0)[0][0]
	scopy=s.copy()
	ampc= doMachine([inp[2],ampb],scopy,0)[0][0]
	scopy=s.copy()
	ampd= doMachine([inp[3],ampc],scopy,0)[0][0]
	scopy=s.copy()
	ampe= doMachine([inp[4],ampd],scopy,0)[0][0]
	if best==0 or ampe > best:
		best= ampe
		bestperm= inp
print("Part 1",bestperm,best)
inputs=permutations([5,6,7,8,9])
best=0
bestcomb=[]
for inp in inputs:
	ampa=s.copy()
	ampb=s.copy()
	ampc=s.copy()
	ampd=s.copy()
	ampe=s.copy()
	#print(inp)
	inpa=[inp[0],0]
	inpb=[inp[1]]
	inpc=[inp[2]]
	inpd=[inp[3]]
	inpe=[inp[4]]
	posa=0
	posb=0
	posc=0
	posd=0
	pose=0
	while True:
		#print(inpa)
		(out,posa)= doMachine(inpa,ampa,posa)
		for o in out:
			inpb.append(o)
		(out,posb)= doMachine(inpb,ampb,posb)
		for o in out:
			inpc.append(o)
		(out,posc)= doMachine(inpc,ampc,posc)
		for o in out:
			inpd.append(o)
		(out,posd)= doMachine(inpd,ampd,posd)
		for o in out:
			inpe.append(o)
		(out,pose)= doMachine(inpe,ampe,pose)
		for o in out:
			inpa.append(o)
		if pose == -1:
			break
	if inpa[0] > best:
		best= inpa[0]
		bestcomb=inp
print("Part 2",bestcomb,best)


from typing import ContextManager
from articles.models import Article
from django.shortcuts import redirect, render, get_object_or_404

# Create your views here.
def index(request):
    articles = Article.objects.order_by('-pk')
    context={
        'articles' : articles,
    }
    return render(request, 'articles/index.html', context)

# def new(request):
#     return render(request, 'articles/new.html')

def create(request):
    if request.method == "POST":
        title = request.POST.get('title')
        content = request.POST.get('content')

        article = Article(title=title, content=content)
        article.save()

        return redirect('articles:detail', article.pk)
    else:
        return render(request, 'articles/new.html')

def detail(request, article_pk):
    article = get_object_or_404(Article, pk=article_pk)

    context = {
        'article':article
    }
    return render(request, 'articles/detail.html', context)

def edit(request, article_pk):
    article = get_object_or_404(Article, pk=article_pk)

    context = {
        'article' : article
    }
    return render(request, 'articles/edit.html', context)

def update(request, article_pk):
    title = request.POST.get('title')
    content = request.POST.get('content')

    article = Article.objects.get(pk=article_pk)
    article.title = title
    article.content = content
    article.save()

    return redirect('articles:detail', article_pk)

def delete(request, article_pk):
    if request.method == 'POST':
        article = Article.objects.get(pk=article_pk)
        article.delete()

        return redirect('articles:index')


import io
import sys
import requests
import json
import bs4
import csv

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

headers = {'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36'}

baseUrl = 'https://www.zhihu.com/api/v4/questions/66515131/answers?include=data%5B%2A%5D.is_normal%2Cadmin_closed_comment%2Creward_info%2Cis_collapsed%2Cannotation_action%2Cannotation_detail%2Ccollapse_reason%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Ccreated_time%2Cupdated_time%2Creview_info%2Crelevant_info%2Cquestion%2Cexcerpt%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cis_labeled%2Cis_recognized%2Cpaid_info%3Bdata%5B%2A%5D.mark_infos%5B%2A%5D.url%3Bdata%5B%2A%5D.author.follower_count%2Cbadge%5B%2A%5D.topics&limit={0}&offset={1}' # from Inspect --> Network --> XHR
url = baseUrl.format('5', '0') # limit and offset, current max offset is 1075

answers = []
isEnd = False

while not isEnd:

    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    responseDict = json.loads(response.text)

    for answersHtml in responseDict['data']:

        answer = ''
        soup = bs4.BeautifulSoup(answersHtml['content'], 'html.parser')

        for paragraphHtml in soup.findAll('p'):

            answer += paragraphHtml.text
            answer += '\n\n'

        answers.append([answer]) # [] for csv writer use

    isEnd = responseDict['paging']['is_end']
    url = responseDict['paging']['next']

with open('rawAnswer.csv', 'w') as f:

    writer = csv.writer(f)

    for answer in answers:
        writer.writerow(answer)


import torch.nn as nn
from utils.Self_Adaptive_Conv import SAPConv
import torch

class SELayer(nn.Module):
    def __init__(self, channel, reduction=16):
        super(SELayer, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Linear(channel, channel // reduction, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channel // reduction, channel, bias=False),
            nn.Sigmoid()
        )

    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x).view(b, c)
        y = self.fc(y).view(b, c, 1, 1)
        return x * y.expand_as(x)

class BasicBlock(nn.Module):
    def __init__(self,
                 in_channels,
                 out_channels,
                 kernel_size,
                 stride=1,
                 downsample=False):
        super(BasicBlock, self).__init__()

        self.stride = stride
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.kernel_size = kernel_size
        self.down = downsample

        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = nn.Conv2d(self.in_channels,
                               self.out_channels,
                               self.kernel_size,
                               self.stride,
                               padding=1,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(self.out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = nn.Conv2d(self.out_channels,
                               self.out_channels,
                               self.kernel_size,
                               padding=1,
                               bias=False)
        self.bn2 = nn.BatchNorm2d(self.out_channels)

        if self.down:
            self.downsample = nn.Sequential(
                nn.Conv2d(self.in_channels,
                          self.out_channels,
                          kernel_size=1,
                          stride=self.stride),
                nn.BatchNorm2d(self.out_channels))

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.down:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out

class MultiBlock(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size):
        super(MultiBlock, self).__init__()

        self.in_channels = in_channels
        self.out_channels = out_channels
        self.kernel_size = kernel_size

        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = nn.Conv2d(self.in_channels,
                               self.out_channels,
                               self.kernel_size,
                               stride=1,
                               padding=1,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(self.out_channels)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = SAPConv(self.out_channels,
                             self.out_channels,
                             is_bias=False)
        self.bn2 = nn.BatchNorm2d(self.out_channels)

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        out += identity
        out = self.relu(out)

        return out

class Resnet18(nn.Module):
    def __init__(self, K_bits=1000):
        super(Resnet18, self).__init__()
        self.conv1 = nn.Conv2d(3,
                               64,
                               kernel_size=7,
                               stride=2,
                               padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        # yapf:disable
        self.layer1 = nn.Sequential(
            BasicBlock(64, 64, kernel_size=3),
            BasicBlock(64, 64, kernel_size=3))
        self.layer2 = nn.Sequential(
            BasicBlock(64, 128, kernel_size=3, stride=2, downsample=True),
            BasicBlock(128, 128, kernel_size=3))
        self.layer3 = nn.Sequential(
            BasicBlock(128, 256, kernel_size=3, stride=2, downsample=True),
            BasicBlock(256, 256, kernel_size=3))
        self.layer4 = nn.Sequential(
            BasicBlock(256, 512, kernel_size=3, stride=2, downsample=True),
            MultiBlock(512, 512, kernel_size=3))
        # MultiBlock(512, 512, kernel_size=3))
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Sequential(nn.BatchNorm1d(512), nn.Linear(512, K_bits))

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x3 = self.layer3(x)
        x4 = self.layer4(x3)

        features = self.avgpool(x4)
        features = features.reshape(features.size(0), -1)
        real_hash = self.fc(features)
        return real_hash


import cv2 as cv
import numpy as np
from google.colab.patches import cv2_imshow

img = cv.imread("imagem1.png")
imagemConvertida = "imagemconvertida.png"

def bitfield(n):
    return [int(digit) for digit in bin(n)[2:]]

def gerar_mensagem(mensagem):
    lista = []
    for m in mensagem:
        val = ord(m)
        bits = bitfield(val)

        if len(bits) < 8:
            for a in range(8-len(bits)):
                bits.insert(0,0)
        lista.append(bits)
    arr = np.array(lista)
    arr = arr.flatten()
    return arr

def converter_mensagem(saida):
    bits = np.array(saida)
    mensagem_out = ''
    bits = bits.reshape((int(len(saida)/8), 8))
    for b in bits:
        sum = 0
        for i in range(8):
            sum += b[i]*(2**(7-i))
        mensagem_out += chr(sum)
    return mensagem_out

def esconder_mensagem(mensagem):
  imgAltera = img.copy()
  altura, largura, x = img.shape
  tamanho_mensagem = len(mensagem)
  print("tamanho da mensagem = "+str(tamanho_mensagem))
  pos = 0

  for i in range(altura):
        for j in range(largura):
            if tamanho_mensagem > pos:
                p = img[i][j][2]
                valor = ((p // 10) * 10) + mensagem[pos]
                imgAltera[i][j][2] = valor
            elif tamanho_mensagem == pos:
                imgAltera[i][j][2] = ((p // 10) * 10) + 2
            pos = pos + 1

  cv2_imshow(imgAltera)
  cv.imwrite(imagemConvertida, imgAltera)
  cv.waitKey(0)

def encontra_mensagem():
    img2 = cv.imread(imagemConvertida)
    altura, largura, x = img.shape
    mensagem = []
    for i in range(altura):
        for j in range(largura):
            p = img2[i][j][2]
            # print(p)
            if (p % 10) < 2:
                mensagem.append(p % 10)
            elif (p % 10) >= 2:
                print("Mensagem encontrada: ")
                print(converter_mensagem(mensagem))
                return mensagem

texto = "Se alguma coisa pode dar errado, dará"
arrayBits = gerar_mensagem(texto)
print("mensagem em binario = " + str(arrayBits))
esconder_mensagem(arrayBits)
encontra_mensagem()
cv2_imshow(img)


from __future__ import with_statement
from builtins import range
import os
import unittest
import numpy as np
import sqlite3
import json
import tempfile
import shutil
import lsst.utils.tests
from lsst.utils import getPackageDir
from lsst.sims.utils.CodeUtilities import sims_clean_up
from lsst.sims.utils import ObservationMetaData
from lsst.sims.catalogs.db import CatalogDBObject
from lsst.sims.catalogs.definitions import InstanceCatalog
from lsst.sims.catUtils.mixins import PhotometryStars, PhotometryGalaxies
from lsst.sims.catUtils.mixins import VariabilityStars, VariabilityGalaxies
from lsst.sims.catUtils.mixins import ExtraGalacticVariabilityModels
from lsst.sims.catUtils.utils import TestVariabilityMixin

from lsst.sims.catUtils.mixins import Variability

VARIABILITY_DB = 'VariabilityTestDatabase.db'
ROOT = os.path.abspath(os.path.dirname(__file__))

def setup_module(module):
    lsst.utils.tests.init()

def makeRRlyTable(size=100, database=VARIABILITY_DB, **kwargs):
    """
    Make a test database to serve information to the rrlyrae test
    """

    # a haphazard sample of stellar SEDs
    sedFiles = ['kp10_8750.fits_g35_8950', 'kp03_10500.fits_g45_10600', 'km50_6750.fits_g20_6750']

    # a haphazard sample of RRLyrae light curves
    lcFiles = ['rrly_lc/RRc/959802_per.txt', 'rrly_lc/RRc/1078860_per.txt', 'rrly_lc/RRab/98874_per.txt',
               'rrly_lc/RRab/3879827_per.txt']

    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE RRly
                     (varsimobjid int, variability text, sedfilename text, parallax real, ebv real)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    mjDisplacement = (rng.random_sample(size)-50.0)*50.0
    for i in range(size):
        sedFile = sedFiles[rng.randint(0, len(sedFiles))]
        varParam = {'varMethodName': 'applyRRly',
                    'pars': {'tStartMjd': 48000.0+mjDisplacement[i],
                             'filename': lcFiles[rng.randint(0, len(lcFiles))]}}
        paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO RRly VALUES (%i, '%s', '%s', 0.01, 0.7)''' % (i, paramStr, sedFile)
        c.execute(qstr)
    conn.commit()
    conn.close()

def makeCepheidTable(size=100, database=VARIABILITY_DB, **kwargs):
    """
    Make a test database to serve information to the cepheid test
    """

    # a haphazard sample of stellar SEDs
    sedFiles = ['kp10_8750.fits_g35_8950', 'kp03_10500.fits_g45_10600', 'km50_6750.fits_g20_6750']

    # a haphazard sample of cepheid light curves
    lcFiles = ['cepheid_lc/classical_longPer_specfile', 'cepheid_lc/classical_medPer_specfile',
               'cepheid_lc/classical_shortPer_specfile', 'cepheid_lc/classical_shortPer_specfile',
               'cepheid_lc/popII_longPer_specfile', 'cepheid_lc/popII_shortPer_specfile']

    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE cepheid
                     (varsimobjid int, variability text, sedfilename text, parallax real, ebv real)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    periods = rng.random_sample(size)*50.0
    mjDisplacement = (rng.random_sample(size)-0.5)*50.0
    for i in range(size):
        sedFile = sedFiles[rng.randint(0, len(sedFiles))]
        varParam = {'varMethodName': 'applyCepheid',
                    'pars': {'period': periods[i], 'lcfile': lcFiles[rng.randint(0, len(lcFiles))],
                             't0': 48000.0+mjDisplacement[i]}}
        paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO cepheid VALUES (%i, '%s', '%s', 0.01, 0.7)''' % (i, paramStr, sedFile)
        c.execute(qstr)
    conn.commit()
    conn.close()

def makeEbTable(size=100, database=VARIABILITY_DB, **kwargs):
    """
    Make a test database to serve information to the Eb test
    """

    # a haphazard sample of eclipsing binary light curves
    lcFiles = ['eb_lc/EB.2294.inp', 'eb_lc/EB.1540.inp', 'eb_lc/EB.2801.inp']

    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE eb
                     (varsimobjid int, variability text, sedfilename text, parallax real, ebv real)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    periods = rng.random_sample(size)*50.0
    mjDisplacement = (rng.random_sample(size)-0.5)*50.0
    for i in range(size):
        sedFile = 'sed_flat_norm.txt'
        varParam = {'varMethodName': 'applyEb',
                    'pars': {'period': periods[i], 'lcfile': lcFiles[rng.randint(0, len(lcFiles))],
                             't0': 48000.0+mjDisplacement[i]}}
        paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO eb VALUES (%i, '%s', '%s', 0.01, 0.7)''' % (i, paramStr, sedFile)
        c.execute(qstr)
    conn.commit()
    conn.close()

def makeMicrolensingTable(size=100, database=VARIABILITY_DB, **kwargs):
    """
    Make a test database to serve information to the microlensing test
    """

    # a haphazard sample of stellar SEDs
    sedFiles = ['kp10_8750.fits_g35_8950', 'kp03_10500.fits_g45_10600', 'km50_6750.fits_g20_6750']

    # there are two microlensing methods; they should be equivalent
    method = ['applyMicrolensing', 'applyMicrolens']
    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE microlensing
                     (varsimobjid int, variability text, sedfilename text, parallax real, ebv real)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    that = rng.random_sample(size)*40.0+40.0
    umin = rng.random_sample(size)
    mjDisplacement = rng.random_sample(size)*50.0
    for i in range(size):
        sedFile = sedFiles[0]
        varParam = {'varMethodName': method[i%len(method)],
                    'pars': {'that': that[i], 'umin': umin[i], 't0': 52000.0+mjDisplacement[i]}}
        paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO microlensing VALUES (%i, '%s', '%s', 0.01, 0.7)''' % (i, paramStr, sedFile)
        c.execute(qstr)
    conn.commit()
    conn.close()

def makeBHMicrolensingTable(size=100, database=VARIABILITY_DB, **kwargs):
    """
    Make a test database to serve information to the BHmicrolensing test
    """

    # a haphazard sample of stellar SEDs
    sedFiles = ['kp10_8750.fits_g35_8950', 'kp03_10500.fits_g45_10600', 'km50_6750.fits_g20_6750']

    # a sample of black hole microlensing light curves that do not repeat time steps
    # (repeating time steps causes the scipy spline interpolation routine to return Nan)
    lcFiles = ['microlens/bh_binary_source/lc_14_25_75_8000_0_0.05_316',
               'microlens/bh_binary_source/lc_14_25_4000_8000_0_phi1.09_0.005_100',
               'microlens/bh_binary_source/lc_14_25_75_8000_0_tets2.09_0.005_316']

    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE bhmicrolensing
                     (varsimobjid int, variability text, sedfilename text, parallax real, ebv real)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    mjDisplacement = rng.random_sample(size)*5.0*365.25
    for i in range(size):
        sedFile = sedFiles[rng.randint(0, len(sedFiles))]
        varParam = {'varMethodName': 'applyBHMicrolens',
                    'pars': {'filename': lcFiles[rng.randint(0, len(lcFiles))],
                             't0': 52000.0-mjDisplacement[i]}}
        paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO bhmicrolensing VALUES (%i, '%s', '%s', 0.01, 0.7)''' % (i, paramStr, sedFile)
        c.execute(qstr)
    conn.commit()
    conn.close()

def makeAmcvnTable(size=100, database=VARIABILITY_DB, **kwargs):
    """
    Make a test database to serve information to the AMCVN test
    """

    # a haphazard sample of white dwarf SEDs
    sedFiles = ['bergeron_He_4750_70.dat_4950', 'bergeron_50000_85.dat_54000']

    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE amcvn
                     (varsimobjid int, variability text, sedfilename text, parallax real, ebv real)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    doesBurst = rng.randint(0, 2, size=size)
    burst_freq = rng.randint(10, 150, size=size)
    burst_scale = 115.0
    amp_burst = rng.random_sample(size)*8.0
    color_excess_during_burst = rng.random_sample(size)*0.2-0.4
    amplitude = rng.random_sample(size)*0.2
    period = rng.random_sample(size)*200.0
    mjDisplacement = rng.random_sample(size)*500.0
    for i in range(size):
        sedFile = sedFiles[rng.randint(0, len(sedFiles))]
        varParam = {'varMethodName': 'applyAmcvn',
                    'pars': {'does_burst': int(doesBurst[i]),  # have to cast to int from np.int for json
                             'burst_freq': int(burst_freq[i]),
                             'burst_scale': burst_scale,
                             'amp_burst': amp_burst[i],
                             'color_excess_during_burst': color_excess_during_burst[i],
                             'amplitude': amplitude[i],
                             'period': period[i],
                             't0': 51500.0-mjDisplacement[i]}}

        paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO amcvn VALUES (%i, '%s', '%s', 0.01, 0.7)''' % (i, paramStr, sedFile)
        c.execute(qstr)
    conn.commit()
    conn.close()

def makeAgnTable(size=100, database=VARIABILITY_DB, **kwargs):
    """
    Make a test database to serve information to the microlensing test
    """

    # a haphazard sample of galaxy SEDs
    sedFiles = ['Exp.31E06.0005Z.spec', 'Inst.79E06.1Z.spec', 'Const.50E07.0005Z.spec']
    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE agn
                     (galid int, varsimobjid int,
                      internalAvBulge real, internalAvDisk real, redshift real,
                      variability text,
                      sedFilenameBulge text, sedFilenameDisk text, sedFilenameAgn text)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    agn_tau = rng.random_sample(size)*100.0+100.0
    agn_sfu = rng.random_sample(size)*2.0
    agn_sfg = rng.random_sample(size)*2.0
    agn_sfr = rng.random_sample(size)*2.0
    agn_sfi = rng.random_sample(size)*2.0
    agn_sfz = rng.random_sample(size)*2.0
    agn_sfy = rng.random_sample(size)*2.0
    mjDisplacement = rng.random_sample(size)*5.0
    avBulge = rng.random_sample(size)*0.5+2.6
    avDisk = rng.random_sample(size)*0.5+2.6
    redshift = rng.random_sample(size)*0.5
    for i in range(size):
        varParam = {'varMethodName': 'applyAgn',
                    'pars': {'agn_tau': agn_tau[i], 'agn_sfu': agn_sfu[i], 'agn_sfg': agn_sfg[i],
                             'agn_sfr': agn_sfr[i], 'agn_sfi': agn_sfi[i], 'agn_sfz': agn_sfz[i],
                             'agn_sfy': agn_sfy[i], 't0_mjd': 48000.0+mjDisplacement[i],
                             'seed': rng.randint(0, 200000)}}

        paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO agn VALUES (%i, %i, %f, %f, %f, '%s', '%s', '%s', '%s')''' % \
               (i, i, avBulge[i], avDisk[i], redshift[i],
                paramStr,
                sedFiles[rng.randint(0, len(sedFiles))],
                sedFiles[rng.randint(0, len(sedFiles))],
                'agn.spec')

        c.execute(qstr)
    conn.commit()
    conn.close()

def makeHybridTable(size=100, database='VariabilityTestDatabase.db', **kwargs):
    """
    Make a test database that contains a mix of Cepheid variables
    and 'testVar' variables (variables that use the applySineVar
    method defined in the TestVariabilityMixin)
    """

    # a haphazard sample of stellar SEDs
    sedFiles = ['kp10_8750.fits_g35_8950', 'kp03_10500.fits_g45_10600', 'km50_6750.fits_g20_6750']

    # a haphazard sample of cepheid light curves
    lcFiles = ['cepheid_lc/classical_longPer_specfile', 'cepheid_lc/classical_medPer_specfile',
               'cepheid_lc/classical_shortPer_specfile', 'cepheid_lc/classical_shortPer_specfile',
               'cepheid_lc/popII_longPer_specfile', 'cepheid_lc/popII_shortPer_specfile']

    conn = sqlite3.connect(database)
    c = conn.cursor()
    try:
        c.execute('''CREATE TABLE hybrid
                     (varsimobjid int, variability text, sedfilename text, parallax real, ebv real)''')
        conn.commit()
    except:
        return

    rng = np.random.RandomState(32)
    periods = rng.random_sample(size)*50.0
    mjDisplacement = (rng.random_sample(size)-0.5)*50.0
    for i in range(size):
        sedFile = sedFiles[rng.randint(0, len(sedFiles))]
        if i%3 == 0:
            # just to make sure that Variability mixins no how to andle
            # objects with no variability
            varParam = None
            paramStr = None
        elif i%2 == 0:
            varParam = {'varMethodName': 'applyCepheid',
                        'pars': {'period': periods[i],
                                 'lcfile': lcFiles[rng.randint(0, len(lcFiles))],
                                 't0': 48000.0+mjDisplacement[i]}}
        else:
            varParam = {'varMethodName': 'testVar',
                        'pars': {'period': rng.random_sample()*100.0, 'amplitude': 2.0}}

        if varParam is not None:
            paramStr = json.dumps(varParam)

        qstr = '''INSERT INTO hybrid VALUES (%i, '%s', '%s', 0.01, 0.7)''' % (i, paramStr, sedFile)
        c.execute(qstr)
    conn.commit()
    conn.close()

class variabilityDB(CatalogDBObject):
    driver = 'sqlite'
    database = VARIABILITY_DB
    idColKey = 'varsimobjid'
    columns = [('id', 'varsimobjid', int),
               ('sedFilename', 'sedfilename', str, 40),
               ('varParamStr', 'variability', str, 600)]

class hybridDB(variabilityDB):
    objid = 'hybridTest'
    tableid = 'hybrid'
    objectTypeId = 54

class rrlyDB(variabilityDB):
    objid = 'rrlyTest'
    tableid = 'RRly'
    objectTypeId = 55

class cepheidDB(variabilityDB):
    objid = 'cepheidTest'
    tableid = 'cepheid'
    objectTypeId = 56

class ebDB(variabilityDB):
    objid = 'ebTest'
    tableid = 'eb'
    objectTypeId = 57

class microlensDB(variabilityDB):
    objid = 'microlensTest'
    tableid = 'microlensing'
    objectTypeId = 58

class BHmicrolensDB(variabilityDB):
    objid = 'bhmicrolensTest'
    tableid = 'bhmicrolensing'
    objectTypeId = 59

class amcvnDB(variabilityDB):
    objid = 'amcvnTest'
    tableid = 'amcvn'
    objectTypeId = 60

class agnDB(variabilityDB):
    objid = 'agnTest'
    tableid = 'agn'
    objectTypeId = 61

class StellarVariabilityCatalog(InstanceCatalog, PhotometryStars, VariabilityStars):
    catalog_type = __file__ + 'stellarVariabilityCatalog'
    column_outputs = ['varsimobjid', 'sedFilename', 'delta_lsst_u']
    default_columns = [('magNorm', 14.0, float)]

class StellarVariabilityCatalogWithTest(InstanceCatalog, PhotometryStars,
                                        VariabilityStars, TestVariabilityMixin):
    catalog_type = __file__ + 'testVariabilityCatalog'
    column_outputs = ['varsimobjid', 'sedFilename', 'delta_lsst_u']
    default_columns = [('magNorm', 14.0, float)]

class OtherVariabilityCatalogWithTest(InstanceCatalog, PhotometryStars,
                                      TestVariabilityMixin, VariabilityStars):
    catalog_type = __file__ + 'other_variability_catalog'
    column_outputs = ['varsimobjid', 'sedFilename', 'delta_lsst_u']
    default_columns = [('magNorm', 14.0, float)]

class GalaxyVariabilityCatalog(InstanceCatalog, PhotometryGalaxies, VariabilityGalaxies):
    catalog_type = __file__ + 'galaxyVariabilityCatalog'
    column_outputs = ['varsimobjid', 'sedFilenameAgn', 'lsstUdiff', 'delta_uAgn']
    default_columns = [('magNormAgn', 14.0, float),
                       ('magNormDisk', 14.0, float),
                       ('magNormBulge', 14.0, float)]

    def get_lsstUdiff(self):
        lsstUvar = self.column_by_name('lsst_u')

        bulge = self.column_by_name('uBulge')
        disk = self.column_by_name('uDisk')
        agn = self.column_by_name('uAgn') - self.column_by_name('delta_uAgn')
        lsstU = self.sum_magnitudes(bulge=bulge, disk=disk, agn=agn)

        return lsstUvar - lsstU

    def get_agnUdiff(self):
        lsstU = self.column_by_name('uAgn')
        lsstUvar = self.column_by_name('uAgn_var')
        return lsstUvar - lsstU

class VariabilityTest(unittest.TestCase):

    longMessage = True

    @classmethod
    def setUpClass(cls):
        cls.scratch_dir = tempfile.mkdtemp(dir=ROOT, prefix='VariabilityTest-')
        cls.variability_db = os.path.join(cls.scratch_dir, VARIABILITY_DB)

    @classmethod
    def tearDownClass(cls):
        sims_clean_up()
        if os.path.exists(cls.variability_db):
            os.unlink(cls.variability_db)
        if os.path.exists(cls.scratch_dir):
            shutil.rmtree(cls.scratch_dir, ignore_errors=True)

    def setUp(self):
        self.obs_metadata = ObservationMetaData(mjd=52000.0)

    def tearDown(self):
        del self.obs_metadata

    def verify_catalogs(self, cat_name):
        """
        Verify that a catalog generated by the unit tests below contains
        the rows it ought to.

        This is done by looking for a corresponding catalog in
        tests/testData and verifying that the two catalogs have identical
        rows.

        Parameters
        ----------
        cat_name is the full path to the test-generated catalog.  The
        comparison catalog will be found in tests/testData
        """

        control_dir = os.path.join(getPackageDir('sims_catUtils'),
                                   'tests', 'testData')
        _, control_name = os.path.split(cat_name)
        control_name = os.path.join(control_dir, control_name)
        with open(control_name, 'r') as control_file:
            control_lines = control_file.readlines()

        with open(cat_name, 'r') as test_file:
            test_lines = test_file.readlines()

        for tt in test_lines:
            self.assertIn(tt, control_lines)

        for cc in control_lines:
            self.assertIn(cc, test_lines)

    def testHybridVariability(self):
        """
        Test that we can generate a catalog which inherits from multiple variability mixins
        (in this case, TestVariability and VariabilityStars).  This is to make sure that
        the register_method and register_class decorators do not mangle inheritance of
        methods from mixins.
        """
        cat_name = os.path.join(self.scratch_dir, 'hybridTestCatalog.dat')
        makeHybridTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('hybridTest', database=self.variability_db)
        myCatalog = StellarVariabilityCatalogWithTest(myDB, obs_metadata=self.obs_metadata)

        myCatalog.write_catalog(cat_name, chunk_size=1000)
        self.verify_catalogs(cat_name)

        if os.path.exists(cat_name):
            os.unlink(cat_name)

        # make sure order of mixin inheritance does not matter
        myCatalog = OtherVariabilityCatalogWithTest(myDB, obs_metadata=self.obs_metadata)
        myCatalog.write_catalog(cat_name, chunk_size=1000)
        self.verify_catalogs(cat_name)

        if os.path.exists(cat_name):
            os.unlink(cat_name)

        # make sure that, if a catalog does not contain a variability method,
        # an error is thrown; verify that it contains the correct error message
        myCatalog = StellarVariabilityCatalog(myDB, obs_metadata=self.obs_metadata)

        with self.assertRaises(RuntimeError) as context:
            myCatalog.write_catalog(cat_name)

        if os.path.exists(cat_name):
            os.unlink(cat_name)

        expectedMessage = "Your InstanceCatalog does not contain a variability method"
        expectedMessage += " corresponding to 'testVar'"
        self.assertEqual(context.exception.args[0], expectedMessage)

    def testApplyVariabilityWithManyMJD(self):
        """
        Use the hybrid variability catalog class from testHybridVariability to
        verify that, if we pass an array of expmjd into applyVariability, we get
        the expected result out.
        """

        makeHybridTable(database=self.variability_db)
        hybrid_db = hybridDB(database=self.variability_db)
        hybrid_cat = StellarVariabilityCatalogWithTest(hybrid_db, obs_metadata=self.obs_metadata,
                                                       column_outputs=['varParamStr'])
        rng = np.random.RandomState(88)
        mjd_arr = rng.random_sample(14)*3653.0+59580.0
        n_time = len(mjd_arr)
        varparams =[]
        n_ceph = 0
        n_test = 0
        for line in hybrid_cat.iter_catalog():
            varparams.append(line[-1])
            if 'Cepheid' in line[-1]:
                n_ceph += 1
            if 'testVar' in line[-1]:
                n_test +=1

        self.assertGreater(n_ceph, 0)
        self.assertGreater(n_test, 0)

        n_obj=len(varparams)

        new_hybrid_cat = StellarVariabilityCatalogWithTest(hybrid_db, obs_metadata=self.obs_metadata)
        delta_mag_vector = new_hybrid_cat.applyVariability(varparams, expmjd=mjd_arr)
        self.assertEqual(delta_mag_vector.shape, (6, len(varparams), len(mjd_arr)))

        n_mags = 0
        for i_time, mjd in enumerate(mjd_arr):
            obs = ObservationMetaData(mjd=mjd)
            control_hybrid_cat = StellarVariabilityCatalogWithTest(hybrid_db, obs_metadata=obs,
                                                                   column_outputs=['delta_lsst_u',
                                                                                'delta_lsst_g',
                                                                                'delta_lsst_r',
                                                                                'delta_lsst_i',
                                                                                'delta_lsst_z',
                                                                                'delta_lsst_y'])

            for i_obj, star_obj in enumerate(control_hybrid_cat.iter_catalog()):
                for i_band in range(6):
                    n_mags += 1
                    self.assertEqual(delta_mag_vector[i_band][i_obj][i_time],
                                     star_obj[-6+i_band],
                                     msg = 'failed on time %d; obj %d; band %d' % (i_time, i_obj, i_band))

        self.assertEqual(n_mags, 6*n_obj*n_time)

    def testRRlyrae(self):
        cat_name = os.path.join(self.scratch_dir, 'rrlyTestCatalog.dat')
        makeRRlyTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('rrlyTest', database=self.variability_db)
        myCatalog = StellarVariabilityCatalog(myDB, obs_metadata=self.obs_metadata)
        myCatalog.write_catalog(cat_name, chunk_size=1000)

        self.verify_catalogs(cat_name)
        if os.path.exists(cat_name):
            os.unlink(cat_name)

    def testCepheids(self):
        cat_name = os.path.join(self.scratch_dir, 'cepheidTestCatalog.dat')
        makeCepheidTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('cepheidTest', database=self.variability_db)
        myCatalog = StellarVariabilityCatalog(myDB, obs_metadata=self.obs_metadata)
        myCatalog.write_catalog(cat_name, chunk_size=1000)

        self.verify_catalogs(cat_name)
        if os.path.exists(cat_name):
            os.unlink(cat_name)

    def testEb(self):
        cat_name = os.path.join(self.scratch_dir, 'ebTestCatalog.dat')
        makeEbTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('ebTest', database=self.variability_db)
        myCatalog = StellarVariabilityCatalog(myDB, obs_metadata=self.obs_metadata)
        myCatalog.write_catalog(cat_name, chunk_size=1000)

        self.verify_catalogs(cat_name)
        if os.path.exists(cat_name):
            os.unlink(cat_name)

    def testMicrolensing(self):
        # Note:  this test assumes that the parameters for the microlensing variability
        # model occur in a standard varParamStr column in the database.
        # Actually, the current database of microlensing events simply store the variability
        # parameters as independent columns in the database.
        # The varParamStr formalism is how the applyMicrolensing methods are written, however,
        # so that is what we will test.

        cat_name = os.path.join(self.scratch_dir, 'microlensTestCatalog.dat')
        makeMicrolensingTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('microlensTest', database=self.variability_db)
        myCatalog = StellarVariabilityCatalog(myDB, obs_metadata=self.obs_metadata)
        myCatalog.write_catalog(cat_name, chunk_size=1000)

        self.verify_catalogs(cat_name)
        if os.path.exists(cat_name):
            os.unlink(cat_name)

    def testBHMicrolensing(self):
        # Note:  this test assumes that the parameters for the BHmicrolensing variability
        # model occur in a standard varParamStr column in the database.
        # Actually, the current database of BHmicrolensing events simply store the variability
        # parameters as independent columns in the database.
        # The varParamStr formalism is how the applyBHMicrolens method is written, however,
        # so that is what we will test.

        cat_name = os.path.join(self.scratch_dir, 'bhmicrolensTestCatalog.dat')
        makeBHMicrolensingTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('bhmicrolensTest', database=self.variability_db)
        myCatalog = StellarVariabilityCatalog(myDB, obs_metadata=self.obs_metadata)
        myCatalog.write_catalog(cat_name, chunk_size=1000)

        self.verify_catalogs(cat_name)
        if os.path.exists(cat_name):
            os.unlink(cat_name)

    def testAmcvn(self):
        # Note:  this test assumes that the parameters for the Amcvn variability
        # model occur in a standard varParamStr column in the database.
        # Actually, the current database of Amcvn events simply store the variability
        # parameters as independent columns in the database.
        # The varParamStr formalism is how the applyAmcvn method is written, however,
        # so that is what we will test.

        cat_name = os.path.join(self.scratch_dir, 'amcvnTestCatalog.dat')
        makeAmcvnTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('amcvnTest', database=self.variability_db)
        myCatalog = StellarVariabilityCatalog(myDB, obs_metadata=self.obs_metadata)
        myCatalog.write_catalog(cat_name, chunk_size=1000)

        self.verify_catalogs(cat_name)
        if os.path.exists(cat_name):
            os.unlink(cat_name)

    def testAgn(self):
        """
        Just verify that the catalog generation code runs in this case
        """

        cat_name = os.path.join(self.scratch_dir, 'agnTestCatalog.dat')
        makeAgnTable(database=self.variability_db)
        myDB = CatalogDBObject.from_objid('agnTest', database=self.variability_db)
        obs = ObservationMetaData(pointingRA=self.obs_metadata.pointingRA,
                                  pointingDec=self.obs_metadata.pointingDec,
                                  boundType=self.obs_metadata.boundType,
                                  boundLength=self.obs_metadata.boundLength,
                                  mjd=60000.0)
        myCatalog = GalaxyVariabilityCatalog(myDB, obs_metadata=obs)
        myCatalog.write_catalog(cat_name, chunk_size=1000)

        with open(cat_name,'r') as input_file:
            lines = input_file.readlines()
            self.assertGreater(len(lines), 10)

        if os.path.exists(cat_name):
            os.unlink(cat_name)

class MemoryTestClass(lsst.utils.tests.MemoryTestCase):
    pass

if __name__ == "__main__":
    lsst.utils.tests.init()
    unittest.main()


from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.by import By

option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=option)
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
})
driver.maximize_window()
driver.get('https://www.dianping.com/shop/H58wRirFQyLQBnSI')
driver.implicitly_wait(5)
pingfen=driver.find_element(By.XPATH,'//div[@class="star-wrapper"]/div[2]')
pingfen=pingfen.text
print(pingfen)

爬取大众点评/爬取店铺评分.py


# -------------check supported languages--------------
# import googletrans
# print(googletrans.LANGUAGES)

# txt = "તમે કેમ છો"
# result3 = translator.translate(txt)
# print(result3.src)

from googletrans import Translator
translator = Translator()
result = translator.translate("cómo estás")
print(result.dest)
print(result.text)

print("")

sentences = ['Bienvenu', 'Comment allez-vous', 'je vais bien']
result2 = translator.translate(sentences )
for trans in result2:
    print(f'{trans.origin} -> {trans.text}')

print("")

mylist = ["Comment allez-vous" , "tu vas bien","nous allons bien","au revoir"]
result4 = translator.translate(mylist, dest="gu")
for trans  in result4:
    print(f'{trans.origin}  ---> {trans.text}')


"""
Created at 2019-12-09 19:00

@author: jinyanliu
"""
from enum import Enum

class Opcode(Enum):
    ADD = 1
    MULTIPLY = 2
    INPUT = 3
    OUTPUT = 4
    JUMP_IF_TRUE = 5
    JUMP_IF_FALSE = 6
    LESS_THAN = 7
    EQUALS = 8
    RELATIVE_BASE = 9
    HALT = 99

class ParametersMode(Enum):
    POSITION = 0
    IMMEDIATE = 1
    RELATIVE = 2

class InstructionDictKey(Enum):
    OPCODE = "opcode"
    FIRST_MODE = "first_mode"
    SECOND_MODE = "second_mode"
    THIRD_MODE = "third_mode"

def get_dict_of_int_input():
    dict_of_int_input = {}
    i = 0
    with open("day_9_input") as lines:
        list_of_string = lines.readline().split(',')
        for s in list_of_string:
            dict_of_int_input[i] = int(s)
            i += 1
    print(dict_of_int_input)
    return dict_of_int_input

def get_dict_instruction(digits):
    instruction_string = str(digits).zfill(5)
    instruction_dict = {InstructionDictKey.OPCODE.value: int(instruction_string[3] + instruction_string[4]),
                        InstructionDictKey.FIRST_MODE.value: int(instruction_string[2]),
                        InstructionDictKey.SECOND_MODE.value: int(instruction_string[1]),
                        InstructionDictKey.THIRD_MODE.value: int(instruction_string[0])}
    return instruction_dict

def get_instructions(instruction_code):
    dict_instruction = get_dict_instruction(instruction_code)
    opcode = dict_instruction[InstructionDictKey.OPCODE.value]
    first_mode = dict_instruction[InstructionDictKey.FIRST_MODE.value]
    second_mode = dict_instruction[InstructionDictKey.SECOND_MODE.value]
    third_mode = dict_instruction[InstructionDictKey.THIRD_MODE.value]
    return opcode, first_mode, second_mode, third_mode

def get_value(mode, input_dict, i, relative_base, number):
    if mode == ParametersMode.POSITION.value:
        return input_dict[input_dict[i + number]] if input_dict[i + number] in input_dict.keys() else 0
    elif mode == ParametersMode.IMMEDIATE.value:
        return input_dict[i + number]
    elif mode == ParametersMode.RELATIVE.value:
        relative_position = relative_base + input_dict[i + number]
        return input_dict[relative_position]

def get_replace_position(mode, input_dict, i, relative_base, number):
    if mode == ParametersMode.POSITION.value:
        return input_dict[i + number]
    elif mode == ParametersMode.RELATIVE.value:
        return relative_base + input_dict[i + number]

def get_last_output(list_of_input_integers, input_dict):
    i = 0
    step = 0
    output_value = None
    relative_base = 0
    while i + 1 < len(input_dict):
        should_increase_i = True

        opcode, first_mode, second_mode, third_mode = get_instructions(input_dict[i])

        if opcode == Opcode.ADD.value:
            first_value = get_value(first_mode, input_dict, i, relative_base, 1)
            second_value = get_value(second_mode, input_dict, i, relative_base, 2)
            replace_position = get_replace_position(third_mode, input_dict, i, relative_base, 3)
            input_dict[replace_position] = first_value + second_value
            step = 3

        elif opcode == Opcode.MULTIPLY.value:
            first_value = get_value(first_mode, input_dict, i, relative_base, 1)
            second_value = get_value(second_mode, input_dict, i, relative_base, 2)
            replace_position = get_replace_position(third_mode, input_dict, i, relative_base, 3)
            input_dict[replace_position] = first_value * second_value
            step = 3

        elif opcode == Opcode.INPUT.value:
            replace_position = get_replace_position(first_mode, input_dict, i, relative_base, 1)
            input_dict[replace_position] = list_of_input_integers[0]
            print("input_value = " + str(list_of_input_integers[0]))
            list_of_input_integers.pop(0)
            step = 1

        elif opcode == Opcode.OUTPUT.value:
            output_value = get_value(first_mode, input_dict, i, relative_base, 1)
            print("output_value = " + str(output_value))
            step = 1

        elif opcode == Opcode.JUMP_IF_TRUE.value:
            first_value = get_value(first_mode, input_dict, i, relative_base, 1)
            if first_value != 0:
                second_value = get_value(second_mode, input_dict, i, relative_base, 2)
                i = second_value
                should_increase_i = False
            step = 2

        elif opcode == Opcode.JUMP_IF_FALSE.value:
            first_value = get_value(first_mode, input_dict, i, relative_base, 1)
            if first_value == 0:
                second_value = get_value(second_mode, input_dict, i, relative_base, 2)
                i = second_value
                should_increase_i = False
            step = 2

        elif opcode == Opcode.LESS_THAN.value:
            first_value = get_value(first_mode, input_dict, i, relative_base, 1)
            second_value = get_value(second_mode, input_dict, i, relative_base, 2)
            place_to_store = get_replace_position(third_mode, input_dict, i, relative_base, 3)
            if first_value < second_value:
                input_dict[place_to_store] = 1
            else:
                input_dict[place_to_store] = 0
            step = 3

        elif opcode == Opcode.EQUALS.value:
            first_value = get_value(first_mode, input_dict, i, relative_base, 1)
            second_value = get_value(second_mode, input_dict, i, relative_base, 2)
            place_to_store = get_replace_position(third_mode, input_dict, i, relative_base, 3)
            if first_value == second_value:
                input_dict[place_to_store] = 1
            else:
                input_dict[place_to_store] = 0
            step = 3

        elif opcode == Opcode.RELATIVE_BASE.value:
            first_value = get_value(first_mode, input_dict, i, relative_base, 1)
            relative_base += first_value
            step = 1

        elif opcode == Opcode.HALT.value:
            break

        if should_increase_i:
            i += step + 1
    return output_value

def get_solution_1():
    return get_last_output([1], get_dict_of_int_input())

def get_solution_2():
    return get_last_output([2], get_dict_of_int_input())

if __name__ == "__main__":
    print(get_solution_1())
    print(get_solution_2())


import gym
import wntr
import numpy as np
import random

from gym import error, spaces
from pkg_resources import resource_filename

class WDSEnv(gym.Env):

    reward_types = ('gaussian', 'delta', 'abs')
    control_types = ('pressure', 'flowrate')

    def __init__(self, reference, control_type, reward_type):
        if not control_type in self.control_types:
            raise ValueError("Control type not supported")
        if not reward_type in self.reward_types:
            raise ValueError("Reward type not supported")
        self.control_type = control_type
        self.reward_type = reward_type

        inp_file = resource_filename(__name__, 'WDS1.inp')
        self.wn = wntr.network.WaterNetworkModel(inp_file)
        self.valve = self.wn.get_link('V1')
        self.demand_node = self.wn.get_node('N3')
        self.initial_setting = self.valve.minor_loss
        self.valve.minor_loss = self.initial_setting
        self.sim = wntr.sim.WNTRSimulator(self.wn)
        self.demand_node.add_leak(self.wn, 0.1, 0.1, start_time = 0)
        self.reference = reference
        self.observation_space = spaces.Box(low = np.array([0]), high = np.array([np.inf]))
        self.action_space = spaces.Box(low = np.array([0]), high = np.array([np.inf]))

    def reset(self):
        self.wn.reset_initial_values()
        self.valve.minor_loss = self.initial_setting
        results = self.sim.run_sim()
        if self.control_type == 'flowrate':
            return np.array([float(results.link['flowrate']['P2'])])
        elif self.control_type == 'pressure':
            return np.array([float(results.node['pressure']['N3'])])

    def step(self, action):
        assert self.action_space.contains(action), "%r (%s) invalid" % (action, type(action))
        self.valve.minor_loss = action[0]
        results = self.sim.run_sim()
        if self.control_type == 'flowrate':
            observation = np.array([float(results.link['flowrate']['P2'])])
        elif self.control_type == 'pressure':
            observation = np.array([float(results.node['pressure']['N3'])])
        if self.reward_type == 'gaussian':
            reward = np.exp(-(self.reference - observation)**2/(self.reference/100))
        elif self.reward_type == 'abs':
            reward = float(-abs(self.reference - observation))
        elif self.reward_type == 'delta':
            reward = 1 if abs(self.reference - observation) < 1e-4 else 0
        self.wn.reset_initial_values()
        return observation, reward, False, {}


import os
import pathlib
import sys

import CppHeaderParser

headers: list[CppHeaderParser.CppHeader] = []

warn_noexcept = False

def absoluteFilePaths(directory: str):
    for dirpath, _, filenames in os.walk(directory):
        for f in filenames:
            yield os.path.abspath(os.path.join(dirpath, f))

def discoverParents(current: CppHeaderParser.CppClass, classes: list[CppHeaderParser.CppClass]) -> list[CppHeaderParser.CppClass]:
    parents: list[CppHeaderParser.CppClass] = []
    for cls in classes:
        for parent in current.get('inherits'):
            if cls.get('name') == parent.get('class'):
                if cls not in parents:
                    parents.append(cls)
                    parents += discoverParents(cls, classes)
    return parents

def getFullSignature(cls: CppHeaderParser.CppClass, method: CppHeaderParser.CppMethod)-> str:
    return f"{cls.get('namespace')}::{cls.get('name')}::{method.get('debug')}"

def getFullSignatureWithFileName(cls: CppHeaderParser.CppClass, method: CppHeaderParser.CppMethod)-> str:
    res = getFullSignature(cls, method)
    res += f" at line {method.get('line_number')} in file {method.get('filename')}"
    return res

def compareParams(lhs: CppHeaderParser.CppMethod, rhs: CppHeaderParser.CppMethod) -> tuple[bool, list[str]]:
    result: tuple[bool, list[str]] = (False, [])

    lhs_params = lhs.get('parameters')
    rhs_params = rhs.get('parameters')

    for i, l_param in enumerate(lhs_params):
        r_param = rhs_params[i]
        if(l_param.get('type') != r_param.get('type')) and (l_param.get('type').replace('const ','') != r_param.get('type').replace('const ','')):
            return (True, [])
        if(l_param.get('constant') != r_param.get('constant')):
            result[1].append(f"Potential const mismatch at parameter {i} ({r_param.get('name')})")
        #if(m lhs_params[i])
    return result

def compareMethods(lhs: CppHeaderParser.CppMethod, rhs: CppHeaderParser.CppMethod, parent: CppHeaderParser.CppClass, other: CppHeaderParser.CppClass):
    #different return type is enough distinction
    if (lhs.get('rtnType') != rhs.get('rtnType')):
        return

    #so is a different number of parameters
    if len(lhs.get('parameters')) != len(rhs.get('parameters')):
        return

    problems: list[str] = []
    #so are different types of params
    res = compareParams(lhs, rhs)

    #There were different param types
    if res[0]:
        return

    problems+= res[1]

    if lhs.get('const') != rhs.get('const'):
        problems.append(f'Methods {getFullSignature(parent, lhs)} and {getFullSignature(other, rhs)} have different const qualifiers.')

    if not lhs.get('virtual'):
        problems.append(f'Method {getFullSignature(parent, lhs)} is not marked virtual.')

    if warn_noexcept and (lhs.get('noexcept') != rhs.get('noexcept')):
        problems.append(f'Methods {getFullSignature(parent, lhs)} and {getFullSignature(other, rhs)} have different noexcept qualifiers.')

    if(len(problems) > 0):
        print(f'Summary for {getFullSignatureWithFileName(other, rhs)}:')
    else:
        if not other.get('override'):
            print(f"Method {getFullSignatureWithFileName(other, rhs)} seems to be an override, consider using the 'override' keyword when compiling with std=c++11 or newer.")

    for problem in problems:
        print(problem)

    return

def findSimilarMethodsInClass(parent: CppHeaderParser.CppClass, other: CppHeaderParser.CppMethod, other_cls: CppHeaderParser.CppClass):
    for method in parent.get('methods').get('public'):
        if method.get('name') == other.get('name'):
            compareMethods(method, other, parent, other_cls)
    return

def findSimilarMethods(classes: list[CppHeaderParser.CppClass], current: CppHeaderParser.CppClass):
    if (len(current.get('inherits')) == 0):
        return
    print(f"\nProcessing methods of {current.get('name')}")

    # discover parent tree
    parents = discoverParents(current, classes)

    for method in current.get('methods').get('public'):
        for cls in parents:
            findSimilarMethodsInClass(cls, method, current)

    for method in current.get('methods').get('protected'):
        for cls in parents:
            findSimilarMethodsInClass(cls, method, current)

def processDir(dirPath: str):
    paths = absoluteFilePaths(dirPath)

    for entry in paths:
        if os.path.isfile(entry):
            if (pathlib.Path(entry).suffix == ".h"):
                try:
                    headers.append(CppHeaderParser.CppHeader(entry))
                except CppHeaderParser.CppHeaderParser.CppParseError:
                    print(f'Excluded classes of header {entry} due to a c++ parser error.')
                except:
                    print(f'An unknown error occured while parsing header {entry}. Some classes may not get checked.')

    classes: list[CppHeaderParser.CppClass] = []
    for header in headers:
        for cls in header.classes:
            classes.append(header.classes.get(cls))

    # process loaded classes
    for cls in classes:
        findSimilarMethods(classes, cls)

def main(argv):
    in_path: str = argv[0]
    print(f'Processing files in directory {in_path}')
    processDir(in_path)

if __name__ == "__main__":
    if (len(sys.argv) > 1):
        sys.exit(main(sys.argv[1:]))
    else:
        sys.exit(main(["./testlib"])) #received no library path


from sqlalchemy import select, and_, not_
import logging

from Test import Test
import db
from configuration import config

maxKeyLength = config.getint('db', 'MaxKeyLength')

class UsedTest(Test):

	def run(self, key, testRun, keyReference, client, makePerm=True):

		comp = self.comparator(key)
		lenComp = len(str(comp))
		if  lenComp > maxKeyLength:
			outputText='The ' + self.compare + ' which should be tested is ' + lenComp + ' bit long, this is too long for UsedModulo. Increase MaxKeyLength.'
			logging.warning(outputText)
			status = 0
			return status, outputText, []

		connection=self.engine.connect()
		s = select([db.usedTable.c.hash]).where(and_(db.usedTable.c.hash == comp, db.usedTable.c.test == self.test))

		if connection.execute(s).first() is None:
			status =1
			outputText = 'The ' + self.compare + ' has not been used before.'
			revokeKeyReference=[]
		else:
			s = select([db.usedTable.c.test_run]).where(
			and_(db.usedTable.c.hash == comp,
			db.usedTable.c.test == self.test,
				not_(and_(db.usedTable.c.key_reference == keyReference,
					db.usedTable.c.client == client
					))
				)
			)

			if connection.execute(s).first() is None:
				status=1
				outputText = 'The ' + self.compare + ' has not been used used twice, but the same key (same key reference and client) has been tested before.'
				revokeKeyReference=[]

			else:
				status =-2
				outputText = 'The ' + self.compare + ' has been used before. For own prior usages see revokeKeyReference.'
				s = select([db.usedTable.c.test_run]).where(and_(db.usedTable.c.hash == comp, db.usedTable.c.test == self.test))
				result = connection.execute(s)
				revokeKeyReference = [r for r, in result]
				result.close()

		if makePerm:
			connection.execute(db.usedTable.insert(), hash=comp, test_run=testRun, test = self.test,
				key_reference=keyReference, client=client)
		connection.close()
		return status, outputText, revokeKeyReference

	def __init__(self, engine, parameter=0, shared = None):
		super(UsedTest,self).__init__(engine, parameter, shared)


import requests
from bs4 import BeautifulSoup

from .models import Module, AssessmentGroup, Assessment
from users.models import User

def get_all_modules():
    modules = Module.objects.values_list('module_code', flat=True).distinct()
    print('Distinct Modules: ' + str(modules.count()))

    modules_19 = list(Module.objects.filter(academic_year='19/20').values_list('module_code', flat=True).distinct())
    modules_18 = list(Module.objects.filter(academic_year='18/19').values_list('module_code', flat=True).distinct())
    modules_17 = list(Module.objects.filter(academic_year='17/18').values_list('module_code', flat=True).distinct())

    print('19/20 Modules: ' + str(len(modules_19)))
    print('18/19 Modules: ' + str(len(modules_18)))
    print('17/18 Modules: ' + str(len(modules_17)))

    missing_modules_19 = [x for x in set(modules_17 + modules_18) if x not in modules_19]
    missing_modules_18 = [x for x in set(modules_17 + modules_19) if x not in modules_18]
    missing_modules_17 = [x for x in set(modules_18 + modules_19) if x not in modules_17]

    print('19/20 Missing Modules: ' + str(len(missing_modules_19)))
    print('18/19 Missing Modules: ' + str(len(missing_modules_18)))
    print('17/18 Missing Modules: ' + str(len(missing_modules_17)))

    print(missing_modules_19)
    print(missing_modules_18)

    URLS = [
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/undergraduate/im/qs301', '19/20'],
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/undergraduate/po/qs104', '19/20'],
        # ['https://warwick.ac.uk/services/aro/dar/quality/modules/undergraduate/po/qs103', '19/20'],
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/undergraduate/ln/ll2b6', '19/20'],
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/undergraduate/im/qs304', '19/20'],

        ['https://warwick.ac.uk/services/aro/dar/quality/modules/archive201819/undergraduate-1819/po/qs203', '18/19'],
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/archive201819/undergraduate-1819/po/QS105', '18/19'],
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/archive201819/undergraduate-1819/po/QS202', '18/19'],
        # ['https://warwick.ac.uk/services/aro/dar/quality/modules/archive201819/undergraduate-1819/po/QS103', '18/19'],
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/archive201819/undergraduate-1819/im/qs304', '18/19'],
        ['https://warwick.ac.uk/services/aro/dar/quality/modules/archive201819/undergraduate-1819/po/QS305', '18/19'],
    ]

    for url in URLS:
        print(url)
        response = requests.get(url[0])
        soup = BeautifulSoup(response.text, 'html.parser')
        module_info = soup.find('ul', class_='list-unstyled').findAll('li')

        # Get the Module info and create it
        module_code = module_info[0].text.split(': ')[1]
        module_name = module_info[1].text.split(': ')[1]
        module_faculty = module_info[2].text.split(': ')[1]

        if not Module.objects.filter(module_code=module_code, academic_year=url[1]).exists():

            module = Module.objects.create(
                academic_year=url[1],
                module_code=module_code,
                module_name=module_name,
            )
            # Get the assessment infomation for the module
            assessment_groups_table = soup.find('table', class_='table table-striped').findAll('tbody')

            for body in assessment_groups_table:
                assessment_groups = body.findAll('tr')
                # create a dictionary, key is the name of the AssessmentGroup and value
                # is a list of Assessments
                assessment_groups_dict = {}
                prev_assessment_name = None
                for row in assessment_groups[1:]:
                    cols = row.findAll('td')
                    assessment_name = cols[0].text.strip()

                    if len(assessment_name) > 1:
                        cats = assessment_groups[0].find('th').text.split(' ')[0]
                        assessment_groups_dict[assessment_name] = [[cats, cols[1].text, cols[2].text]]
                        prev_assessment_name = assessment_name
                    else:
                        assessment_groups_dict.get(prev_assessment_name, []).append([None, cols[1].text, cols[2].text])

                for key, value in assessment_groups_dict.items():
                    assessment_group = AssessmentGroup.objects.create(
                        module=module,
                        assessment_group_name=key,
                        assessment_group_code=key.split(' ', 1)[0],
                        module_cats=value[0][0]
                    )

                    for assessment in value:
                        Assessment.objects.create(
                            assessment_group=assessment_group,
                            assessment_name=assessment[1],
                            percentage=float(assessment[2].strip('%'))
                        )


import random
import getch
import gspread
from google.oauth2.service_account import Credentials

SCOPE = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive.file",
    "https://www.googleapis.com/auth/drive"
    ]

CREDS = Credentials.from_service_account_file('creds.json')
SCOPED_CREDS = CREDS.with_scopes(SCOPE)
GSPREAD_CLIENT = gspread.authorize(SCOPED_CREDS)
SHEET = GSPREAD_CLIENT.open('2048')

print("\033c")

def is_cell_free(grid, row, cell):
    '''It returns true if an index is equal to 0'''
    return grid[row][cell] == 0

def get_free_cells(grid):
    '''It gets a list of indexes in the grid which equal 0'''
    free_cells = []
    row_count = -1

    for row in grid:
        row_count = row_count + 1
        index_count = -1
        for value_index in row:
            index_count = index_count + 1
            if value_index == 0:
                free_cells.append([row_count, index_count])
    return(free_cells)

def get_random_free_cell(grid):
    '''It gets a random index from the grid'''
    free_cells = get_free_cells(grid)
    random_free_cell = random.choice(free_cells)

    return(random_free_cell)

def place_random_number(grid):
    '''It places a 2 on a random index on the grid'''
    random_cell = get_random_free_cell(grid)

    array[random_cell[0]][random_cell[1]] = 2

def check_if_grid_is_full(grid):
    cells = []
    i = 0
    for x in grid:
        for y in x:
            cells.append(y)
    if i in cells:
        return False
    else:
        return True

array = [
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
]

place_random_number(array)
for row in array:
    print(row[0], row[1], row[2], row[3])
print('\n\nh = up\nj = down\nk = left\nl = right')

# Move Up Functionality

def get_columns_top_empty_cell(grid, row_index, cell_index):
    '''It returns the topmost cell in a column whos value equals 0'''

    for x in reversed(range(row_index + 1)):
        # If its any row, and any cell above is full, return index before full cell
        if is_cell_free(grid, x - 1, cell_index) is False:
            return([x, cell_index])
        # next, if its any row, and above cell is (empty && row 1) -> return row 1 index
        elif is_cell_free(grid, x - 1, cell_index) and x == 1:
            return([x - 1, cell_index])

def move_cell_up(grid, row_index, cell_index):
    '''It moves the current cell to the highest empty cell'''
    target_index = get_columns_top_empty_cell(grid, row_index, cell_index)
    cell_value = grid[row_index][cell_index]

    grid[int(target_index[0])][cell_index] = cell_value

    if row_index != target_index[0]:
        grid[row_index][cell_index] = 0
    return grid

# !!!This function is not in use yet!!!
def merge_cells(grid, cell, i, j):
    '''It will contain merge cells logic and reduce nested looping in move_grid_up'''
    for row in range(1, 4):
        if (cell != 0 and cell != grid[row][j] and grid[row][j]):
            continue
        elif (cell == grid[row][j]):
            array[i][j] = cell + grid[row][j]
            array[row][j] = 0

def move_grid_up(grid):
    '''It moves each cell on the board up'''
    # Loop over the array and merge a cell if the same cell is below it
    for x in range(4):
        for y in range(4):
            cell = grid[x][y]
            if (cell != 0):
               for n in range(x + 1, 4):
                if (cell != 0 and cell != grid[n][y] and grid[n][y] != 0):
                    continue
                elif (cell == grid[n][y]):
                    grid[x][y] = cell + cell
                    grid[n][y] = 0

    # Move all cells up to the highest 'empty' cell
    for x in range(4):
        for y in range(4):
            if is_cell_free(grid, x, y) is False and x != 0 and is_cell_free(grid, x - 1, y) is True:
                grid = move_cell_up(grid, x, y)

    place_random_number(array)
    for row in array:
        print(row[0], row[1], row[2], row[3])

# Move Down Functionality

def move_grid_down(grid):
    '''It moves each cell on the board down'''
    grid.reverse()

    # Loop over the array and merge a cell if the same cell is above it
    for x in range(4):
        for y in range(4):
            cell = grid[x][y]
            if (cell != 0):
               for n in range(x + 1, 4):
                if (cell != 0 and cell != grid[n][y] and grid[n][y] != 0):
                    continue
                elif (cell == grid[n][y]):
                    grid[x][y] = cell + cell
                    grid[n][y] = 0

    # Move all cells down to the lowest 'empty' cell
    for x in range(4):
        row = grid[x]
        for y in range(4):
            if is_cell_free(grid, x, y) is False and x != 0:
                move_cell_up(grid, x, y)

    grid.reverse()

    place_random_number(array)
    for row in array:
        print(row[0], row[1], row[2], row[3])

# Move Left Functionality

def get_rows_leftmost_empty_cell(grid, row_index, cell_index):
    '''It returns the leftmost cell in a row whos value equals 0'''
    for x in reversed(range(cell_index + 1)):
        # if its any cell, and any cell to the left is full, return index before full cell
        if is_cell_free(grid, row_index, x - 1) is False:
            return([row_index, x])
        # next, if its any row, and left cell is (empty && col 1) -> return col 1 index
        elif is_cell_free(grid, row_index, x - 1) and x == 1:
            return([row_index, x - 1])

def move_cell_left(grid, row_index, cell_index):
    '''It moves an individual cell left to the leftmost empty cell'''
    target_index = get_rows_leftmost_empty_cell(grid, row_index, cell_index)
    cell_value = grid[row_index][cell_index]

    grid[row_index][int(target_index[1])] = cell_value

    if cell_index != target_index[1]:
        grid[row_index][cell_index] = 0
    return grid

def move_grid_left(grid):
    '''It moves each cell on the board left'''
    for x in range(4):
        for y in range(4):
            current_cell = grid[x][y]
            if y == 0:
                continue
            if current_cell == grid[x][y - 1] and current_cell != 0:
                # merge cells
                grid[x][y - 1] = current_cell + current_cell
                grid[x][y] = 0
            elif is_cell_free(grid, x, y) is False and is_cell_free(grid, x, y - 1) is True:
                move_cell_left(grid, x, y)

    place_random_number(array)
    for row in array:
        print(row[0], row[1], row[2], row[3])

# Move Right Functionality

def get_rows_rightmost_empty_cell(grid, row_index, cell_index):
    '''It returns the rightmost cell in a row whos value equals 0'''
    for x in reversed(range(cell_index + 1)):
        # check column 3 with one empty ceel to right
        if x == 2 and grid[row_index][x + 1] == 0:
            return[row_index,x + 1]
        # check column 2 with two empty cells to right
        elif x == 1 and grid[row_index][x + 1] == 0 and grid[row_index][x + 2] == 0:
            return[row_index,x + 2]
        # check column 1 with three empty cells to right
        elif x == 0 and grid[row_index][x + 1] == 0 and grid[row_index][x + 2] == 0  and grid[row_index][x + 3] == 0:
            return[row_index,x + 3]
        # check column 2 with one empty cells to right
        elif x == 1 and  grid[row_index][x + 1] == 0 and grid[row_index][x + 2] != 0:
            return[row_index,x + 1]
        # check column 1 with two empty cells to right
        elif x == 0 and  grid[row_index][x + 1] == 0 and grid[row_index][x + 2] == 0  and grid[row_index][x + 3] != 0:
            return[row_index,x + 2]
        # check column 1 with one empty cell to right
        elif x == 0 and  grid[row_index][x + 1] == 0 and grid[row_index][x + 2] != 0  and grid[row_index][x + 3] != 0:
            return[row_index, x + 1]

def move_cell_right(grid, row_index, cell_index):
    '''It moves an individual cell right to the rightmost empty cell'''
    target_index = get_rows_rightmost_empty_cell(grid, row_index, cell_index)
    cell_value = grid[row_index][cell_index]

    grid[row_index][int(target_index[1])] = cell_value

    if cell_index != target_index[0]:
        grid[row_index][cell_index] = 0
    return grid

def move_grid_right(grid):
    '''It moves each cell on the board right'''
    for x in range(4):
        for y in reversed(range(4)):
            current_cell = grid[x][y]
            if y == 3:
                continue
            # merge cells
            if current_cell == grid[x][y + 1] and current_cell != 0:
                #print(f'merge {current_cell} + {grid[x][y + 1]}')
                grid[x][y + 1] = current_cell + current_cell
                grid[x][y] = 0
            # move any full cell to the right
            elif is_cell_free(grid, x, y) is False and is_cell_free(grid, x, y + 1) is True:
                move_cell_right(grid, x, y)

    place_random_number(array)
    for row in array:
        print(row[0], row[1], row[2], row[3])

# SCOREBOARD
def count_score(grid):
    '''It returns the highest number on the board'''
    cell_list = []
    for x in range(4):
        for y in range(4):
            cell_list.append(grid[x][y])

    current_score = max(cell_list)
    return(current_score)

# End Game & Update Leader Board
scores = SHEET.worksheet('scoreboard')
data = scores.get_all_values()

def update_high_score(data):
    '''It takes the highest number on the board, and updates google sheet if its a new high score'''

    scoreboard = SHEET.worksheet('scoreboard')

    high_score = scoreboard.acell('A2').value

    if int(data) > int(high_score):
        scoreboard.update('A2', data)
        print('New high score: ', data)
    else:
        print('Play again to try beat the high score')

# User presses h, j, k, l to play
while True:
    char = getch.getch()

    if char == 'h':
        if check_if_grid_is_full(array) is False:
            print("\033c")
            move_grid_up(array)
            print('\n\nh = up\nj = down\nk = left\nl = right')
        elif check_if_grid_is_full(array) is True:
            print('\nGAME OVER')
            score = count_score(array)
            update_high_score(score)

    elif char == 'j':
        if check_if_grid_is_full(array) is False:
            print("\033c")
            move_grid_down(array)
            print('\n\nh = up\nj = down\nk = left\nl = right')
        if check_if_grid_is_full(array) is True:
            print('\nGAME OVER')
            score = count_score(array)
            update_high_score(score)

    elif char == 'k':
        if check_if_grid_is_full(array) is False:
            print("\033c")
            move_grid_left(array)
            print('\n\nh = up\nj = down\nk = left\nl = right')
        if check_if_grid_is_full(array) is True:
            print('\nGAME OVER')
            score = count_score(array)
            update_high_score(score)

    elif char == 'l':
        if check_if_grid_is_full(array) is False:
            print("\033c")
            move_grid_right(array)
            print('\n\nh = up\nj = down\nk = left\nl = right')
        if check_if_grid_is_full(array) is True:
            print('\nGAME OVER')
            score = count_score(array)
            update_high_score(score)


try:
    import tkinter as tk
    from tkinter import ttk
except ImportError:
    import Tkinter as tk
    import ttk
from tkinter import *
from tkinter.ttk import *
from tkinter import filedialog
import pandas as pd
import easygui as eg
from datetime import datetime
from tkcalendar import Calendar
# LIBRERIAS A UTILIZAR

"""class Test ():
    def __init__(self):
        self.rar= tk.Tk"""

def prueba(l):

    l=Label(raiz, text="PRUEBA").grid(pady=10, padx=15)

def forget (x):
    x.grid_forget()

# FUNCION PARA APARECER LOS PARAMETOS EN 'X' Y 'Y'
def retrieve (x,y):

    x.grid(row = 0, column = 0, ipady = 10, pady = 10, padx = 15)
    y.grid(row = 0, column = 1, ipady = 10, pady = 10, padx = 15)

# NUEVA VENTANA CON EL BOTON CONVERTIR
def ventanaconvertir():
    # CREAMOS UNA FUNCION PARA CONTENER TODA LA VENTANA DE CONVERTIR
    def convertitCSV():

        print(archivo2.get())
        # LEEMOS EL ARCHIVO A CONVERTIR
        dt = pd.read_csv(archivo2.get())

        # AL GUARDAR EL ARCHIVO CONVERTIMOS LE DAMOS TIEMPO DE FECHA DE CONVERSION
        time = str(datetime.today().strftime('%B %d %Y %H-%M-%S'))

        # CREAMOS VENTANA EMERGENTE PARA PEDRILE AL USUARIO A DONDE DESEA GUARDAR EL ARCHIVO CONVERTIDO
        directorio = eg.diropenbox(msg="EL ARCHIVO CSV:",
                                   title="DONDE DESEA GUARDAR",
                                   default='/home/')
        #LE COLOCAMOS UN NOMBRE POR DEFECTO AL ARCHIVO
        ruta = str(directorio + f"/GRAFICA ({str(time)}).csv")
        print(ruta)
        dt.to_csv(ruta)

# AL CREAR LA VENTANA DE CONVERTIR LE DEDEMOS ESPECIFICAR QUE DEBE ESTAR DENTRO DE LA VENTANA PRINCIPAL
    winCor = Toplevel(raiz)

# LE MANDAMOS EL TITULO DE LA VENTANA
    winCor.title("CONVERSION TXT A CSV")

# LE COLOCAMOS LAS POSICIONES DE LA VENTANA
    winCor.geometry("400x100")

# REDIMIENCIONAMOS LA VENTANA
    winCor.resizable(False,False)

# CREAMOS UN LABEL ESPESIFICANDO LA FACILIDAD DEL USUARIO
    etq = Label(winCor, text="Archivo A Convertir :")

# POSICIONES DEL LABEL
    etq.place(x=5, y=10)

# ENTRY PARA GUARDAR LA RUTA DEL ARCHIVO
    enlace2 = Entry(winCor, textvariable=archivo2).place(x=150, y=10, width=150, height=22)

# BOTON PARA CON LA FUNCION PARA BUSCAR EL ARCHIVO, JUNTO SUS PARAMETROS REQUERIDOS
    winCor.button = tk.Button(winCor, text="BUSCAR", command= lambda :archivo2.set(filedialog.askopenfilename(title="SELECCIONE EL ARCHIVO TXT : ", initialdir="/home/"))).place(x=315, y=6)

# BOTON PARA CONVERTIR EL ARCHIVO 'TXT' A 'CSV', JUNTO A SUS PARAMETROS REQUERIDOS
    con = tk.Button(winCor, text='Convertir a CSV..', command=convertitCSV , relief="raised", borderwidth=5)
    con.grid(row=0, column=0, sticky=W, ipady=0, ipadx=0, padx=150, pady=45)
    #mi_Entry = Entry(raiz, textvariable=archivo1).place(x=180, y=80, width=300, height=22)  # Creación de Entry buscar archivo

# CERRAMOS LA VENTANA DE CONVERTIR

raiz = Tk()

# SE MANDAN LOS PARAMETROS DE LA VENTANA PRINCIPAL

# TAMAÑO DE LA VENTANA
raiz.geometry("750x600")

# ESTE PARAMETRO NOS SIRVE PARA NO REDIMENZIONAR LA VENTANA
raiz.resizable(False,False)

# IMPORTAMOS UN INCON PARA NUESTRA VENTANA
#raiz.iconbitmap('E:\\PYTHON\\GUI\\img.ico')

# NOMBRE DE LA APP
raiz.title("App Graficación")

# IMAGEN DE FONDO DE LA PANTALLA PRINCIPAL
#imagen = PhotoImage(file = "fondo redi.png")

# MANDAMOS LOS PARAMETRO REQUERIDOS PARA NUESTRO FONDO DE LA PANTALLA PRINCIPAL

background = Label( text = "Imagen S.O de fondo")#image = imagen,
background.place(x = 0, y = 0, relwidth = 1, relheight = 1)

# CREAMOS NUESTRO TITULO, JUNTO LE MANDAMOS LOS PARAMTROS REQUERIDOS

lb1=Label(raiz,  text="MONITOREO DE INVERNADERO ",   font=('Andale Mono', 25),foreground="black",background='white')#titulo de la pagina , su ubicacion, colores
lb1.place( x=180, y=25)

# CREAMOS UN TEXTO LLAMADO RUTA: JUNTOIS SUS PARAMETROS REQUERIDOS

lb2=Label(raiz,  text="RUTA",   font=('Andale Mono', 14),foreground="black",background='white')
lb2.place(x=170,y=102)

# CREAMOS ESTAS VARIABLES QUE HA FUTURO SON 3 BOTONES REQUERIDOS POR EL SISTEMA, LOS DECLARAMOS DE FORMA
# Stringvar() FORMA GLOBAL

b1=StringVar()
b2=StringVar()
b3=StringVar()
l=StringVar()
l=Label(raiz, text="asss").place(x=150, y=350)

# UTILIZAMOS LA PRIMERA VARIABLE B1 PARA UTILIZARLA DE FORMA BOTON, LE MANDAMOS EL CONTENIDO
# JUNTO A LA FUNCION FORGE CON SU CONTENIDO

b1 = Button(raiz, text = "FECHAS", command=  lambda : [forget(b2),retrieve(l,b1) ]) #boton fecha
b1.grid(row = 0, column = 1, ipadx = 0, ipady = 10, pady = 155, padx = 15)

# POSICIONAMOS EL BOTON

# UTILIZAMOS LA SEGUNDA VARIABLE B2 PARA UTILIZARLA DE FORMA BOTON, LE MANDAMOS EL CONTENIDO
# JUNTO A LA FUNCION FORGE CON SU CONTENIDO

b2 = Button(raiz, text = "DIAS", command = lambda : [forget(b1), retrieve(l,b1)])#boton dias
#b2.place(x=510,y=120)

# POSICIONAMOS EL BOTON
b2.grid(row = 0, column = 2, ipadx=0, ipady = 10, pady = 155, padx = 15)

# UTILIZAMOS LA TERCERA VARIABLE B3 PARA UTILIZARLA DE FORMA BOTON, LE MANDAMOS EL CONTENIDO
# JUNTO A LA FUNCION FORGE CON SU CONTENIDO

b3 = Button(raiz, text = "RESTABLECER", command = lambda : [retrieve(b1, b2), forget(l)])#BOTON RESTABLECER
b3.grid(row = 0, column = 3,ipadx=0, ipady = 10, pady = 155, padx = 15)

#BOTONES BOTONES BOTONES BOTONES BOTONES BOTONES BOTONES BOTONES BOTONES BOTONES

# CREAMOS ESTAS VARIABLES DE FORMA GLOBAL
archivo1 = StringVar()
archivo2 = StringVar()
enlace2 = StringVar()
url = StringVar()

# ESTE METODO  LO CREAMOS PARA PODER BUSCAR BUSCAR  EL ARCHIVO YA CONVERTIDO EN CSV, JUNTO LE MANDAMOS
# SUS PARAMETROS REQUERIDOS

raiz.button = tk.Button(raiz, text="BUSCAR",command= lambda :archivo1.set(filedialog.askopenfilename
(title="SELECCIONE EL ARCHIVO CSV : ", initialdir="/home/"))).place(x=550, y=97,width=80, height=35)                      #direccionamiento del boton BUSCAR

# CREAMOS UN ENTRY PARA PODER GUARDAR Y REFLEJAR LA RUTA DEL ARCHIVO IMPORTADO
mi_Entry = Entry(raiz,textvariable=archivo1).place( x=230, y=105, width=300, height=22) #Creación de Entry buscar archivo

# CREAMOS UN BOTON 'CONVERTIR' HACEMOS EL LLAMADO DE LA VENTANA DE CONVERTIR
btnconvertir = tk.Button(raiz, text="Convertir",command=ventanaconvertir)

# MANDAMOS SU POSICION
btnconvertir.place(x=650, y=97, width=80, height=35)
#btnconvertir.pack(padx=5, pady=100, ipadx=10, ipady=10) #direccionamiento con la funcion pack

#raiz.button = tk.Button(raiz, text="CONVERTIR").place(x=630, y=75) #BOTON CONVERTIR Y SU DIRECCIONAMIENTO
raiz.button = tk.Button(raiz, text="GRAFICAR").place(x=10, y=560) #BOTON GRAFICAR Y SU DIRECCIONAMIENTO

# CERRAMOS LA VENTANA PRINCIPAL
raiz.mainloop()


from setuptools import find_packages, setup

with open("requirements.txt") as f:
    install_requires = f.read().strip().split("\n")

with open("README.md") as f:
    long_description = f.read()

CLASSIFIERS = [
    "License :: OSI Approved :: Apache Software License",
    "Operating System :: OS Independent",
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.7",
    "Programming Language :: Python :: 3.8",
    "Programming Language :: Python :: 3.9",
]

setup(
    name="intake-html-table",
    description="Intake plugin for HTML tables, e.g. index pages from webservers.",
    long_description=long_description,
    long_description_content_type="text/markdown",
    python_requires=">=3.7",
    maintainer="Compiler",
    maintainer_email="kegan@compiler.la",
    classifiers=CLASSIFIERS,
    project_urls={
        "Source": "https://github.com/compilerla/intake-html-table",
        "Tracker": "https://github.com/compilerla/intake-html-table/issues",
    },
    packages=find_packages(),
    package_dir={"intake-html-table": "intake-html-table"},
    include_package_data=True,
    install_requires=install_requires,
    license="Apache 2.0",
    entry_points={
        "intake.drivers": [
            "apache_dir = intake_html_table.apache_dir:ApacheDirectoryCatalog",
            "html_table = intake_html_table.html_table:HtmlTableSource",
        ]
    },
    keywords="intake, catalog",
)