import torch
import torch.nn as nn
import torch.nn.functional as F

class Mish(nn.Module):
    def __init__(self):
        super(Mish, self).__init__()

    def forward(self, x):
        return x * torch.tanh(F.softplus(x))

ACTIVATIONS = {
    'mish': Mish(),
    'leaky': nn.LeakyReLU(negative_slope=0.1),
    'linear': nn.Identity()
}

class Conv(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, stride=1, activation='mish'):
        super(Conv, self).__init__()

        self.conv = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size,
                      stride, kernel_size//2, bias=False),
            nn.BatchNorm2d(out_channels),
            ACTIVATIONS[activation]
        )

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

class CSPBlock(nn.Module):
    def __init__(self, in_channels, out_channels, hidden_channels=None, residual_activation='linear'):
        super(CSPBlock, self).__init__()

        if hidden_channels is None:
            hidden_channels = out_channels

        self.block = nn.Sequential(
            Conv(in_channels, hidden_channels, 1),
            Conv(hidden_channels, out_channels, 3)
        )

        self.activation = ACTIVATIONS[residual_activation]

    def forward(self, x):
        return self.activation(x+self.block(x))

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

        self.downsample_conv = Conv(in_channels, out_channels, 3, stride=2)

        self.split_conv0 = Conv(out_channels, out_channels, 1)
        self.split_conv1 = Conv(out_channels, out_channels, 1)

        self.blocks_conv = nn.Sequential(
            CSPBlock(out_channels, out_channels, in_channels),
            Conv(out_channels, out_channels, 1)
        )

        self.concat_conv = Conv(out_channels*2, out_channels, 1)

    def forward(self, x):
        x = self.downsample_conv(x)

        x0 = self.split_conv0(x)
        x1 = self.split_conv1(x)

        x1 = self.blocks_conv(x1)

        x = torch.cat([x0, x1], dim=1)
        x = self.concat_conv(x)

        return x

