import sys
sys.path.insert(0, '..')
import argparse
import cv2
import numpy as np
from os import path
import os
from numpy.random import default_rng
from tqdm import tqdm
from utils.misc import find_iou_bulk, create_bbr_annotation_v2_bulk, crop_and_resize_v2
from PNet.model import pnet_predict, pnet_predict_v2
from RNet.model import rnet_predict
import tensorflow as tf
from matplotlib import pyplot as plt
import matplotlib
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

def get_arguments():
    """
    Get arguments from the command line.
    """
    parser = argparse.ArgumentParser(description='Create Positives, Negatives and Part Faces from the WIDER FACE dataset for R-Net.')
    parser.add_argument(
        '-a',
        '--annotation-file',
        type=str,
        help='The path to the annotation file of the WIDER FACE dataset',
        required=True
    )
    parser.add_argument(
        '-i',
        '--images-directory',
        type=str,
        help='The path to the folder that contains WIDER FACE dataset',
        required=True
    )
    parser.add_argument(
        '-o',
        '--output-directory',
        type=str,
        help='The path to the folder where you want to save your output',
        default='./data/temp'
    )
    parser.add_argument(
        '--pnet',
        type=str,
        help='The path to the .hdf5 file containing the weights of P-Net',
        required=True
    )
    parser.add_argument(
        '--rnet',
        type=str,
        help='The path to the .hdf5 file containing the weights of R-Net',
        required=True
    )
    return parser.parse_args()

def main():

    rng = default_rng()

    # Get arguments
    args = get_arguments()

    # Create saving folder
    if not path.exists(args.output_directory):
        os.makedirs(args.output_directory)

    # Load P-Net
    # pnet = pnet_predict()
    pnet = pnet_predict_v2()
    pnet.load_weights(filepath=args.pnet, by_name=True)

    # Load R-Net
    rnet = rnet_predict()
    rnet.load_weights(filepath=args.rnet, by_name=True)

    # These are for storing the images
    pos_images = list()
    par_images = list()
    neg_images = list()

    # These are for storing the annotations of bounding box regression task
    pos_bboxes = list()
    par_bboxes = list()

    # Open the annotation file
    f = open(args.annotation_file)
    batch = 0
    for i in tqdm(range(12880)): # Because there are a total of 12880 images in the Wider Face dataset

        # Read the file line by line
        line = f.readline()

        # Obtain the number of faces in this image
        num_faces = int(f.readline())

        # Skip the image if it does not contain any faces
        if num_faces == 0:
            f.readline()
            continue

        # Obtain bounding boxes while taking into account invalid faces
        ground_truth = np.zeros((num_faces, 4), np.int32)
        invalid = []
        for j in range(num_faces):
            face = f.readline()
            if face[-7] == '1':
                invalid.append(j)
                continue
            ground_truth[j] = face[:-14].split(' ')

        # if i < 10000:
        #     continue

        # if rng.random() > 0.01:
        #     continue
        # count += 1

        # Remove invalid faces
        if len(invalid) > 0:
            ground_truth = np.delete(ground_truth, invalid, 0)
            if ground_truth.shape[0] == 0:
                continue
        # num_faces = ground_truth.shape[0]

        min_size = np.min(ground_truth[:, 2:])
        min_size = int(min_size * 0.6)
        min_size = max(min_size, 20)

        # Read the image
        img = cv2.imread(args.images_directory + '/' + line[:-1])[:, :, ::-1]
        # print(img.shape)

        # Get the original image size
        height, width = img.shape[:2]

        # Initialize the scale
        scale = 12 / min_size
        h = round(height * scale)
        w = round(width * scale)

        c_bboxes = list()
        confidence = list()

        # Start the loop
        while h >= 12 and w >= 12:

            # Resize the image
            resized_img = cv2.resize(img, (w, h)).reshape((1, h, w, 3))

            # Preprocess the image
            resized_img = np.add(resized_img, -127.5, dtype=np.float32) / 127.5

            # Pass the image to P-Net
            c_bboxes_i, confidence_i = pnet(resized_img)

            # If there are no faces, move on to next loop
            if c_bboxes_i.shape[0] == 0:
                scale = scale * 0.8
                h = round(height * scale)
                w = round(width * scale)
                continue

            c_bboxes.append(c_bboxes_i / scale)
            confidence.append(confidence_i)

            # Calculate the next scale
            scale = scale * 0.8
            h = round(height * scale)
            w = round(width * scale)

        # if i == 4155:
        #     print(c_bboxes)
        #     exit()

        # Apply non maximum suppression one last time
        # try:
        #     c_bboxes = tf.concat(c_bboxes, axis=0)
        # except:
        #     print(i)
        #     print(c_bboxes)
        #     print(len(c_bboxes))
        #     exit()
        if len(c_bboxes) == 0:
            continue
        c_bboxes = tf.concat(c_bboxes, axis=0)
        # print(c_bboxes.shape)
        confidence = tf.concat(confidence, axis=0)
        final_indices = tf.image.non_max_suppression(c_bboxes, confidence, confidence.shape[0], 0.7)
        c_bboxes = tf.gather(c_bboxes, final_indices)

        c_bboxes = square(c_bboxes)

        # print(c_bboxes.shape)
        # exit()

        # Round out the values
        c_bboxes = tf.cast(tf.round(c_bboxes), tf.int32)
        # print(type(c_bboxes))
        # print(c_bboxes.shape)
        # print(c_bboxes[0])
        # exit()

        c_bboxes = c_bboxes.numpy()[:, :3]
        c_bboxes[:, 2] = c_bboxes[:, 2] - c_bboxes[:, 0]
        # print(type(c_bboxes))
        # print(c_bboxes.shape)
        # print(c_bboxes[0])
        # exit()

        # print(type(ground_truth))
        # print(ground_truth.shape)
        # print(ground_truth[0])
        # # exit()

        ground_truth[:, :2] = ground_truth[:, :2][:, ::-1]
        ground_truth[:, 2:] = ground_truth[:, 2:][:, ::-1]

        # temp = ground_truth[:, 0].copy()
        # ground_truth[:, 0] = ground_truth[:, 1]
        # ground_truth[:, 1] = temp
        # temp = ground_truth[:, 2].copy()
        # ground_truth[:, 2] = ground_truth[:, 3]
        # ground_truth[:, 3] = temp

        # print(type(ground_truth))
        # print(ground_truth.shape)
        # print(ground_truth[0])
        # exit()

        # print(ground_truth.shape)
        # print(c_bboxes.shape)

        # Create R-Net input
        rnet_input = list()
        for bbox in c_bboxes:
            # print(bbox)
            # exit()
            rnet_input.append(crop_and_resize_v2(img, bbox, 24))
        rnet_input = np.asarray(rnet_input)
        # inspect(rnet_input)

        # Preprocess R-Net input
        rnet_input = np.add(rnet_input, -127.5, dtype=np.float32) / 127.5

        # Stage 2
        # print(type(c_bboxes))
        # print(rnet_input.shape)
        # print(c_bboxes.shape)
        c_bboxes = rnet([rnet_input, c_bboxes])
        # print(c_bboxes)
        # print(type(c_bboxes))
        # print(c_bboxes.shape)
        # print(c_bboxes[0])
        # show(img, c_bboxes.numpy())
        # if count == 15:
        #     exit()
        # continue
        # exit()

        c_bboxes = c_bboxes.numpy()[:, :3]
        c_bboxes[:, 2] = c_bboxes[:, 2] - c_bboxes[:, 0]

        # Calculate iou
        ious = find_iou_bulk(c_bboxes, ground_truth)

        # print(c_bboxes.shape[0])
        # print(np.count_nonzero(ious > 0.65))
        # exit()

        # h, w = img.shape[:2]
        # dpi = matplotlib.rcParams['figure.dpi']
        # figsize = w / dpi, h / dpi
        # figure, ax = plt.subplots(1, figsize=figsize)
        # ax.imshow(img)
        # for bbox in c_bboxes:
        #     bb = matplotlib.patches.Rectangle(xy=(bbox[1], bbox[0]), width=bbox[2], height=bbox[2], fill=False, edgecolor='b')
        #     ax.add_patch(bb)

        # Start creating data
        num_windows = c_bboxes.shape[0]
        max_iou_mask = np.argmax(ious, axis=1)
        max_ious = ious[np.arange(num_windows), max_iou_mask]

        # print(max_ious.shape)
        # exit()

        # Create positives
        pos_mask = max_ious > 0.65
        num_pos = np.count_nonzero(pos_mask)
        if num_pos > 0:
            pos_windows = c_bboxes[pos_mask]
            # num_pos = pos_windows.shape[0]
            pos_bboxes_i = create_bbr_annotation_v2_bulk(pos_windows, ground_truth[max_iou_mask[pos_mask]])
            pos_bboxes.extend(pos_bboxes_i)
            for bbox in pos_windows:
                # print(bbox)
                # bb = matplotlib.patches.Rectangle(xy=(bbox[1], bbox[0]), width=bbox[2], height=bbox[2], fill=False, edgecolor='g')
                # ax.add_patch(bb)
                pos_images.append(crop_and_resize_v2(img, bbox, 48))
        # else:
        #     num_pos = 0
        # print(ground_truth[max_iou_mask[max_ious > 0.65]])
        # print(create_bbr_annotation_v2_bulk(c_bboxes[max_ious > 0.65], ground_truth[max_iou_mask[max_ious > 0.65]]))
        # print(pos_bboxes)
        # print(pos_images[0].shape)
        # print(pos_images[0].shape)
        # exit()

        # Create part faces
        par_mask = np.logical_and(0.45 <= max_ious, max_ious <= 0.65)
        num_par = np.count_nonzero(par_mask)
        if num_par > 0:
            par_windows = c_bboxes[par_mask]
            par_bboxes_i = create_bbr_annotation_v2_bulk(par_windows, ground_truth[max_iou_mask[par_mask]])
            par_bboxes.extend(par_bboxes_i)
            for bbox in par_windows:
                # bb = matplotlib.patches.Rectangle(xy=(bbox[1], bbox[0]), width=bbox[2], height=bbox[2], fill=False, edgecolor='y')
                # ax.add_patch(bb)
                par_images.append(crop_and_resize_v2(img, bbox, 48))
        #     print(par_windows)
        #     print(ground_truth)
        # print(np.count_nonzero(par_mask))
        # print(par_mask)
        # exit()

        # Create negatives
        # print(num_windows)
        neg_mask = max_ious < 0.3
        num_neg = np.count_nonzero(neg_mask)
        # print(num_neg)
        if num_neg > 0:
            count = 0
            limit = 100
            size = []
            indices = rng.permutation(np.arange(num_windows)[neg_mask])
            # print(indices)
            for j in indices:
                if c_bboxes[j, 2] not in size:
                    size.append(c_bboxes[j, 2])
                    # print(c_bboxes[j])
                    count = count + 1
                    neg_images.append(crop_and_resize_v2(img, c_bboxes[j], 48))
                    # bbox = c_bboxes[j]
                    # bb = matplotlib.patches.Rectangle(xy=(bbox[1], bbox[0]), width=bbox[2], height=bbox[2], fill=False, edgecolor='r')
                    # ax.add_patch(bb)
                elif rng.random() < 0.1:
                    count = count + 1
                    neg_images.append(crop_and_resize_v2(img, c_bboxes[j], 48))
                    # bbox = c_bboxes[j]
                    # bb = matplotlib.patches.Rectangle(xy=(bbox[1], bbox[0]), width=bbox[2], height=bbox[2], fill=False, edgecolor='r')
                    # ax.add_patch(bb)
                if count == limit:
                    break

        # plt.axis('off')
        # plt.show()
        # if i == 5:
        #     exit()

        if (i + 1) % 1000 == 0:

            # Save the images
            pos_images = np.asarray(pos_images)
            par_images = np.asarray(par_images)
            neg_images = np.asarray(neg_images)
            np.save(args.output_directory + '/positive_images_' + str(batch) + '.npy', pos_images)
            np.save(args.output_directory + '/part_face_images_' + str(batch) + '.npy', par_images)
            np.save(args.output_directory + '/negative_images_' + str(batch) + '.npy', neg_images)
            pos_images = list()
            par_images = list()
            neg_images = list()

            # Save the bounding box annotations
            par_bboxes = np.asarray(par_bboxes)
            pos_bboxes = np.asarray(pos_bboxes)
            np.save(args.output_directory + '/part_faces_' + str(batch) + '.npy', par_bboxes)
            np.save(args.output_directory + '/positives_' + str(batch) + '.npy', pos_bboxes)
            pos_bboxes = list()
            par_bboxes = list()

            batch = batch + 1

    # Always close the file
    f.close()

    # Save the images
    pos_images = np.asarray(pos_images)
    par_images = np.asarray(par_images)
    neg_images = np.asarray(neg_images)
    np.save(args.output_directory + '/positive_images_' + str(batch) + '.npy', pos_images)
    np.save(args.output_directory + '/part_face_images_' + str(batch) + '.npy', par_images)
    np.save(args.output_directory + '/negative_images_' + str(batch) + '.npy', neg_images)

    # Save the bounding box annotations
    par_bboxes = np.asarray(par_bboxes)
    pos_bboxes = np.asarray(pos_bboxes)
    np.save(args.output_directory + '/part_faces_' + str(batch) + '.npy', par_bboxes)
    np.save(args.output_directory + '/positives_' + str(batch) + '.npy', pos_bboxes)

