from Gauss_gen import *
from conv import *
import cv2

img = cv2.imread("Lena.jpg")
edge_size = 50
img_padding = np.zeros((img.shape[0] + 2 * edge_size, img.shape[1] + 2 * edge_size, 3))
# kernel = Gauss_gen(1.5)
# img_gauss = np.zeros((img.shape[0] - len(kernel) + 1, img.shape[1] - len(kernel) + 1, 3))
for i in range(3):
    img_padding[:, :, i] = padding(img[:, :, i], edge_size, "wrap_around")
#     img_gauss[:, :, i] = conv2d(img[:, :, i], kernel, 1)

cv2.imshow("ori", img)
cv2.imshow("zeor", img_padding.astype("uint8"))
# cv2.imshow("gauss", img_gauss.astype("uint8"))
cv2.waitKey(0)


import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score
import matplotlib
from matplotlib import pyplot as plt
import os

def plotAUROC(snames, labels: np.array, preds: np.array, med_ex: np.array, binary=False):
    fig, axs = plt.subplots(len(snames), 1)
    for i, name in enumerate(snames):
        num_genes = 1000
        if not binary:
            A = (labels[name] > med_ex[name]).astype(int).reshape(-1, num_genes)
            P = (preds[name] > med_ex[name]).astype(int).reshape(-1, num_genes)
        else:
            A = labels[name].astype(float).reshape(-1, num_genes)
            P = preds[name].astype(float).reshape(-1, num_genes)
        roc_auc_scores = np.zeros(num_genes)
        count = 0
        difference = 0
        for gene in range(num_genes):
            if (np.any(A[:, gene] == 0) and np.any(A[:, gene] == 1)):
                # Has both classes
                difference += abs(np.mean(A[:, gene] - P[:, gene]))
                roc_auc_scores[gene] = roc_auc_score(A[:, gene], P[:, gene])
                count += 1
            else:
                # Put -1 if ROC curve is not defined
                roc_auc_scores[gene] = -1
        axs[i].hist(roc_auc_scores[roc_auc_scores >= 0], bins=20)
        print(f"Median AUROC - {np.median(roc_auc_scores[roc_auc_scores >= 0])}")

def plotAP(snames, labels: np.array, preds: np.array, med_ex: np.array, binary=False):
    fig, axs = plt.subplots(len(snames), 1)
    for i, name in enumerate(snames):
        num_genes = 1000
        if not binary:
            A = (labels[name] > med_ex[name]).astype(int).reshape(-1, num_genes)
            P = (preds[name] > med_ex[name]).astype(int).reshape(-1, num_genes)
        else:
            A = labels[name].astype(float).reshape(-1, num_genes)
            P = preds[name].astype(float).reshape(-1, num_genes)

        ap_scores = np.zeros(num_genes)
        for gene in range(num_genes):
            if (np.any(A[:, gene] == 0) and np.any(A[:, gene] == 1)):
                ap_scores[gene] = average_precision_score(A[:, gene], P[:, gene])
            else:
                ap_scores[gene] = -1
        axs[i].hist(ap_scores[ap_scores >= 0], bins=20)
        print(f"Median AP - {np.median(ap_scores[ap_scores >= 0])}")

def plotHeatmaps(image, index, labels: np.array, xys: np.array, binary=False):
    cmap = matplotlib.cm.get_cmap('viridis')
    if binary:
        intensities = labels[:, index]
    else:
        intensities = 1 / (1 + np.exp(-labels[:, index]));
    colors = cmap(intensities, alpha=0.5);
    heatmap = draw_heatmap(np.copy(image), 5, xys, colors, 100);
    return heatmap

def draw_heatmap(image: np.ndarray, downsample: int, xys: np.ndarray, colors: np.array, size: int):
    # Generate "true" photo
    new_image: np.ndarray = image[::downsample, ::downsample, :].copy()
    size = size // downsample
    for i, (xy, color) in enumerate(zip(xys, colors)):
        x, y = xy
        # Center around gene locations
        x = int(x) // downsample - size // 2
        y = int(y) // downsample - size // 2

        if len(color) == 3:
            alpha = 0.50
        else:
            alpha = color[3]
        new_image[y:y + size, x:x + size] = np.uint8((1 - alpha) * new_image[y:y + size, x:x + size].astype(np.float32) + 255 * alpha * color[:3])
    return new_image


import psycopg2

def delete_table(cursor):
    cursor.execute("""
        DROP TABLE email;
        DROP TABLE phone;
        DROP TABLE name;
    """)