class CSPStage(nn.Module):
    def __init__(self, in_channels, out_channels, num_blocks):
        super(CSPStage, self).__init__()

        self.downsample_conv = Conv(in_channels, out_channels, 3, stride=2)

        self.split_conv0 = Conv(out_channels, out_channels//2, 1)
        self.split_conv1 = Conv(out_channels, out_channels//2, 1)

        self.blocks_conv = nn.Sequential(
            *[CSPBlock(out_channels//2, out_channels//2)
                       for _ in range(num_blocks)],
            Conv(out_channels//2, out_channels//2, 1)
        )

        self.concat_conv = Conv(out_channels, out_channels, 1)

    def forward(self, x):
        x = self.downsample_conv(x)

        x0 = self.split_conv0(x)
        x1 = self.split_conv1(x)

        x1 = self.blocks_conv(x1)

        x = torch.cat([x0, x1], dim=1)
        x = self.concat_conv(x)

        return x

class CSPDarknet53(nn.Module):
  def __init__(self,
               stem_channels=32,
               feature_channels=[64, 128, 256, 512, 1024],
               num_features=3,
               num_classes=1000):

    super(CSPDarknet53, self).__init__()

    self.stem_conv = Conv(3, stem_channels, 3)

    self.stages = nn.ModuleList([
      CSPFirstStage(stem_channels, feature_channels[0]),
      CSPStage(feature_channels[0], feature_channels[1], 2),
      CSPStage(feature_channels[1], feature_channels[2], 8),
      CSPStage(feature_channels[2], feature_channels[3], 8),
      CSPStage(feature_channels[3], feature_channels[4], 4)
    ])

    self.feature_channels = feature_channels
    self.num_classes = num_classes

    self.gap = nn.AdaptiveAvgPool2d((1, 1))
    self.fc = nn.Conv2d(1024, self.num_classes, 1)

    for m in self.modules():
      if isinstance(m, nn.Conv2d):
          nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
      elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
          nn.init.constant_(m.weight, 1)
          nn.init.constant_(m.bias, 0)

  def extract_features(self, x):
    features = []

    x = self.stem_conv(x)

    x = self.stages[0](x)#//2
    x = self.stages[1](x)#//4
    x8 = self.stages[2](x)#//8
    features.append(x8)

    x16 = self.stages[3](x8)#//16
    features.append(x16)

    x32 = self.stages[4](x16)#//32
    features.append(x32)

    return features

  def forward(self, x):
    features = self.extract_features(x)
    x = self.gap(features[-1])
    x = self.fc(x)
    x = x.flatten(start_dim=1)
    return x

if __name__ == '__main__':
    model = CSPDarknet53(num_classes=1000)
    x = torch.randn(1, 3, 224, 224)
    out = model(x)


import json
from functions import wrap_response
from application.handlers.base import BaseHandler

class UACSAPIV2Handler(BaseHandler):
    def get(self):
        """
            Handles the /api/v1/uacs endpoint.
            Returns list of uacs.
        """
        response = {
            "code": 200,
            "type": "",
            "method": "GET",
            "response": "OK",
            "description": "",
            "data": []
        }

        if not self.GET("uacs_type"):
            response["response"] = "ERROR"
            response["desc"] = "Parameter uacs_type is required."
            wrap_response(self, response)
            return

        uacs_type = self.GET("uacs_type")
        if uacs_type.lower() not in ["funding source", "organization", "location", "pap", "object code"]:
            response["response"] = "ERROR"
            response["desc"] = "Invalid uacs_type: "+uacs_type+"."
            wrap_response(self, response)
            return

        if self.GET("uacs_code"):
            if uacs_type.lower() == "organization":
                if len(self.GET("uacs_code")) > 12 or len(self.GET("uacs_code")) == 0:
                    response["response"] = "ERROR"
                    response["desc"] = "Invalid uacs_code: "+self.GET("uacs_code")+"."
                    wrap_response(self, response)
                    return

        if uacs_type.lower() == "organization":
            uacs_json_file = json.load(open('uacs_organization.json'))

        uacs_code = self.GET("uacs_code")
        if uacs_type.lower() == "organization" and uacs_code:
            if len(uacs_code) == 2:
                if uacs_code in uacs_json_file:
                    response_json = uacs_json_file[uacs_code]
                    response["type"] = "Department"
                    response["description"] = "List of department agencies."
                    response["data"] = response_json
                else:
                    response["code"] = 404
                    response["response"] = "NOT FOUND"
            elif len(uacs_code) == 5:
                department_uacs = uacs_code[:2]
                if department_uacs in uacs_json_file:
                    if uacs_code in uacs_json_file[department_uacs]["AGENCY"]:
                        response_json = uacs_json_file[department_uacs]["AGENCY"][uacs_code]
                        response["type"] = "Agency"
                        response["description"] = "List of regions in a department agency."
                        response["data"] = response_json
                    else:
                        response["code"] = 404
                        response["response"] = "NOT FOUND"
                else:
                    response["code"] = 404
                    response["response"] = "NOT FOUND"
            elif len(uacs_code) == 7:
                department_uacs = uacs_code[:2]
                agency_uacs = uacs_code[:5]
                region_uacs = uacs_code
                if department_uacs in uacs_json_file:
                    if agency_uacs in uacs_json_file[department_uacs]["AGENCY"]:
                        if region_uacs in uacs_json_file[department_uacs]["AGENCY"][agency_uacs]["REGION"]:
                            response_json = uacs_json_file[department_uacs]["AGENCY"][agency_uacs]["REGION"][region_uacs]
                            response["type"] = "Region"
                            response["description"] = "Low level operating unit in a department agency region."
                            response["data"] = response_json
                        else:
                            response["code"] = 404
                            response["response"] = "NOT FOUND"
                    else:
                        response["code"] = 404
                        response["response"] = "NOT FOUND"
                else:
                    response["code"] = 404
                    response["response"] = "NOT FOUND"
            elif len(uacs_code) == 12:
                department_uacs = uacs_code[:2]
                agency_uacs = uacs_code[:5]
                region_uacs = uacs_code[:7]
                lower_lvl_op_unit_uacs = uacs_code
                if department_uacs in uacs_json_file:
                    if agency_uacs in uacs_json_file[department_uacs]["AGENCY"]:
                        if region_uacs in uacs_json_file[department_uacs]["AGENCY"][agency_uacs]["REGION"]:
                            if lower_lvl_op_unit_uacs in uacs_json_file[department_uacs]["AGENCY"][agency_uacs]["REGION"][region_uacs]["LOWER LEVEL OPERATING UNIT"]:
                                response_json = uacs_json_file[department_uacs]["AGENCY"][agency_uacs]["REGION"][region_uacs]["LOWER LEVEL OPERATING UNIT"][uacs_code]
                                response["type"] = "Lower Level Operating Unit"
                                response["description"] = "List of low level operating unit in a department agency region."
                                response["data"] = response_json
                            else:
                                response["code"] = 404
                                response["response"] = "NOT FOUND"
                        else:
                            response["code"] = 404
                            response["response"] = "NOT FOUND"
                    else:
                        response["code"] = 404
                        response["response"] = "NOT FOUND"
                else:
                    response["code"] = 404
                    response["response"] = "NOT FOUND"
            else:
                response["code"] = 404
                response["response"] = "NOT FOUND"
        else:
            department = ""
            agency = ""
            region = ""
            operating_unit = ""

            if self.GET('department'):
                department = self.GET('department').upper().strip()

            if self.GET('agency'):
                agency = self.GET('agency').upper().strip()

            if self.GET('region'):
                region = self.GET('region').upper().strip()

            if self.GET('operating_unit'):
                operating_unit = self.GET('operating_unit').upper().strip()

            response_json = []

            if department:
                if department in uacs_json_file:
                    if agency:
                        if agency in uacs_json_file[department]["AGENCY"]:
                            if region:
                                if region in uacs_json_file[department][agency]:
                                    response_json = uacs_json_file[department][agency][region]
                                else:
                                    response["code"] = 404
                                    response["response"] = "NOT FOUND"
                            else:
                                response_json = uacs_json_file[department]["AGENCY"][agency]
                        else:
                            response["code"] = 404
                            response["response"] = "NOT FOUND"
                    else:
                        response_json = uacs_json_file[department]
                else:
                    response["code"] = 404
                    response["response"] = "NOT FOUND"

            else:
                response_json = uacs_json_file

            response['data'] = response_json

        if self.GET("callback"):
            callback = self.GET("callback")
            d = json.dumps(response)

            self.response.out.write(callback + "(" + d + ");")
        else:
            wrap_response(self, response)


import pandas as pd
import numpy as np
import os
from tqdm import *
tqdm.pandas()

from sklearn.preprocessing import LabelEncoder

CLASS_NAME=\
['The_Eiffel_Tower', 'The_Great_Wall_of_China', 'The_Mona_Lisa', 'airplane', 'alarm_clock', 'ambulance', 'angel',
 'animal_migration', 'ant', 'anvil', 'apple', 'arm', 'asparagus', 'axe', 'backpack', 'banana', 'bandage', 'barn',
 'baseball', 'baseball_bat', 'basket', 'basketball', 'bat', 'bathtub', 'beach', 'bear', 'beard', 'bed', 'bee',
 'belt', 'bench', 'bicycle', 'binoculars', 'bird', 'birthday_cake', 'blackberry', 'blueberry', 'book',
 'boomerang', 'bottlecap', 'bowtie', 'bracelet', 'brain', 'bread', 'bridge', 'broccoli', 'broom',
 'bucket', 'bulldozer', 'bus', 'bush', 'butterfly', 'cactus', 'cake', 'calculator', 'calendar', 'camel',
 'camera', 'camouflage', 'campfire', 'candle', 'cannon', 'canoe', 'car', 'carrot', 'castle', 'cat', 'ceiling_fan',
 'cell_phone', 'cello', 'chair', 'chandelier', 'church', 'circle', 'clarinet', 'clock', 'cloud', 'coffee_cup',
 'compass', 'computer', 'cookie', 'cooler', 'couch', 'cow', 'crab', 'crayon', 'crocodile', 'crown', 'cruise_ship',
 'cup', 'diamond', 'dishwasher', 'diving_board', 'dog', 'dolphin', 'donut', 'door', 'dragon', 'dresser',
 'drill', 'drums', 'duck', 'dumbbell', 'ear', 'elbow', 'elephant', 'envelope', 'eraser', 'eye', 'eyeglasses',
 'face', 'fan', 'feather', 'fence', 'finger', 'fire_hydrant', 'fireplace', 'firetruck', 'fish', 'flamingo',
 'flashlight', 'flip_flops', 'floor_lamp', 'flower', 'flying_saucer', 'foot', 'fork', 'frog', 'frying_pan',
 'garden', 'garden_hose', 'giraffe', 'goatee', 'golf_club', 'grapes', 'grass', 'guitar', 'hamburger',
 'hammer', 'hand', 'harp', 'hat', 'headphones', 'hedgehog', 'helicopter', 'helmet', 'hexagon', 'hockey_puck',
 'hockey_stick', 'horse', 'hospital', 'hot_air_balloon', 'hot_dog', 'hot_tub', 'hourglass', 'house', 'house_plant',
 'hurricane', 'ice_cream', 'jacket', 'jail', 'kangaroo', 'key', 'keyboard', 'knee', 'ladder', 'lantern', 'laptop',
 'leaf', 'leg', 'light_bulb', 'lighthouse', 'lightning', 'line', 'lion', 'lipstick', 'lobster', 'lollipop', 'mailbox',
 'map', 'marker', 'matches', 'megaphone', 'mermaid', 'microphone', 'microwave', 'monkey', 'moon', 'mosquito',
 'motorbike', 'mountain', 'mouse', 'moustache', 'mouth', 'mug', 'mushroom', 'nail', 'necklace', 'nose', 'ocean',
 'octagon', 'octopus', 'onion', 'oven', 'owl', 'paint_can', 'paintbrush', 'palm_tree', 'panda', 'pants',
 'paper_clip', 'parachute', 'parrot', 'passport', 'peanut', 'pear', 'peas', 'pencil', 'penguin', 'piano',
 'pickup_truck', 'picture_frame', 'pig', 'pillow', 'pineapple', 'pizza', 'pliers', 'police_car', 'pond',
 'pool', 'popsicle', 'postcard', 'potato', 'power_outlet', 'purse', 'rabbit', 'raccoon', 'radio', 'rain',
 'rainbow', 'rake', 'remote_control', 'rhinoceros', 'river', 'roller_coaster', 'rollerskates', 'sailboat',
 'sandwich', 'saw', 'saxophone', 'school_bus', 'scissors', 'scorpion', 'screwdriver', 'sea_turtle', 'see_saw',
 'shark', 'sheep', 'shoe', 'shorts', 'shovel', 'sink', 'skateboard', 'skull', 'skyscraper', 'sleeping_bag',
 'smiley_face', 'snail', 'snake', 'snorkel', 'snowflake', 'snowman', 'soccer_ball', 'sock', 'speedboat',
 'spider', 'spoon', 'spreadsheet', 'square', 'squiggle', 'squirrel', 'stairs', 'star', 'steak', 'stereo',
 'stethoscope', 'stitches', 'stop_sign', 'stove', 'strawberry', 'streetlight', 'string_bean', 'submarine',
 'suitcase', 'sun', 'swan', 'sweater', 'swing_set', 'sword', 't-shirt', 'table', 'teapot', 'teddy-bear',
 'telephone', 'television', 'tennis_racquet', 'tent', 'tiger', 'toaster', 'toe', 'toilet', 'tooth',
 'toothbrush', 'toothpaste', 'tornado', 'tractor', 'traffic_light', 'train', 'tree', 'triangle',
 'trombone', 'truck', 'trumpet', 'umbrella', 'underwear', 'van', 'vase', 'violin', 'washing_machine',
 'watermelon', 'waterslide', 'whale', 'wheel', 'windmill', 'wine_bottle', 'wine_glass', 'wristwatch',
 'yoga', 'zebra', 'zigzag']

def softmax(X, theta = 1.0, axis = None):
    """
    Compute the softmax of each element along an axis of X.

    Parameters
    ----------
    X: ND-Array. Probably should be floats.
    theta (optional): float parameter, used as a multiplier
        prior to exponentiation. Default = 1.0
    axis (optional): axis to compute values along. Default is the
        first non-singleton axis.

    Returns an array the same size as X. The result will sum to 1
    along the specified axis.
    """

    # make X at least 2d
    y = np.atleast_2d(X)

    # find axis
    if axis is None:
        axis = next(j[0] for j in enumerate(y.shape) if j[1] > 1)

    # multiply y against the theta parameter,
    y = y * float(theta)

    # subtract the max for numerical stability
    y = y - np.expand_dims(np.max(y, axis = axis), axis)

    # exponentiate y
    y = np.exp(y)

    # take the sum along the specified axis
    ax_sum = np.expand_dims(np.sum(y, axis = axis), axis)

    # finally: divide elementwise
    p = y / ax_sum

    # flatten if X was 1D
    if len(X.shape) == 1: p = p.flatten()

    return p

def clean_data(data_clean, data_clean_out, data_predict_path):
    lb = LabelEncoder()
    lb.fit(CLASS_NAME)

    all_cls = lb.classes_
    idx2cls = np.zeros(all_cls.shape, dtype=object)
    for i, cls in enumerate(all_cls):
        idx2cls[i] = cls

    # Load predicted train by other models
    # train_predict = np.load("./logs/clean_model_1_resnet34/dataset.predictions.data_clean_train.npy")
    data_predict = np.load(data_predict_path)
    data_predict = softmax(data_predict, axis=1)

    # all_class = os.listdir(data_2_train)
    # Load non-clean data
    dfs = []
    for cls in CLASS_NAME:
        cls = cls.replace("_", ' ')
        df = pd.read_csv(os.path.join(data_clean, cls + ".csv"))
        df["word"] = cls.split(".")[0]
        dfs.append(df)
    dfs = pd.concat(dfs, axis=0)

    pred = np.argmax(data_predict, axis=1)
    pred_cls = idx2cls[pred]

    probs = []
    for i, predict_prob in enumerate(data_predict):
        probs.append(predict_prob[pred[i]])

    dfs["predict_word"] = pred_cls
    dfs["predict_word"] = dfs["predict_word"].apply(lambda x: x.replace("_", " "))
    dfs["prob"] = probs
    print("Predicted df: ", dfs.head())

    del data_predict
    import gc
    gc.collect()

    threshold = 0.90

    def re_assign_label(row):
        if row["recognized"] == False and row["word"] != row["predict_word"] and row["prob"] > threshold:
            row["new_word"] = row["predict_word"]
        else:
            row["new_word"] = row["word"]
        return row

    recognized_df = dfs[dfs["recognized"] == True]
    unrecognized_df = dfs[dfs["recognized"] == False]
    del dfs
    gc.collect()

    clean_df = unrecognized_df.progress_apply(re_assign_label, axis=1)
    print("Number of data is corrected is: ", (clean_df["word"] != clean_df["new_word"]).sum())
    recognized_df["new_word"] = recognized_df["word"]
    clean_dfs = pd.concat([clean_df, recognized_df], axis=0)
    del clean_df, recognized_df
    gc.collect()

    all_class = clean_dfs["new_word"].unique()
    os.makedirs(data_clean_out, exist_ok=True)

    # Save csv
    for cls in tqdm(all_class):
        cls_df = clean_dfs[clean_dfs["new_word"] == cls]
        cls_df.to_csv(data_clean_out + cls + ".csv", index=False)

    del clean_dfs
    gc.collect()

def main():
    data_clean_train = "/media/ngxbac/Bac/competition/kaggle/competition_data/quickdraw/data/100k_clean_unrecognized/train/"
    data_clean_valid = "/media/ngxbac/Bac/competition/kaggle/competition_data/quickdraw/data/100k_clean_unrecognized/valid/"

    data_clean_train_out = "/media/ngxbac/Bac/competition/kaggle/competition_data/quickdraw/data/100k_clean_unrecognized/train_clean/"
    data_clean_valid_out = "/media/ngxbac/Bac/competition/kaggle/competition_data/quickdraw/data/100k_clean_unrecognized/valid_clean/"

    data_train_predict = "./logs/se_resnext101_50k_2/dataset.predictions.data_clean_train.logits.npy"
    data_valid_predict = "./logs/se_resnext101_50k_2/dataset.predictions.data_clean_valid.logits.npy"

    # Clean train
    clean_data(data_clean_train, data_clean_train_out, data_train_predict)
    # Clean validation
    clean_data(data_clean_valid, data_clean_valid_out, data_valid_predict)

if __name__ == '__main__':
    main()


"""
Extension which adds the scanner applet to allow the user to create, start and control scans.

Implementations
---------------
Applets: `Scanner`
"""
from typing import Sequence, Dict, List
from pathlib import Path

from dltscontrol.apptk import Component, Service, Applet, Panel, Context, showerror
from dltscontrol.dlts import IScan, ScanAreaConfig

import re

import numpy as np

import tkinter as tk
import tkinter.ttk as ttk
import dltscontrol.tkext as tkext

# extension dependencies
from dltscontrol.app.core import rootLogger, IDltsComponent, IUserConfigComponent
from dltscontrol.app.scanning import IScanCreationComponent, ScanProgressPanel
from dltscontrol.app.objectsaving import ISaveServiceComponent

logger = rootLogger.getChild(__name__)

class Scanner(Applet, IDltsComponent, IScanCreationComponent, ISaveServiceComponent, IUserConfigComponent):
    """ An applet to create, start and stop user parameterized scans based on scan creation services.

    The scanner allows to create and start scans which are provided by scan creation services. The scanner keeps track of the
    scan progress and provides the means to control the started scan. Additionally it comes with an automatic and user-configuarable
    scan raw data logger.

    Used Panels
    -----------
    `ScanProgressPanel`
    """
    _REFRESH_PERIOD_MS = 1000
    _RAW_DATA_LOG_PERIOD_MS = 3000

    _BUTTON_WIDTH = 10

    _FRAME_PADX = 2
    _FRAME_PADY = 2

    _DEFAULT_SCAN_NAME = "None"

    _RAW_DATA_LOG_SECTION = "Scanner Raw Data Log Defaults"

    _RAW_DATA_LOG_ENABLED_KEY = "enabled"
    _RAW_DATA_LOG_ENABLED_DEFAULT = "True"

    _RAW_DATA_LOG_FORMAT_KEY = "format"
    _RAW_DATA_LOG_FORMAT_DEFAULT = "None"

    _RAW_DATA_LOG_DIRECTOY_KEY = "directory-name"
    _RAW_DATA_LOG_DIRECTOY_DEFAULT = "ScanRawDataLog"

    _RAW_DATA_LOG_DATE_FORMAT_KEY = "date-format"
    _RAW_DATA_LOG_DATE_FORMAT_DEFAULT = "%Y%m%d-%H%M%S"

    _RAW_DATA_LOG_FILE_NAME_FORMAT_KEY = "name-format"
    _RAW_DATA_LOG_FILE_NAME_FORMAT_DEFAULT = "{date}_{name}_x{xmin}-{xmax}_y{ymin}-{ymax}_z{z}_xt{xtilt}_i{intensity}_{index}"

    def __init__(self, tkMaster, context):
        super().__init__(tkMaster, context)

        self.Window.title("Scanner")

        self.Window.geometry("600x80")
        self.Window.resizable(True, True)

        self._scan: IScan = None
        self._periodicRefreshCaller = tkext.PeriodicCaller(self.getTk(), self._REFRESH_PERIOD_MS, self.refresh)
        self._selectedScanNameVariable = tk.StringVar(self.getTk(), self._DEFAULT_SCAN_NAME)

        self._rawDataLogCaller = tkext.PeriodicCaller(self.getTk(), self._RAW_DATA_LOG_PERIOD_MS, self._logScanRawData)
        self._scanImagesLoggedStateList: List[bool] = list()

        self._rawLogTimeFormat = self._RAW_DATA_LOG_DATE_FORMAT_DEFAULT
        self._rawLogFileNameFormat = self._RAW_DATA_LOG_FILE_NAME_FORMAT_DEFAULT
        self._rawLogRelativeDirectory = Path(self._RAW_DATA_LOG_DIRECTOY_DEFAULT)

        self._rawLogEnabledVariable = tk.BooleanVar(self.getTk(), self._RAW_DATA_LOG_ENABLED_DEFAULT)
        self._rawLogFormatVariable = tk.StringVar(self.getTk(), self._RAW_DATA_LOG_FORMAT_DEFAULT)

        creationFrame = ttk.Frame(self.getTk())

        rawDataCheckButton = ttk.Checkbutton(creationFrame, text = "Raw Data Log:", variable = self._rawLogEnabledVariable, command = self._updateRawDataLogCaller)
        self._rawDataFormatOptionMenu = tkext.OptionMenu(creationFrame, self._rawLogFormatVariable, self._RAW_DATA_LOG_FORMAT_DEFAULT)

        self._creationOptionMenu = tkext.OptionMenu(creationFrame, self._selectedScanNameVariable, self._DEFAULT_SCAN_NAME)
        self._selectedScanNameVariable.set('Multi Intensity Scan')  # TODO: DEBUG.. Remove me later

        startButton = ttk.Button(creationFrame, text = "Start", width = self._BUTTON_WIDTH, command = self._onScanStartClick)
        abortButton = ttk.Button(creationFrame, text = "Abort", width = self._BUTTON_WIDTH, command = self._onScanAbortClick)

        self._scanProgressPanel = self.createPanel(ScanProgressPanel, self.getTk())

        rawDataCheckButton.pack(side = tk.LEFT)
        self._rawDataFormatOptionMenu.pack(side = tk.LEFT, padx = self._FRAME_PADX, pady = self._FRAME_PADY)
        abortButton.pack(side = tk.RIGHT)
        startButton.pack(side = tk.RIGHT, padx = self._FRAME_PADX, pady = self._FRAME_PADY)

        self._creationOptionMenu.pack(side = tk.RIGHT)

        creationFrame.pack(side = tk.TOP, fill = tk.X, padx = self._FRAME_PADX, pady = self._FRAME_PADY)
        self._scanProgressPanel.MainFrame.pack(side = tk.BOTTOM, fill = tk.X, padx = self._FRAME_PADX, pady = self._FRAME_PADY)

    @property
    def Scan(self) -> IScan:
        """ The current scan. """
        return self._scan

    @Scan.setter
    def Scan(self, scan: IScan):
        if self._scan is not scan:
            self._scan = scan
            self._scanProgressPanel.Scan = scan
            self._scanImagesLoggedStateList.clear()

    @property
    def RawDataLogEnabled(self) -> bool:
        return self._rawLogEnabledVariable.get() and self.SelectedRawLogFormat != self._RAW_DATA_LOG_FORMAT_DEFAULT

    @property
    def SelectedRawLogFormat(self) -> str:
        return self._rawLogFormatVariable.get()

    def onCreate(self):
        super().onCreate()

        self._rawDataFormatOptionMenu.Options = self.getToFileNamesForType(np.ndarray)
        self._creationOptionMenu.Options = self.getScanNames()

        userConfig = self.getUserConfig()

        if userConfig is not None:
            self._rawLogEnabledVariable.set(userConfig.getSet(self._RAW_DATA_LOG_SECTION, self._RAW_DATA_LOG_ENABLED_KEY, self._RAW_DATA_LOG_ENABLED_DEFAULT))
            self._rawLogFormatVariable.set(userConfig.getSet(self._RAW_DATA_LOG_SECTION, self._RAW_DATA_LOG_FORMAT_KEY,
                next(iter(self._rawDataFormatOptionMenu.Options), self._RAW_DATA_LOG_FORMAT_DEFAULT)))

            self._rawLogRelativeDirectory = userConfig.getSet(self._RAW_DATA_LOG_SECTION, self._RAW_DATA_LOG_DIRECTOY_KEY, self._RAW_DATA_LOG_DIRECTOY_DEFAULT)
            self._rawLogTimeFormat = userConfig.getSet(self._RAW_DATA_LOG_SECTION, self._RAW_DATA_LOG_DATE_FORMAT_KEY, self._RAW_DATA_LOG_DATE_FORMAT_DEFAULT)
            self._rawLogFileNameFormat = userConfig.getSet(self._RAW_DATA_LOG_SECTION, self._RAW_DATA_LOG_FILE_NAME_FORMAT_KEY, self._RAW_DATA_LOG_FILE_NAME_FORMAT_DEFAULT)

        self._rawLogDirectory = self.getContext().Application.WorkingDirectory / self._rawLogRelativeDirectory

        if not self._rawLogDirectory.exists():
            self._rawLogDirectory.mkdir()

        self._updateRawDataLogCaller()

    def onFocusIn(self, event):
        if not self._periodicRefreshCaller.IsRunning:
            self._periodicRefreshCaller.start()

    def onFocusOut(self, event):
        if self._periodicRefreshCaller.IsRunning:
            self._periodicRefreshCaller.cancel()

    @showerror
    def _onScanStartClick(self):
        """ Called when the user clicks on the scan start button. Creates the selected scan using a scan factory service and start it afterwards. """
        scan = self.requestScanCreationService(self._selectedScanNameVariable.get()).createScan()

        if scan is not None:
            dlts = self.getDlts()

            if dlts is not None:
                dlts.startScan(scan)
                self.Scan = scan

    @showerror
    def _onScanAbortClick(self):
        """ Called when the user clicks the scan abort button. Trys to abort the current scan. """
        if self.Scan is not None and self.Scan.isRunning():
            self.Scan.abort()

    def _updateRawDataLogCaller(self):
        if self.RawDataLogEnabled:
            if not self._rawDataLogCaller.IsRunning:
                self._rawDataLogCaller.start()
        else:
            if self._rawDataLogCaller.IsRunning:
                self._rawDataLogCaller.cancel()

    def _logScanRawData(self):
        """ Called periodically if raw data log is enabled. Saves the array raw data contained by the current scan's scan images in a user-configurable format using save services. """
        try:
            if self.Scan is not None:
                for scanImageIndex, scanImage in enumerate(self.Scan.getScanImages()):
                    if len(self._scanImagesLoggedStateList) <= scanImageIndex:
                        self._scanImagesLoggedStateList.append(False)

                    if not self._scanImagesLoggedStateList[scanImageIndex] and (scanImage.isCompleted() or self.Scan.isFinished()):
                        self._scanImagesLoggedStateList[scanImageIndex] = True

                        saveService = self.requestSaveService(np.ndarray, self.SelectedRawLogFormat)

                        position = scanImage.getPosition()
                        size = scanImage.getSize()

                        name = "".join(map(lambda match: match[-1], re.findall("(^|\s)([A-Z])", scanImage.getName())))
                        if not name:
                            name = scanImage.getName()

                        date = scanImage.getScanDate()
                        dateString = date.strftime(self._rawLogTimeFormat) if date is not None else "#NA"

                        xmin = position[0]
                        xmax = xmin + size[0]
                        ymin = position[1]
                        ymax = ymin + size[1]

                        fileName = self._rawLogFileNameFormat.format(date = dateString, name = name, xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax,
                            z = scanImage.getZPosition(), xtilt = scanImage.getXTilt(), intensity = scanImage.getLaserIntensity(), index = scanImageIndex)

                        saveService.save(scanImage.getImageArray(), self._rawLogDirectory / fileName)
        except Exception as ex:
            logger.exception("Raw data logging has failed. Reason: %s", ex)

    def refresh(self):
        """ Called periodically. Checks the service-provided DLTS for any scans and refreshs the scan progress panel. """
        if self.Scan is None and self.IsDltsPresent:
            dlts = self.getDlts()

            if dlts is not None and dlts.Scan is not None:
                self.Scan = dlts.Scan

        self._scanProgressPanel.refresh()

# extension area

from dltscontrol.app.manifest import manifest

# applets
manifest.insert(Scanner, entry = "Scanner", root = True)


GIFTS = [
    'twelve Drummers Drumming, ',
    'eleven Pipers Piping, ',
    'ten Lords-a-Leaping, ',
    'nine Ladies Dancing, ',
    'eight Maids-a-Milking, ',
    'seven Swans-a-Swimming, ',
    'six Geese-a-Laying, ',
    'five Gold Rings, ',
    'four Calling Birds, ',
    'three French Hens, ',
    'two Turtle Doves, and ',
    'a Partridge in a Pear Tree.'
]

ORDINALS = [
    "first",
    "second",
    "third",
    "fourth",
    "fifth",
    "sixth",
    "seventh",
    "eighth",
    "ninth",
    "tenth",
    "eleventh",
    "twelfth"
]

def recite(start_verse, end_verse):
    return [build_verse(n) for n in range(start_verse, end_verse+1)]

def build_verse(verse):
    preface = (f"On the {ORDINALS[verse-1]} day of Christmas "
                "my true love gave to me: ")
    gifts = ''.join(GIFTS[len(GIFTS)-verse:])
    return ''.join([preface, gifts])


'''

Find the largest number less than N whose each digit is prime number
'''
# check for optimisation

def largestPrime(N):
    for i in range(N-1, 1, -1):
        currPrime = True
        a = i

        while a != 0:
            # counter+=1
            digit = a%10
            a = a//10

            if digit != 2 and digit != 5 and digit != 7:
                currPrime = False
                break

        if currPrime == True:
            return i

print(largestPrime(1000))


import os
import re

from io import BytesIO

import PIL
from PIL import Image

from config import CONFIG
from model import BlackListHash, Map, create_map
from webscrapper.network import request_file
from webscrapper.image import image_hash

class Post:
    def __init__(self, submission):
        self.submission = submission
        self.setters = [self.set_author, self.set_name, self.set_url, self.set_extension, self.set_timestamp, self.set_subreddit, self.set_image, self.set_image_hash, self.set_image_thumbnail, self.set_dimensions, self.set_square_dimensions]
        self.valid = True
        self.author = ""
        self.name = ""
        self.extension = ""
        self.subreddit = ""
        self.timestamp = 0
        self.url = ""
        self.image = None
        self.image_hash = ""
        self.thumbnail = None
        self.width = 0
        self.height = 0
        self.square_width = None
        self.square_height = None

        for setter in self.setters:
            setter()
            if not self.valid:
                break

    def set_author(self):
        self.author = self.submission.get("author", self.author)
        if not (CONFIG.MINIMUM_NAME_LENGTH < len(self.author) < CONFIG.MAXIMUM_NAME_LENGTH):
            self.valid = False
            return

    def set_name(self):
        self.name = self.submission.get("title", self.name)
        if not (CONFIG.MINIMUM_NAME_LENGTH < len(self.name) < CONFIG.MAXIMUM_NAME_LENGTH):
            self.valid = False
            return
        self.name = self.name.lower()
        self.name = re.sub(r"[^a-zA-Z]+", " ", self.name)
        self.name = re.sub(r" +", " ", self.name)
        self.name = re.sub(" $|^ ", "", self.name)
        self.name = " ".join([word.capitalize() for word in self.name.split(" ") if len(word) >= 3])

    def set_extension(self):
        url = self.submission["url"].upper()
        self.extension = re.search(r".*\.(JPG|PNG|JPEG)", url)
        if not self.extension:
            self.valid = False
            return
        self.extension = self.extension.group(1).upper()
        self.extension = self.extension if self.extension != "JPG" else "JPEG"

    def set_timestamp(self):
        self.timestamp = self.submission["created_utc"]

    def set_subreddit(self):
        self.subreddit = self.submission["subreddit"]

    def set_url(self):
        self.url = self.submission["url"]
        if not self.url:
            self.valid = False
            return

    def set_image(self):
        self.image = request_file(self.url, timeout=1)
        if self.image is None:
            self.valid = False
            return
        self.image = self.image.content
        if not (CONFIG.MINIMUM_IMAGE_LENGTH < len(self.image) < CONFIG.MAXIMUM_IMAGE_LENGTH):
            self.valid = False
            return
        self.image = BytesIO(self.image)
        try:
            self.image = Image.open(self.image)
        except PIL.UnidentifiedImageError:
            self.valid = False
            return

    def set_image_thumbnail(self):
        self.thumbnail = self.image.resize((CONFIG.THUMBNAIL_SIZE, CONFIG.THUMBNAIL_SIZE), Image.ANTIALIAS)

    def set_image_hash(self):
        self.image_hash = image_hash(self.image)
        if Map.query.filter_by(image_hash=self.image_hash).first() is not None or BlackListHash.query.filter_by(image_hash=self.image_hash).first() is not None:
            self.valid = False
            return

    def set_dimensions(self):
        self.width, self.height = self.image.size

    def set_square_dimensions(self):
        size = re.search(r"((?<!\d)\d{1,2}(?!\d))x((?<!\d)\d{1,2}(?!\d))", self.submission["title"])
        if not size:
            return
        self.square_width = size.group(1)
        self.square_height = size.group(2)

    def save(self):
        file_name = f"{self.image_hash}.{self.extension}"
        image_path = os.path.join(CONFIG.IMAGE_DIRECTORY, file_name)
        thumbnail_path = os.path.join(CONFIG.THUMBNAIL_DIRECTORY, file_name)
        self.image = self.image.convert("RGB")
        self.thumbnail = self.thumbnail.convert("RGB")
        self.image.save(os.path.join(os.path.dirname(CONFIG.app.instance_path), image_path))
        self.thumbnail.save(os.path.join(os.path.dirname(CONFIG.app.instance_path), thumbnail_path))
        create_map(vars(self), image_path, thumbnail_path)


import sys
from multiprocessing import Queue
from threading import Thread

K_TUP_LEN = 6
MATCH_POINTS = 4
transition = -1
transversion = -2

def read_fasta(fasta_file):
	file_in = open(fasta_file, "r")
	fasta_seq = []
	for line in file_in:
		if line[0] != ">":               # header lines start with '>'
			fasta_seq.append(line.strip())
	gene = ''.join(fasta_seq )
	return gene

def get_ktups(sequence, k):
	result = set()
	for i in range(0,len(sequence)-k+1):
		result.add(sequence[i:i+k])
	return result

def gap_rule(gap_len):
	return -(5 + gap_len*2)

def overlap_regions(search_string, subword_ktups, k):
	match_regions = []
	previous_region = None
	previous_region_score = None

	for i in range(0, len(search_string)-k+1):
		sub_search_string = search_string[i:i+k]
		match = False
		if sub_search_string in subword_ktups:
			match = True

		if match:
			if previous_region:
				previous_region_end = previous_region[1]
				gap = i - previous_region_end
				if gap > 1:
					if gap_rule(gap) + previous_region_score > 0:
						previous_region = (previous_region[0], i+k-1)
						previous_region_score = gap_rule(gap) + previous_region_score + MATCH_POINTS*k
					else:
						match_regions.append(previous_region)
						previous_region = (i, i+k-1)
						previous_region_score = MATCH_POINTS
				else:
					previous_region = (previous_region[0], i+k-1)
					previous_region_score = previous_region_score + MATCH_POINTS*(k+gap-1)
			else:
				previous_region = (i, i+k-1)
				previous_region_score = MATCH_POINTS

	if previous_region:
		match_regions.append(previous_region)

	return match_regions

def generate_global_memo(s, t):
	memo = [ [0 for i in range(len(s) + 1)] for j in range(len(t) + 1)]

	for i in range(len(s) + 1):
		memo[0][i] = -2 * i
	for j in range(len(t) + 1):
		memo[j][0] = -2 * j

	for i in range(1, len(t) + 1):
		for j in range(1, len(s) + 1):
			match = -1
			if t[i-1] == s[j-1]:
				match = 1
			memo[i][j] = max(memo[i-1][j] -2, memo[i][j-1] - 2, memo[i-1][j-1] + match)
	return memo

def global_traceback(memo, s, t):
	resultS = ""
	resultT = ""

	i = len(s)
	j = len(t)

	while i>=0 and j>=0:
		if i==0 and j==0:
			break
		elif i == 0:
			resultS = "-" + resultS
			resultT = t[j-1] + resultT
			j = j-1
		elif j == 0:
			resultT = "-" + resultT
			resultS = s[i-1] + resultS
			i = i-1
		else:
			if memo[i][j] == memo[i-1][j] - 2:
				resultT = '-' + resultT
				resultS = s[i-1] + resultS
				i = i-1
			elif (memo[i][j] == memo[i-1][j-1]-1 and s[i-1] != t[j-1]) or (memo[i][j] == memo[i-1][j-1]+1 and s[i-1]==t[j-1]):
				resultT = t[j-1] + resultT
				resultS = s[i-1] + resultS
				i = i-1
				j = j-1
			else:
				resultT = t[j-1] + resultT
				resultS = '-' + resultS
				j=j-1
	return (resultS, resultT)

def generate_k_band_memo(s, t, k):
	#s is along the rows and t is along the columns
	memo = [ [0 for i in range(len(t) + 1)] for j in range(len(s) + 1)]

	#Initialize row and column zero
	for i in range(k):
		memo[0][i] = -2 * i
	for j in range(k):
		memo[j][0] = -2 * j

	#Initialize diagonals with minimum integer
	for i in range(len(s) - k + 1):
		memo[i + k][i] = -sys.maxsize
	for j in range(len(t) - k + 1):
		memo[j][j+k] = -sys.maxsize

	t_len = len(t)

	#Fill in the k band
	for i in range(1, len(s) + 1):
		for j in range(1, 2*k):
			column = i - k + j
			if column>0 and column < t_len + 1:
				match = -1
				if s[i-1] == t[column-1]:
					match = 1
				memo[i][column] = max(memo[i-1][column] -2, memo[i][column-1] - 2, memo[i-1][column-1] + match)
	return memo

def print_2d(memo):
	for line in memo:
		print(line)

def alignment_score(resultS, resultT):
	score = 0
	for i in range(0,len(resultS)):
		if resultS[i] == resultT[i]:
			score += 1
		elif resultS[i] == "-":
			score -=2
		elif resultT[i] == "-":
			score -=2
		else:
			score -=1
	return score

def score_diagonal(search_string, subword_ktups, k):
	match_regions = []
	previous_region = None

	for i in range(0, len(search_string)-k+1):
		sub_search_string = search_string[i:i+k]
		match = False
		if sub_search_string in subword_ktups:
			match = True

		if match:
			if previous_region:
				previous_region_end = previous_region[1]
				gap = i - previous_region_end
				if gap > 1:
					match_regions.append(previous_region)
					previous_region = (i, i+k-1)
				else:
					previous_region = (previous_region[0], i+k-1)
			else:
				previous_region = (i, i+k-1)

	if previous_region:
		match_regions.append(previous_region)

	score = 0
	for region in match_regions:
		score = score + region[1] - region[0]

	return score

def alus_in_subword(alu, human_chromosome_19, i, search_segment_end, result_queue):

	subword_ktups = get_ktups(alu, K_TUP_LEN)
	chromosome_length = len(human_chromosome_19)
	alu_length = len(alu)

	num_alus = 0
	while i < (chromosome_length - alu_length - 1) and i < search_segment_end:
		score = score_diagonal(human_chromosome_19[i: i + alu_length], subword_ktups, K_TUP_LEN)
		if score < 150:
			i = i + alu_length
		elif score > 175:
			memo = generate_k_band_memo(alu,human_chromosome_19[i: i+alu_length], 10)
			aligned_strings = global_traceback(memo, alu, human_chromosome_19[i: i+alu_length])
			result_score = alignment_score(aligned_strings[0], aligned_strings[1])
			if result_score > 50:
				print(i, "of", chromosome_length, "got", num_alus)
				num_alus += 1
				i = i + alu_length
			i = i + 1
		else:
			i = i + 1
	result_queue.put(num_alus)

def main():
	mode = sys.argv[1]
	if mode not in ["serial", "parallel"]:
		print("Usage: python3 lab3.py [serial,parallel]")
		exit()

	human_chromosome_19 = read_fasta("human_chromosome_19.fasta")
	alu = "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAAAA"

	if mode == "parallel":
		thread_list = list()
		result_queue = Queue()

		for i in range(0, len(human_chromosome_19), 5000000):
			thread = Thread(target=alus_in_subword, args=(alu, human_chromosome_19, i, i + 5000000, result_queue))
			thread_list.append(thread)
			thread.start()

		for thread in thread_list:
			thread.join()

		total_alus = 0
		while not result_queue.empty():
			total_alus += result_queue.get()

		print("Total Alus found ", total_alus)
	else:
		result_queue = Queue()
		alus_in_subword(alu, human_chromosome_19, 0, len(human_chromosome_19), result_queue)
		print("Total Alus found ", result_queue.get())

	#To do keep track of overlapping ALUs maybe?

if __name__ == '__main__':
	main()


# RETO 25

comunidades = ["Madrid", "Aragón",
                    "Valencia", "Cataluña",
                    "Extremadura", "Castilla y León",
                    "Castilla La Mancha", "Asturias",
                    "Murcia", "Cantabria", "País Vasco",
                    "Andalucia"]

def ordenar_por_long(lst):
    lst = sorted(lst, key=len, reverse = True)
    print(lst)

ordenar_por_long(comunidades)


import numpy as np
import cv2
import thread

def input_thread(a):
    num = int(raw_input())
    a.append(num)

cv2.namedWindow("main",cv2.WINDOW_NORMAL)
cv2.resizeWindow("main",600,400)
cv2.moveWindow("main",0,0)
a = []
num = int(input())
while(1):
    if (num == 1):
        video = 'night.avi'
    elif (num == 2):
        video = 'sun.avi'
    else:
        video = 'turnado.avi'

        # Capture video from file
    cap = cv2.VideoCapture(video)
    frame_counter = 0
    a = []
    thread.start_new(input_thread, (a,))
    while(cap.isOpened() and a == []):
        ret, frame = cap.read()
        frame_counter += 1
        if frame_counter == cap.get(cv2.CAP_PROP_FRAME_COUNT):
                frame_counter = 0
                cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
        cv2.imshow("main",frame)
        if cv2.waitKey(25) and 0xFF == ord('q'):
            break
    cap.release()
    num = a[0]
    a = []
cv2.destroyWindow()


from mixers.jukebar_mixer_abstract import JukebarMixerAbstract

class JukebarMixerLinux(JukebarMixerAbstract):
    """
    Linux mixer class implementation.
    """

    def __init__(self):
        from pulsectl import Pulse
        self.pulse = Pulse('client1')

    def set_mute_all(self, mute):
        sink_input_list = self.pulse.sink_input_list()
        for sink in sink_input_list:
            self.pulse.mute(sink, mute)

    def set_mute_pid(self, mute, pid):
        sink_input_list = self.pulse.sink_input_list()
        for sink in sink_input_list:
            proplist = sink.proplist
            # for some reason sometimes the value is a string
            if proplist.get('application.process.id') in [pid, str(pid)]:
                self.pulse.mute(sink, mute)


'''

Engine: APE
Zone: Tirisfall Glades
Creature: Meven Korgal

'''

import arcemu
from arcemu import Unit

MEVEN_KORGAL_TEXTS = [
"These undead atrocities will be destroyed!",
"We must be vigilant to eradicate this plague!",
"Keep up the good work.  This scourge will be cleansed!",
"The Scarlet Crusade will scour these lands!",
"Let none with the foul taint of plague live!"
]

MEVEN_KORGAL_STATE = {}

NPC_ID_MEVEN_KORGAL = 1667

def MevenKorgal_onAIUpdate( unit, event ):
    guid = unit.getGUID()

    if guid not in MEVEN_KORGAL_STATE:
        MEVEN_KORGAL_STATE[ guid ] = 0

    state = MEVEN_KORGAL_STATE[ guid ]

    unit.sendChatMessage( arcemu.CHAT_MSG_MONSTER_YELL, arcemu.LANG_UNIVERSAL, MEVEN_KORGAL_TEXTS[ state ] )

    if state == 4:
            state = 0
    else:
            state = state + 1

    MEVEN_KORGAL_STATE[ unit.getGUID() ] = state

def MevenKorgal_onLoad( unit, event ):

    unit.RegisterAIUpdateEvent( 90000 )

arcemu.RegisterUnitEvent( NPC_ID_MEVEN_KORGAL, arcemu.CREATURE_EVENT_ON_LOAD, MevenKorgal_onLoad )
arcemu.RegisterUnitEvent( NPC_ID_MEVEN_KORGAL, arcemu.CREATURE_EVENT_ON_AIUPDATE, MevenKorgal_onAIUpdate )


#1번
def solution(id_list, report, k):

    data=[]
    for i in id_list:
        data.append([i])

    dict={}
    #딕셔너리
    for i in id_list:
        dict[i]=0
    report=list(set(report))
    for i in report:
        a,b=i.split()
        for j in range(len(id_list)):
            if data[j][0]==str(a):
                if b not in data[j]:
                    data[j].append(b)
                    dict[b]+=1
    for i in range(len(data)):
        data[i].append(0)

    for a,b in dict.items():
        if b>=k:
            for i in range(len(data)):
                for j in range(1,len(data[i])):
                    if a == data[i][j]:
                        data[i][-1]+=1
    ans=[]
    for i in range(len(data)):
        ans.append(data[i][-1])

    return ans

#2번
import string
def is_prime_number(x):
    print('x:',x)
    print(type(x))
    for i in range(2, x):
        # x가 해당 수로 나누어떨어진다면
        if x % i == 0:
            return False # 소수가 아님
    return True # 소수임

tmp = string.digits+string.ascii_lowercase
def convert(num, base) :
    q, r = divmod(num, base)
    if q == 0 :
        return tmp[r]
    else :
        return convert(q, base) + tmp[r]

def solution(n, k):
    s=convert(n,k)
    s=s.split('0')
    ans=0

    for i in s:
        if len(i)==0: continue
        if int(i)<2 : continue
        if is_prime_number(int(i)):
            ans+=1

    return ans

#3번
def solution(fees, records):
    answer = []
    car_in={}
    car_time={} #누적시간
    car_fee=[]
    for i in records:
        a,b,c=i.split() #들어온 시간, 차번호, 출입유무
        if b not in car_in.keys():
            car_in[b]=9999
            car_time[b]=0
        if c=='IN':
            d,e=map(int,a.split(':'))
            car_in[b]=d*60+e
        elif c=='OUT':
            d,e=map(int,a.split(':'))
            tmp=d*60+e
            car_time[b]+=(tmp-car_in[b])
            car_in[b]=9999
    print('car_in:',car_in)
    print('car_time:',car_time)
    #23:59분되도 안나간 차들 계산
    for a,b in car_in.items():
        if b!=9999:
            car_time[a]+=(23*60+59)-b
            car_in[a]=9999

    #요금계산
    for a,b in car_time.items(): #a=차번호 b=누적시간
        if b<fees[0]: #기본시간보다 적을때
            fee=fees[1]
        else:
            fee=fees[1] #기본요금
            b-=fees[0]
            if b%fees[2]>0:
                fee+=(b//fees[2]+1)*fees[3]
            else:
                fee+=(b//fees[2])*fees[3]
        answer.append([a,fee])
    answer.sort()
    ans=[]
    for i in range(len(answer)):
        ans.append(answer[i][1])

    return ans

#5.
shp=0
wol=0
def dfs(node,sheep, wolf,visited,graph,info):
    global shp, wol
    if sheep<=wolf:
        return
    for i in graph[node]:
        if visited[i]==True: continue
        visited[i]=True
        shp=sheep
        wol=wolf
        if info[i]==0: sheep+=1
        else : wolf+=1
        dfs(i,sheep,wolf,visited,graph,info)
        visited[i]=False
    return shp,wol

def solution(info, edges):
    global shp, wol
    answer = 0
    sheep=0
    wolf=0
    graph=[[] for i in range(len(info))]
    for i in edges:
        a,b=i[0],i[1]
        graph[a].append(b)
    print('graph:', graph)
    visited=[False]*len(info)
    shp,wol=dfs(graph[0][0],0,0,visited,graph,info)
    print('sheep,wolf',shp,wol)
    dfs(graph[0][1],shp,wol,visited,graph,info)
    ans=shp
    visited=[False]*len(info)
    dfs(graph[0][1],0,0,visited,graph,info)
    dfs(graph[0][0],shp,wol,visited,graph,info)
    if ans<shp:
        ans=shp
    ans+=1
    print(ans)
    return answer

구현,시뮬레이션/카카오1.py


from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
from flask import Flask, redirect, url_for, render_template, request
from dotenv import load_dotenv
import os
import requests

app = Flask(__name__)
load_dotenv()

API_ID = os.getenv("API_ID")
API_SECRET = os.getenv("API_SECRET")

@app.route("/")
def rende_home_page():

    try:
            return render_template('index.html')

            if __name__ == '__main__':
                app.run()
    except (ConnectionError, Timeout, TooManyRedirects) as e:
        print(e)

@app.route("/teams", methods=["POST", "GET"])
def rende_team_page():

    try:
        if request.method == "POST":

            url = "https://nba-player-individual-stats.p.rapidapi.com/players/team"

            team = request.form['team']

            querystring = {"name": f'{team}'}

            headers = {
                 'x-rapidapi-key': API_ID,
                  'x-rapidapi-host': API_SECRET
                  }

            response = requests.request("GET", url, headers=headers, params=querystring)

            dataName = json.loads(response.text)

            return render_template('team.html', len=len(dataName), dataName=dataName)

            if __name__ == '__main__':
                app.run()
    except (ConnectionError, Timeout, TooManyRedirects) as e:
        print(e)


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

' 一些政策网站的爬虫 '

__author__ = 'fslong'
__version__ = '0.0.1'

import json
import os,re

import pyquery,time,datetime
import requests,traceback

class Spider(object):
    def __init__(self):
        self.path = os.path.dirname(__file__)
        self.headers = {
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.18204',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language':
            'en-US,en,zh-CN;q=0.5',
            'Accept-Encoding':
            'gzip, deflate, br',
            'DNT':
            '1',
            'Connection':
            'keep-alive',
        }
        self.num = 0
        self.results = []
        self.params = {}
        self.cookies = {'Cookie': ''}
        self.newNewsNum=0
        self.newNews={}
        self.oldJsonData={}
        self.date=str(time.strftime("%Y-%m-%d", time.localtime()))
        yesterday=datetime.datetime.now()+datetime.timedelta(days=-1)
        self.yesterday=str(yesterday.strftime("%Y-%m-%d"))
        '''
        with open(os.path.join(os.path.dirname(__file__),'新公告.txt'),'w+',encoding='utf-8') as f:
            f.write('欢迎使用！\n')
        '''
        if os.path.isfile(os.path.join(os.path.dirname(__file__), 'news.json')):
            with open(os.path.join(os.path.dirname(__file__), 'news.json'), 'r', encoding='utf-8') as f:
                self.oldJsonData = json.load(f)
        self.results={}

class Cqsaisi(Spider):

    # 获取经信委通知：
    def getJxw(self):
        print('\n开始查找经信委网站信息:\n----------------------')
        jsonData = []

        def getData(page):
            self.url = 'http://wjj.cq.gov.cn/MoreList/MoreList.asp'
            self.params = {'pageno': page, 'intSTID': 6791}
            req = requests.get(self.url, params=self.params,
                               headers=self.headers, timeout=15)
            PQ = pyquery.PyQuery(req.text)
            data = PQ('body > table > tr > td > table > tr > td > table').items()

            for i in data:
                if '共' in i('tr td').text():
                    pass
                else:
                    text = ''
                    for j in i('tr td').items():
                        text += j.text()
                    href = i('tr td a').attr('href').replace(u'\\', u'/')
                    jsonData.append({'标题': text, '网址': href})
        print('经信委网站近期通知公告数据获取中，请稍等...')
        for i in range(8):
            getData(i+1)
        self.results['jxw']=jsonData
        print('经信委网站近期通知公告数据获取完毕，开始分析...')
        if self.oldJsonData!={} and self.oldJsonData.get('jxw','')!='':
            oldJsonData = self.oldJsonData.get('jxw','')
            m = 0
            newNews = []
            for i in jsonData:
                k = 0
                for j in oldJsonData:
                    if i['网址'] == j['网址']:
                        k += 1
                if k == 0:
                    m += 1
                    newNews.append({'标题': i['标题'], '网址': i['网址']})

            if m == 0:
                print('----------------------\n没有查找到新的通知公告！\n')
            else:
                print('----------------------\n找到了{0}条新纪录，如下：\n'.format(m))
                #self.saveNewNews('-------------------------------\n经信委网站新公告:\n',newNews)
                for i in newNews:
                    print('标题：', i['标题'], '网址：', i['网址'])
        else:
            print('没有找到本地数据，开始显示所有获取到的信息...')
            #self.saveNewNews('-------------------------------\n经信委网站新公告:\n',jsonData)
            newNews=jsonData
            for i in jsonData:
                print('标题：', i['标题'], '网址：', i['网址'])
        self.newNews['jxw']=newNews

    # 获取科技局通知：

    def getKjj(self):
        print('\n开始查找科技局网站信息:\n----------------------')
        jsonData = []

        def getData(clsId=230, PageIndex=2):
            self.url = 'http://www.cstc.gov.cn/Class.aspx'
            self.params = {'PageIndex': PageIndex, 'clsId': clsId}
            req = requests.get(self.url, params=self.params,
                               headers=self.headers, timeout=15)
            PQ = pyquery.PyQuery(req.text)
            cssChoose = '#ctl02 > table > tr > td > table > tr > td > span > table > tr > td > table >  tr > td > table >  tr'
            cssChoose2 = 'td:nth-child(2)'
            cssChoose3 = 'td:nth-child(3)'
            table = PQ(cssChoose).items()
            for i in table:
                if i(cssChoose2)('strong').text() == '':
                    if i(cssChoose2)('a').attr('href'):
                        jsonData.append(
                            {'标题': i(cssChoose2).text()+' '+i(cssChoose3).text(),
                             '网址': 'http://www.cstc.gov.cn'+str(i(cssChoose2)('a').attr('href'))
                             })
        print('科技局网站近期通知公告数据获取中，请稍等...')
        for i in range(8):
            getData(PageIndex=i+1)
        self.results['kjj']=jsonData
        print('科技局网站近期通知公告数据获取完毕，开始分析...')

        if self.oldJsonData!={} and self.oldJsonData.get('kjj','')!='':
            oldJsonData = self.oldJsonData.get('kjj','')
            m = 0
            newNews = []
            for i in jsonData:
                k = 0
                for j in oldJsonData:
                    if i['网址'] == j['网址']:
                        k += 1
                if k == 0:
                    m += 1
                    newNews.append({'标题': i['标题'], '网址': i['网址']})

            if m == 0:
                print('----------------------\n没有查找到新的通知公告！\n')
            else:
                print('----------------------\n找到了{0}条新纪录，如下：\n'.format(m))
                #self.saveNewNews('-------------------------------\n科技局网站新公告:\n',newNews)
                for i in newNews:
                    print('标题：', i['标题'], '网址：', i['网址'])
        else:
            print('没有找到本地数据，开始显示所有获取到的信息...')
            #self.saveNewNews('-------------------------------\n科技局网站新公告:\n',jsonData)
            newNews=jsonData
            for i in jsonData:
                print('标题：', i['标题'], '网址：', i['网址'])
        self.newNews['kjj']=newNews

    # 获取商务委员会数据：
    def getSwwyh(self):
        print('\n开始查找商务委员会网站信息:\n----------------------')
        jsonData = []

        def getData(categoryId=137, pageIndex=0):
            self.url = 'http://wsy.cq.gov.cn/api/directive/contentList'
            self.data = {'showParamters': True, 'categoryId': categoryId,'pageIndex':pageIndex,'count':18}
            req = requests.post(self.url, data=self.data,
                               headers=self.headers, timeout=15)
            json1=json.loads(req.text,encoding='utf-8')
            for i in json1['page']['list']:
                jsonData.append({
                    '标题':i['title'].strip()+' '+re.match(r'(\D.*?)(\d*-\d*-\d*)(\.*)',i['url']).group(2),
                    '网址':'http://wsy.cq.gov.cn'+i['url']
                })
        print('商务委员会网站近期通知公告数据获取中，请稍等...')
        for i in range(8):
            getData(pageIndex=i+1)
        print('商务委员会网站近期通知公告数据获取完毕，开始分析...')
        self.results['swwyh']=jsonData

        if self.oldJsonData!={} and self.oldJsonData.get('swwyh','')!='':
            oldJsonData = self.oldJsonData.get('swwyh','')
            m = 0
            newNews = []
            for i in jsonData:
                if i in oldJsonData:
                    pass
                else:
                    m += 1
                    newNews.append({'标题': i['标题'], '网址': i['网址']})

            if m == 0:
                print('----------------------\n没有查找到新的通知公告！\n')
            else:
                print('----------------------\n找到了{0}条新纪录，如下：\n'.format(m))
                #self.saveNewNews('-------------------------------\n商务委员会网站新公告:\n',newNews)
                for i in newNews:
                    print('标题：', i['标题'], '网址：', i['网址'])
        else:
            print('没有找到本地数据，开始显示所有获取到的信息...')
            newNews=jsonData
            #self.saveNewNews('-------------------------------\n商务委员会网站新公告:\n',jsonData)
            for i in jsonData:
                print('标题：', i['标题'], '网址：', i['网址'])

        self.newNews['swwyh']=newNews

# 获取发改委通知：

    def getFgw(self):
        print('\n开始查找发改委网站信息:\n----------------------')
        jsonData = []

        def getData(urlP=''):
            baseurl = 'http://www.cqdpc.gov.cn/xxgk/tzgg/index'
            self.url=baseurl+urlP+'.shtml'
            req = requests.get(self.url, headers=self.headers, timeout=15)
            PQ = pyquery.PyQuery(req.text)
            cssChoose = '.list > ul > li'
            lists = PQ(cssChoose).items()
            for i in lists:
                jsonData.append({
                    '标题':i.text().strip(),
                    '网址':'http://www.cqdpc.gov.cn'+i('a').attr('href')
                })

        print('发改委网站近期通知公告数据获取中，请稍等...')
        for i in ['','_2','_3','_4','_5']:
            getData(i)

        print('发改委网站近期通知公告数据获取完毕，开始分析...')

        if self.oldJsonData!={} and self.oldJsonData.get('fgw','')!='':
            oldJsonData = self.oldJsonData.get('fgw','')
            m = 0
            newNews = []
            for i in jsonData:
                k = 0
                for j in oldJsonData:
                    if i['网址'] == j['网址']:
                        k += 1
                if k == 0:
                    m += 1
                    newNews.append({'标题': i['标题'], '网址': i['网址']})

            if m == 0:
                print('----------------------\n没有查找到新的通知公告！\n')
            else:
                print('----------------------\n找到了{0}条新纪录，如下：\n'.format(m))
                #self.saveNewNews('-------------------------------\n发改委网站新公告:\n',newNews)
                for i in newNews:
                    print('标题：', i['标题'], '网址：', i['网址'])
        else:
            print('没有找到本地数据，开始显示所有获取到的信息...')
            newNews=jsonData
            #self.saveNewNews('-------------------------------\n发改委网站新公告:\n',jsonData)
            for i in jsonData:
                print('标题：', i['标题'], '网址：', i['网址'])
        self.results['fgw']=jsonData
        self.newNews['fgw']=newNews

    def saveNewNews(self,title,news):
        with open(os.path.join(os.path.dirname(__file__),'新公告.txt'),'a',encoding='utf-8') as f:
            f.write(title)
            for i in news:
                self.newNewsNum+=1
                f.write('序号：{0}  标题:{1}  网址:{2}\n'.format(self.newNewsNum,i['标题'],i['网址']))
    def saveAllNews(self):
        with open(os.path.join(os.path.dirname(__file__), 'news.json'), 'w+', encoding='utf-8') as f:
            json.dump(self.results, f, ensure_ascii=False, indent=4)

    def createHtml(self):
        htmlHead='<!DOCTYPE html><meta charset="utf-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge"><title>通知公告聚合</title><meta name="viewport" content="width=device-width, initial-scale=1">'
        htmlFoot=''
        htmlbody='

经信委网站公告：

'
        for i in self.results['jxw']:
            if str(i['标题']).endswith(self.date) or i not in self.oldJsonData.get('jxw',['test']) :
                htmlbody+='
【新】{1}

'.format(i['网址'],i['标题'])
            else:
                htmlbody+='
{1}

'.format(i['网址'],i['标题'])
        htmlbody+='

'
        htmlbody+='

科技局网站公告：

'
        for i in self.results['kjj']:
            if str(i['标题']).endswith(self.date) or i not in self.oldJsonData.get('kjj',['test']):
                htmlbody+='
【新】{1}

'.format(i['网址'],i['标题'])
            else:
                htmlbody+='
{1}

'.format(i['网址'],i['标题'])
        htmlbody+='

'
        htmlbody+='

商务委员会网站公告：

'
        for i in self.results['swwyh']:
            if str(i['标题']).endswith(self.date)  or i not in self.oldJsonData.get('swwyh',['test']):
                htmlbody+='
【新】{1}

'.format(i['网址'],i['标题'])
            else:
                htmlbody+='
{1}

'.format(i['网址'],i['标题'])
        htmlbody+='

'
        htmlbody+='

发改委网站公告：

'
        for i in self.results['fgw']:
            if str(i['标题']).endswith(self.date)  or i not in self.oldJsonData.get('fgw',['test']):
                htmlbody+='
【新】{1}

'.format(i['网址'],i['标题'])
            else:
                htmlbody+='
{1}

'.format(i['网址'],i['标题'])
        htmlbody+='

'
        return (htmlHead+htmlbody+htmlFoot)

if __name__ == '__main__':
    cqsaisi = Cqsaisi()
    try:
        cqsaisi.getJxw()
    except:
        print('经信委数据爬取出错，请联系作者处理。')
        traceback.print_exc()
    try:
        cqsaisi.getKjj()
    except:
        print('科技局数据爬取出错，请联系作者处理。')
    try:
        cqsaisi.getSwwyh()
    except:
        print('商务委员会数据爬取出错，请联系作者处理。')
    try:
        cqsaisi.getFgw()
    except:
        print('发改委数据爬取出错，请联系作者处理。')
    cqsaisi.saveAllNews()

    with open(os.path.join(os.path.dirname(__file__), '新闻.html'), 'w+', encoding='utf-8') as f:
        f.write(cqsaisi.createHtml())

    print('\n-------------------------\n新通知公告获取完毕，谢谢使用，可以打开《新闻.html》查看本次获取到的新通知。')
    input('-------------------------\n请按回车键退出...')


#! /usr/bin/env python
#
def r8vec_dot_product ( n, v1, v2 ):

#*****************************************************************************80
#
## R8VEC_DOT_PRODUCT finds the dot product of a pair of R8VEC's.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    04 February 2016
#
#  Author:
#
#    John Burkardt
#
#  Parameters:
#
#    Input, real V1(N), V2(N), the vectors.
#
#    Output, real VALUE, the dot product.
#

  value = 0.0
  for i in range ( 0, n ):
    value = value + v1[i] * v2[i]

  return value

def r8vec_dot_product_test ( ):

#*****************************************************************************80
#
## R8VEC_DOT_PRODUCT_TEST tests R8VEC_DOT_PRODUCT.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    04 February 2016
#
#  Author:
#
#    John Burkardt
#
  import platform
  from r8vec_uniform_01 import r8vec_uniform_01
  from r8vec2_print import r8vec2_print

  print ( '' )
  print ( 'R8VEC_DOT_PRODUCT_TEST:' )
  print ( '  Python version: %s' % ( platform.python_version ( ) ) )
  print ( '  R8VEC_DOT_PRODUCT computes the dot product of two R8VEC\'s.' )

  n = 10
  seed = 123456789
  v1, seed = r8vec_uniform_01 ( n, seed )
  v2, seed = r8vec_uniform_01 ( n, seed )
  r8vec2_print ( n, v1, v2, '  V1 and V2:' )

  value = r8vec_dot_product ( n, v1, v2 )

  print ( '' )
  print ( '  V1 dot V2 = %g' % ( value ) )
#
#  Terminate.
#
  print ( '' )
  print ( 'R8VEC_DOT_PRODUCT_TEST:' )
  print ( '  Normal end of execution.' )
  return

if ( __name__ == '__main__' ):
  from timestamp import timestamp
  timestamp ( )
  r8vec_dot_product_test ( )
  timestamp ( )


# Number guessing game in python
import random

def number_guessing():
    # our random number
    system_number = random.randint(0, 10)

    # get user number
    user_number = int(input("Enter an integer number! : "))

    # Keep the program going as long as the answer is wrong
    while(user_number != system_number):
        # generate random numbers
        system_number = random.randint(0, 10)
        print(system_number)

        #user guessed number
        user_number = int(input("Enter an integer number! : "))

        if(user_number!=system_number):
            print("Wrong guess Try Again! ")
            print(f"The correct number was { system_number } but you gave us { user_number }")

        #if(user_number==system_number):
            #break

    else:
        print("CONGRATULATIONS! You win!")

number_guessing()


# Write the solution for "Filter Vowels".

# open file and read in the words
with open("inputs/vowels.txt", "r") as f:
    words = f.read().splitlines()

vowels = {"a", "e", "i", "o", "u"}

# filter out the vowels
res = 0
for i in words:
    for j in i:
        if j.lower() in vowels:
            res += 1

# write the output to a file
file_name = f"vowels-{res}.txt"
with open(f"outputs/{file_name}", "w") as f:
    f.write("\n".join(words))


import json
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import random
import torch
from dqn import DQN, Agent
import json

uri = "mongodb+srv://IMaster:Password@indexmaster.epnwmxt.mongodb.net/?retryWrites=true&w=majority"

client = MongoClient(uri, server_api=ServerApi('1'))

db = client['IndexMaster']
collection = db['DatasetCatalog']

with open('train_workload_1.json', 'r') as json_file:
    query_attributes_list = json.load(json_file)

training_dataset = []

state_dim = 5  # Dimension of the state/query
action_dim = 5  # Number of possible actions
    # Load the saved model architecture
model = DQN(state_dim, action_dim)
    # Load the model's state dictionary
model.load_state_dict(torch.load('trained_model.pth'))

model.eval()

state_dim = 5 # Dimension of the state/query
action_dim = 5  # Number of possible actions
learning_rate = 0.005
discount_factor = 0.95
    # Initialize the agent
agent = Agent(state_dim, action_dim, learning_rate, discount_factor)

for i in range(len(query_attributes_list)):

    query_attributes = query_attributes_list[i]

    try :
        next_state = query_attributes_list[i+1]
    except IndexError:
        next_state = query_attributes_list[0]
    #query_list = [str(value) for value in query.values()]
    #query_list = [hash(value) % state_dim for value in query_list]
    mongodb_selected_index = random.choice(['passport_number_1', 'email_1', 'first_name_1_last_name_1','address_text','job_title_1_company_1'])
    model_selected_index = agent.select_action(query_attributes,mongodb_selected_index)

    query_result = collection.find(query_attributes).hint(mongodb_selected_index)

    performance_metric = query_result.explain()["executionStats"]["executionTimeMillis"]

    query_result = collection.find(query_attributes).hint(model_selected_index)

    performance_metric2 = query_result.explain()["executionStats"]["executionTimeMillis"]

    sample = {
        'state': query_attributes,
        'action - MongoDB auto': mongodb_selected_index,
        'action - Model' : model_selected_index,
        'reward - MongoDB auto': performance_metric,
        'reward - Model': performance_metric2,
    }

    training_dataset.append(sample)

    print(i,"done")

with open('evaluation.json', 'w') as json_file:
    json.dump(training_dataset, json_file, indent=4)

client.close()


# python3
# -*- coding:utf-8 -*-
"""
"""
# ------------------------------------------------------------------------------------------------------------------------------------------
import logging
import cv2
from cv2.typing import MatLike
from typing import TYPE_CHECKING, Any, Union
from config import Config
# ------------------------------------------------------------------------------------------------------------------------------------------
logger:logging.Logger = logging.getLogger("motion")
# ------------------------------------------------------------------------------------------------------------------------------------------
class MotionDetector:
    def __init__(self, cfg:Config):
        self.mog = cv2.createBackgroundSubtractorMOG2()
        self.threshold = cfg.motion_detection.get('threshold', 1000)
        self.mask_img:Union[None,MatLike] = None
        self.mask_width:int = cfg.motion_detection.get('width', 0)
        self.mask_height:int = cfg.motion_detection.get('height', 0)
        mask_img_name = cfg.motion_detection.get('mask', None)
        if mask_img_name:
            self.mask_img = cv2.imread(mask_img_name)
            self.mask_width = self.mask_img.shape[1]
            self.mask_height = self.mask_img.shape[0]
            logger.info("masking with image '%s' with size %s x %s", mask_img_name, self.mask_width, self.mask_height)

    def on_first_frame(self, frame:MatLike):
        width = frame.shape[1]
        height = frame.shape[0]
        if self.mask_width == 0:
            if width > 640:
                self.mask_width = 576
                self.mask_height = self.mask_width * (width / height)
            else:
                self.mask_width = width
                self.mask_height = height
        logger.info('detection frame size %s x %s', self.mask_width, self.mask_height)

    def __call__(self, frame:MatLike)->bool:
        frame = cv2.resize(frame, dsize=(self.mask_width, self.mask_height), interpolation=cv2.INTER_LINEAR)
        if self.mask_img is not None:
            frame = cv2.bitwise_and(frame, self.mask_img, mask=None)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        fgmask = self.mog.apply(gray)
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
        fgmask = cv2.erode(fgmask, kernel, iterations=1)
        fgmask = cv2.dilate(fgmask, kernel, iterations=1)

        contours, _unused = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        for contour in contours:
            # Ignore small contours
            if cv2.contourArea(contour) < self.threshold:
                continue
            return True
        return False

    def cleanup(self):
        logger.info('starting cleanup')
        logger.debug('finished cleanup')


filename = "D:/Harsh/vscodes python/cgschool/student.txt"
f = open(filename, "r")  # make sure to replace '\' with '/' in above string
r = f.read()
a = r.split("\n")
l = len(a)
s="harsh"
for i in range(5):
#     for j in range(1):
#         print(a[i].split()[j],a[i].split()[j+1])
    print(f"my name is{i}")


# 20

# 22 else가 없다면 같이 실행이 된다.
number = 30

if number % 2 == 0: print('입력한 값은 짝수입니다.')
else: print('입력한 값은 홀수입니다.')

# 25 - 복권 발행
# 난수 생성시 random 모듈의 randrange(start, end-1)
import random as rnd
your_key = int(input('세자리의 번호 입력'))
lotto_key = rnd.randrange(111, 1000)

if your_key == lotto_key:
    print('복권 당첨')
else: print('꽝')

# 26 - 연봉/결혼 여부 세금 계산
salary = int(input(' 연봉은?'))
isMarried = int(input('결혼 여부(0:미혼 1:기혼)'))
tax = 0

if isMarried:
    if salary < 6000: tax = salary * 0.15
    else: tax = salary * 0.35
else:
    if salary < 3000: tax = salary * 0.1
    else: tax = salary * 0.25

print(salary, isMarried, tax)

# 27 - 윤년 여부 2020 2024 윤년
year = int(input("연도를 입력하시오"))
if ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):
    print(f'{year}년은 윤년입니다.')
else:print(f'{year}년은 윤년이 아닙니다.')


import pytest

from basilisk import thermal

def test_thermalEmitter():
    """
    This test checks that the heat emitted from a surface is calculated correctly

    It uses user-set messages to simulate connected temperature. It sets non-default parameters
    """

    UT = thermal.TemperatureMsgClass()
    UTData = thermal.TemperatureMsg()
    UTData.temperature = 100
    UTw = UT.get_writer()
    UTw(UTData)
    UTr = UT.get_reader()

    e = thermal.ThermalEmitter()
    e.readUpstreamTemperature = UT.get_reader()
    e.area = 2
    e.epsilon = 0.8
    e.UpdateState(0)
    er = e.outputHeatRateMsg.get_reader()

    expectedResult = thermal.sigma_SB * e.epsilon * e.area * UTr().temperature**4
    assert er().heatRate == pytest.approx(expectedResult)

if __name__ == "__main__":
    test_thermalEmitter()


import random

rock = 'Rock'
scissors = 'Scissors'
paper = 'Paper'

while True:
    player_choice = input("Please choose 'r' for rock, 's' for scissors and 'p' for paper: ").lower()
    if player_choice == 'r':
        player_choice = rock
    elif player_choice == 's':
        player_choice = scissors
    elif player_choice == 'p':
        player_choice = paper
    else:
        print('Wrong choice ! Please try again !')
        continue

    computer_choice = random.randint(1, 3)

    if computer_choice == 1:
        computer_choice = rock
    elif computer_choice == 2:
        computer_choice = scissors
    elif computer_choice == 3:
        computer_choice = paper
    print(f'Computer\'s choose : {computer_choice}')
    while True:
        flag = False
        if player_choice == rock and computer_choice == scissors or \
                player_choice == scissors and computer_choice == paper or \
                player_choice == paper and computer_choice == rock:
            print('You win !')
        elif player_choice == computer_choice:
            print('Draw ! \nChoose again !')
            flag = True
            break
        else:
            print('You lose ! \nTry again')
        answer = input('Do you want to continue "Yes" or "No"? ').lower()
        if answer == "yes":
            flag = True
            break
        elif answer == 'no':
            print('Hope to see you soon !')
            exit()
        else:
            while True:
                print('Incorrect answer !')
                answer = input('Do you want to continue "Yes" or "No"? ').lower()
                if answer == 'yes' or answer == 'no':
                    break
        break
    if flag:
        continue


from datetime import datetime, timedelta
from pytz import reference

def is_bst(time_tup):
    return reference.LocalTimezone().tzname(time_tup) == "BST"

def adjust_timestamp_for_api_bst_bug(
    updated_time: str, updated_date: str
) -> (str, str):
    """
    Take a time represented as HH:MM string, and return the same format string with 1 hour subtracted
    :param updated_time: str
    :param updated_date: str
    :return new_time: str
    """

    # The bug only happens during BST
    combined_time = f"{updated_time}-{updated_date}"
    time_tup = datetime.strptime(combined_time, "%H:%M-%d/%m/%Y")

    if is_bst(time_tup):
        print("Is BST")
        new_combined_time = time_tup - timedelta(hours=1)
        new_time = datetime.strftime(new_combined_time, "%H:%M")
        new_date = datetime.strftime(new_combined_time, "%d/%m/%Y")
        return new_time, new_date

    else:
        print("Not BST")
        return updated_time, updated_date


from typing import cast
from pddshapley import PartialDependenceDecomposition
from pddshapley.sampling import RandomSubsampleCollocation,\
      IndependentConditioningMethod, GaussianConditioningMethod,\
      KernelConditioningMethod
from experiments.util import eval
import numpy as np
from experiments.synthetic.multilinear_polynomial import RandomMultilinearPolynomial
import pandas as pd
from sklearn.model_selection import train_test_split

if __name__ == "__main__":
    # Generate input data
    num_features = 3
    np.random.seed(0)
    #num_features = 2
    mean = np.zeros(num_features)
    cov = np.diag(np.ones(num_features))
    X = np.random.multivariate_normal(mean, cov, size=1000).astype(np.float32)
    X_df = pd.DataFrame(X, columns=[f"feat_{i}" for i in range(num_features)])

    # Create model and compute ground truth Shapley values
    #model = RandomMultilinearPolynomial(num_features, [-1, -1, 5])
    model = RandomMultilinearPolynomial(num_features, [-1, -1, -1])
    print(model)
    y = model(X)
    X_train, X_test, y_train, y_test = train_test_split(X_df, y, test_size=0.9)
    X_train = cast(pd.DataFrame, X_train)
    X_test = cast(pd.DataFrame, X_test)

    true_values = np.expand_dims(model.shapley_values(X_test.to_numpy()), -1)

    # Compute Shapley values using PDD-SHAP
    decomposition = PartialDependenceDecomposition(
            model,
            collocation_method=RandomSubsampleCollocation(),
            conditioning_method=IndependentConditioningMethod(X_train),
            #conditioning_method=GaussianConditioningMethod(X_train),
            #conditioning_method=KernelConditioningMethod(X_train.values, sigma_sq=0.1),
            estimator_type="knn", est_kwargs={"k": 3})
            #estimator_type="gp")
    decomposition.fit(X_train, max_size=2)
    pdd_values = decomposition.shapley_values(X_test, project=False,
                                              partial_ordering=[[0], [1]])

    eval.print_metrics(pdd_values, true_values, "PDD-SHAP", "Ground truth")

    print()
    for key in decomposition.components.keys():
        print(key)


from math import *
t=int(input())
while t>0:
    n=int(input())
    lst=[]
    for i in range(n):
        p=input()
        lst.append(p)
    a=0
    b=0
    for i in range(n):
        c=lst[i]
        lst1=list(c)
        d=0
        for j in range(n):
            if(lst1[j]=='*'):
                a=i+1
                b=j+1
                d=1
                break

        if d==1:
            break

    e=ceil(n/2)
    f=abs(e-a)+abs(e-b)
    print(f)

    t=t-1