# def inspect(x):
#     print(type(x))
#     print(x.shape)
#     print(x.dtype)
#     exit()

def show(img, c_bboxes):
    h, w = img.shape[:2]
    print(h, w)
    dpi = matplotlib.rcParams['figure.dpi']
    figsize = w / dpi, h / dpi
    figure, ax = plt.subplots(1, figsize=figsize)
    ax.imshow(img)
    for bbox in c_bboxes:
        bb = matplotlib.patches.Rectangle(xy=(bbox[1], bbox[0]), width=bbox[3] - bbox[1], height=bbox[2] - bbox[0], fill=False, edgecolor='r')
        ax.add_patch(bb)
    plt.axis('off')
    plt.show()

def square(bboxes):
    """
    Turn the bounding boxes into squares.
    Args:
    - bboxes: (n, 4) tensor with each row encoded as [y1, x1, y2, x2]
    Return:
    - square_bboxes: (n, 4) tensor of squared bounding boxes
    """
    h = bboxes[:, 2] - bboxes[:, 0]
    w = bboxes[:, 3] - bboxes[:, 1]
    size = tf.math.maximum(h, w)
    x_margin = (size - w) / 2
    y_margin = (size - h) / 2
    y1 = bboxes[:, 0] - y_margin
    x1 = bboxes[:, 1] - x_margin
    y2 = bboxes[:, 2] + y_margin
    x2 = bboxes[:, 3] + x_margin
    square_bboxes = tf.stack([y1, x1, y2, x2], axis=1)
    return square_bboxes

if __name__ == "__main__":
    main()


n = int(input())
a = list(map(int, input().split()))

so_am = so_duong = so_chan = so_le = 0

for i in range(n):
    #
    if a[i] < 0:
        so_am += 1
    elif a[i] > 0:
        so_duong += 1
    #
    if abs(a[i]) % 2 == 0:
        so_chan += 1
    else:
        so_le += 1

print(so_am)
print(so_duong)
print(so_chan)
print(so_le)


from base.base import Base
import page

class Page_03(Base):

    # 获取商品名称、充值类型、面值
    def page_get_dy_values(self):
        list = []
        # 获取商品名称
        dy_name = self.base_get_text(page.pc_dy_name)
        list.append("商品名称：{}".format(dy_name))
        # 获取充值类型
        dy_account_type = self.base_get_text(page.pc_goods_account_type)
        list.append("充值类型：{}".format(dy_account_type))
        # 获取面值
        pc_dy_values = self.base_get_text(page.pc_goods_values)
        list.append(pc_dy_values.replace("\n"," "))
        return list

    # 点击立即购买按钮
    def page_click_buy_btn(self):
        self.base_click(page.pc_buy_btn)

    # 组合业务方法
    def page_pc_landing_dy(self):
        # 获取商品信息
        value_list = self.page_get_dy_values()
        # 点击购买按钮
        if self.base_element_is_exist(page.pc_buy_btn):
            self.page_click_buy_btn()
            print("购买按钮存在，可正常点击")
        else:
            print("出错啦！未识别到购买按钮")
        return value_list


from bs4 import BeautifulSoup
from selenium import webdriver
import time
def get_follower(url="https://twitter.com/KMbappe") :
    # try:
    #init webdriver
    options = webdriver.ChromeOptions()
    options.add_argument("headless")
    driver = webdriver.Chrome(options=options)
    time.sleep(1)
    driver.get(url)
    time.sleep(1)

    # page_source checking
    # file = open("output.txt","w",encoding="utf-8")
    # file.write(driver.page_source)
    # file.close()

    #scrape page_source using beautifulsoup
    bs = BeautifulSoup(driver.page_source,"lxml")
    get_tag = bs.find("a",href=lambda  href:href and "follower" in href)
    # print(get_tag)
    follower = get_tag.find_all("span")[1].string
    print(follower)
    driver.quit()
    # except :
    #     print("Something gone wrong")
    return follower

if __name__ == "__main__":
    inp = str(input("Please enter : ").strip())
    if "https://twitter.com/" not in inp :
        get_follower()
    else :
        get_follower(inp)


'''Exercício 2 - Primos
Escreva a função maior_primo que recebe um número inteiro maior ou igual a 2 como parâmetro e devolve o maior número primo menor ou igual ao número passado à função'''

m = 0
def maior_primo(m):
    total = 0
    for c in range(m):
      for c in range(2, m+1):
        if m%c == 0:
          total = total + 1

      if total==1:
        return m
        break
      else:
        m = m - 1
        total = 0


import os

import time
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score

from language_clf import LangClf
import pdb

# --- Tirando referências -----

path = r'../Resources/bibles/'
stems_path = r'../Resources/stems/stems.csv'
new_dir = r'../Resources/texts/'

def load_data(training_split=.8, number_documents=100):
    """
     It loads the data according to a given threshold. The threshold will tell us the number of books to be loaded.
     Here the train, test, and stems are loaded.
    :param number_documents: The total number of documents to be retrieved
    :param training_split: How you want to split them
    :return: the training set, testing set and stem dictionary
    """

    x_text, y_text = [], []

    stems_dic = pd.read_csv(stems_path, encoding='utf-8').dropna()
    X_train = []
    y_train = []

    X_test = []
    y_test = []

    for filename in os.listdir(new_dir):
        file = open(new_dir + filename, encoding='utf-8')
        text = [line.strip('\n') for line in file.readlines()]

        text = text[:number_documents]
        train_size = int(len(text) * training_split)
        X_train.append(text[:train_size])
        y_train.append(filename.split('.')[0])
        X_test.append(text[train_size:])
        y_test.append(filename.split('.')[0])

    return stems_dic, np.array(X_train), np.array(y_train), np.array(X_test), np.array(y_test)

def classify(threshold=4):
    """
    Makes the classification of all languages according to a threshold
    :return: two vectors with the text label, predicted, similarity of all predictions
    """
    start = time.time()  # initial time

    stems_dic, X_train, y_train, X_test, y_test = load_data(.1)  # Loads the data according to the established
    print('Train shape: ', X_train.shape)
    print('X_test shape: ', X_test.shape)
    # threshold in
    # terms of number of books
    clf = LangClf(stems_dic)
    print('Fitting the clf...')

    clf.fit(X_train, y_train)  # Fits the Classifier with the training and test set
    print('Testing...')
    y_pred = clf.test(X_test)

    time_taken = (time.time() - start)

    accuracy = accuracy_score(y_test, y_pred)

    print("Threshold: ", threshold)
    print("Accuracy: ", accuracy)
    print("Final time: {:.5f}min".format(time_taken / 60))
    clf.run_som()

    print()
    print('-' * 40)
    print()
    # clf.get_test_plot()
    return {"Threshold": threshold,
            "Accuracy": accuracy,
            "Time": time_taken / 60}

def run_experiment():
    for i in range(1, 2):
        classify(i)

def main():
    run_experiment()

if __name__ == "__main__":
    main()


import tensorflow as tf

from causal_self_attention import CausalSelfAttention
from cross_attention import CrossAttention
from feed_forward import FeedForward

class DecoderLayer(tf.keras.layers.Layer):
    def __init__(self, *, d_model, num_heads, dff, dropout_rate=0.1):
        """
        Args:
            d_model (integer): self attention: size of each attention head for query and key
            num_heads (integer): self attention: number of attention heads
            dff (integer): internal dimensionality of the FeedForward layer
            dropout_rate (float, optional): self attention: dropout probability. Defaults to 0.1.
        """
        super(DecoderLayer, self).__init__()

        self.causal_self_attention = CausalSelfAttention(
            num_heads=num_heads,
            key_dim=d_model,
            dropout=dropout_rate)

        self.cross_attention = CrossAttention(
            num_heads=num_heads,
            key_dim=d_model,
            dropout=dropout_rate)

        self.ffn = FeedForward(d_model, dff)

    def call(self, x, context):
        x = self.causal_self_attention(x=x)
        x = self.cross_attention(x=x, context=context)

        # Cache the last attention scores for plotting later
        self.last_attn_scores = self.cross_attention.last_attn_scores

        x = self.ffn(x)  # Shape `(batch_size, seq_len, d_model)`.
        return x


import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds
from matplotlib import pyplot as plt
import string
from PIL import Image

# 标签数据 对应 字符
# 0-9
# 10-35 A~Z
# 36-61 a~z
label = list(string.digits + string.ascii_uppercase + string.ascii_lowercase)
# 记录已经遍历的数量
records = [0 for x in label]
# 存储文件夹
path = 'D:\\Temp\\emnist\\'

# 加载数据
(train, test), ds_info = tfds.load(
    'emnist',
    split=['train', 'test'],
    data_dir='./tensorflow_datasets',
    shuffle_files=True,  #
    as_supervised=True,
    with_info=True,
)

# emnist数据集天生旋转，翻转每张图片数据
def normalize_img(image, label):
    """Normalizes images: `uint8` -> `float32`."""
    # image = tf.transpose(image, perm=[1, 0, 2])
    # return tf.cast(image, tf.float32) / 255., label
    # perm=[1,0,2]表示只翻转第一第二维度
    return tf.transpose(image, perm=[1, 0, 2]), label

# 开始翻转图片数据
train = train.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)
test = test.map(normalize_img, num_parallel_calls=tf.data.AUTOTUNE)

# 将图片数据转为numpy
train_numpy = np.vstack(tfds.as_numpy(train))
test_numpy = np.vstack(tfds.as_numpy(test))

# 保存图片
for p in train_numpy:
    image_array = np.asarray(p[0])
    image_array = image_array.reshape(28, 28)
    image = Image.fromarray(image_array.astype('uint8'))
    lab = p[1]
    directory = label[lab]
    if lab >= 36:
        directory += directory
    path_train = path + '\\train\\' + directory + '\\' + label[lab] + '-' + str(records[lab]) + '.png'
    image.save(path_train)
    records[lab] += 1