def create_db(cursor):
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS name(
        name_id SERIAL PRIMARY KEY,
        first_name VARCHAR(40) NOT NULL,
        last_name VARCHAR(40) NOT NULL
    );
    """)
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS email(
        id SERIAL PRIMARY KEY,
        address VARCHAR(320) NOT NULL,
        name_id INTEGER NOT NULL REFERENCES name(name_id)
    );
    """)
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS phone(
        id SERIAL PRIMARY KEY,
        number INTEGER NOT NULL,
        name_id INTEGER NOT NULL REFERENCES name(name_id)
    );
    """)

def add_new_client(cursor, f_name, l_name, e_address, ph_number=None):
    cursor.execute("""
        INSERT INTO name(first_name, last_name) VALUES(%s, %s) RETURNING name_id;
    """, (f_name, l_name))
    id_new_client = cur.fetchone()

    cursor.execute("""
        SELECT * FROM name;
    """)
    print(cursor.fetchall())

    cursor.execute("""
        INSERT INTO email(address, name_id) VALUES(%s, %s);
    """, (e_address, id_new_client))

    cursor.execute("""
        SELECT * FROM email;
    """)
    print(cursor.fetchall())

    if ph_number != None:
        cursor.execute("""
            INSERT INTO phone(number, name_id) VALUES(%s, %s);
        """, (ph_number, id_new_client))

    cursor.execute("""
        SELECT * FROM phone;
    """)
    print(cursor.fetchall())

def add_phone(cursor, ph_number, cl_id):
    cursor.execute("""
        INSERT INTO phone(number, name_id) VALUES(%s, %s);
    """, (ph_number, cl_id))

    cursor.execute("""
        SELECT * FROM phone;
    """)
    print(cursor.fetchall())

def change_data(cursor, cl_id, f_name=None, l_name=None, e_address=None, ph_number=None):
    if f_name != None:
        cursor.execute("""
            UPDATE name SET first_name=%s WHERE name_id=%s;
        """, (f_name, cl_id))

    if l_name != None:
        cursor.execute("""
            UPDATE name SET last_name=%s WHERE name_id=%s;
        """, (l_name, cl_id))

    cursor.execute("""
        SELECT * FROM name;
    """)
    print(cursor.fetchall())

    if e_address != None:
        cursor.execute("""
            UPDATE email SET address=%s WHERE name_id=%s;
        """, (e_address, cl_id))

    cursor.execute("""
        SELECT * FROM email;
    """)
    print(cursor.fetchall())

    if ph_number != None:
        cursor.execute("""
            UPDATE phone SET number=%s WHERE name_id=%s;
        """, (ph_number, cl_id))

    cursor.execute("""
        SELECT * FROM phone;
    """)
    print(cursor.fetchall())

def delete_phone(cursor, ph_number, cl_id):
    cursor.execute("""
        DELETE FROM phone WHERE number=%s AND name_id=%s;
    """, (ph_number, cl_id,))

    cursor.execute("""
        SELECT * FROM phone;
    """)
    print(cursor.fetchall())

def delete_client(cursor, cl_id):
    cursor.execute("""
        DELETE FROM email WHERE name_id=%s;
    """, (cl_id,))

    cursor.execute("""
        SELECT * FROM email;
    """)
    print(cursor.fetchall())

    cursor.execute("""
        DELETE FROM phone WHERE name_id=%s;
    """, (cl_id,))

    cursor.execute("""
        SELECT * FROM phone;
    """)
    print(cursor.fetchall())

    cursor.execute("""
        DELETE FROM name WHERE name_id=%s;
    """, (cl_id,))

    cursor.execute("""
        SELECT * FROM name;
    """)
    print(cursor.fetchall())

def find_client(cursor, f_name=None, l_name=None, e_address=None, ph_number=None):
    cursor.execute("""
        SELECT n.name_id, n.first_name, n.last_name, e.address, p.number FROM email e
        join name n ON e.name_id=n.name_id
        join phone p ON n.name_id=p.name_id
        WHERE first_name=%s OR last_name=%s OR address=%s OR number=%s;
    """, (f_name, l_name, e_address, ph_number))
    print(cur.fetchall())

with psycopg2.connect(database="client", user="postgres", password="****") as conn:
    with conn.cursor() as cur:
        delete_table(cur)

        create_db(cur)

        add_new_client(cur, 'Иван', 'Иванов', 'ivanov@mail.ru', 11111)

        add_new_client(cur, 'Петр', 'Петров', 'petrov@mail.ru', 22222)

        add_phone(cur, 33333, 2)

        change_data(cur, 2, f_name='Семен', l_name='Семенов')

        delete_phone(cur, 11111, 1)

        delete_client(cur, 1)

        find_client(cur, ph_number=22222)

conn.close()


# -------------------------------------------------------------------
# Connect to the remote database, SeisCloud (https://seis.cloud).
#
# Author: Liang Ding
# Email: myliang.ding@mail.utoronto.ca
# Data: Jun. 7th, 2023
# -------------------------------------------------------------------

class dbBase():
    '''
    The remote database.
    '''
    def __init__(self, db_url=None, db_port=None):
        '''
        The base class of SeisClient.
        The address to the database on SeisCloud.

        :param db_url:  The url.
        :param db_port: The port.
        '''
        if db_url is None and db_port is None:
            self.db_url = "https://db.seis.cloud"
            self.db_port = None
        else:
            self.db_url = db_url
            self.db_port = db_port


from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.models import load_model
import tensorflow
import numpy as np
import io
import json

model = load_model("IR_podcast_v3.h5")

tokenizer = Tokenizer()
seed_text = "I once knew a man named Justin"
next_words = 50

# Load Podcast vocab
tokenizer = Tokenizer()
# All the IR podcast transcripts from https://building.infinite.red/
data = open('./podcasts.txt').read()

# break it into lines
corpus = data.lower().split("\n")

# converts each word into a unique number (ordered by most used)
tokenizer.fit_on_texts(corpus)
# print(tokenizer.word_index)
# exit()
total_words = len(tokenizer.word_index) + 1

# Gathered from other scripts
max_sequence_len = 252

# Generate `next_words` using the model
for _ in range(next_words):
    token_list = tokenizer.texts_to_sequences([seed_text])[0]
    token_list = pad_sequences(
        [token_list], maxlen=max_sequence_len - 1, padding='pre')
    print(token_list)
    predicted = model.predict_classes(token_list, verbose=0)
    output_word = ""
    for word, index in tokenizer.word_index.items():
        if index == predicted:
            output_word = word
            break
    seed_text += " " + output_word
print(seed_text)


from django.test import TestCase,Client
from rest_framework import status
from rest_framework.test import APIClient
from capitals.db_api import country_create
from django.urls import reverse

class QuizViewTestCase(TestCase):
    def setUp(self):
        self.client = APIClient()
        self.country_instance = country_create(name="dummy",capital="fake")

    def test_get(self):
        response = self.client.get(reverse('quiz-details'),content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIn('country_name', response.data['data'])

    def test_post_correct_guess(self):
        payload = {
            'country_name': self.country_instance.name,
            'guess': self.country_instance.capital,
        }
        response = self.client.post(reverse('quiz-details'), data=payload)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['data']['message'], 'Guessed Capital is Correct')

    def test_post_incorrect_guess(self):
        payload = {
            'country_name': self.country_instance.name,
            'guess': 'Real Capital',
        }
        response = self.client.post(reverse('quiz-details'), data=payload)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn('error', response.data['data'])

    def test_post_invalid_country(self):
        payload = {
            'country_name': 'Unknow Country',
            'guess': 'Capital',
        }
        response = self.client.post(reverse('quiz-details'), data=payload)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn('error', response.data['data'])


#!/usr/bin/python
#! -*- encoding: utf-8 -*-

# This file is changed from OpenMVG (Open Multiple View Geometry) C++ library example.

import os
import subprocess
import sys

# Indicate the openMVG binary directory
# OPENMVG_SFM_BIN = "H:/projects/SLAM/sfm/openMVG_example/openMVG_SfM_official/build/SfM/Release"
# OPENMVG_Localization_BIN = "H:/projects/SLAM/sfm/openMVG_example/openMVG_SfM_official/build/Localization/Release"

OPENMVG_SFM_BIN = "H:/projects/SLAM/sfm/openMVG_develop/src/release/Windows-AMD64-Release/Release"
OPENMVG_Localization_BIN = OPENMVG_SFM_BIN

#WORK_DIR = "H:/projects/SLAM/sfm/openMVG_example/openMVG_Pose_Estimation/SfM_Aided/"

WORK_DIR = os.path.split(os.path.realpath(__file__))[0] + '/'

print("WORK_DIR:", WORK_DIR)

OPENMVG_SFM_MINE_BIN = WORK_DIR+"build/SfM/Release"
OPENMVG_Geodesy_MINE_BIN = WORK_DIR+"build/Geodesy/Release"

def cvt_SfM_data(input_dir, output_dir, filename):
  basename = os.path.basename(filename)
  f_no_ext, ext_f = os.path.splitext(basename)
  input_file = os.path.join(input_dir, filename)

  for ext in ['bin', 'json', 'ply']:
    if ext == ext_f:
      continue
    output_file = os.path.join(output_dir, f_no_ext+'.'+ext)
    pCvt = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_ConvertSfM_DataFormat"),  "-i", input_file, "-o", output_file] )
    pCvt.wait()

def incremental_SfM_pipeline(dataset_dir, output_dir, K_value, suffix='.jpg'):
  init_dir = os.path.join(dataset_dir, "sfm_init_data") # folder of train images, should make sure
  faked_gps_path = os.path.join(dataset_dir, "fake_gps_file.txt")

  if not os.path.exists(dataset_dir) or not os.path.exists(init_dir):
    print("Seems no valid dataset")
    exit()

  if not os.path.exists(faked_gps_path):
    print("no faked gps provided")
    exit()

  matches_dir = os.path.join(output_dir, "matches")
  reconstruction_dir = os.path.join(output_dir, "reconstruction_sequential")

  print ("Using dataset dir  : ", dataset_dir)
  print ("      images in {} for initialization".format(init_dir))
  print ("      output_dir : ", output_dir)
  print ("      matches_dir : ", matches_dir)
  print ("      reconstruction_dir : ", reconstruction_dir)

  # Create the ouput/matches folder if not present
  if not os.path.exists(output_dir):
    os.mkdir(output_dir)
  if not os.path.exists(matches_dir):
    os.mkdir(matches_dir)

  print ("1. Intrinsics analysis")
  pIntrisics = subprocess.Popen( [os.path.join(OPENMVG_SFM_MINE_BIN, "SfMInit_ImageListing"),  "--imageDirectory", init_dir, "--outputDirectory", matches_dir, "--intrinsics", K_value] )
  pIntrisics.wait()

  print("1.x Geodesy, add position prior")
  pGeodesy = subprocess.Popen( [os.path.join(OPENMVG_Geodesy_MINE_BIN, "registration_faked_gps_position"),  "--input_file", matches_dir+"/sfm_data.json", "--output_file", matches_dir+"/sfm_data.json", "--faked_gps_path", faked_gps_path] )
  pGeodesy.wait()

  # time, 33s for 10 images, an improvement to be needed
  print ("2. Compute features")
  pFeatures = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_ComputeFeatures"),  "--input_file", matches_dir+"/sfm_data.json", "--outdir", matches_dir, "--describerMethod", "SIFT", "--numThreads", "7"] ) # threads num is related to CPU
  pFeatures.wait()

  # with guidedmatching, 32s will be used, really long
  print ("3. Compute matches")
  pMatches = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_ComputeMatches"),  "--input_file", matches_dir+"/sfm_data.json", "--out_dir", matches_dir] )
  # pMatches = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_ComputeMatches"),  "--input_file", matches_dir+"/sfm_data.json", "--out_dir", matches_dir, "--geometric_model", "e", "--guided_matching", "1"] )
  pMatches.wait()

  # Create the reconstruction if not present
  if not os.path.exists(reconstruction_dir):
      os.mkdir(reconstruction_dir)

  print ("4. Do Sequential/Incremental reconstruction")
  pRecons = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_IncrementalSfM"),  "--input_file", matches_dir+"/sfm_data.json", "--matchdir", matches_dir, "--outdir", reconstruction_dir, "--refineIntrinsics", "NONE", "--prior_usage", "--initialPairA", "1"+suffix, "--initialPairB", "4"+suffix] )
  pRecons.wait()
  # pRecons = subprocess.Popen( [os.path.join(OPENMVG_SFM_MINE_BIN, "openMVG_main_IncrementalSfM"),  "--input_file", matches_dir+"/sfm_data.json", "--matchdir", matches_dir, "--outdir", reconstruction_dir, "--refineIntrinsics", "NONE", "--prior_usage"] )
  # pRecons.wait()

  print("4.1 Convert format for easy looking")
  cvt_SfM_data(reconstruction_dir, reconstruction_dir, "sfm_data.bin")

  # print ("4.2 Colorize Structure") # no need to do this, to save time
  # pRecons = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_ComputeSfM_DataColor"),  "-i", reconstruction_dir+"/"+incremental_SfM_data_name, "-o", os.path.join(reconstruction_dir,"colorized_incremental_SfM.ply")] )
  # pRecons.wait()

  # optional, compute final valid structure from the known camera poses, a refine part
  # Note the matches.e.bin or matches.f.bin
  print ("5. Structure from Known Poses (robust triangulation)")
  pRecons = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_ComputeStructureFromKnownPoses"),  "--input_file", reconstruction_dir+"/sfm_data.bin", "--match_dir", matches_dir, "--output_file", os.path.join(reconstruction_dir,"robust.bin")] )
  pRecons.wait()

  print("5.1 Convert format for easy looking")
  cvt_SfM_data(reconstruction_dir, reconstruction_dir, "robust.bin")

  # print ("5.2 Colorize Structure")
  # pRecons = subprocess.Popen( [os.path.join(OPENMVG_SFM_BIN, "openMVG_main_ComputeSfM_DataColor"),  "-i", reconstruction_dir+"/robust.bin", "-o", os.path.join(reconstruction_dir,"robust_colorized.ply")] )
  # pRecons.wait()

def localization_pipeline(dataset_dir, output_dir,
  incremental_SfM_data_name,
  reference_im_name="reference_2.jpg",
  query_im_name="query_1.jpg"
  ):

  query_dir = os.path.join(dataset_dir, "sfm_query_data")

  matches_dir = os.path.join(output_dir, "matches")
  reconstruction_dir = os.path.join(output_dir, "reconstruction_sequential")
  localization_dir = os.path.join(output_dir, "Localization")

  log_file = os.path.join(localization_dir,'localization_log_'+reference_im_name[:-4]+'_'+query_im_name[:-4])

  query_im_path = os.path.join(query_dir, query_im_name)

  print ("Using dataset dir  : ", dataset_dir)
  print ("      output_dir : ", output_dir)
  print ("      localization_dir : ", localization_dir)

  # Create the ouput/matches folder if not present
  if not os.path.exists(output_dir) or not os.path.exists(matches_dir):
    print("seems we have not do initial SfM")
    exit()
  if not os.path.exists(localization_dir):
        os.mkdir(localization_dir)

  if os.path.exists(log_file):
        os.remove(log_file)

  ##NOTE: the `-s –single_intrinsics` is rather important, it will not try to BA the intrinsics, leave our methods more stable

  print ("1. Localization ..")
  pLocal = subprocess.Popen( [os.path.join(OPENMVG_Localization_BIN, "openMVG_main_SfM_Localization"),  "--input_file",  reconstruction_dir+"/"+incremental_SfM_data_name, "--match_dir", matches_dir, "--out_dir", localization_dir, "--match_out_dir", localization_dir, "--query_image_dir", query_im_path, "--single_intrinsics"], shell=True,stdout = open(log_file+'.txt','w') )
  pLocal.wait()

  print ("2. Calc relative pose of {}, regrding to reference image {}".format(query_im_name, reference_im_name))
  pRelativePose = subprocess.Popen( [os.path.join(OPENMVG_SFM_MINE_BIN, "relativePosePair_test"),  "--input_file",  localization_dir+"/sfm_data_expanded.json", "--reference_im_name", reference_im_name, "--query_im_name", query_im_name, "-o", log_file+'.json'], shell=True,stdout = open(log_file+'.txt','a+') )
  pRelativePose.wait()

  return log_file+'.json'

if __name__ == "__main__":
  """
  Some user defined variables
  """
  # dataset_dir = WORK_DIR+"dataset_cartoon_1/"
  # output_dir = WORK_DIR + "sequential_cartoon_1_jpg"
  # # dataset_dir = WORK_DIR+"dataset_Marx_1/"
  # # output_dir = WORK_DIR + "sequential_Marx_1_jpg"
  # K_value = "8607.8639;0;2880.72115;0;8605.4303;1913.87935;0;0;1" # K for big images, jpg
  # suffix = ".jpg"

  # dataset_dir = WORK_DIR+"dataset_cartoon_1_bmp/"
  # output_dir = WORK_DIR + "sequential_cartoon_1_bmp"
  # K_value = "1444.29449;0.0;482.68264;0.0;1444.79783;319.3993;0.0;0.0;1" # K for small images, bmp
  # suffix = ".jpg" # we should convert the suffix first

  dataset_dir = WORK_DIR+"dataset_cartoon_1_less_pic/"
  output_dir = WORK_DIR + "sequential_dataset_cartoon_1_less_pic"
  K_value = "1444.29449;0.0;482.68264;0.0;1444.79783;319.3993;0.0;0.0;1" # K for small images, bmp

  incremental_SfM_pipeline(dataset_dir, output_dir, K_value)

  localization_pipeline(dataset_dir, output_dir,
  "robust.bin",
  reference_im_name="1.jpg",
  query_im_name="query_4.jpg"
  )

  # strs = [str(x) for x in range(1, 10)]
  # # strs.extend(['1a', '1b', '1c', '1d', '4a', '4b', '7a', '7b'])
  # strs = sorted(strs)

  # for im in strs:
  #   query = "query_"+im+suffix
  #   localization_pipeline(dataset_dir, output_dir,
  #   "robust.bin",
  #   reference_im_name="reference_1"+suffix,
  #   query_im_name=query
  #   )


a = [] #a변수에 빈 리스트를 생성합니다.
total = 0#평균값을 구하기 위해 입력받은값의 총합을 total변수에 받을 준비를 합니다.

for i in range(10): #range(10)을 이용하여 총 10번의 반복을 합니다.
     num = int(input("숫자를 입력하세요: "))#num변수에 값을 입력받습니다.
     a.append(num)#append함수를 이용하여 입력받은 값을 a리스트에 차곡차곡 저장합니다.
     total = total+ num #total변수에 입력받은 값을 차근차근 더해줍니다.

minimum = a[0] #최소값을 구하기 위해 맨 처음 a리스트의 0번째 값을 저장합니다.
maximum = a[0] #최대값을 구하기 위해 맨 처음 a리스트의 0번째 값을 저장합니다.
for num in a: #num변수에 a리스트에 있는 10가지의 값을 차례대로 저장합니다.
     if num < minimum:#a리스트의 n번째 값이 이전 리스트의 값보다 작으면 minimum변수에 그 값을 저장하여 최소값을 구합니다.
          minimum = num
     if num > maximum:#a리스트의 n번째 값이 이전 리스트의 값보다 크면 maximum변수에 그 값을 저장합니다.
          maximum = num

average = total / 10#입력받은 모든 값의 합인 total변수를 10으로 나누어 평균을 구하여 average변수에 저장합니다.
print("최대값은: %d\n최소값은: %d\n평균값은: %0.1f" % (maximum, minimum, average))
#포매팅하여 각 자리에 알맞은 변수를 넣어 출력합니다.


# coding: utf-8

# In[ ]:

def mylogger(name):
    logger = logging.getLogger(name)
    if not len(logger.handlers):
        logger = logging.getLogger(name)
        hdlr = logging.FileHandler(logfile)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)
        logger.setLevel(logging.INFO)

    return logger

#function overlap calculate how much 2 rectangles overlap
def overlap_area(boxes):
    if(len(boxes) == 0):
        return 0

    xx1 = max(boxes[0,0], boxes[1,0])
    yy1 = max(boxes[0,1], boxes[1,1])
    xx2 = min(boxes[0,2], boxes[1,2])
    yy2 = min(boxes[0,3], boxes[1,3])

    w = max(0, xx2 - xx1 + 1)
    h = max(0, yy2 - yy1 + 1)

    ##box1 area
    area1 = (boxes[0,2]-boxes[0,0]) * (boxes[0,3]-boxes[0,1])
    ##box2 area
    area2 = (boxes[1,2]-boxes[1,0]) * (boxes[1,3]-boxes[1,1])
    if area1 > area2:
        area = area2
    else:
        area = area1

    overlap = (w * h) / area

    return overlap

def get_costs(pos,points):
    distances = [math.floor(math.sqrt((x2-pos[0])**2+(y2-pos[1])**2)) for (x2,y2) in points]
    return distances


import Matrix

str = input("Please input points, split by blank\n")
str = str.strip()   # eat the white before or after the valid input
strpoints = str.split(" ")  # divide the input and store it in a string list
points = []
for point in strpoints:
    try:
        points.append(float(point)) # transfer the string point to float
    except:
        print("Input error")

iMatrix = Matrix.matrix(points)
# call the cluster function until there is only one cluster
while(len(iMatrix.m) > 1):
    iMatrix.nextcluster()
# show the cluster result
print(iMatrix.PointsDic[0])


import sys
import random
import numpy as np
from inspect import getmembers, isfunction

from iqtests import IQ_001_Counting as iq1
from iqtests import IQ_002_BumpTest as iq2
from iqtests import IQ_003_ShortestPath as iq3

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def test_iq1_1():
    G, V = iq1.problem(10, False)
    s = G.generate_batch(1)
    expected = ([[['box', 'contains', 'trinket'], ['box', 'contains', 'trinket'], ['noise2', 'noise1', 'noise1'],
       ['box', 'contains', 'trinket'], ['box', 'contains', 'trinket'], ['box', 'contains', 'trinket'],
       ['noise1', 'box', 'trinket'], ['box', 'contains', 'trinket'], ['box', 'contains', 'trinket'],
       ['trinket', 'noise1', 'trinket'], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], [0.7], [10])
    if str(s) == str(expected):
        return True
    else:
        return False

def test_iq1_sequential():
    G, V = iq1.problem(10, True)
    prob, sol, length = G.generate_batch(2)
    oh = V.one_hot(prob)
    if oh.shape == (2, 60, 27):
        return True
    else:
        return False

def test_iq2():
    G, V = iq2.problem(2, False)
    s = G.generate_batch(1)
    expected = ([[['problem', 'is', '0'], ['start', 'is', 'room_1_0'], ['destination', 'is', 'room_1_1'], ['direction', 'is', 'room_0_0'], ['room_0_0', 'path', 'room_1_0'], ['room_1_0', 'path', 'room_0_0'], ['room_1_0', 'path', 'room_1_1'], ['room_1_1', 'path', 'room_1_0'], ['0', '0', '0']]], [1.0])
    if str(s) == str(expected):
        return True
    else:
        return False

def test_iq2_sequential():
    G, V = iq2.problem(2, True)
    s = G.generate_batch(2)[0]
    if V.one_hot(s).shape == (2, 36, 13):
        return True
    else:
        return False

def test_iq3_1():
    G, V = iq3.problem(2, False)
    s = G.generate_batch(1)
    expected = ([[['problem', 'is', '0'], ['start', 'is', 'room_1_0'], ['destination', 'is', 'room_1_1'], ['direction', 'is', 'room_0_0'], ['room_0_0', 'path', 'room_1_0'], ['room_1_0', 'path', 'room_0_0'], ['room_1_0', 'path', 'room_1_1'], ['room_1_1', 'path', 'room_1_0']]], [0.0])
    if str(s) == str(expected):
        return True
    else:
        return False

def test_iq3_sequential():
    G, V = iq3.problem(2, True)
    s = G.generate_batch(2)[0]
    expected = (2, 32, 13)
    if V.one_hot(s).shape == expected:
        return True
    else:
        return False

def test_solve_iq2():
    G, V = iq2.problem(2, False)
    prob, sol = G.generate_batch(100)
    start = dir = None
    for i,p in enumerate(prob):
        out = 0.0
        for src,arc,dst in p:
            if src=="start" and arc=="is":
                start = dst
            if src=="direction" and arc=="is":
                dir = dst
            if src==start and arc=="path" and dst==dir:
                out=1.0
                break
        if out!=sol[i]:
            return False
    return True

def test_solve_iq3():
    G, V = iq2.problem(2, False)
    prob, sol = G.generate_batch(100)
    start = dir = None
    for i,p in enumerate(prob):
        return False
    return True

def run_all():
    functions_list = [o for o in getmembers(sys.modules[__name__]) if isfunction(o[1]) and o[0].startswith("test_")]
    for f in functions_list:
        random.seed(0)
        np.random.seed(0)
        res = f[1]()
        color = None
        if res:
            color = bcolors.OKGREEN
        else:
            color = bcolors.FAIL
        print(f"{f[0].ljust(25)}:{color}{res}{bcolors.ENDC}")

def dbg():
    random.seed(0)
    np.random.seed(0)
    G, V = iq3.problem(2, False)
    s = G.generate_batch(5)[0]
    a = V.one_hot(s)

    print(a.shape)
    G, V = iq3.problem(2, True)
    s = G.generate_batch(5)[0]
    a = V.one_hot(s)
    print(a.shape)

if __name__=="__main__":
    run_all()
    #dbg()


"""
quick_3_string.py
Reads string from standard input and 3-way string quicksort them.
"""
import random

class Quick3String:
    CUTOFF = 15

    @classmethod
    def sort(cls, a):
        random.shuffle(a)
        n = len(a)
        cls.__sort(a, 0, n - 1, 0)
        assert cls.__is_sorted(a)

    @classmethod
    def __sort(cls, a, lo, hi, d):
        if hi <= lo + cls.CUTOFF:
            cls.__insertion(a, lo, hi, d)
            return

        lt, gt = lo, hi
        v = cls.__char_at(a[lo], d)
        i = lo + 1
        while i <= gt:
            t = cls.__char_at(a[i], d)
            if t < v:
                lt += 1
                i += 1
                a[i], a[lt] = a[lt], a[i]
            elif t > v:
                gt -= 1
                a[i], a[gt] = a[gt], a[i]
            else:
                i += 1

        # a[lo..lt-1] < v = a[lt..gt] < a[gt+1..hi].
        cls.__sort(a, lo, lt-1, d)
        if v >= 0:
            cls.__sort(a, lt, gt, d+1)
        cls.__sort(a, gt+1, hi, d)

    @classmethod
    def __char_at(cls, s, d):
        assert 0 <= d <= len(s)
        if d == len(s):
            return -1
        return ord(s[d])

    @classmethod
    def __less(cls, v, w, d):
        i = d
        while i < min(len(v), len(w)):
            if v[i] < w[i]:
                return True
            if v[i] > w[i]:
                return False
            i += 1
        return len(v) < len(w)

    @classmethod
    def __insertion(cls, a, lo, hi, d):
        for i in range(lo, hi + 1):
            for j in range(i, lo, -1):
                if cls.__less(a[j], a[j - 1], d):
                    a[j], a[j - 1] = a[j - 1], a[j]

    @classmethod
    def __is_sorted(cls, a):
        for i in range(1, len(a)):
            if a[i] < a[i - 1]:
                return False
        return True

def main():
    with open("../resources/shells.txt", ) as f:
        a = "".join(f.readlines()).splitlines()
        words = []
        w = len(a[0].split(' '))
        for line in a:
            assert w == len(line.split(' '))
            words.extend(line.split())
        Quick3String.sort(words)
        for item in words:
            print(item)

if __name__ == '__main__':
    main()


"""updating bio