for p in test_numpy:
    image_array = np.asarray(p[0])
    image_array = image_array.reshape(28, 28)
    image = Image.fromarray(image_array.astype('uint8'))
    lab = p[1]
    directory = label[lab]
    if lab >= 36:
        directory += directory
    path_train = path + '\\test\\' + directory + '\\' + label[lab] + '-' + str(records[lab]) + '.png'
    image.save(path_train)
    records[lab] += 1


import math

from rlmath import axis_to_rotation
from vec import Vec3, cross, normalize, dot

def draw_circle(bot, center: Vec3, normal: Vec3, radius: float, pieces: int, color_func):
    # Construct the arm that will be rotated
    arm = normalize(cross(normal, center)) * radius
    angle = 2 * math.pi / pieces
    rotation_mat = axis_to_rotation(angle * normalize(normal))
    points = [center + arm]

    for i in range(pieces):
        arm = dot(rotation_mat, arm)
        points.append(center + arm)

    bot.renderer.draw_polyline_3d(points, color_func())


from jinja2 import Environment, FileSystemLoader

## Necessaire pour les dates en français
import datetime
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')

TMPL_DIR = "tmpl"
fichier = "index.jinja"

templateLoader = FileSystemLoader(searchpath=TMPL_DIR)
templateEnv = Environment(loader=templateLoader)
template = templateEnv.get_template(fichier)

data={
        'time_stamp':datetime.datetime.now().strftime("%x %X")
    }

print( template.render( data ) )


import numpy as np
import matplotlib.pyplot as plt

def sinusGenerator(amplitude, frequency, time, theta):
    t = np.arange(0,time,0.1)
    y = amplitude * np.sin(2*frequency*t + np.deg2rad(theta))
    return t,y

t1, y1 = sinusGenerator(1,1,4,0)
t2, y2 = sinusGenerator(1,1,4,90)

# 1st Type
# plt.plot(t1,y1, label="sin(0)")
# plt.plot(t2,y2, label="sin(90)")
# plt.legend()

# 2nd Type
# plt.plot(t1,y1, label="sin(0)")
# plt.plot(t2,y2, label="sin(90)")
# plt.legend(loc="upper center")

# 3rd Type
# plt.plot(t1,y1, label="sin(0)")
# plt.plot(t2,y2, label="sin(90)")
# plt.legend(loc="upper center", bbox_to_anchor=(0.5,-0.05))

# 4th Type
plt.figure(1)
ax = plt.subplot(111)
plt.plot(t1,y1, "r--", label="sin(0)" )
plt.plot(t2,y2, "b--", label="sin(90)")
box = ax.get_position()
# shrink to 0.75
ax.set_position([box.x0, box.y0, box.width*0.75, box.height])
plt.legend(loc="upper center", bbox_to_anchor=(1.2,1))
plt.xlabel("Time(second)")
plt.ylabel("Amplitude(cm)")

#show plot
plt.show()


import logging
from functools import partial

from pyqtgraph.Qt import QtWidgets
from pyqtgraph import SpinBox

class DP832Widget(QtWidgets.QWidget):
    """A Qt widget for controlling the Rigol DP832 power supply."""
    def __init__(self, driver):
        """
        Args:
            driver: The dp832 driver.
        """
        super().__init__()

        self.driver = driver

        # top level layout
        layout = QtWidgets.QGridLayout()

        channels = 3
        for ch in range(1, channels+1):
            layout_row = 0

            # label
            layout.addWidget(QtWidgets.QLabel(f'Ch {ch}'), layout_row, ch)
            layout_row += 1

            # for on/off buttons
            def toggle(checked, ch, state):
                self.driver.toggle_output(ch=ch, state=state)

            # button to turn the channel on
            self.on_button = QtWidgets.QPushButton('On')
            self.on_button.clicked.connect(partial(toggle, ch=ch, state=True))
            layout.addWidget(self.on_button, layout_row, ch)
            layout_row += 1

            # button to turn the channel off
            self.off_button = QtWidgets.QPushButton('Off')
            self.off_button.clicked.connect(partial(toggle, ch=ch, state=False))
            layout.addWidget(self.off_button, layout_row, ch)
            layout_row += 1

            # voltage spinbox
            volts_layout = QtWidgets.QHBoxLayout()
            volts_layout.addWidget(QtWidgets.QLabel('Volts'))
            volts_spinbox = SpinBox(value=self.driver.get_voltage(ch), bounds=(0, 30), siPrefix=False)
            def set_volts(spinbox, ch):
                self.driver.set_voltage(ch, spinbox.value(), confirm=False)
            volts_spinbox.sigValueChanged.connect(partial(set_volts, ch=ch))
            volts_layout.addWidget(volts_spinbox)
            layout.addLayout(volts_layout, layout_row, ch)
            layout_row += 1

            # current spinbox
            amps_layout = QtWidgets.QHBoxLayout()
            amps_layout.addWidget(QtWidgets.QLabel('Amps'))
            amps_spinbox = SpinBox(value=self.driver.get_current(ch), bounds=(0, 3), siPrefix=False)
            def set_amps(spinbox, ch):
                self.driver.set_current(ch, spinbox.value(), confirm=False)
            amps_spinbox.sigValueChanged.connect(partial(set_amps, ch=ch))
            amps_layout.addWidget(amps_spinbox)
            layout.addLayout(amps_layout, layout_row, ch)
            layout_row += 1

        # take up any additional space in the final row with padding
        layout.setRowStretch(layout_row, 1)

        self.setLayout(layout)


import pygame

class Graphics(object):
    def __init__(self, element):
        self.color = (0, 0, 0)
        self.elem = element
    def draw(self, screen, x, y, w, h):
        from Spike import Spike
        #print("drawing at: ", x, y, w, h, self.elem)
        """draws a rectangle representation of the element defined in the
        constructor
        """
        if isinstance(self.elem, Spike):
            print(y)
        pygame.draw.rect(screen,self.color,[int(x),int(y),w,h],2)


"""Category selection menu."""

class CategoryMenu:
    """Category selection menu."""

    def __init__(self):
        """Initialize category selection menu."""
        self.main_choice = {
            "1": "Eau minérale ",
            "2": "Yaourt ",
            "3": "Fromage ",
            "4": "Poisson ",
            "5": "Confiture ",
            "6": "Sauce ",
            "7": "Conserve ",
            "8": "Biscuit ",
            "9": "Jambon ",
            "10": "Purée ",
            "11": "Riz",
            "12": "Apéritif ",
            "13": "Plat préparé ",
            "14": "Menu principal",
        }

    def show(self):
        """Display the categories menu."""
        print("Bienvenue sur la page catégorie, faites votre choix :\n")
        for key, value in self.main_choice.items():
            print(key, " - ", value)


#%% [markdown]
# ## Rock, Paper, Scissors Categorical Classifier with ConvNet

#%% [markdown]
# ### Loading required libraries
import os, signal
import zipfile
import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.image as mpimage
import numpy as np
import random

#%% [markdown]
# ### Extract the zip file containing train data
local_zip = "./training-rps.zip"
zip_ref = zipfile.ZipFile(local_zip, "r")
zip_ref.extractall("./Training Data/Rock, Paper, Scissors")
zip_ref.close()

#%% [markdown]
# ### Extract the zip file containing validation data
local_zip = "./validation-rps.zip"
zip_ref = zipfile.ZipFile(local_zip, "r")
zip_ref.extractall("./Validation Data/Rock, Paper, Scissors")
zip_ref.close()

#%% [markdown]
# ### Defining training and validation images directories as path variables
train_rock_dir = os.path.join("./Training Data/Rock, Paper, Scissors/rock")
train_paper_dir = os.path.join("./Training Data/Rock, Paper, Scissors/paper")
train_scissors_dir = os.path.join("./Training Data/Rock, Paper, Scissors/scissors")
validation_rock_dir = os.path.join("./Validation Data/Rock, Paper, Scissors/rock")
validation_paper_dir = os.path.join("./Validation Data/Rock, Paper, Scissors/paper")
validation_scissors_dir = os.path.join(
    "./Validation Data/Rock, Paper, Scissors/scissors"
)

#%% [markdown]
# ### Let's see how the filenames look like
train_rock_names = os.listdir(train_rock_dir)
train_paper_names = os.listdir(train_paper_dir)
train_scissors_names = os.listdir(train_scissors_dir)
print(train_rock_names[:10])
print(train_paper_names[:10])
print(train_scissors_names[:10])
validation_rock_names = os.listdir(validation_rock_dir)
validation_paper_names = os.listdir(validation_paper_dir)
validation_scissors_names = os.listdir(validation_scissors_dir)
print(validation_rock_names[:10])
print(validation_paper_names[:10])
print(validation_scissors_names[:10])

#%% [markdown]
# ### Total number of training and validation images
print("Total training rock images: ", len(train_rock_names))
print("Total training paper images: ", len(train_paper_names))
print("Total training scissors images: ", len(train_scissors_names))
print("Total validation rock images: ", len(validation_rock_names))
print("Total validation paper images: ", len(validation_paper_names))
print("Total validation scissors images: ", len(validation_scissors_names))

#%% [markdown]
# ### Let's look at some of the pictures
nrows, ncols = 6, 4
pic_index = 0
random.seed(100)
rock_sample = random.sample(train_rock_names, 8)
rock_pics = [os.path.join(train_rock_dir, name) for name in rock_sample]
paper_sample = random.sample(train_paper_names, 8)
paper_pics = [os.path.join(train_paper_dir, name) for name in paper_sample]
scissors_sample = random.sample(train_scissors_names, 8)
scissors_pics = [os.path.join(train_scissors_dir, name) for name in scissors_sample]
fig = plt.gcf()
fig.set_size_inches(ncols * 2, nrows * 2)
for index, image_path in enumerate(rock_pics + paper_pics + scissors_pics):
    sp = plt.subplot(nrows, ncols, index + 1)
    sp.axis("Off")
    img = mpimage.imread(image_path)
    plt.imshow(img)
plt.show()

#%% [markdown]
# ### Structuring the ConvNet architecture
model = tf.keras.models.Sequential(
    [
        tf.keras.layers.Conv2D(
            64, (3, 3), activation="relu", input_shape=(300, 300, 3)
        ),
        tf.keras.layers.MaxPooling2D(2, 2),
        tf.keras.layers.Conv2D(64, (3, 3), activation="relu"),
        tf.keras.layers.MaxPooling2D(2, 2),
        tf.keras.layers.Conv2D(128, (3, 3), activation="relu"),
        tf.keras.layers.MaxPooling2D(2, 2),
        tf.keras.layers.Conv2D(128, (3, 3), activation="relu"),
        tf.keras.layers.MaxPooling2D(2, 2),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dropout(0.5),
        tf.keras.layers.Dense(512, activation="relu"),
        tf.keras.layers.Dense(3, activation="softmax"),
    ]
)

#%% [markdown]
# ### Get the model summary
model.summary()

#%% [markdown]
# ### Compiling the model
model.compile(
    optimizer=tf.keras.optimizers.RMSprop(lr=0.001),
    loss="categorical_crossentropy",
    metrics=["acc"],
)

#%% [markdown]
# ### Generating training and validation labeled data from images in directories
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
    rescale=1 / 255,
    rotation_range=40,
    width_shift_range=0.2,
    height_shift_range=0.2,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True,
    fill_mode="nearest",
)
validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1 / 255)
train_generator = train_datagen.flow_from_directory(
    "./Training Data/Rock, Paper, Scissors",
    target_size=(300, 300),
    class_mode="categorical",
)
validation_generator = validation_datagen.flow_from_directory(
    "./Validation Data/Rock, Paper, Scissors",
    target_size=(300, 300),
    class_mode="categorical",
)

#%% [markdown]
# ### Train the model
history = model.fit_generator(
    train_generator, epochs=25, verbose=1, validation_data=validation_generator
)

#%% [markdown]
# ### Plot training and validation accuracy
acc = history.history["acc"]
val_acc = history.history["val_acc"]
loss = history.history["loss"]
val_loss = history.history["val_loss"]
epochs = range(len(acc))
plt.plot(epochs, acc, "r", label="Training Accuracy")
plt.plot(epochs, val_acc, "b", label="Validation Accuracy")
plt.title("Training vs. Validation Accuracy")
plt.legend(loc=0)
plt.show()

#%% [markdown]
# ### Test classifier with real images
path = "./Validation Data/External Images/Rock, Paper, Scissors/scissors_test.jpg"
img = tf.keras.preprocessing.image.load_img(path, target_size=(300, 300))
x = tf.keras.preprocessing.image.img_to_array(img)
x = np.expand_dims(x, axis=0)
prediction = model.predict(x)
print(prediction)

#%% [markdown]
# ### Save the Model in a File and Cleanup memory
model.save("rps.h5")
os.kill(os.getpid(), signal.SIGKILL)


import os
import sys

def diff(file1, file2):
	os.system('powershell;$a=Get-Content ' + file1 + ';$b=Get-Content ' + file2 + ';diff $a $b')

if __name__ == '__main__':
	if len(sys.argv) != 3:
		print('python diff.py $file1 $file2')
	else:
		diff(sys.argv[1], sys.argv[2])


#!/usr/bin/python -u
#
# these functions exec psql instead of using a python adapter because
#  copy from/to don't work without root permissions but psql's \copy does.
#

from __future__ import absolute_import
import os
import sys
import re
import glob
import subprocess
import ConfigParser
import argparse

_UP = os.path.abspath( os.path.join( os.path.split( __file__ )[0], ".." ) )
sys.path.append( _UP )
import loader

#
# 1st row in file is column headers
# column order may not match database
#
# if table has upper-case letter, quote it
# ditto for column names
#
def _fromcsv( filename, dsn, schema, table, verbose = False ) :

# pgdb vs psycopg2
#
    if "database" in dsn.keys() : cmd = [ loader.PSQL, "-d", dsn["database"] ]
    else : cmd = [ loader.PSQL, "-d", dsn["dbname"] ]
    if "user" in dsn.keys() : cmd.extend( ["-U", dsn["user"]] )
    if "host" in dsn.keys() : cmd.extend( ["-h", dsn["host"]] )
    if "port" in dsn.keys() : cmd.extend( ["-p", dsn["port"]] )
    if not verbose : cmd.append( "-q" )

    infile = os.path.realpath( filename )
    if not os.path.exists( infile ) : raise IOError( "Not found: %s" % (infile,) )