Revision ID: 1cf6901ea903
Revises: 1837077807ac
Create Date: 2021-01-03 16:20:41.351378

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '1cf6901ea903'
down_revision = '1837077807ac'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('bio', schema=None) as batch_op:
        batch_op.add_column(sa.Column('text', sa.String(length=3000), nullable=True))
        batch_op.add_column(sa.Column('timestamp', sa.DateTime(), nullable=True))
        batch_op.create_index(batch_op.f('ix_bio_timestamp'), ['timestamp'], unique=False)
        batch_op.drop_column('body')

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('bio', schema=None) as batch_op:
        batch_op.add_column(sa.Column('body', sa.VARCHAR(length=140), nullable=True))
        batch_op.drop_index(batch_op.f('ix_bio_timestamp'))
        batch_op.drop_column('timestamp')
        batch_op.drop_column('text')

    # ### end Alembic commands ###


import turtle as t
import math

ITERATIONS = 100
ENLARGEMENT = 10
t.left(180)

for i in range(ITERATIONS):
    t.forward(math.sqrt(i) * ENLARGEMENT)
    t.left(90)
    t.forward(1 * ENLARGEMENT)
    t.goto(0, 0)

t.mainloop()


f = open('24_/27686.txt')
s = f.readline()
mx = 0
cnt = 1
for i in range(len(s)-1):
    if s[i] == 'X' and s[i+1] == 'X':
        cnt += 1
        if cnt > mx:
            mx = cnt
    else:
        cnt = 1
mx = max(cnt, mx)
print(mx)


import time
from cProfile import Profile
from timeit import default_timer
from typing import Dict, Optional

from py_grpc_profile.adapter.interfaces import Adapter

class CProfileAdapter(Adapter):
    DEFAULT_FILENAME_FORMAT = (
        "grpc-server-{service}-{method}-{elapsed:.0f}ms-{time:.0f}.prof"
    )

    def __init__(
        self,
        filename_format: Optional[str] = None,
    ):
        self.filename_format = (
            self.DEFAULT_FILENAME_FORMAT if filename_format is None else filename_format
        )

    def run(self, behavior, request_or_iterator, servicer_context, metadata: Dict):
        profile = Profile()
        start = default_timer()
        profile.enable()

        try:
            response_or_iterator = behavior(
                request_or_iterator,
                servicer_context,
            )
        finally:
            profile.disable()
            elapsed = default_timer() - start
            filename = self.filename_format.format(
                service=metadata["grpc_service_name"],
                method=metadata["grpc_method_name"],
                elapsed=elapsed * 1000.0,
                time=time.time(),
            )
            profile.dump_stats(filename)
        return response_or_iterator


from django import forms