# column names
#
    cols = []
    with open( infile, "rU" ) as f :
        l = f.readline()
        for col in l.split( "," ) :
            cols.append( col.strip().strip( "'\"" ) )

    if len( cols ) < 1 :
        sys.stderr.write( "no columns in %s\n" % (infile,) )
        return False

    colstr = ""
    for c in cols :
        if c.islower() : colstr += c
        else : colstr += '"' + c + '"'
        colstr += ","
    colstr = colstr[:-1]

    if (schema is None) or (str( schema ).strip() == "") :
        scam = ""
    else :
        scam = "%s." % (str( schema ).strip(),)

    if table.islower() :
        tbl = table
    else :
        tbl = '"%s"' % (table,)

    stmt = "\\copy %s%s (%s) from '%s' csv header" % (scam,tbl,colstr,infile,)

    cmd.extend( ["-c", stmt] )

    if verbose :
        sys.stderr.write( " ".join( j for j in cmd ) )
        sys.stderr.write( "\n" )

    p = subprocess.Popen( cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
    (out, err) = p.communicate()
    if p.returncode != 0 :
        sys.stderr.write( "ERR: psql returned %d\n" % (p.returncode,))
        sys.stderr.write( " ".join( j for j in cmd ) )
        sys.stderr.write( "\n" )
        sys.stderr.write( "** STDERR **\n" )
        for j in err.splitlines() :
            sys.stderr.write( j )
            sys.stderr.write( "\n" )
        sys.stderr.write( "** STDOUT **\n" )
        for j in out.splitlines() :
            sys.stderr.write( j )
            sys.stderr.write( "\n" )

        return False

    if verbose :
        sys.stderr.write( "** STDERR **\n" )
        for j in err.splitlines() :
            sys.stderr.write( j )
            sys.stderr.write( "\n" )
        sys.stderr.write( "** STDOUT **\n" )
        for j in out.splitlines() :
            sys.stderr.write( j )
            sys.stderr.write( "\n" )

    return True

# public wrapper
#
def fromcsv( dsn, filename, schema, table, verbose = False ) :
 return _fromcsv( filename, dsn, schema, table, verbose )

#TODO
#
# tables are <schema>.<table>.csv
#
#
def all_fromcsv( path, config, verbose = False ) :

    d = os.path.realpath( path )
    if not os.path.isdir( d ) : raise IOError( "Not a directory: %s" % (d,) )
    pat = re.compile( r"([^.]+)\.([^.]+)\.csv$" )
    errs = 0
    for i in glob.glob( os.path.join( d, "*.csv" ) ) :
        m = pat.search( os.path.split( i )[1] )
        if not m :
            sys.stderr.write( "%s does not match pattern, skipping\n" % (i,) )
            errs += 1
            continue

        if not _fromcsv( i, dsn = loader.dsn( config, "bmrbeverything" ),
                schema = m.group( 1 ), table = m.group( 2 ), verbose = verbose ) :
            errs += 1

    return (errs == 0)

#
#
#
if __name__ == "__main__" :

    ap = argparse.ArgumentParser( description = "load 'bmrbeverything' PostgreSQL database" )
    ap.add_argument( "-v", "--verbose", help = "print lots of messages to stdout", dest = "verbose",
        action = "store_true", default = False )

    ap.add_argument( "-c", "--config", help = "config file", dest = "conffile", required = True )
    ap.add_argument( "-d", "--dir", help = "directory with input files", dest = "indir", required = True )
    args = ap.parse_args()

    wd = os.path.realpath( args.indir )
    if not os.path.isdir( wd ) :
        sys.stderr.write( "Not a directory: %s\n", (wd,) )
        sys.exit( 1 )

    cp = ConfigParser.SafeConfigParser()
    f = os.path.realpath( args.conffile )
    cp.read( f )

    if not all_fromcsv( path = wd, config = cp, verbose = args.verbose ) :
        sys.exit( 1 )

#    if cp.has_option( "dictionary", "rouser" ) :
#        loader.add_ro_grants( dsn = loader.dsn( cp, "dictionary" ), schema = cp.get( "dictionary", "schema" ),
#            user = cp.get( "dictionary", "rouser" ),  verbose = args.verbose )
#
#
# eof


import json

# 設定 JSON 檔案的相對路徑
file_path = "F-C0032-001.json"

# 讀取 JSON 檔案內容
with open(file_path, "r") as file:
    data_json = json.load(file)

location = data_json["cwbopendata"]["dataset"]["location"]  # 取出 location 的內容
for i in location:
    print(f"{i}")


import os
import azure.functions as func
import boto3
from botocore.exceptions import ClientError

def main(req: func.HttpRequest) -> func.HttpResponse:
    username = req.params.get('username')
    policyarn = req.params.get('policyarn')
    if username and policyarn:
        try:
            iam = boto3.client('iam',
                               aws_access_key_id=os.environ["AWS_AccessKeyId"],
                               aws_secret_access_key=os.environ["AWS_SecretAccessKey"])
            try:
                iam.detach_user_policy(UserName=username, PolicyArn=policyarn)
            except iam.exceptions.NoSuchEntityException or iam.exceptions.LimitExceededException or \
                   iam.exceptions.InvalidInputException as err:
                return func.HttpResponse(str(err), status_code=404)
            return func.HttpResponse("Successfully detached the user policy.", status_code=200)
        except ClientError as err:
            return func.HttpResponse(str(err), status_code=401)
    else:
        return func.HttpResponse("Please pass a username and a policyarn on the query string", status_code=400)


import random

card=["A",2,3,4,5,6,7,8,9,"J","Q","K"]

for i in range(2):
    card1=random.choice(card)
    card2=random.choice(card)

print(f"your cards: {card1},{card2}")

cardp=[]
cardp.append(card1)
cardp.append(card2)

for j in range(len(cardp)):
    print(j)
    print(cardp[j])

for j in cardp:
    print(j)
    print(cardp[j])


"""add teams table

Revision ID: 142624f4f7a0
Revises: bcb16e8d296b
Create Date: 2022-12-05 22:26:34.032944

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '142624f4f7a0'
down_revision = 'bcb16e8d296b'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('teams',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=50), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    with op.batch_alter_table('candidates', schema=None) as batch_op:
        batch_op.add_column(sa.Column('team_id', sa.Integer(), nullable=True))
        batch_op.create_foreign_key(None, 'teams', ['team_id'], ['id'])

    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('candidates', schema=None) as batch_op:
        batch_op.drop_constraint(None, type_='foreignkey')
        batch_op.drop_column('team_id')

    op.drop_table('teams')
    # ### end Alembic commands ###


__author__ = 'yuhenglong@google.com (Yuheng Long)'

import flags
from flags import Flag

def ClimbNext(flags_dict, climb_spec):
  """Get the flags that are different from |flags_dict| by |climb_spec|.

  Given a set of flags, |flags_dict|, return a new set of flags that are
  adjacent along the flag spec |climb_spec|.

  An example flags_dict is {foo=[1-9]:foo=5, bar=[1-5]:bar=2} and climb_spec is
  bar=[1-5]. This method changes the flag that contains the spec bar=[1-5]. The
  results are its neighbors dictionaries, i.e., {foo=[1-9]:foo=5,
  bar=[1-5]:bar=1} and {foo=[1-9]:foo=5, bar=[1-5]:bar=3}.

  Args:
    flags_dict: The dictionary containing the original flags whose neighbors are
      to be explored.
    climb_spec: The spec in the flags_dict is to be changed. The spec is a
      definition in the little language, a string with escaped sequences of the
      form [<start>-<end>] where start and end is an positive integer for a
      fillable value. An example of a spec is "foo[0-9]".

  Returns:
    List of dictionaries of neighbor flags.
  """

  # This method searches for a pattern [start-end] in the spec. If the spec
  # contains this pattern, it is a numeric flag. Otherwise it is a boolean flag.
  # For example, -finline-limit=[1-1000] is a numeric flag and -falign-jumps is
  # a boolean flag.
  numeric_flag_match = flags.Search(climb_spec)

  # If the flags do not contain the spec.
  if climb_spec not in flags_dict:
    results = flags_dict.copy()

    if numeric_flag_match:
      # Numeric flags.
      results[climb_spec] = Flag(climb_spec,
                                 int(numeric_flag_match.group('start')))
    else:
      # Boolean flags.
      results[climb_spec] = Flag(climb_spec)

    return [results]

  # The flags contain the spec.
  if not numeric_flag_match:
    # Boolean flags.
    results = flags_dict.copy()

    # Turn off the flag. A flag is turned off if it is not presented in the
    # flags_dict.
    del results[climb_spec]
    return [results]

  # Numeric flags.
  flag = flags_dict[climb_spec]

  # The value of the flag having spec.
  value = flag.GetValue()
  results = []

  if value + 1 < int(numeric_flag_match.group('end')):
    # If the value is not the end value, explore the value that is 1 larger than
    # the current value.
    neighbor = flags_dict.copy()
    neighbor[climb_spec] = Flag(climb_spec, value + 1)
    results.append(neighbor)

  if value > int(numeric_flag_match.group('start')):
    # If the value is not the start value, explore the value that is 1 lesser
    # than the current value.
    neighbor = flags_dict.copy()
    neighbor[climb_spec] = Flag(climb_spec, value - 1)
    results.append(neighbor)
  else:
    # Delete the value, i.e., turn off the flag. A flag is turned off if it is
    # not presented in the flags_dict.
    neighbor = flags_dict.copy()
    del neighbor[climb_spec]
    results.append(neighbor)

  return results


import pandas as pd
import numpy as np

from sklearn import model_selection
from sklearn import linear_model
from sklearn import naive_bayes
from sklearn import svm
from sklearn import metrics
from sklearn import feature_selection

COLUMNS_NAME = ['age', 'workclass', 'fnlwgt', 'education', 'education-num',
                'marital-status', 'occupation', 'relationship', 'race', 'gender',
                'capital-gain', 'capital-loss', 'hours-per-week', 'native-country', 'income']

DATA_PATH = ('../uci_data/adult.data.txt',
             '../uci_data/adult.test.txt')

def preprocess(data):
    # remove row with missing value
    data = data[data["workclass"] != "?"]
    data = data[data["occupation"] != "?"]
    data = data[data["native-country"] != "?"]

    data.replace(['Married-civ-spouse', 'Divorced', 'Never-married',
                  'Separated', 'Widowed', 'Married-spouse-absent', 'Married-AF-spouse'],
                 ['married', 'not married', 'not married',
                  'not married', 'not married', 'married', 'married'], inplace=True)

    category_col =['race','marital-status', 'gender', 'income', 'relationship',
                   'native-country', 'workclass', 'occupation', 'education']
    for col in category_col:
        _, c = np.unique(data[col], return_inverse=True)
        data[col] = c

    return data

def load_data():
    train_data = pd.read_csv(DATA_PATH[0], header=None, names=COLUMNS_NAME)
    test_data = pd.read_csv(DATA_PATH[1], header=None, names=COLUMNS_NAME)

    # the first row is invalid
    test_data = test_data.drop([0])

    train_data = preprocess(train_data)
    test_data = preprocess(test_data)

    return (train_data, test_data)

def cal_scores(y_pred, y_true, name):
    acc = metrics.accuracy_score(y_test, y_pred)
    auc = metrics.roc_auc_score(y_test, y_pred)
    logloss = metrics.log_loss(y_test, y_pred)
    print('{name} \nacc: {0} \nauc:{1} \nlogloss:{2}\n========='.format(acc, auc, logloss, name=name))

def naive_bayes_model(x_train, y_train, x_test, y_test):
    model = naive_bayes.GaussianNB()
    model.fit(x_train, y_train)
    y_pred = model.predict(x_test)

    cal_scores(y_pred, y_test, 'GaussianNB')

def logistic_regress_model(x_train, y_train, x_test, y_test):
    model = linear_model.LogisticRegressionCV()
    model.fit(x_train, y_train)
    y_pred = model.predict(x_test)

    cal_scores(y_pred, y_test, 'Logistic')

def svm_model(x_train, y_train, x_test, y_test):
    model = svm.SVC()
    model.fit(x_train, y_train)
    y_pred = model.predict(x_test)

    cal_scores(y_pred, y_test, 'SVC')

if __name__ == '__main__':
    train_data, test_data = load_data()

    feature_cols = ['marital-status', 'education-num', 'relationship', 'age']
    y_train = train_data['income']
    x_train = train_data[feature_cols]
    y_test = test_data['income']
    x_test = test_data[feature_cols]

    naive_bayes_model(x_train, y_train, x_test, y_test)
    logistic_regress_model(x_train, y_train, x_test, y_test)
    svm_model(x_train, y_train, x_test, y_test)


"""
deepdataspace.model.object

The object model.
"""

from typing import Dict
from typing import List
from typing import Literal
from typing import Optional
from typing import Union

from deepdataspace import constants
from deepdataspace.model._base import BaseModel
from deepdataspace.utils.file import create_file_url

class Object(BaseModel):
    """
    Objects are predictions, ground truths, or user annotations of an image.
    It is not stored in mongodb collections directly, but saved as nested documents in the image document.

    Attributes:
    -----------
    label_name: str
        The label name.
    label_type: str
        Is it a prediction? a GroundTruth? or a user annotation?, see :class:`deepdataspace.constants.LabelType`.
    label_id: str
        The label id.
    category_id: str
        The category id.
    category_name: str
        The category name.
    conf: float
        The confidence of the prediction.
    is_group: bool
        Is it a group of objects?
    bounding_box: dict
        The bounding box of the object, {"xmin": 0, "ymin": 0, "xmax": 0, "ymax": 0}.
    segmentation: str
        The segmentation of the object.
    alpha: str
        The alpha of the object.
    points: list
        The points of the object.
    lines: list
        The lines of the object.
    point_colors: list
        The point colors of the object.
    point_names: list
        The point names of the object.
    caption: str
        The caption of the object.
    confirm_type: int
        The image confirm type, 0 for unconfirmed, 1 for confirmed, 2 for rejected.
    compare_result: dict
        The compare result of the object, {"90": "FP", ..., "10": "OK"}.
    matched_det_idx: int
        The matched ground truth index, for prediction objects only.
    """

    @classmethod
    def get_collection(cls, *args, **kwargs):
        """
        Objects are stored directly inside the image document.
        """
        return None

    # the mandatory fields
    # every object must belong to a label set
    label_name: str
    label_type: str

    # the optional fields
    label_id: str = ""
    category_id: str = ""
    category_name: str = ""
    conf: Union[float, int] = 1.0
    is_group: Optional[bool] = False
    bounding_box: Optional[Dict[str, Union[float, int]]] = {}
    segmentation: Optional[str] = ""
    alpha: Optional[str] = ""
    points: Optional[List[Union[float, int]]] = []
    lines: Optional[List[int]] = []
    point_colors: Optional[List[int]] = []
    point_names: Optional[List[str]] = []
    caption: Optional[str] = ""
    confirm_type: Optional[int] = 0  # the image confirm type, 0 no confirm required, 1 gt may be fn, 2 pred may be fp
    compare_result: Optional[Dict[str, str]] = {}  # {"90": "FP", ..., "10": "OK"}
    matched_det_idx: Optional[int] = None  # The matched ground truth index, for prediction objects only.

    @staticmethod
    def _convert_file_path_to_url(file_uri: str):
        """
        Convert a local file path to a visible file url.
        """

        file_path = file_uri[7:]
        file_url = create_file_url(file_path=file_path,
                                   read_mode=constants.FileReadMode.Binary)
        return file_url

    def post_init(self):
        """
        Override the post_init method to convert the alpha file path to url.
        """

        if self.alpha and self.alpha.startswith("file://"):
            self.alpha = self._convert_file_path_to_url(self.alpha)


import webbrowser
import re
# 更新建议 使用模板引擎，将HTML和python代码分开

#
# f = open(HTML, 'w')
# message =
#
# f.write(message)
# f.close()
#
# webbrowser.open(HTML, new=1)

def create_html(latex_string):
    """
    将传入的latex 字符串 插入到 HTML 文件中
    :param latex_string: latex 字符串
    :return: None
    """
    HTML = "show_latex_page.html"  # 命名生成的html
    with open(HTML, 'r') as f:
        message = f.read()
    message = message.replace('latex_string', latex_string)

    with open(HTML, 'w') as f:
        f.write(message)


import os
import re

import xlrd
from openpyxl import Workbook

def clean(text):
    if isinstance(text, (int, float)):
        return text
    if not text:
        return ''
    for c in ['\r\n', '\n\r', u'\n', u'\r', u'\t', u'\xa0', '\\']:
        text = text.replace(c, ' ')
    return re.sub(' +', ' ', text).strip()

class MergeExcelLeadsScript:
    file_headers = [
        "company name", "address", "city", "state", "zip", "country", "phone",
    ]

    def __init__(self):
        self.sheet_row_index = 1
        self.wb = Workbook()
        self.sheet = self.wb.active
        self.create_xls_write_headers()

        self.parse_excel_files()

        self.wb.save('All Leads.xlsx')

    def parse_excel_files(self):
        for fp in self.get_files_path():
            col_values = self.get_excel_rows(fp)
            raw = "\n".join(str(e).replace('.0', '') if e else "," for e in col_values)

            for r in raw.split('\n,'):
                rows = [e.strip() for e in r.split('\n') if clean(e)]

                item = {}
                item["company name"] = rows[0].strip()
                item["address"] = clean(' '.join(rows[1].split(',')[::-1]))
                item["city"] = clean(rows[1].split(',')[-1])
                item["country"] = clean(rows[2])
                item["state"] = clean(rows[3])
                item["zip"] = int(rows[4]) if rows[4:] and clean(rows[4]).isdigit() else ''
                item["phone"] = rows[5] if rows[5:] and len(rows[5]) > 7 else ''

                self.write_xls(item)

            a = 0

    def get_excel_rows(self, file_path):
        wb = xlrd.open_workbook(file_path)
        sheet = wb.sheet_by_index(0)
        # return [sheet.cell_value(i, 0) for i in range(1, sheet.nrows)]
        return sheet.col_values(0)

    def get_files_path(self):
        return [f"data/{file}" for file in os.listdir('data') if file.endswith(".xlsx")]

    def create_xls_write_headers(self):
        for index, value in enumerate(self.file_headers):
            self.sheet.cell(row=self.sheet_row_index, column=index + 1).value = value
        self.sheet_row_index += 1

    def write_xls(self, item):
        for idx, key in enumerate(self.file_headers):
            self.sheet.cell(row=self.sheet_row_index, column=idx + 1).value = item[key]

        self.sheet_row_index += 1
        print(item)

if __name__ == "__main__":
    MergeExcelLeadsScript()


import dataclasses

import numpy as np
import pandas as pd
import pytest

from . import close
from .conftest import TEST
from .. import analysis, factory
from ..measures import Accuracy

@pytest.fixture(scope="module")
def d_expert(fixt_data_factory):  # see conftest.py
    d = fixt_data_factory.make(data_src="test_expert")
    return d

@pytest.fixture(scope="module")
def d_others(fixt_data_factory):
    d_others_ = {}
    for i in range(2):
        data_src = f"test_crowd_{i}"
        d_others_[data_src] = fixt_data_factory.make(data_src=data_src)
    # print([d.data_src for d in d_others_.values()])
    return d_others_

@pytest.fixture(scope="module")
def expert_consensuses_n_parameters(d_expert):
    model_ = factory.Factory.make("DawidSkene")
    expert_consensuses, expert_parameters = model_.fit_and_compute_consensuses_from_data(d_expert, TEST.QUESTIONS)
    return expert_consensuses, expert_parameters

@pytest.fixture(scope="module")
def parameters_others(expert_consensuses_n_parameters, d_others):
    model_ = factory.Factory.make("DawidSkene")
    expert_consensuses, _ = expert_consensuses_n_parameters
    parameters_others_ = analysis.compute_crossed(model_, d_others, expert_consensuses)
    return parameters_others_

def test_compute_crossed(expert_consensuses_n_parameters, parameters_others):
    _, expert_parameters = expert_consensuses_n_parameters
    for question, dgp in expert_parameters.items():
        expert_dgp = dataclasses.asdict(dgp)
        for param_name, expert_param_val in expert_dgp.items():
            for other in parameters_others:
                other_dgp = dataclasses.asdict(parameters_others[other][question])
                assert np.array_equal(expert_param_val, other_dgp[param_name])

def test_prospective_analysis(d_expert, expert_consensuses_n_parameters, parameters_others):
    _, expert_parameters = expert_consensuses_n_parameters
    measures = {Accuracy.name: Accuracy}
    repeats = 2
    question = TEST.QUESTIONS[0]
    model_ = factory.Factory.make("DawidSkene")
    ds = factory.Factory.make("DawidSkene")
    mv = factory.Factory.make("MajorityVoting")
    models = {"DS": ds, "MV": mv}
    options = {"n_tasks": [10, 100],
               "n_annotations_per_task": [3, 9]}
    scenarios = ds.DataGenerationParameters.product_from_dict(options)
    df = analysis.prospective_analysis(question, d_expert.data_src, expert_parameters, parameters_others,
                                       generative_model=model_, models=models, measures=measures, dgps=scenarios,
                                       repeats=repeats)
    # print(df)
    assert isinstance(df, pd.DataFrame)
    assert df.shape[0] == repeats * len(models) * len(options["n_tasks"]) * \
           len(options["n_annotations_per_task"]) * (len(parameters_others.keys()) + 1)  # +1 for experts

def test_compare_data_to_consensus(d_expert, d_others, expert_consensuses_n_parameters):
    expert_consensuses, _ = expert_consensuses_n_parameters
    for d_other in d_others.values():
        for question in TEST.QUESTIONS:
            df = analysis.compare_data_to_consensus(d_expert, d_other, expert_consensuses, question,
                                                    add_total_cols=True)
            # assert df is DataFrame
            assert isinstance(df, pd.DataFrame)
            # #Rows == #Labels
            assert df.shape[0] == d_other.n_labels(question)
            # #Columns == #Classes
            assert (df.shape[1] - 1 == len(d_other.get_classes(question)))
            # Total column == Sum(other columns)
            assert np.allclose(df.iloc[:, -1].to_numpy(), df.iloc[:, :-1].sum(axis=1).to_numpy())

def test_gen_confusion_matrix(d_expert, expert_consensuses_n_parameters):
    expert_consensuses, _ = expert_consensuses_n_parameters
    for question in TEST.QUESTIONS:
        df = analysis.gen_confusion_matrix(expert_consensuses[question], expert_consensuses[question],
                                           d_expert, question)
        # assert df is DataFrame
        assert isinstance(df, pd.DataFrame)
        # assert all categories are in the index and in the columns
        categories = d_expert.get_categories()[question].categories.tolist()
        assert df.index.to_list() == categories
        assert df.columns.to_list() == categories
        # assert dataframe total sum = # of tasks
        assert np.nansum(df.to_numpy()) == len(np.unique(d_expert.get_tasks(question)))
        # TODO (OM, 20210716): assert the values of rows?


#############################
## (C) Shay Goldshmit 2022 ##
#############################

import random
import MyGames.ConstColors as colors
from os import environ as env_var
try:
    import tkinter.messagebox
    import tkinter
except Exception:
    print(f'can not import tkinter!')
    tk_flag = False
else:
    tk_flag = True

env_var['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'  # for hiding an annoying message from Pygame
import pygame

pygame.init()
pygame.display.set_caption('Shay\'s Snake')

# constants
KEYBOARD_PRESSED = pygame.KEYDOWN
GAME_SPEED_START = 60
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
SCREEN_COLOR = colors.SEAGREEN4
SNAKE_SIZE = SCREEN_HEIGHT // 100
STEP_LENGTH = SNAKE_SIZE
SNAKE_COLOR = colors.YELLOW1

# global variables
game_screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
food_size = 2 * SNAKE_SIZE
food_color = colors.BANANA
game_over = None
game_speed = None
snake_dir = None
head_pos_x = None
head_pos_y = None
snake_pos_lst = None
is_space = None
pos_food_x = SCREEN_HEIGHT // 2
pos_food_y = SCREEN_WIDTH // 2
score = None

def draw_food(rand_new=False):
    global pos_food_x
    global pos_food_y
    global food_color
    global food_size

    if rand_new:
        pos_food_x = random.randint(10, SCREEN_WIDTH - 5)
        pos_food_x -= pos_food_x % SNAKE_SIZE
        pos_food_y = random.randint(10, SCREEN_HEIGHT - 5)
        pos_food_y -= pos_food_y % SNAKE_SIZE
        while True:
            colo = colors.get_rand_color()
            food_color = colo[0]
            food_color_name = colo[1]
            if (food_color != SCREEN_COLOR) and ('green' not in food_color_name):
                break

        food_size_factor = 2 * random.random() + 1
        food_size = int(food_size_factor * SNAKE_SIZE)
        print(f'Food: ({pos_food_x}, {pos_food_y}), Size - {food_size}, Color - {colo[1]}')

    if food_size % 3 == 0:
        pygame.draw.rect(game_screen, food_color, [pos_food_x, pos_food_y, food_size, food_size])
    elif food_size % 3 == 1:
        pygame.draw.circle(game_screen, food_color, center=(pos_food_x, pos_food_y), radius=food_size)
    else:
        pygame.draw.polygon(game_screen, food_color, ((pos_food_x - food_size, pos_food_y),
                                                      (pos_food_x, pos_food_y - food_size),
                                                      (pos_food_x + food_size, pos_food_y),
                                                      (pos_food_x, pos_food_y + food_size)))

def init_game():
    global game_over
    global game_speed
    global snake_dir
    global head_pos_x
    global head_pos_x
    global head_pos_y
    global head_pos_y
    global snake_pos_lst
    global game_screen
    global is_space
    global score

    game_over = False
    game_speed = GAME_SPEED_START
    snake_dir = ''
    head_pos_x = random.randint(SCREEN_WIDTH // 2 - SCREEN_WIDTH // 4, SCREEN_WIDTH // 2 + SCREEN_WIDTH // 4)
    head_pos_x -= (head_pos_x % SNAKE_SIZE)
    head_pos_y = random.randint(SCREEN_HEIGHT // 2 - SCREEN_HEIGHT // 4, SCREEN_HEIGHT // 2 + SCREEN_HEIGHT // 4)
    head_pos_y -= (head_pos_y % SNAKE_SIZE)
    snake_pos_lst = [(head_pos_x, head_pos_y)]  # list of tuples
    is_space = True
    score = 0
    draw_food(True)

def finish_game():
    global game_over

    while not game_over:
        draw_score()
        font = pygame.font.Font('freesansbold.ttf', SCREEN_HEIGHT // 15)
        text = font.render('Game Over!', True, colors.RED1, colors.BLUE)
        textRect = text.get_rect()
        textRect.center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
        game_screen.blit(text, textRect)
        pygame.display.update()

        for game_event in pygame.event.get():
            if game_event.type == pygame.QUIT:
                game_over = True
            elif game_event.type == KEYBOARD_PRESSED:
                if game_event.key == pygame.K_ESCAPE:
                    game_over = True
                else:
                    init_game()
                    return

def draw_score():
    global score

    font = pygame.font.Font('freesansbold.ttf', SCREEN_HEIGHT // 30)
    text = font.render(f'Score: {score}', True, colors.BLACK, SCREEN_COLOR)
    textRect = text.get_rect()
    textRect.center = (SCREEN_WIDTH / 14, SCREEN_HEIGHT / 40)
    game_screen.blit(text, textRect)

def draw_snake():
    global snake_pos_lst

    for pos_tpl in snake_pos_lst:
        pygame.draw.circle(game_screen, color=SNAKE_COLOR, center=tuple(pos_tpl), radius=SNAKE_SIZE)

def game_action(key: pygame.key):
    global head_pos_x
    global head_pos_y
    global snake_dir
    global snake_pos_lst
    global is_space
    global game_speed
    global score
    tail = snake_pos_lst[0]

    if (key == pygame.K_DOWN) and (snake_dir != 'up'):
        snake_dir = 'down'
    elif (key == pygame.K_UP) and (snake_dir != 'down'):
        snake_dir = 'up'
    if (key == pygame.K_RIGHT) and (snake_dir != 'left'):
        snake_dir = 'right'
    elif (key == pygame.K_LEFT) and (snake_dir != 'right'):
        snake_dir = 'left'
    elif key == pygame.K_s:
        is_space ^= 1
    elif key == pygame.K_n:
        init_game()
    elif key == pygame.K_p:
        snake_dir = ''

    if snake_dir == 'down':
        head_pos_y += STEP_LENGTH
    elif snake_dir == 'up':
        head_pos_y -= STEP_LENGTH
    elif snake_dir == 'right':
        head_pos_x += STEP_LENGTH
    elif snake_dir == 'left':
        head_pos_x -= STEP_LENGTH
    else:
        # pause game
        return

    for (pox, poy) in snake_pos_lst:
        # check if the head hits part of the body
        if (pox, poy) == (head_pos_x, head_pos_y) and len(snake_pos_lst) > 1:
            finish_game()
            return

        # check if the head hits the screen edges
        if (pox >= SCREEN_WIDTH) or (pox <= 0) or (poy >= SCREEN_HEIGHT) or (poy <= 0):
            finish_game()
            return

    snake_pos_lst.append((head_pos_x, head_pos_y))
    if is_space:
        tail = snake_pos_lst.pop(0)

    if (abs(head_pos_x - pos_food_x) <= SNAKE_SIZE) and (abs(head_pos_y - pos_food_y) <= SNAKE_SIZE):
        print(f'Head: ({head_pos_x}, {head_pos_y})\n')
        draw_food(True)
        snake_pos_lst.insert(0, tail)
        game_speed += 2
        score += 1

def play_game():
    global game_over
    global game_screen
    global head_pos_x
    global head_pos_y
    global game_speed
    draw_food(True)
    key = None

    while not game_over:
        game_screen.fill(SCREEN_COLOR)
        game_action(key)
        draw_snake()
        draw_food()
        draw_score()
        pygame.display.update()
        pygame.time.Clock().tick(game_speed)

        key = None
        for game_event in pygame.event.get():
            if game_event.type == KEYBOARD_PRESSED:
                if game_event.key == pygame.K_ESCAPE:
                    finish_game()
                else:
                    key = game_event.key
            elif game_event.type == pygame.QUIT:
                finish_game()

if __name__ == '__main__':
    try:
        init_game()
        play_game()
    except Exception as e:
        if tk_flag:
            msg = tkinter.Tk()
            msg.title('Snake Cather )-;')
            msg.geometry('300x1')
            tkinter.messagebox.showwarning('Snake Cather )-;', f'Unfortunately, the game has closed ({e})', parent=msg)
        else:
            print(f'Snake Cather - Unfortunately, the game has closed ({e})')


def solution(N, stages):
    users = len(stages) # 사용자 수
    stages = sorted(stages)  # 게임라운드 정렬
    stage = {i:0 for i in range(1,N+1)} # 각 스테이지 마다의 실패율을 저장하기 위한 딕셔너리
    arr = [ar for ar in range(1,N+1)] # N까지의 스테이지 배열

    for j in arr: # 스테이지를 돌면서
        if users == 0: # 앞에서 라운드 마다의 사람을 총 인원에서 빼고 실패율을 계산하기 때문에 인원수가 0일때 경우에는 실패율 0으로 설정(zero error 대비)
            stage[j] = 0
        else:
            fail = (stages.count(j)) / users # 실패율 = 스테이지에 머무른 사람수 / 사용자수
            stage[j] = fail # 딕셔너리의 실패율 값 초기화
            users -= stages.count(j) # 각 라운드 별로 사람들을 빼고 다음 라운드로 진행

    result_dict = sorted(stage.items(), key = lambda item: item[1], reverse = True) # lambda를 이용해서 딕셔너리의 key(실패율) 기준으로 내림차순 정렬
    result = [] # 실패율 등수에 따른 스테이지 번호를 반환
    for k in range(len(result_dict)):
        result.append(result_dict[k][0])

    return result


"""
Actuator that moves the lift platform inside the shaft to a given floor.

Interface is via service "move_to_floor(floor_number)", floor_number is 0:3
"""
import logging; logger = logging.getLogger("morse." + __name__)

import morse.core.actuator

from morse.core.services import service, async_service, interruptible
from morse.core import status
from morse.helpers.components import add_data, add_property

T=0.01**2 # max tollerence 1mm for position of platform

class Platform(morse.core.actuator.Actuator):
    _name = "Platform"
    _short_desc = "Move the elevator platform to given level"

    # define here the data fields required by your actuator
    # format is: field name, initial value, type, description
    #add_data('target_floor', 0, 'int', 'The floor to move to')
    add_data('current_floor', 0, 'int', 'The current floor. Read 999 if between floors.')

    def __init__(self, obj, parent=None):
        logger.info("%s initialization" % obj.name)
        # Call the constructor of the parent class
        super(self.__class__, self).__init__(obj, parent)

        # Do here actuator specific initializations

        self.local_data['current_floor'] = 0
        self.target_floor=0

        self.lift_cage= parent.bge_object.children['LiftCage']
        self.floor_height={-1:1.5, 0:4.5, 1:7.5, 2:10.5}

    @service
    def get_floor(self):
        """
        Return the current floor number
        """

        return self.local_data['current_floor']

    @interruptible
    @async_service
    def move_to_floor(self, floor):
        """ Move the platform to the given floor then return
        """
        self.target_floor = floor

    def default_action(self):
        """ Main loop of the actuator.

        Implements the component behaviour
        """

        # check if we have an on-going asynchronous task...
        if self.target_floor == self.local_data['current_floor']:
            self.completed(status.SUCCESS, self.local_data['current_floor'])

        # move the platform at given speed to target level.
        pos = self.lift_cage.localPosition
        distance =  self.floor_height[self.target_floor]  - pos[2]
        direction = -1 if distance < 0 else 1

        if distance**2 > T:
            vz = direction * 0.9 / self.frequency # 0.9m/s
        else:
            vz=0
            self.local_data['current_floor'] = self.target_floor

        self.lift_cage.localPosition[2]+=vz


import pandas as pd
import dateparser

try:
    # change
    user_reviews = pd.read_csv('./DataFiles/reviews.csv')
    review_num_of_rows = user_reviews.shape[0]
except:
    print('Error while handling user_reviews file.')

try:
    # change
    apps = pd.read_csv('./DataFiles/apps.csv', parse_dates=["Last Updated"], date_parser=lambda x: dateparser.parse(x))
    apps_num_of_rows = apps.shape[0]
except:
    print('Error while handling apps file.')

try:
    if __name__ == '__main__':
        print('user_reviews table:')
        print('Number of rows: ', review_num_of_rows)
        print('Columns names: ', list(user_reviews.columns))
        print('\napps table:')
        print('Number of rows: ', apps_num_of_rows)
        print('Columns names: ', list(apps.columns))

        # number of categories
        apps_categories_count = apps['Category'].drop_duplicates().size
        print('\nTotal count of apps categories: {}'.format(apps_categories_count))

        # heaviest app
        max_size = apps[apps['Size'].str.contains('M$', na=False)]['Size'].max()
        heaviest_app = apps[apps['Size'] == max_size]['App'].drop_duplicates().values
        print('\nThe heaviest apps: {}'.format(heaviest_app))

        # most installations
        max_installs = apps['Installs'].max()
        most_installed_app = apps[apps['Installs'] == max_installs]['App'].drop_duplicates().values
        print('\nThe apps with most installations: {}'.format(most_installed_app))

        # most updated
        max_update_date = apps['Last Updated'].max()
        updated_app = apps[apps['Last Updated'] == max_update_date]['App'].drop_duplicates().values
        print('\nThe most updated apps: {}'.format(updated_app))

        # most popular app genres
        most_popular_app = apps[apps['Installs'] == apps['Installs'].max()][
            ['App', 'Rating', 'Genres']].drop_duplicates()
        most_popular_app_max_rating = most_popular_app['Rating'].max()
        most_popular_app_genre = most_popular_app[most_popular_app['Rating'] == most_popular_app_max_rating][
            'Genres'].drop_duplicates()
        print('\nThe most popular app\'s genres: {}'.format(most_popular_app_genre.values))
except:
    print('Error while handling apps file.')

# The tables has no PK or Fk, because they don't have a unique values. we understand that the column 'App' in user_reviwe
# should be a Fk, but in reality there are apps in user_review which does not exist in apps table.


import socket
import os
import json
import tqdm

soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create socket object
BUFFER_SIZE = 4096
host = "127.0.0.1" # host to connect to
port = 5001 # port to connect to

print(f"[+] Connecting to {host}:{port}")
soc.connect((host, port)) # connect to host
print("[+] Connected.")

fileName = 'test.jpg'
fileSize = os.path.getsize(fileName)

data = fileName + ':' + str(fileSize)
soc.send(data.encode())
file_ = open(fileName, 'rb')

while True:
    # read the bytes from the file
    bytes_read = file_.read(BUFFER_SIZE)
    if not bytes_read:
        # file transmitting is done
        break
    # we use sendall to assure transimission in
    # busy networks
    soc.sendall(bytes_read)

soc.close()


from process import process
from print_p import print_p

class pRR:
    def __init__(self, pid, ST, FT):
        self.pid = pid
        self.start = ST
        self.finish = FT

def update_readyQ(pList, readyQ, time):
    for i in range(len(pList)):
        if(pList[i].arrival <= time) and (pList[i].arrival != -1):
            pList[i].arrival = -1
            readyQ.append(pList[i])
    return readyQ

def RR(pList, qt, cst):

    pList.sort(key=lambda x: x.arrival, reverse=False)

    readyQ = list()
    readyQ.append(pList[0])
    time = pList[0].arrival
    pList[0].arrival = -1
    prev = readyQ[0]

    avg_tat = 0.0
    avg_wtat = 0.0

    chart = []
    first = 0
    complete = 0
    while complete != len(pList):
        if first == 0:
            time += cst
            first = 1

        if len(readyQ) == 0:
            if time < pList[complete].copy_arrival:
                time = pList[complete].copy_arrival
            update_readyQ(pList, readyQ, time)
            time += cst

        if readyQ[0].running > qt:
            readyQ[0].running -= qt

            chart.append(pRR(readyQ[0].pid, time, time + qt))

            time += qt
            update_readyQ(pList, readyQ, time)
            readyQ.append(readyQ[0])
            prev = readyQ[0]
            del readyQ[0]
        else:
            chart.append(pRR(readyQ[0].pid, time, time + readyQ[0].running))

            time += readyQ[0].running
            readyQ[0].running = 0
            readyQ[0].finish = time
            readyQ[0].tat = readyQ[0].finish - readyQ[0].copy_arrival
            readyQ[0].wait = readyQ[0].tat - readyQ[0].copy_running
            readyQ[0].wtat = readyQ[0].tat / readyQ[0].copy_running
            avg_tat += readyQ[0].tat
            avg_wtat += readyQ[0].wtat
            prev = readyQ[0]
            del readyQ[0]
            complete += 1

        if len(readyQ) != 0:
            if prev != readyQ[0]:
                time += cst

    avg_tat /= float(len(pList))
    avg_wtat /= float(len(pList))

    print_p(pList, avg_tat, avg_wtat, "RR")
    return chart


# https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/
# TC: O(N)
# SC: O(M) M<=N
class Solution:
    def minSteps(self, s: str, t: str) -> int:

        d = dict()

        for ch in s:
            d[ch] = d.get(ch, 0) + 1

        count = 0

        for ch in t:
            if ch in d and d[ch] > 0:
                d[ch] = d[ch] - 1
            else:
                print(ch)
                count += 1

        return count


from typing import *
import operator
import os
import csv

class View:
    # creates folder path if not already exists
    RESULT_PATH = os.path.join(os.getcwd(), '..', 'output')

    def prompt_constraints(self):
        """ Asks for and returns minimum support, confidence, lift
        """
        min_supp = int(input('Enter min support (int): '))
        min_conf = float(input('Enter min confidence(A->C) (float): '))
        min_lift = float(input('Enter min lift(A->C) (float): '))
        constraints = (min_supp, min_conf, min_lift)
        return constraints

    def write_csv(self, out_folder: str, out_filename: str,
                  data: Union[List, Dict], header=None):
        """Data from List or Dict gets written to CSV file
        header is first line to be written to CSV file
        """
        if not os.path.exists(self.RESULT_PATH):
            os.makedirs(self.RESULT_PATH, exist_ok=False)
        folder_path = os.path.join(self.RESULT_PATH, out_folder)
        if not os.path.exists(folder_path):
            os.makedirs(folder_path, exist_ok=False)
        write_path = os.path.join(folder_path, out_filename)
        with open(write_path, 'w', newline='') as csv_file:
            csv_writer = csv.writer(csv_file)
            if header is not None:
                csv_writer.writerow(header)  # write header
            if type(data) == list:
                csv_writer.writerows(data)
            if type(data) == dict:
                for i in data.items():
                    csv_writer.writerow(i)

    def write_frequency(self, out_folder: str, out_filename: str,
                        itemset_tidset_dict):
        """Finds number of occurrences of k-itemsets and writes them
        """
        itemset_frequency = []
        for key, value in itemset_tidset_dict.items():
            temp_list = []
            if type(key) is tuple:
                temp_list.append(len(key))  # k
            else:
                temp_list.append(1)
            temp_list.append(key)  # k-item set
            temp_list.append(len(value))  # number of occurrences
            itemset_frequency.append(temp_list)
        # Sort by number of occurrences
        itemset_frequency = sorted(itemset_frequency,
                                   key=operator.itemgetter(2), reverse=True)
        # Sort by k
        itemset_frequency = sorted(itemset_frequency,
                                   key=operator.itemgetter(0), reverse=False)
        self.write_csv(out_folder, out_filename, itemset_frequency)

    def write_rule_stat(self, out_folder: str, out_filename: str,
                        rule_stat_dict):
        """Writes rule stat dict data nicely
        """
        rule_stat_list = []
        for rule, stat in rule_stat_dict.items():
            ante, cons = rule[0], rule[1]
            supp, conf, lift = stat[0], stat[1], stat[2]
            k = len(ante) + len(cons)
            rule_stat_list.append([k, len(ante), len(cons), ante, cons,
                                   supp, conf, lift])
        # Sort by lift
        rule_stat_list = sorted(rule_stat_list, key=operator.itemgetter(7),
                                reverse=True)
        # Sort by size(A+C)
        rule_stat_list = sorted(rule_stat_list, key=operator.itemgetter(0),
                                reverse=True)
        self.write_csv(out_folder, out_filename, rule_stat_list,
                       ['Size(A+C)', 'Size(A)', 'Size(C)', 'A', 'C',
                        'Supp(A->C)', 'Conf(A->C)', 'Lift(A->C)'])


from model import *

import minizinc
import conf
import sys

class Problem:
    def __init__(self, file):
        self.solver = minizinc.Solver.lookup('gecode')
        self.n = int(file.readline().strip())

        self.model = minizinc.Model()
        self.tasks = {i:
                      Task.from_line(self.model,
                                     i, file.readline()) for i in range(
                          1, self.n + 1)}

        for t in self.tasks.values():
            t.add_deps(file.readline())

        cycle = self.find_task_cycle()
        while cycle is not None:
            self.remove_cycle(cycle)
            cycle = self.find_task_cycle()

        self.task_map = dict()

        id = 1
        for t in self.tasks.values():
            self.task_map[t.id] = list(range(id, id + len(t.frags)))
            id += len(t.frags)

        # self.transitive_task_closure()

        self.frags = {f.id: f for f in sum(
            (t.generate_frags(
                self.task_map) for t in self.tasks.values()),
            list())}

        self.task_frag_map = dict()
        for tid in self.tasks:
            self.task_frag_map[tid] = [self.frags[id]
                                       for id in self.task_map[tid]]
        self.transitive_dep_closure()

    def __repr__(self):
        return '\n'.join(repr(f) for f in self.frags.values())

    def transitive_task_closure(self):
        # private method
        # finds the transitive closure of dependencies
        # ie: if T1 depends on T2 and T2 depends on T3, add a dependency from T1 to T3
        #
        deps = dict()

        def find_deps(t):
            if t in deps:
                return deps[t]
            ideps = sum(map(lambda x: find_deps(
                self.tasks[x]), t.deps), t.deps)
            deps[t] = ideps
            return deps[t]

        for i, f in self.frags.items():
            find_deps(i)

        for i, f in self.frags.items():
            f.deps = find_deps(i)

    def transitive_dep_closure(self):
        # private method
        # finds the transitive closure of dependencies
        # ie: if F1 depends on F2 and F2 depends on F3, add a dependency from F1 to F3
        #
        deps = dict()

        def find_deps(i):
            if i in deps:
                return deps[i]
            ideps = sum(map(lambda x: find_deps(
                x), self.frags[i].deps), self.frags[i].deps)
            deps[i] = ideps
            return deps[i]

        for i, f in self.frags.items():
            find_deps(i)

        for i, f in self.frags.items():
            f.deps = find_deps(i)

    def remove_cycle(self, cycle):
        to_delete = [x for x in cycle]
        while len(to_delete) > 0:
            while len(to_delete) > 0:
                id = to_delete.pop()
                del(self.tasks[id])

            for t in self.tasks.values():
                if any(id not in self.tasks for id in t.deps):
                    to_delete.append(t.id)

    def find_task_cycle(self):
        stack = list()
        visited = set()

        def visit(self, task):
            if task.id in visited:
                return None
            if task.id in stack:
                return stack[stack.index(task.id):]
            stack.append(task.id)
            for tid in task.deps:
                task2 = self.tasks[tid]
                cycle = visit(self, task2)
                if cycle is not None:
                    return cycle
            stack.pop()
            visited.add(task.id)
            return None

        for t in self.tasks.values():
            cycle = visit(self, t)
            if cycle is not None:
                return cycle

        return None

    def encode(self):
        for i, frag in self.frags.items():
            # dependencies
            for dep in map(lambda x: self.frags[x], frag.deps):
                self.model.add_string(
                    'constraint if {} then {} endif;\n'.format(
                        frag.exec(), dep.exec()))
                self.model.add_string(
                    'constraint if {} then {} >= {} + {} endif;\n'.format(
                        frag.exec(), frag.start(), dep.start(), dep.proc_time))

            # exclusive access
            for j, frag2 in self.frags.items():
                if j <= i or frag2.deadline < frag.min_start() or frag.deadline < frag2.min_start():
                    continue

                self.model.add_string(
                    'constraint if {0} /\\ {1} then ({2} >= {3} + {5}) xor ({3} >= {2} + {4}) endif;\n'.format(
                        frag.exec(),
                        frag2.exec(),
                        frag.start(),
                        frag2.start(),
                        frag.proc_time,
                        frag2.proc_time))

        self.model.add_string('solve maximize {};\n'.format(
            ' + '.join(t.exec_var for t in self.tasks.values())))

    def compute(self):
        self.instance = minizinc.Instance(self.solver, self.model)
        self.result = self.instance.solve(processes=16)
        assert self.result.status.has_solution(), 'UNSAT'
        return self.result

    def solve(self):
        result = self.compute()
       # print('---------------------')
       #print('\n'.join('{} {}'.format(t, ' '.join(str(f.min_start()) for f in frags)) for t, frags in self.task_frag_map.items()))
       # print('---------------------')
       # print(''.join(self.model._code_fragments))
       # print('---------------------')
        print(result['objective'])
        for task, frags in self.task_frag_map.items():
            if result[self.tasks[task].exec_var]:
                start_times = map(lambda f: result[f.start_var], frags)
                print(
                    '{} {}'.format(
                        task, ' '.join(
                            str(i) for i in start_times)))

if __name__ == '__main__':
    s = Problem(open('../tests/test1.sms'))
    s.encode()
    s.solve()


import math
import torch
import torchvision
import numpy as np

def xywh2xyxy(box):
    if isinstance(box, torch.Tensor):
        x, y, w, h = box.chunk(4, 1)

        return torch.cat((x - w / 2, y - h / 2, x + w / 2, y + h / 2), 1)

    else:
        x, y, w, h = box[:, 0], box[:, 1], box[:, 2], box[:, 3]

        return np.stack((x - w / 2, y - h / 2, x + w / 2, y + h / 2), 1)

def xyxy2xywh(box):
    if isinstance(box, torch.Tensor):
        x1, y1, x2, y2 = box.chunk(4, 1)

        return torch.cat(((x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1), 1)

    else:
        x1, y1, x2, y2 = box[:, 0], box[:, 1], box[:, 2], box[:, 3]

        return np.stack(((x1 + x2) / 2, (y1 + y2) / 2, x2 - x1, y2 - y1), 1)

def xywh_norm2xyxy(box, w, h, offset_x, offset_y):
    if isinstance(box, torch.Tensor):
        bx, by, bw, bh = box.chunk(4, 1)

        return torch.cat((w * (bx - bw / 2) + offset_x,
                          h * (by - bh / 2) + offset_y,
                          w * (bx + bw / 2) + offset_x,
                          h * (by + bh / 2) + offset_y), 1)

    else:
        bx, by, bw, bh = box[:, 0], box[:, 1], box[:, 2], box[:, 3]

        return np.stack((w * (bx - bw / 2) + offset_x,
                         h * (by - bh / 2) + offset_y,
                         w * (bx + bw / 2) + offset_x,
                         h * (by + bh / 2) + offset_y), 1)

def xyxy2xywh_norm(box, w, h):
    if isinstance(box, torch.Tensor):
        x1, y1, x2, y2 = box.chunk(4, 1)

        return torch.cat((((x1 + x2) / 2) / w, ((y1 + y2) / 2) / h, (x2 - x1) / w, (y2 - y1) / h), 1)

    else:
        x1, y1, x2, y2 = box[:, 0], box[:, 1], box[:, 2], box[:, 3]

        return np.stack((((x1 + x2) / 2) / w, ((y1 + y2) / 2) / h, (x2 - x1) / w, (y2 - y1) / h), 1)

def bbox_iou(box1, box2, foreach=False, type='IoU', eps=1e-7):
    b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, 1)
    b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, 1)

    if foreach:
        b1_x1 = b1_x1.unsqueeze(2)
        b1_y1 = b1_y1.unsqueeze(2)
        b1_x2 = b1_x2.unsqueeze(2)
        b1_y2 = b1_y2.unsqueeze(2)

    w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1
    w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1

    # Intersection Area
    inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
            (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)

    # Union Area
    union = w1 * h1 + w2 * h2 - inter + eps

    iou = inter / union

    if type == 'GIoU' or type == 'DIoU' or type == 'CIoU':
        cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)
        ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)

        d2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
        c2 = cw ** 2 + ch ** 2 + eps

        if type == 'GIoU':
            c_area = cw * ch + eps
            iou = iou - (c_area - union) / c_area

        elif type == 'DIoU':
            iou = iou - d2 / c2

        elif type == 'CIoU':
            v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
            alpha = v / (1 - iou + v + eps)

            iou = iou - (d2 / c2 + alpha * v)

    return iou.squeeze(2) if foreach else iou

def non_max_suppression(preds, conf_t, multi_label, max_box, max_wh, iou_t, max_det, merge):
    B = preds.shape[0]
    num_cls = preds.shape[2] - 5
    candidates = preds[:, :, 4] > conf_t
    multi_label = multi_label & (num_cls > 1)

    output = [torch.zeros((0, 6), device=preds.device)] * B

    for index, pred in enumerate(preds):
        pred = pred[candidates[index]]

        if pred.shape[0] == 0:
            continue

        pred[:, 5:] *= pred[:, 4:5]

        box = xywh2xyxy(pred[:, :4])

        if multi_label:
            i, j = (pred[:, 5:] > conf_t).nonzero(as_tuple=False).T
            pred = torch.cat((box[i], pred[i, j + 5, None], j[:, None].float()), 1)

        else:
            conf, cls = pred[:, 5:].max(1, keepdim=True)
            pred = torch.cat((box, conf, cls.float()), 1)[conf.view(-1) > conf_t]

        num = pred.shape[0]
        if num == 0:
            continue

        elif num > max_box:
            pred = pred[pred[:, 4].argsort(descending=True)[:max_box]]

        scale = pred[:, 5:6] * max_wh
        boxes, confs = pred[:, :4] + scale, pred[:, 4]
        indices = torchvision.ops.nms(boxes, confs, iou_t)

        if indices.shape[0] > max_det:
            indices = indices[:max_det]

        if merge:
            iou = bbox_iou(boxes[indices], boxes, True) > iou_t
            weights = iou * confs[None]
            pred[indices, :4] = torch.mm(weights, pred[:, :4]).float() / weights.sum(1, keepdim=True)

        output[index] = pred[indices]

    return output


from collections import deque

def solution(picks, minerals):
    mine = deque() # ['dia', 'iron', 'iron', 'iron', 'stone', 'stone']
    pick = ["dia", "iron", "stone"]
    k = -1
    for i in picks:
        k += 1
        for j in range(i):
            mine.append(pick[k])
    minerals = deque(minerals)
    fatigability = 0
    mine_pick = ''
    for l in range(len(mine)):
        while mine or minerals:
            if len(mine) == 0:
                break
            mine_pick = mine[l]
            mine.popleft()
            for m in range(5):
                if len(minerals) == 0:
                    break
                if mine_pick == "dia":
                    minerals.popleft()
                    fatigability += 1
                elif mine_pick == "iron":
                    if minerals[0] == 'diamond':
                        fatigability += 5
                        minerals.popleft()
                    else:
                        fatigability += 1
                        minerals.popleft()
                else:
                    if minerals[0] == "diamond":
                        fatigability += 25
                        minerals.popleft()
                    elif minerals[0] == "iron":
                        fatigability += 5
                        minerals.popleft()
                    else:
                        fatigability += 1
                        minerals.popleft()
    return fatigability

print(solution([1, 3, 2], ["diamond", "diamond", "diamond", "iron", "iron", "diamond", "iron", "stone"]))

프로그래머스/lv2/172927. 광물 캐기/(1차 fail) 광물캐기.py