class LAForm01(forms.Form):

    def __init__(self, *args, **kwargs):
        if 'qal' in kwargs:
            qal = kwargs.pop('qal')
            super(LAForm01, self).__init__(*args, **kwargs)
            qanum = 0
            for qa in qal:
                #qal is the question answer list which alternates question, answer so
                # %2 is used first (if) to get question then (else) to get answer
                qnum = qanum // 2
                if qanum % 2 == 0:
                    self.fields['answer-' + str(qnum)] = forms.CharField(label=qa, max_length=30, widget=forms.NumberInput)
                    self.fields['hiddenq-' + str(qnum)] = forms.CharField(initial=qa, widget=forms.HiddenInput)
                else:
                    self.fields['hiddena-' + str(qnum)] = forms.CharField(initial=qa, widget=forms.HiddenInput)
                qanum += 1
        else:
            super(LAForm01, self).__init__(*args, **kwargs)

    def q_marks(self, n):
        qm = []
        for i in range(n):
            if self.cleaned_data['answer-' + str(i)] == self.cleaned_data['hiddena-' + str(i)]:
                qm.append("-CORRECT-")
            else:
                qm.append("--WRONG--")
        return qm

"""
solution for multiple/list of fields
 from https://jacobian.org/writing/dynamic-form-generation/
 also see https://stackoverflow.com/questions/17159567/how-to-create-a-list-of-fields-in-django-forms

forms documentation
 working with - https://docs.djangoproject.com/en/1.10/topics/forms/
 reference - https://docs.djangoproject.com/en/1.10/ref/forms/
 field widgets - https://docs.djangoproject.com/en/1.10/ref/forms/widgets/

    def __init__(self, *args, **kwargs):
        extra = kwargs.pop('extra')
        super(UserCreationForm, self).__init__(*args, **kwargs)

        for i, question in enumerate(extra):
            self.fields['custom_%s' % i] = forms.CharField(label=question)
"""


""" MISR-GRU for multi-image super resolution """

import torch.nn as nn
import torch
from torch.autograd import Variable

class ResidualBlock(nn.Module):
    def __init__(self, channel_size=64, kernel_size=3):
        '''
        Args:
            channel_size : int (c), number of hidden channels
            kernel_size : int, shape of a 2D kernel
        '''

        super(ResidualBlock, self).__init__()
        padding = kernel_size // 2
        self.block = nn.Sequential(
            nn.Conv2d(in_channels=channel_size, out_channels=channel_size, kernel_size=kernel_size, padding=padding),
            nn.PReLU(),
            nn.Conv2d(in_channels=channel_size, out_channels=channel_size, kernel_size=kernel_size, padding=padding),
            nn.PReLU()
        )

    def forward(self, x):
        '''
        Args:
            x : tensor (b, c, w, h), hidden representations
        Returns:
            x + residual: tensor (b, c, w, h), new hidden representations
        '''

        residual = self.block(x)
        return x + residual

class EncoderUnit(nn.Module):
    def __init__(self, in_channels, num_res_layers, kernel_size, channel_size):
        '''

        Each unit in the encoder is composed 2 conv layers and 2 residual blocks and parametric-relu as the
            activation function
        Args:
            in_channels : int (c_in), number of input channels
            num_res_blocks : int, number of resnet blocks
            kernel_size : int, shape of a 2D kernel,
            channel_size : int (c), number of hidden channels
        '''
        super(EncoderUnit, self).__init__()
        padding = kernel_size // 2
        self.init_layer = nn.Sequential(
            nn.Conv2d(in_channels=in_channels, out_channels=channel_size, kernel_size=kernel_size, padding=padding),
            nn.PReLU())

        res_layers = [ResidualBlock(channel_size, kernel_size) for _ in range(num_res_layers)]
        self.res_layers = nn.Sequential(*res_layers)

        self.final = nn.Sequential(
            nn.Conv2d(in_channels=channel_size, out_channels=channel_size, kernel_size=kernel_size, padding=padding)
        )

    def forward(self, x):
        '''
        Encodes an input tensor x.
        Args:
            x : tensor (b, c_in, W, H), input
        Returns:
            out: tensor (b, C, W, H), hidden representations
        '''

        x = self.init_layer(x)
        x = self.res_layers(x)
        x = self.final(x)
        return x

class ConvGRUUnit(nn.Module):
    def __init__(self, in_channels, hidden_channels, kernel_size):
        '''
            Args:
                in_channels : int (i_c), number of input channels
                hidden_channels : int (h_c), number of hidden channels
                kernel_size : kernel size
        '''
        super(ConvGRUUnit, self).__init__()
        padding = kernel_size // 2
        self.hidden_channels = hidden_channels
        self.reset_gate = nn.Conv2d(in_channels + hidden_channels, hidden_channels, kernel_size, padding=padding)
        self.update_gate = nn.Conv2d(in_channels + hidden_channels, hidden_channels, kernel_size, padding=padding)
        self.out_gate = nn.Conv2d(in_channels + hidden_channels, hidden_channels, kernel_size, padding=padding)

    def forward(self, x, prev_state):
        '''
            Args:
                x : tensor (b, c, w, h), input to gru unit
            Returns:
                out: tensor (b, h_c, w, h), hidden states
        '''

        # generate empty prev_state, if it is None
        if prev_state is None:
            state_size = [x.shape[0], self.hidden_channels] + list(x.shape[2:])
            prev_state = Variable(torch.zeros(state_size))
            if torch.cuda.is_available():
                prev_state = prev_state.cuda()

        stacked = torch.cat([x, prev_state], dim=1)
        update = torch.sigmoid(self.update_gate(stacked))
        reset = torch.sigmoid(self.reset_gate(stacked))
        candidate_state = torch.tanh(self.out_gate(torch.cat([x, prev_state * reset], dim=1)))
        new_state = (1 - update) * prev_state + update * candidate_state

        return new_state

class FusionModule(nn.Module):
    def __init__(self, fuse_config):
        '''
        Args:
            fuse_config : dict, fusion configuration
        '''
        super(FusionModule, self).__init__()
        self.input_channels = fuse_config["in_channels"]
        self.num_hidden_layers = fuse_config["num_hidden_layers"]
        hidden_channels = fuse_config["hidden_channels"]
        kernel_sizes = fuse_config["kernel_sizes"]

        gru_units = []
        for i in range(0, self.num_hidden_layers):
            cur_input_dim = self.input_channels if i == 0 else hidden_channels[i - 1]
            gru_unit = ConvGRUUnit(in_channels=cur_input_dim, hidden_channels=hidden_channels[i],
                                   kernel_size=kernel_sizes[i])
            gru_units.append(gru_unit)
        self.gru_units = nn.ModuleList(gru_units)

    def forward(self, x, alphas, h=None):

        '''
            Args:
                x : tensor (B, L, C, W, H), hidden states
                alphas : tensor (B, L, 1, 1, 1), boolean indicator (0 if padded low-res view, 1 otherwise)
            Returns:
                out: tensor (B, C, W, H), fused hidden state
        '''

        if h is None:
            hidden_states = [None] * self.num_hidden_layers
        num_low_res = x.shape[1]
        cur_layer_input = x

        for l in range(self.num_hidden_layers):
            gru_unit = self.gru_units[l]
            h = hidden_states[l]

            out = []
            for t in range(num_low_res):
                h = gru_unit(cur_layer_input[:, t, :, :, :], h)
                out.append(h)

            out = torch.stack(out, dim=1)
            cur_layer_input = out

        fused_representations = torch.sum(cur_layer_input * alphas, 1) / torch.sum(alphas, 1)

        return fused_representations

class Decoder(nn.Module):
    def __init__(self, dec_config):
        '''
        Args:
            dec_config : dict, decoder configuration
        '''

        super(Decoder, self).__init__()

        self.deconv = nn.Sequential(nn.ConvTranspose2d(in_channels=dec_config["deconv"]["in_channels"],
                                                       out_channels=dec_config["deconv"]["out_channels"],
                                                       kernel_size=dec_config["deconv"]["kernel_size"],
                                                       stride=dec_config["deconv"]["stride"]),
                                    nn.PReLU())

        self.final = nn.Conv2d(in_channels=dec_config["final"]["in_channels"],
                               out_channels=dec_config["final"]["out_channels"],
                               kernel_size=dec_config["final"]["kernel_size"],
                               padding=dec_config["final"]["kernel_size"] // 2)

    def forward(self, x):
        '''
        Decodes a hidden state x.
        Args:
            x : tensor (b, c, w, h), fused hidden state
        Returns:
            out: tensor (b, c_out, 3xw, 3xw), super resolved image

        '''
        x = self.deconv(x)
        x = self.final(x)

        return x

class MISRGRU(nn.Module):
    ''' MISRGRU, a neural network for multi-image super resolution (MISR) using ConvGRU. '''

    def __init__(self, config):
        '''
        Args:
            config : dict, configuration file
        '''

        super(MISRGRU, self).__init__()
        self.unit1 = EncoderUnit(in_channels=config["encoder"]["in_channels"],
                                 num_res_layers=config["encoder"]["num_res_blocks"],
                                 kernel_size=config["encoder"]["kernel_size"],
                                 channel_size=config["encoder"]["channel_size"])
        self.fuse = FusionModule(config["fusion"])
        self.decode = Decoder(config["decoder"])
        self.unit2 = EncoderUnit(in_channels=config["encoder"]["channel_size"] * 2,
                                 num_res_layers=config["encoder"]["num_res_blocks"],
                                 kernel_size=config["encoder"]["kernel_size"],
                                 channel_size=config["encoder"]["channel_size"])

    def forward(self, lrs, alphas):
        '''
        Super resolves a batch of low-resolution images.
        Args:
            lrs : tensor (B, L, W, H), low-resolution images
            alphas : tensor (B, L), boolean indicator (0 if padded low-res view, 1 otherwise)
        Returns:
            srs: tensor (B, C_out, W, H), super-resolved images
        '''

        ###################### Encode #########################
        batch_size, num_low_res, height, width = lrs.shape
        # Extend channel dimension
        lrs = lrs.view(batch_size, num_low_res, 1, height, width)
        # create a reference view based on median statistics
        refs, _ = torch.median(lrs[:, :9], 1)

        alphas = alphas.view(-1, num_low_res, 1, 1, 1)

        # encode LR views
        lrs = lrs.view(batch_size * num_low_res, 1, height, width)
        lrs = self.unit1(lrs)
        lrs = lrs.view(batch_size, num_low_res, -1, height, width)

        # encode ref view
        refs = self.unit1(refs)
        refs = refs.unsqueeze(1)
        refs = refs.repeat(1, num_low_res, 1, 1, 1)

        # Co-register ref encoded features with LR encoded features
        out = torch.cat([lrs, refs], 2)
        out = out.view(batch_size * num_low_res, -1, height, width)
        out = self.unit2(out)
        out = out.view(batch_size, num_low_res, -1, height, width)  # tensor (b, l, c, w, h)

        ###################### Fuse #########################
        out = self.fuse(out, alphas)

        ###################### Decode #########################
        out = self.decode(out)

        return out


from pathlib import Path
import sys
import numpy as np
from sklearn.model_selection import train_test_split
import torch
from torch import nn
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
import torch.multiprocessing

class Model(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.height = self.width = 8
        self.ouput_size = 8 * 8
        self.dropout_late = 0.5
        in_channels = 2
        channels = 16

        self.relu = nn.ReLU()
        self.layer1 = nn.Sequential(
            nn.Conv2d(in_channels, channels, 3, padding=1),
            nn.BatchNorm2d(channels),
            self.relu,
            nn.Conv2d(channels, channels, 3, padding=1),
            nn.BatchNorm2d(channels),
            self.relu,
            nn.Conv2d(channels, channels, 3),
            nn.BatchNorm2d(channels),
            self.relu,
            nn.Conv2d(channels, channels, 3),
            nn.BatchNorm2d(channels),
            self.relu,
        )

        self.fc_input = channels * (self.width - 4) * (self.height - 4)
        self.dropout = nn.Dropout(self.dropout_late, inplace=True)
        self.layer2 = nn.Sequential(
            nn.Linear(self.fc_input, 512),
            nn.BatchNorm1d(512),
            self.relu,
            self.dropout,
            nn.Linear(512, 256),
            nn.BatchNorm1d(256),
            self.relu,
            self.dropout,
        )

        self.fc3 = nn.Linear(256, 64)
        self.fc4 = nn.Linear(256, 1)
        self.softmax = nn.LogSoftmax(dim=1)
        self.tanh = nn.Tanh()

    def forward(self, x):
        x = self.layer1(x)
        x = x.view(-1, self.fc_input)
        x = self.layer2(x)
        policy = self.fc3(x)
        value = self.fc4(x)
        return self.softmax(policy), self.tanh(value)

class Dataset:
    def __init__(self, states, policy, values) -> None:
        self.states = states
        self.policy = policy
        self.values = values

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

    def __getitem__(self, idx):
        return self.states[idx], self.policy[idx], self.values[idx]

class LightingModule(pl.LightningModule):
    def __init__(self) -> None:
        super().__init__()
        self.model = Model()
        self.loss_p = nn.BCEWithLogitsLoss()
        self.loss_v = nn.MSELoss()

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

    def shared_step(self, batch):
        x, policy, value = batch
        p, v = self.model(x)
        return self.loss_p(policy, p) + self.loss_v(value, v.squeeze())

    def training_step(self, batch, batch_idx):
        loss = self.shared_step(batch)
        self.log('train_loss', loss)
        return loss

    def validation_step(self, batch, batch_idx):
        loss = self.shared_step(batch)
        self.log('val_loss', loss)

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

def main():
    data_path = Path(sys.argv[1])
    policy = np.load(data_path / 'policy.npy')
    states = np.load(data_path / 'states.npy').astype(np.float32)
    values = np.load(data_path / 'values.npy').astype(np.float32)
    # print(policy.shape, states.shape, values.shape)
    train_p, val_p, train_s, val_s, train_v, val_v = train_test_split(
        policy, states, values, test_size=0.2, shuffle=True, random_state=42
    )
    train_dataset = Dataset(train_s, train_p, train_v)
    val_dataset = Dataset(val_s, val_p, val_v)
    train_dataloder = DataLoader( train_dataset, batch_size=256, shuffle=True)
    val_dataloder = DataLoader(val_dataset, batch_size=256)
    module = LightingModule()
    trainer = pl.Trainer(
        max_epochs=500,
        log_every_n_steps=10,
        callbacks=[
            ModelCheckpoint(monitor='val_loss'),
            EarlyStopping(monitor='val_loss'),
        ],
    )
    trainer.fit(module, train_dataloder, val_dataloder)
    dummy_input = torch.randn(1, 2, 8, 8)
    module.to_onnx("models/model.onnx", dummy_input, export_params=True)

if __name__ == '__main__':
    main()


import logging
from telegram.ext import Updater, CommandHandler
from ipgetter2 import IPGetter

#logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

def ip(update, context):
    getter = IPGetter()
    ips=getter.get()
    update.message.reply_text('Your ips:\n v4:{0}\n v6:{1}'.format(ips.v4,ips.v6))

# main

tokenFile = open("token.txt", "r")
token=tokenFile.readline()

updater = Updater(token, use_context=True)

updater.dispatcher.add_handler(CommandHandler('ip', ip))

updater.start_polling()
updater.idle()


from pydantic import BaseModel, Field, constr, confloat, create_model
from typing import Optional

validate_str = constr(
    max_length=50,
    min_length=3,
    strict=True
)

validate_float = confloat(
    gt=0.0,
    strict=True
)

class BaseProducto(BaseModel):
    nombre: validate_str = Field(...)
    marca: validate_str = Field(...)
    precio: validate_float = Field(...)

    @classmethod
    def as_optional(cls):
        annonations = cls.__fields__
        fields = {attribute: (Optional[data_type.type_], None) for attribute, data_type in annonations.items()}
        OptionalModel = create_model(f"Optional{cls.__name__}", **fields)
        return OptionalModel

class Producto(BaseProducto):
    id: int = Field(...)


#!/usr/bin/env python3
import configparser
import datetime
import json
import os
import subprocess
import sys

import requests
from dateutil.parser import parse

cache = None

def get_access_token(rclone_config_path=None, remote_name='onedrive'):
    global cache
    if cache is not None:
        return cache
    if rclone_config_path is None:
        rclone_config_path = os.path.expanduser('~/.config/rclone/rclone.conf')
    try:
        config = configparser.ConfigParser()
        config.read(rclone_config_path)
        token_info = json.loads(config[remote_name]['token'])
        if is_token_expired(token_info):
            raise Exception()
    except Exception as e:
        refresh_token_with_rclone(rclone_config_path, remote_name)
        return get_access_token(rclone_config_path, remote_name)
    cache = token_info['access_token']
    return cache

def is_rclone_installed():
    try:
        subprocess.run(['rclone', '--version'], check=True, stdout=subprocess.PIPE)
        return True
    except Exception as e:
        return False

def is_token_expired(token_info):
    expiry = parse(token_info['expiry'])
    now = datetime.datetime.now(datetime.timezone.utc)
    return expiry < now

def refresh_token_with_rclone(rclone_config_path, remote_name):
    if not is_rclone_installed():
        print('rclone is not installed. Please install it.', file=sys.stderr)
        sys.exit(1)
    try:
        subprocess.run(
            ['rclone', 'config', 'update', remote_name, 'token', rclone_config_path],
            check=True,
            stdout=subprocess.PIPE
        )
    except subprocess.CalledProcessError as e:
        subprocess.run(
            ['rclone', 'config', 'create', remote_name, 'onedrive', 'drive_type', 'personal', 'token', rclone_config_path],
            check=True,
            stdout=subprocess.PIPE
        )

def upload_file_to_onedrive(filepath, remotepath):
    if remotepath.startswith('/'):
        remotepath = remotepath[1:]
    if remotepath.endswith('/'):
        remotepath = remotepath[:-1]
    filename = os.path.basename(filepath)
    access_token = get_access_token()
    headers = {"Authorization": "Bearer " + access_token}
    endpoint = f"https://graph.microsoft.com/v1.0/me/drive/root:/{remotepath}/" + filename + ":/content"

    with open(filepath, 'rb') as f:
        r = requests.put(endpoint, headers=headers, data=f)
        r.raise_for_status()

    return r.json().get('id')

def create_embed_link(file_id):
    access_token = get_access_token()
    headers = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"}
    endpoint = "https://graph.microsoft.com/v1.0/me/drive/items/" + file_id + "/createLink"

    payload = {
        "type": "embed"
    }

    r = requests.post(endpoint, headers=headers, json=payload)
    r.raise_for_status()

    return r.json().get('link').get('webUrl')

def main(filepath, remotepath):
    file_id = upload_file_to_onedrive(filepath, remotepath)
    embed_link = create_embed_link(file_id)
    print(embed_link)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("odpd: OneDrive Picture Direct Link Generator")
        print("  Usage: odpd.py <filepath> [remotepath]")
        sys.exit(1)
    main(sys.argv[1], "files/" if len(sys.argv) < 3 else sys.argv[2])


import sys
import hashlib
import binascii
import os
from gmpy2 import mpz, iroot, powmod, mul, t_mod

# Variables globales

rsa = 0

def main():
    if len(sys.argv) == 2 and sys.argv[1] == 'rsa_old':
        import_rsa(0)
    else:
        import_rsa(1)

    (sig, message) = forge()
    (priv, pub) = genkeys()
    verify(message, sig, priv)

def import_rsa(new):
    global rsa
    if not new:
        print ('use version 3.2.3')
        sys.path.append('../include/rsa-3.2.3')
    else:
        print ('use version 3.4.2')
        sys.path.append('../include/rsa-3.4.2')

    import rsa

def genkeys():
    global pub, priv, rsa
    (pub, priv) = rsa.newkeys(2048)
    pub.e = 3

    return (pub,priv)

def verify(message, sig, priv):
    try:
        rsa.verify(message, sig, priv)
        print("L'identite de l'expediteur a bien ete confirmee")
    except:
        print("Impossible de confirmer l'expediteur du message")

def forge():

    def to_bytes(n):
        """ Return a bytes representation of a int """
        return n.to_bytes((n.bit_length() // 8) + 1, byteorder='big')

    def from_bytes(b):
        """ Makes a int from a bytestring """
        return int.from_bytes(b, byteorder='big')

    def get_bit(n, b):
        """ Returns the b-th rightmost bit of n """
        return ((1 << b) & n) >> b

    def set_bit(n, b, x):
        """ Returns n with the b-th rightmost bit set to x """
        if x == 0: return ~(1 << b) & n
        if x == 1: return (1 << b) | n

    def cube_root(n):
        return int(iroot(mpz(n), 3)[0])

# Message dont on veut contrefaire une signature
# message = "Ciao, ma888".encode("ASCII") # plante pour un hash pair (dernier bit = 0)
    message = "Hello, i'm Alice :p".encode("ASCII")
# On calcule son hash
    message_hash = hashlib.sha256(message).digest()

# La partie ASN.1
    ASN1_blob = rsa.pkcs1.HASH_ASN1['SHA-256']
# Suffixe que doit avoir la signature une fois décodée
    suffix = b'\x00' + ASN1_blob + message_hash

# Aperçu du suffix a obtenir après application de la clé publique sur la signature
    binascii.hexlify(suffix)

    len(suffix)

# On vérifie que le dernier bit du hash vaut 1
    suffix[-1]&0x01 == 1 # easy suffix computation works only with odd target

# suffixe de la signature avant déchiffrement avec la clé publique (avant mise au cube)
    sig_suffix = 1
# On boucle sur chaque bit du suffixe a obtenir.
# poids faible -> poids fort
    for b in range(len(suffix)*8):
        # On fait en sort que le cube de sig_suffixe soit égal à suffix, au moins sur la taille du suffix à obtenir
        if get_bit(sig_suffix ** 3, b) != get_bit(from_bytes(suffix), b):
            sig_suffix = set_bit(sig_suffix, b, 1)

# On vérifie que la fin du cube du suffixe à obtenir est égale au suffixe à obtenir
    to_bytes(sig_suffix ** 3).endswith(suffix) # BOOM

    len(to_bytes(sig_suffix ** 3)) * 8

# On construit le prefix de la signature
    while True:
        # Après application du cube, on aimerait obtenir ce prefixe
        prefix = b'\x00\x01' + os.urandom(2048//8 - 2)

        # On prend la racine cubique du prefix visé (On fait l'hyp que (00 01 *)^3 ~ 00 01)
        # A la fin, ajout de zéros de la taille du suffixe (pour faire l'addition)
        sig_prefix = to_bytes(cube_root(from_bytes(prefix)))[:-len(suffix)] + b'\x00' * len(suffix)

        # On crée la signature en additionnant suffixe et prefixe
        sig = sig_prefix[:-len(suffix)] + to_bytes(sig_suffix)

        # Il ne faut pas de zéro qui soit dans le préfix de la signature déchiffrée
        if b'\x00' not in to_bytes(from_bytes(sig) ** 3)[:-len(suffix)]: break

    return sig, message

if __name__ == "__main__":
    main()


import pygame
import sys
from pygame.locals import *
import csv
import math
import asyncio

pygame.init()
screen = pygame.display.set_mode((1000,1000))
myfont = pygame.font.Font(None, 60)
screen.fill((255,255,255))

inp = ""

def loadData(tag) :

    global screen

    screen.fill((255, 255, 255))

    black = (0, 0, 0)
    white = (255, 255, 255)
    red = (255, 0, 0)
    blue = (0, 0, 255)

    color = black

    file = open("tagdataOld.txt", "r")
    reader = csv.reader(file, delimiter="|")

    x = 0
    y = 0
    counter = 0
    xpos = 0
    ypos = 0

    for i, row in enumerate(reader):

        if (i < 750) :

            if (row[1] == tag) :

                print (i)

                x = float(row[2])
                y = float(row[3])
                x = math.floor(x)
                y = math.floor(y)

                xpos = xpos + x
                ypos = ypos + y

                counter = counter+1

                if (counter == 5) :
                    xpos = (xpos/50)*2
                    ypos = (ypos/50)*2
                    counter = 0
                    print (row[0],str(xpos),str(ypos))
                    pygame.draw.circle(screen, color, (math.floor(xpos), math.floor(ypos)), 2, 2)
                    pygame.display.update()

            '''
            x = float(row[2])/10
            y = float(row[3]+2000)/10
            x = math.floor(x)
            y = math.floor(y)

            xpos = xpos+x
            ypos = ypos+y

            if (row[1] == '27211') :
                color = blue
            if (row[1] == '27245') :
                color = red
            if (row[1] == '27205') :
                color = black
            '''
    '''
    xpos = xpos/10
    ypos = ypos/10

    print (xpos,ypos)
    pygame.draw.circle(screen, color, (math.floor(xpos), math.floor(ypos)), 2, 2)
    pygame.display.update()
    '''

async def detectKeys() :

    line = 0

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_1:
                        print ('loading 27211')
                        loadData('27211')
                    if event.key == pygame.K_2:
                        print ('loading 27205')
                        loadData('27205')
                    if event.key == pygame.K_3:
                        print ('loading 27241')
                        loadData('27241')
detectKeys()

async def main():
    detectKeysTask = asyncio.create_task(detectKeys())
    await detectKeysTask

asyncio.run(main())


import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import  layers
import numpy as np

mnits = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnits.load_data()

x_train, x_test = x_train / 255.0, x_test / 255.0

# 堆叠模型

model = tf.keras.Sequential()

model.add(layers.Flatten(input_shape=(28, 28)))

model.add(layers.Dense(128, activation='relu'))

model.add(layers.Dropout(0.2))

model.add(layers.Dense(10, activation='softmax'))

model.compile(optimizer="adam",
              loss="sparse_categorical_crossentropy",
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10, batch_size=32)

model.evaluate(x_test, y_test, verbose=2)


# Lista para almacenar el tipo de vehículo y su tarifa correspondiente
tarifas = [("automóvil", 10), ("camión", 20), ("autobús", 30)]

# Diccionario para almacenar la cantidad de vehículos que han pasado por el peaje y su tarifa total
recaudación = {"automóvil": 0, "camión": 0, "autobús": 0, "tarifa_total": 0}

while True:
    # Preguntar al usuario el tipo de vehículo
    opcion = input("Introduce el número para elegir el tipo de vehículo (1: automóvil, 2: camión, 3: autobús o 0 para salir): ")

    if opcion == "0":
        break

    if not opcion:
        continue

    # Buscar el tipo de vehículo correspondiente a la opción
    tipo_vehiculo = ""
    tarifa = 0
    if opcion == "1":
        tipo_vehiculo = "automóvil"
        tarifa = 10
    elif opcion == "2":
        tipo_vehiculo = "camión"
        tarifa = 20
    elif opcion == "3":
        tipo_vehiculo = "autobús"
        tarifa = 30

    # Aumentar la cantidad de vehículos y la tarifa total para el tipo de vehículo
    recaudación[tipo_vehiculo] += 1
    recaudación["tarifa_total"] += tarifa

# Imprimir la recaudación total
print("Recaudación total:", recaudación["tarifa_total"], "dólares")

# Imprimir la cantidad de vehículos y la recaudación por tipo de vehículo
for tv, t in tarifas:
    print("Cantidad de", tv, ":", recaudación[tv])
    print("Recaudación por", tv, ":", recaudación[tv] * t, "dólares")

# En este código, se agrega una línea para comprobar si el usuario ha introducido algo cuando se pulsa Intro. Si no se ha introducido nada, el programa vuelve al inicio del bucle sin aumentar la cantidad de vehículos ni la tarifa total. De lo contrario, se sigue el resto del código de la misma manera que en la versión anterior.
# Si pukso numero 6 se sale


#!/usr/bin/env python

import requests #for http requests
import re
import json

BASSINPREFIX = 'href="./niv2-bassin.php?CdEntVigiCru='
STATIONPREFIX = 'niv3-station.php?'

EXTRACTSTATIONIDRE = re.compile('CdStationHydro=([A-Z0-9]+)')

def extract_stationid(url):
    return EXTRACTSTATIONIDRE.findall(url)[0]

def parse_page(t,prefix):
    i=0
    while i!=-1:
        i = t.find(prefix,i)
        if i==-1:
            break
        j = t.find('"', i+len(prefix))
        yield t[i:j]
        i = j

def main():
    all_stations=[]
    r = requests.get('http://www.vigicrues.gouv.fr')
    t = r.text.encode(r.encoding)
    bassins = map(lambda hrefurl: int(hrefurl[len(BASSINPREFIX):]),list(set(parse_page(t,BASSINPREFIX))))
    for bassin in bassins:
        print('Bassin %s' % bassin)
        r = requests.get('http://www.vigicrues.gouv.fr/niv2-bassin.php?CdEntVigiCru=%s'%bassin)
        t = r.text.encode(r.encoding)
        all_stations += list(map(extract_stationid,parse_page(t,STATIONPREFIX)))
    all_stations = list(set(all_stations))
    all_stations_obj = []
    for station in all_stations:
        r = requests.get('http://www.vigicrues.gouv.fr/services/station.json/index.php?CdStationHydro=%s'%station)
        all_stations_obj.append({'id':station,'river':r.json()['LbCoursEau'].encode(r.encoding),'name':r.json()['LbStationHydro'].encode(r.encoding)})
    json.dump(all_stations_obj,open('stations_vigicrues.json','w'))

if __name__=='__main__':
    main()


from pynput.keyboard import Key

languages = [ 'en-us', 'de', 'en-US', 'de-DE' ]

replacements = {
    'equal': '=',
    'equals': '=',
    'equal spaced': ' = ',
    'dash': '-',
    'backtick': '`',
    'dollar sign': '$',
    'one': '1',
    'two': '2',
    'to': '2',
    'three': '3',
    'tree': '3',
    'free': '3',
    'for': '4',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
    'ten': '10',
    'eleven': '11',
    'twelve': '12',
    'thirteen': '13',
    'fourteen': '14',
    'fifteen': '15',
    'twenty': '20',
    'twentyfive': '25',
    'get pull': 'git pull',
    'get paul': 'git pull',
    'get push': 'git push',
    'get checkout': 'git checkout',
    'get branch': 'git branch -vv',
    'git branch': 'git branch -vv',
    'get status': 'git status',
    'get log': 'git log',
    'git cherry pick': 'git cherry-pick',
    'get cherry-pick': 'git cherry-pick',
    'get cherry pick': 'git cherry-pick',
    'get fetch': 'git fetch',
    'get rebase': 'git rebase',
    'get push upstream': 'git push upstream',
    'get push revamp': 'git push revamp',
    'get stash': 'git stash',
    'get stash pop': 'git stash pop',
    'kids checkout': 'git checkout',
    'kids status': 'git status',
    'get this': 'git diff',
    'get diff': 'git diff',
    'get ad': 'git add',
    'get remote': 'git remote',
    'h.top': 'htop',
    'c d': 'cd',
}

keys = {
    'enter': Key.enter,
    'center': Key.enter,
    'hunter': Key.enter,
    'wetter': Key.enter,
    'space': Key.space,
    'keyspace': Key.space,
    'backspace': Key.backspace,
    'arrow left': Key.left,
    'arrow right': Key.right,
    'arrow write': Key.right,
    'arrow up': Key.up,
    'arrow down': Key.down,
    'tab': Key.tab,
    'tabulator': Key.tab,
    'page up': Key.page_up,
    'page down': Key.page_down,
}


# Contains common utility functions
import pandas as pd

def print_fun(message: str, status: str = '') -> None:
    """Summary
        For printing updates across package
    """
    separator = '-'
    custom_msg = '\n' + '{1}' * 20 + ' | {0}' + ' | ' + '{1}' * 20 + '\n'
    if status == 'step':
        separator = '*'

    print(custom_msg.format(message, separator))

def stringify_dataframe(data: pd.DataFrame, start_idx: int = -1, end_idx: int = -1) -> str:
    """Summary
        Used to stringify dataframes for hashing
    """
    # If need to stringify complete dataframe
    if start_idx != -1:
        data = data.iloc[start_idx: end_idx]

    return data.to_json(orient='records')


import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl

df = pd.DataFrame([[500,450,520,610], [690,700,820,900],[1100,1030,1200,1380],
                    [1500,1650,1700,1850],[1990,2020,2300,2420],[1020,1600,2200,2550]],
                    index=[2015,2016,2017,2018,2019,2020],
                    columns=['1Q','2Q','3Q','4Q']
)

# df.to_csv('sales.csv',header=False,index=True,encoding='utf-8-sig')
# print(df)

font_name = mpl.font_manager.FontProperties(
    fname='c:/Windows/fonts/malgun.ttf').get_name()
mpl.rc('font',family=font_name)

# df를 그래프로 표현
df = df.transpose() #행,열 전환
df.plot()
plt.show()

# plt.figure(figsize=(7,6))
# plt.plot(df.columns,df.loc[2015],label=2015)
# plt.plot(df.columns,df.loc[2016],label=2016)
# plt.plot(df.columns,df.loc[2017],label=2017)
# plt.plot(df.columns,df.loc[2018],label=2018)
# plt.plot(df.columns,df.loc[2019],label=2019)
# plt.plot(df.columns,df.loc[2020],label=2020)

# plt.title('sales')
# plt.xlabel('Quarters')
# plt.ylabel('Sales')
# # plt.xticks(df.columns,df.columns,fontsize=10)
# plt.legend()
# plt.show()


from api_python.database.db import get_db

import sqlite3
import pytest

def test_get_db(app):
    # Assert the connection is the same within the same request context
    with app.app_context():
        conn = get_db()
        assert conn is get_db()

    # Assert the connection is closed
    with pytest.raises(sqlite3.ProgrammingError) as e:
        conn.execute('SELECT 1')
    assert 'closed' in str(e.value)

def test_init_db_command(runner, monkeypatch):
    class Recorder():
        called = False

    def fake_init_db():
        Recorder.called = True

    monkeypatch.setattr('api_python.database.db.init_db', fake_init_db)
    result = runner.invoke(args=['init-db'])
    assert 'Initialized' in result.output
    assert Recorder.called

def test_add_user_command(runner):
    result = runner.invoke(args=['add-user', 'example@ex.ex', '1234', 'user'])
    assert 'added' in result.output


my_list = [4, 7, -12, 14, 28, 28, 4, 2, 1, -5, 18, 12]

# finde das Maximum
maximum = my_list[0]
for value in my_list:
    if value > maximum:
        maximum = value
print(f"Das Maximum ist {maximum}")

# Zusatz
# Erstelle eine neue Liste,
# in der das alte Maximum fehlt
# ggf. muss man es häufiger entfernen
new_list = my_list[:]
while maximum in new_list:
    new_list.remove(maximum)
second_maximum = new_list[0]

for value in new_list:
    if value > second_maximum:
        second_maximum = value
print(f"Der zweitgrößte Werte ist {second_maximum}")


import os, sys

normalized_types_filename = sys.argv[1]
sra_studies_filename = sys.argv[2]
output_filename = sys.argv[3]

normalized_types_file = open(normalized_types_filename, "r")
sra_studies_file = open(sra_studies_filename, "r")
output_file = open(output_filename, "w")

normalized_types_list = []
for line in normalized_types_file:
    normalized_type = list.strip().split("\n")
    normalized_types_list.append(normalized_type)

sra_studies_list = []
for line_2 in sra_studies_file:
    sra_studies = line_2.strip().split("\n")
    sra_studies_list.append(sra_studies)

for normalized_types in normalized_types_list:
    file_to_be_created = "merged_"+normalized_types+".tsv"
    filename_to_be_created = open(file_to_be_created, "w")
    for sra_study in sra_studies_list:
        filename_to_be_used = sra_study+"_counts_for_norm_within_studies.tsv"
        sra_study_gene_to_counts = {}
        file_to_be_used = open(filename_to_be_used, "r")
        for line in file_to_be_used:
            gene = line.strip().split("\t")[0]
            counts = line.strip().split("\t")[1:]
            if gene not in sra_study_gene_to_counts:
                sra_study_gene_to_counts[gene] = counts
    for sra_study_in_dict in sra_study_gene_to_counts:
        filename_to_be_created.write(sra_study_gene_to_counts+"\t"+"\t")


from Filme import Filme
class Node:
    def __init__(self, filme=None, left=None, right=None):
        self._filme = filme
        self._left = left
        self._right = right
        self.balance = 0
    def set_filme(self, filme):
        self._filme = filme

    def get_filme(self):
        return self._filme

    def set_left(self, left):
        self._left = left

    def get_left(self):
        return self._left

    def set_right(self, right):
        self._right = right

    def get_right(self):
        return self._right

    def insert(self, filme):
        if self.get_filme() == None:
            self.set_filme(filme)
            return self
        else:
            p = self
            while True:
                if p.get_filme().get_nome() > filme.get_nome():
                    if p.get_left() == None:
                        node = Node(filme)
                        p.set_left(node)
                        break
                    else:
                        p = p.get_left()
                elif p.get_filme().get_nome() < filme.get_nome():
                    if p.get_right() == None:
                        node = Node(filme)
                        p.set_right(node)
                        break
                    else:
                        p = p.get_right()
                elif p.get_filme().get_nome() == filme.get_nome():
                    print(filme.get_nome())
                    return None
            if self.is_balanced(self) == False:
            	self = self.do_balance(self, filme.get_nome())
            	#pass
            return self
    def left_rotation(self, root):
        y = root.get_right()
        z = y.get_left()

        # Rotaciona
        y.set_left(root)
        root.set_right(z)

        # Muda os pesos
        lh = root.height(root.get_left()) - 1
        rh = root.height(root.get_right()) - 1
        root.balance = lh - rh

        lh = root.height(y.get_left()) - 1
        rh = root.height(y.get_right()) - 1
        y.balance = lh - rh

        # Retorna a raiz
        return y

    def right_rotation(self, root):
        y = root.get_left()
        z = y.get_right()

        # Rotaciona
        y.set_right(root)
        root.set_left(z)

        # Muda os pesos
        lh = root.height(root.get_left()) - 1
        rh = root.height(root.get_right()) - 1
        root.balance = lh - rh

        lh = root.height(y.get_left()) - 1
        rh = root.height(y.get_right()) - 1
        y.balance = lh - rh

        # Retorna a raiz
        return y

    def do_balance(self, root, key):
        balance = root.balance
        # Esquerda - Esquerda
        if balance > 1 and key < root.get_left().get_filme().get_nome():
            return self.right_rotation(root)

        # Direita - Direita
        if balance < -1 and key > root.get_right().get_filme().get_nome():
            y = self.left_rotation(root)
            return y
        #Rotacao dupla Esquerda - Direta
        if balance > 1 and key > root.get_left().get_filme().get_nome():
            root.set_left(root.left_rotation(root.get_left()))
            return self.right_rotation(root)

        # Rotacao dupla Direita - Esquerda
        if balance < -1 and key < root.get_right().get_filme().get_nome():
            root.set_right(root.right_rotation(root.get_right()))
            return self.left_rotation(root)

        return root
    def list_items(self):
        right = self.get_right()
        left = self.get_left()
        if self is not None and self.get_filme() is not None:
            if left != None:
                left.list_items()
            print(self.get_filme().get_nome())
            if right != None:
                right.list_items()

    def search_by_name(self, name):
        #Busca pelo nome
        p = self
        while True:
            #caso nao ache um filme, eventualmente o p sera None
            if p is None or p.get_filme() is None:
                return None
            if p.get_filme().get_nome() == name:
                return p.get_filme()
            else:
                #move o p de acordo com a possivel posição (esquerda/direita) do filme(node)
                if p.get_filme().get_nome() > name:
                    p = p.get_left()
                elif p.get_filme().get_nome() < name:
                    p = p.get_right()

    def search(self, name):
        #usando recursividade
        left = self.get_left()
        right = self.get_right()
        if self is not None:
            if self.get_filme().get_nome() > name:
                if left is not None:
                    return left.search(name)
            elif self.get_filme().get_nome() < name:
                if right is not None:
                    return right.search(name)
            else:
                return self
    def in_order_successor(self, root):

       	    p = root.get_right()
       	    while p.get_left() is not None:
       	    	p  = p.get_left()
       	    return p

    def search_by_id(self, aid):

        left = self.get_left()
        right = self.get_right()
        if self is not None:
            if left is not None:
                left.search_by_id(aid)
            if self.get_filme().get_aid() == aid:
                print("Nome: ", self.get_filme().get_nome())
                print("Ano: ", self.get_filme().get_ano())
                print("id: ", self.get_filme().get_aid())
                print("-" * 20)
            if right is not None:
                right.search_by_id(aid)

    def height(self, root):
    #Altura da arvore
        if root is None:
            return 0
        return max(self.height(root.get_right()), self.height(root.get_left())) + 1

    def is_balanced(self, root):
    #Se balanceada, = a true
        if root is None:
            return True

        lh = root.height(root.get_left()) - 1
        rh = root.height(root.get_right()) - 1
        root.balance = lh - rh

        if ((abs(lh - rh) <= 1) and self.is_balanced(root.get_left()) is True and self.is_balanced(root.get_right()) is True):
            return True

        return False

    def __str__(self, depth=0):
        ret = ""

        # Print right branch
        if self._right != None:
            ret += self._right.__str__(depth + 1)

        # Print own value
        ret += "\n" + ("    "*depth) + str(self._filme._aid)

        # Print left branch
        if self._left != None:
            ret += self._left.__str__(depth + 1)

        return ret


import traceback
from flask_restful import Resource,reqparse
from flask_jwt import jwt_required

from models.stats import StatsModel
from utils.performance import GamePerformance

class Stats(Resource):
    # (tournamentID, playerID, attendance, appearance, start, goal,
    #   penalty, penaltyShootout, penaltyTaken, ownGoal, header, weakFootGoal,
    #   assist, yellow, red, cleanSheet, penaltySaved)
    parser = reqparse.RequestParser()
    parser.add_argument('attendance', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('appearance', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('start', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('goal', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('penalty', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('freekick', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('penaltyShootout', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('penaltyTaken', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('ownGoal', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('header', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('weakFootGoal', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('otherGoal', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('assist', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('yellow', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('red', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('cleanSheet', type=int, required=True, help="This field cannot be blank.")
    parser.add_argument('penaltySaved', type=int, required=True, help="This field cannot be blank.")

    def get(self,tournamentID,clubID,playerID):  # get stats
        stats = StatsModel.find_stats(tournamentID,clubID,playerID)
        if not stats:
            return {'message' : 'stats not found.'}, 404
        try:
            playerStats = {
                'stats' : stats.json(),
                'gamePerformance' : {
                    "win" : 0,
                    "draw" : 0,
                    "loss" : 0,
                }
            }

            gamePerformance = GamePerformance.get_player_tournament_performance(tournamentID,clubID,playerID)
            if gamePerformance:
                playerStats['gamePerformance'] = gamePerformance
            return playerStats, 200
        except:
            traceback.print_exc()
            return {'message' : 'Internal Server Error. Cannot load player total stats.'}, 500

    def post(self,tournamentID,clubID,playerID): # create a new stats
        stats = StatsModel.find_stats(tournamentID,clubID,playerID)
        if stats:
            return {'message' : 'stats already exists.'}, 400
        stats = StatsModel(tournamentID,clubID,playerID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
        try:
            stats.save_to_db()
            return stats.json(), 201
        except:
            traceback.print_exc()
            return {'message' : 'Internal server error, create stats failed.'}, 500

    def delete(self,tournamentID,clubID,playerID): # delete a stats
        stats = StatsModel.find_stats(tournamentID,clubID,playerID)
        if not stats:
            return {'message' : 'stats not found.'}, 404
        try:
            stats.delete_from_db()
            return {'message' : 'stats deleted.'}, 200
        except:
            traceback.print_exc()
            return {'message' : 'Internal server error, delete stats failed.'}, 500

    def put(self,tournamentID,clubID,playerID):  # update an existing stats
        stats = StatsModel.find_stats(tournamentID,clubID,playerID)
        if not stats:
            return {'message' : 'stats not found'}, 404

        data = self.parser.parse_args()
        vector = StatsModel(tournamentID,clubID,playerID,**data)
        new_stats = StatsModel.get_updated_stats(stats,vector)

        try:
            new_stats.save_to_db()
            return new_stats.json(), 200
        except:
            traceback.print_exc()
            return {'message' : 'Internal server error, update stats failed.'}, 500

class StatsList(Resource):

    def get(self):
        return {'stats':[stats.json() for stats in StatsModel.find_all()]},200

class StatsByPlayer(Resource):

    def get(self,playerID):
        try:
            playerStats = {
                'stats' : StatsModel.find_player_total_stats(playerID),
                'gamePerformance' : {
                    "win" : 0,
                    "draw" : 0,
                    "loss" : 0,
                }
            }
            gamePerformance = GamePerformance.get_player_total_performance(playerID)
            if gamePerformance:
                playerStats['gamePerformance'] = gamePerformance
            return playerStats, 200
        except:
            traceback.print_exc()
            return {'message' : 'Internal Server Error. Cannot load player total stats.'}, 500

class StatsByClubPlayer(Resource):

    def get(self,clubID,playerID):
        try:
            playerStats = {
                'stats' : StatsModel.find_club_player_stats(clubID,playerID),
                'gamePerformance' : {
                    "win" : 0,
                    "draw" : 0,
                    "loss" : 0,
                }
            }
            gamePerformance = GamePerformance.get_player_club_performance(clubID,playerID)
            if gamePerformance:
                playerStats['gamePerformance'] = gamePerformance
            return playerStats, 200
        except:
            traceback.print_exc()
            return {'message' : 'Internal Server Error. Cannot load player total stats.'}, 500

class StatsByTournamentPlayer(Resource):

    def get(self,tournamentID,clubID,playerID):
        try:
            playerStats = {
                'stats' : StatsModel.find_stats(tournamentID,clubID,playerID),
                'gamePerformance' : {
                    "win" : 0,
                    "draw" : 0,
                    "loss" : 0,
                }
            }
            gamePerformance = GamePerformance.get_player_tournament_performance(tournamentID,clubID,playerID)
            if gamePerformance:
                playerStats['gamePerformance'] = gamePerformance
            return playerStats, 200
        except:
            traceback.print_exc()
            return {'message' : 'Internal Server Error. Cannot load player total stats.'}, 500

class StatsByTournamentClub(Resource):

    def get(self,tournamentID,clubID): # get club's total stats in this tournament
        try:
            clubStats = {
                'stats' : StatsModel.find_tournament_club_total_stats(tournamentID,clubID),
                'gamePerformance' : {
                    "win" : 0,
                    "draw" : 0,
                    "loss" : 0,
                    "cleanSheet" : 0,
                    "goalsConceded" : 0,
                }
            }
            gamePerformance = GamePerformance.get_club_tournament_performance(tournamentID,clubID)
            if gamePerformance:
                clubStats['gamePerformance'] = gamePerformance
            return clubStats, 200
        except:
            traceback.print_exc()
            return {'message' : 'Internal Server Error. Cannot load club tournament total stats.'}, 500


from captcha.image import ImageCaptcha
from random import randint, randbytes
from hashlib import sha1, sha256
from os.path import isfile

def create_captcha_salt():
    print("Creating captcha salt...")
    f = open("./data/captcha-salt.txt", "x")
    f.write(sha256(randbytes(1024)).hexdigest())
    f.close()

def read_captcha_salt():
    if not isfile("./data/captcha-salt.txt"):
        create_captcha_salt()

    f = open("./data/captcha-salt.txt", "r")
    s = f.read()
    f.close()
    return s

capctha_salt = read_captcha_salt()

img_captcha = ImageCaptcha(
    width=160,
    height=80,
    fonts=["./captchas/fonts/Caveat.ttf", "./captchas/fonts/IndieFlower.ttf"]
)

def generate_captcha_pair():
    numbers = "".join([str(randint(0, 9)) for _ in range(4)])
    hash = sha1()
    hash.update(numbers.encode("ascii"))
    hash.update(capctha_salt.encode("ascii"))

    return (numbers, hash.hexdigest())

def generate_captcha():
    (num, hash) = generate_captcha_pair()
    img_captcha.write(num, f"./data/captchas/{hash}.png", "png")
    return hash

def validate_captcha_pair(numbers: str, hash: str):
    h = sha1()
    h.update(numbers.encode("ascii"))
    h.update(capctha_salt.encode("ascii"))
    valid = hash == h.hexdigest()

    return valid


# -*- coding: utf-8 -*-
# __author__ = 'zoujiaxun'
import os
import unittest
import pandas as pd
from Bio import SeqIO
import re

from biocluster.agent import Agent
from biocluster.tool import Tool
from mbio.packages.whole_transcriptome.utils import runcmd
from biocluster.core.exceptions import OptionError

class GetfastaCircAgent(Agent):
    '''
    last_modify: 2019.10.21
    '''

    def __init__(self, parent):
        super(GetfastaCircAgent, self).__init__(parent)
        options = [
            {'name': 'circbase', 'type': 'infile', 'format': 'whole_transcriptome.fasta'},
            {'name': 'circbase_bed', 'type': 'outfile', 'format': 'whole_transcriptome.common'},
            {'name': 'genome', 'type': 'infile', 'format': 'whole_transcriptome.fasta'},

            {'name': 'circfasta', 'type': 'outfile', 'format': 'ref_rna_v2.fasta'},

        ]
        self.add_option(options)

    def check_options(self):
        pass

    def set_resource(self):
        self._cpu = 10
        self._memory = '40G'

    def end(self):
        super(GetfastaCircAgent, self).end()

class GetfastaCircTool(Tool):
    def __init__(self, config):
        super(GetfastaCircTool, self).__init__(config)
        self.program = {
            'bedtools': 'bioinfo/rna/bedtools2-master/bin/bedtools'

        }
        self.file = {
            'circbase_bed':os.path.join(self.output_dir,'circbase_bed.bed'),
            'circfasta': os.path.join(self.output_dir, 'circrna.fasta'),

        }
        self.script = {

        }

    def run(self):
        super(GetfastaCircTool, self).run()
        self.run_circbase_bed()
        # self.run_bed()
        self.run_getfasta()
        self.set_output()
        self.end()

    def run_circbase_bed(self):
        with open(self.file['circbase_bed'], 'w') as bed:
            for seq_record in SeqIO.parse(self.option('circbase').path, "fasta"):
                id = seq_record.id
                (circbase_id, chr_start_end_strant, host_gene_id, protein_id) = id.rstrip().split('|')
                chr_start_end = chr_start_end_strant[:-1]
                (chr, start, end) = re.split('[:-]', chr_start_end)
                bed.write(chr+'\t'+str(int(start)+1)+'\t'+end+'\n')

    #
    #
    #
    # def run_bed(self):
    #     df_bed = dict()
    #     df = pd.read_table(self.option('circbase').path)
    #     df_bed['chr']=df['chr']
    #     df_bed['start']=df['circrna_start']
    #     df_bed['end']=df['circrna_end']
    #     circ_bed = pd.DataFrame(df_bed)
    #     circ_bed_reindex = circ_bed.reindex(columns=['chr', 'start', 'end'])
    #     circ_bed_reindex.to_csv(self.file['circbed'], index=False, header=False, sep='\t')

    def run_getfasta(self):
        cmd = '{} getfasta -fi {} -bed {} -fo {}'.format(self.program['bedtools'], self.option('genome').path, self.file['circbase_bed'], self.file['circfasta'])
        cmd_name = 'run_getfasta'
        runcmd(self,cmd_name,cmd)

    def set_output(self):
        self.option('circfasta').set_path(self.file['circfasta'])

class TestFunction(unittest.TestCase):
    '''
    This is test for the tool. Just run this script to do test.
    '''

    def test(self):
        import random
        from mbio.workflows.single import SingleWorkflow
        from biocluster.wsheet import Sheet
        data = {
            'id': 'getfasta_{}_{}'.format(random.randint(1000, 9999), random.randint(1000, 9999)),
            'type': 'tool',
            'name': 'whole_transcriptome.circrna.getfasta_circ',
            'instant': False,
            'options': {
                'genome': '/mnt/ilustre/users/sanger-dev/sg-users/qinjincheng/database/mouse/Mus_mm9.fasta',
                'circbase': '/mnt/ilustre/users/sanger-dev/sg-users/zoujiaxun/mouse_mm9_circRNAs_putative_spliced_sequence.fa'

            }
        }
        wsheet = Sheet(data=data)
        wf = SingleWorkflow(wsheet)
        wf.run()

if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTests([TestFunction('test')])
    unittest.TextTestRunner(verbosity=2).run(suite)


import os

import paddle.fluid as fluid
from paddle.fluid.dygraph import Conv2D, Pool2D
from paddle.nn import SyncBatchNorm as BatchNorm

from dygraph.cvlibs import manager
from dygraph import utils

class UNet(fluid.dygraph.Layer):
    """
    U-Net: Convolutional Networks for Biomedical Image Segmentation.
    https://arxiv.org/abs/1505.04597

    Args:
        num_classes (int): the unique number of target classes.
        pretrained_model (str): the path of pretrained model.
        ignore_index (int): the value of ground-truth mask would be ignored while computing loss or doing evaluation. Default 255.
    """

    def __init__(self, num_classes, pretrained_model=None, ignore_index=255):
        super(UNet, self).__init__()
        self.encode = UnetEncoder()
        self.decode = UnetDecode()
        self.get_logit = GetLogit(64, num_classes)
        self.ignore_index = ignore_index
        self.EPS = 1e-5

        self.init_weight(pretrained_model)

    def forward(self, x, label=None):
        encode_data, short_cuts = self.encode(x)
        decode_data = self.decode(encode_data, short_cuts)
        logit = self.get_logit(decode_data)
        if self.training:
            return self._get_loss(logit, label)
        else:
            score_map = fluid.layers.softmax(logit, axis=1)
            score_map = fluid.layers.transpose(score_map, [0, 2, 3, 1])
            pred = fluid.layers.argmax(score_map, axis=3)
            pred = fluid.layers.unsqueeze(pred, axes=[3])
            return pred, score_map

    def init_weight(self, pretrained_model=None):
        """
        Initialize the parameters of model parts.
        Args:
            pretrained_model ([str], optional): the pretrained_model path of backbone. Defaults to None.
        """
        if pretrained_model is not None:
            if os.path.exists(pretrained_model):
                utils.load_pretrained_model(self.backbone, pretrained_model)
                utils.load_pretrained_model(self, pretrained_model)
            else:
                raise Exception('Pretrained model is not found: {}'.format(
                    pretrained_model))

    def _get_loss(self, logit, label):
        logit = fluid.layers.transpose(logit, [0, 2, 3, 1])
        label = fluid.layers.transpose(label, [0, 2, 3, 1])
        mask = label != self.ignore_index
        mask = fluid.layers.cast(mask, 'float32')
        loss, probs = fluid.layers.softmax_with_cross_entropy(
            logit,
            label,
            ignore_index=self.ignore_index,
            return_softmax=True,
            axis=-1)

        loss = loss * mask
        avg_loss = fluid.layers.mean(loss) / (
            fluid.layers.mean(mask) + self.EPS)

        label.stop_gradient = True
        mask.stop_gradient = True
        return avg_loss

class UnetEncoder(fluid.dygraph.Layer):
    def __init__(self):
        super(UnetEncoder, self).__init__()
        self.double_conv = DoubleConv(3, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        self.down4 = Down(512, 512)

    def forward(self, x):
        short_cuts = []
        x = self.double_conv(x)
        short_cuts.append(x)
        x = self.down1(x)
        short_cuts.append(x)
        x = self.down2(x)
        short_cuts.append(x)
        x = self.down3(x)
        short_cuts.append(x)
        x = self.down4(x)
        return x, short_cuts

class UnetDecode(fluid.dygraph.Layer):
    def __init__(self):
        super(UnetDecode, self).__init__()
        self.up1 = Up(512, 256)
        self.up2 = Up(256, 128)
        self.up3 = Up(128, 64)
        self.up4 = Up(64, 64)

    def forward(self, x, short_cuts):
        x = self.up1(x, short_cuts[3])
        x = self.up2(x, short_cuts[2])
        x = self.up3(x, short_cuts[1])
        x = self.up4(x, short_cuts[0])
        return x

class DoubleConv(fluid.dygraph.Layer):
    def __init__(self, num_channels, num_filters):
        super(DoubleConv, self).__init__()
        self.conv0 = Conv2D(
            num_channels=num_channels,
            num_filters=num_filters,
            filter_size=3,
            stride=1,
            padding=1)
        self.bn0 = BatchNorm(num_filters)
        self.conv1 = Conv2D(
            num_channels=num_filters,
            num_filters=num_filters,
            filter_size=3,
            stride=1,
            padding=1)
        self.bn1 = BatchNorm(num_filters)

    def forward(self, x):
        x = self.conv0(x)
        x = self.bn0(x)
        x = fluid.layers.relu(x)
        x = self.conv1(x)
        x = self.bn1(x)
        x = fluid.layers.relu(x)
        return x

class Down(fluid.dygraph.Layer):
    def __init__(self, num_channels, num_filters):
        super(Down, self).__init__()
        self.max_pool = Pool2D(
            pool_size=2, pool_type='max', pool_stride=2, pool_padding=0)
        self.double_conv = DoubleConv(num_channels, num_filters)

    def forward(self, x):
        x = self.max_pool(x)
        x = self.double_conv(x)
        return x

class Up(fluid.dygraph.Layer):
    def __init__(self, num_channels, num_filters):
        super(Up, self).__init__()
        self.double_conv = DoubleConv(2 * num_channels, num_filters)

    def forward(self, x, short_cut):
        short_cut_shape = fluid.layers.shape(short_cut)
        x = fluid.layers.resize_bilinear(x, short_cut_shape[2:])
        x = fluid.layers.concat([x, short_cut], axis=1)
        x = self.double_conv(x)
        return x

class GetLogit(fluid.dygraph.Layer):
    def __init__(self, num_channels, num_classes):
        super(GetLogit, self).__init__()
        self.conv = Conv2D(
            num_channels=num_channels,
            num_filters=num_classes,
            filter_size=3,
            stride=1,
            padding=1)

    def forward(self, x):
        x = self.conv(x)
        return x

@manager.MODELS.add_component
def unet(*args, **kwargs):
    return UNet(*args, **kwargs)


import json, csv
from argparse import ArgumentParser
from analysis import Motif, ensemble_from_string, load_ground_truth, prc

parser = ArgumentParser()
parser.add_argument("--ground-truth", required=True)
parser.add_argument("--image", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--ensemble", default="count")

args = parser.parse_args()

# main
if __name__ == "__main__":
    # load the ground truth
    with open(args.ground_truth, 'r') as f:
        gt, _ = load_ground_truth(json.load(f))

    # load the image
    motifs = []
    with open(args.image, 'r') as f:
        for motif in json.load(f):
            motifs.append(Motif.of_json(motif))

    # compute the ensemble
    ensemble = ensemble_from_string(args.ensemble)(motifs)

    # if there's also a prc output, do that thing
    prc(ensemble, gt, output=args.output)