import random

def read_input_number() -> int:
    """Метод предлагает пользователю ввести в консоль целое число, обрабатывает ввод и возвращает это число.

    Returns:
        input_number: введенное число.
    """

    input_correctly = False
    input_number = None

    while input_correctly is False:
        try:
            input_number = int(input("Введите число: "))
            input_correctly = True

        except ValueError:
            print('Введите, пожалуйста число!')
            input_correctly = False

    return input_number

def compare_numbers(input_number: int, hidden_number: int) -> bool:
    """Метод сравнивает два целых числа и возвращает результат сравнения

    Args:
        input_number: введенное пользователем число.
        hidden_number: число сгенерированное системой, которое должен угадать пользователь.

    Returns:
        win: результат сравнения двух переменных
    """
    if input_number == hidden_number:
        print('Победа!')
        win = True

    else:
        print('Введенное число больше загаданного') if input_number > hidden_number \
            else print('Введенное число меньше загаданного')
        win = False

    return win

def game(counter=3, hidden_number=None):
    """Метод считывает с консоли вводимое число и сравнивает его с hidden_number.

    Args:
        counter: количество попыток угадать число.
        hidden_number: загаданное число, с которым будет сравниваться ответ пользователя.

    """

    win = False

    if hidden_number is None:
        hidden_number = random.randrange(0, 10)

    print('Система сгенерировала случайное число. Количество попыток: {n}'.format(n=str(counter)))

    while win is False and counter != 0:
        input_number = read_input_number()

        win = compare_numbers(input_number=input_number, hidden_number=hidden_number)

        if win is False:
            counter -= 1
            print(f'Осталось попыток: {counter}')
    print('Загаданное число: ' + str(hidden_number))

def read_input_continue_game() -> str:
    """Метод выводит в консоль предложение продолжить игру и возвращает введенный ответ

    Returns:
        input_response: введенное пользователем значение.
    """
    input_correctly = False

    while input_correctly is False:
        input_response = str(input('Продолжить? (y/n): '))

        if input_response != 'y' and input_response != 'n':
            print('Ошибка. Попробуйте ввести один из предложенных вариантов.')

        else:
            input_correctly = True

            return input_response


from django import template
from google.appengine.api import images

register = template.Library()

@register.simple_tag
def get_resized_image(image, size):
	blob_key = str(image.blobstore_info.key())
	thumbnail_picture_url = images.get_serving_url(blob_key, size)
	return thumbnail_picture_url


import cv2
import numpy as np
from utils import PriorBox, py_cpu_nms, decode, decode_landm

class RetinaDetection:
    def __init__(self, cfg, model_path="./checkpoints/faceDetector_RFB.onnx"):
        self.cfg = cfg
        self.model_path = model_path
        self.load(self.model_path)

    def load(self, model_path):
        self.model = cv2.dnn.readNetFromONNX(model_path)

    def forward(self, image):
        """image: should be BGR image"""
        img, scale, resize, im_height, im_width = self.preprocess(image)
        self.model.setInput(img)
        loc, conf, landms = self.model.forward(["output0", "532","531"])
        #post_process
        priorbox = PriorBox(self.cfg, image_size=(im_height, im_width))
        prior_data = priorbox.forward()
        boxes = decode(np.squeeze(loc,axis=0), prior_data, self.cfg['variance'])
        boxes = boxes * scale / resize
        scores = np.squeeze(conf, axis=0)[:, 1]
        landms = decode_landm(np.squeeze(landms, axis=0), prior_data, self.cfg['variance'])
        scale1 = np.array([img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                                img.shape[3], img.shape[2], img.shape[3], img.shape[2],
                                img.shape[3], img.shape[2]])
        landms = landms * scale1 / resize
        # ignore low scores
        inds = np.where(scores > self.cfg["confidence_threshold"])[0]
        boxes = boxes[inds]
        landms = landms[inds]
        scores = scores[inds]

        # keep top-K before NMS
        order = scores.argsort()[::-1][:self.cfg["top_k"]]
        boxes = boxes[order]
        landms = landms[order]
        scores = scores[order]

        # do NMS
        dets = np.hstack((boxes, scores[:, np.newaxis])).astype(np.float32, copy=False)
        keep = py_cpu_nms(dets, self.cfg["nms_threshold"])
        # keep = nms(dets, args.nms_threshold,force_cpu=args.cpu)
        dets = dets[keep, :]
        landms = landms[keep]

        # keep top-K faster NMS
        dets = dets[:self.cfg["keep_top_k"], :]
        landms = landms[:self.cfg["keep_top_k"], :]

        dets = np.concatenate((dets, landms), axis=1)
        return dets

    def preprocess(self,img):
        target_size = self.cfg["long_side"]
        max_size = self.cfg["long_side"]
        im_shape = img.shape
        im_size_min = np.min(im_shape[0:2])
        im_size_max = np.max(im_shape[0:2])
        resize = float(target_size) / float(im_size_min)
        # prevent bigger axis from being more than max_size:
        if np.round(resize * im_size_max) > max_size:
            resize = float(max_size) / float(im_size_max)
        if self.cfg["origin_size"]:
            resize = 1
        if resize != 1:
            img = cv2.resize(img, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR)
        im_height, im_width, _ = img.shape
        scale = np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
        img -= (104, 117, 123)
        img = img.transpose(2, 0, 1)
        img = np.expand_dims(img, axis=0)
        return img, scale, resize, im_height, im_width


#!/usr/bin/env python
"""BINF 690 | Annotation Project - Driver Menu
Main menu driver for all annotation options
run this menu to get user prompts and annotate your genes

Requirements:
    this file assumes that it is in the main directory,
    with two sub directorys for
    1. API_dir, with the API scripts housed in it
    2. Input_Options with the UI and input drivers in it
"""

### Import Packages
import sys
import re
from API_dir.API_Class import API
from Input_Options.UserInput import UserInput
from Input_Options import input_options
from Input_Options import UserInput_Menus

### Initialize Classes
inputIDOpts = input_options.inputIDOpts
inputSourceFormatOpts = input_options.inputSourceFormatOpts
inputOutputFormatOpts = input_options.inputOutputFormatOpts

UIn = UserInput()
UIn.__init__()

API_Caller = API()
API_Caller.__init__()

### def a invalid menu option class
class InvalidMenuOption(Exception):
    pass

### Run initial Menu
UIn.setUploadType(UserInput_Menus.inputTypeMenu())

### Main Menu Looper
while True:
    # initial try-er
    try:
        #############################################
        ###### Check the input type for errors ######
        if (UIn.getUploadType() == 0):
            break
            sys.exit(0)

        elif (1 <= UIn.getUploadType() <= 2):
            ##################################
            ##### Get the Gene ID Inputs #####
            if (UIn.getUploadType() == 1):
            ### run submenu for gene ID input
                UIn.setGeneID(UserInput_Menus.inputIDString())

            ### run submenu for multiple gene IDs
            elif (UIn.getUploadType() == 2):
                print("Please input your IDs below seperated by either spaces or new line characters")
                print("After we read in your list, please review it to make sure everything looks okay before moving forward.")
                multiple_gene_input = UserInput_Menus.inputIDString()
                multiple_gene_input = re.split(r"\n|\s",multiple_gene_input)

                print("Okay, we got {N} IDs from you. They were:\n\t {inlist}\n"
                      .format(N=len(multiple_gene_input),
                              inlist=(multiple_gene_input)))
                print("Does everything look okay? Enter Y for 'Yes' or N for 'No'")
                input_confirmation = raw_input("  Y/N: ")

                if (input_confirmation.upper()=="Y"):
                    pass
                elif(input_confirmation.upper()=="N"):
                    print("no worries, let's try again.")
                    raise InvalidMenuOption()
                else:
                    print("your input didn't make sense, let's start over.")
                    raise InvalidMenuOption()

            ##################################
            ##### Get the Gene ID Format #####
            ### run the user input menu
            UIn.setIDFormat(UserInput_Menus.inputIdFormatMenu())

            ### check the input for the next menu
            # if 0, back to the main menu
            if (UIn.getIDFormat() == 0):
                print("going back to the main menu!\n\n")
                UIn.setUploadType(UserInput_Menus.inputTypeMenu())
            # if within the range of options
            elif(1 <= UIn.getIDFormat() <= 6):
                ###################################
                ##### get the output file info ####
                OutputFileDetails = UserInput_Menus.inputOutputFormatMenu()

                # check logic to see if they have a correctly formatted input
                if (OutputFileDetails[0] == 0):
                    print("going back to the main menu!\n\n")
                    UIn.setUploadType(UserInput_Menus.inputTypeMenu())

                elif(1 <= OutputFileDetails[0] <= 3):
                    # set the outfile format
                    UIn.setOutFileFormat(OutputFileDetails[0])
                    # set the outdir
                    UIn.setOutFileDir(OutputFileDetails[1])
                    # set the out filename
                    UIn.setOutFileName(OutputFileDetails[2])
                else:
                    print("The output format was not in the list, please try again.")
                    raise InvalidMenuOption()

                ############################################
                ##### run submenu for Annotation Souce  ####
                UIn.setAnnotationSource(UserInput_Menus.inputAnnotationSourceMenu())
                ## back to main menu
                if (UIn.getAnnotationSource() == 0):
                     UIn.setUploadType(UserInput_Menus.inputTypeMenu())

                elif(1 <= UIn.getAnnotationSource() <= 5):

                    ####################################################
                    ##### get the annotations for a single gene ID  ####
                    if (UIn.getUploadType() == 1):
                        print("Okay! Hang tight while the annotation(s) get extracted! \n Progress:  \n\t"),
                        # run the retriever to get the data
                        OutData = UIn.runAnnotationRetriever()
                        # output the data
                        UserInput_Menus.WriteOutputFile(OutData, UIn.getOutFileFormat(), UIn.getOutFileDir(), UIn.getOutFileName())
                        # write a confirmation message
                        print("""\nYour input gene {gene} that is formatted as {GIS} was searched in {AnS} and output as a {OUTF} file\n"""
                                  .format(gene = UIn.getGeneID(),
                                          GIS = inputIDOpts[UIn.getIDFormat()][0],
                                          AnS = inputSourceFormatOpts[UIn.getAnnotationSource()][1],
                                          OUTF = inputOutputFormatOpts[UIn.getOutFileFormat()][1]
                                          )
                            )

                    ####################################################
                    ##### get the annotations for multiple gene IDs  ####
                    elif (UIn.getUploadType() == 2):
                        # print the confirmation message
                        print("Okay! Hang tight while the annotation(s) get extracted! \n Progress:  \n\t"),

                        # preset lists to fill in a loop through the inputs
                        OutData_inputGeneId = []
                        OutData_Input_IdFormat = []
                        OutData_Output_AnnotationSource = []
                        OutData_Output_IdFormat = []
                        OutData_output_geneIDs = []
                        OutData_output_annotation = []

                        # loop through the input ids retrieving data as needed
                        for ids in multiple_gene_input:
                            UIn.setGeneID(ids)
                            OutData = UIn.runAnnotationRetriever()
                            # fill in OutData Lists
                            OutData_inputGeneId.append(OutData["Input_GeneId"])
                            OutData_Input_IdFormat.append(OutData["Input_IdFormat"])
                            OutData_Output_AnnotationSource.append(OutData["Output_AnnotationSource"])
                            OutData_Output_IdFormat.append(OutData["Output_IdFormat"])
                            OutData_output_geneIDs.append(OutData["Output_GeneId"])
                            OutData_output_annotation.append(OutData["Annotation"])

                        # merge the output into a single dictionary for the output writer handler
                        OutData_Merged = {"Input_GeneId":OutData_inputGeneId,
                                        "Input_IdFormat":OutData_Input_IdFormat,
                                        "Output_AnnotationSource":OutData_Output_AnnotationSource,
                                        "Output_IdFormat":OutData_Output_IdFormat,
                                        "Output_GeneId":OutData_output_geneIDs,
                                        "Annotation":OutData_output_annotation
                                        }

                        ## confirmation message
                        print("""\nYour input genes {gene} that is formatted as {GIS} was searched in {AnS} and output as a {OUTF} file\n"""
                                  .format(gene = multiple_gene_input,
                                          GIS = inputIDOpts[UIn.getIDFormat()][0],
                                          AnS = inputSourceFormatOpts[UIn.getAnnotationSource()][1],
                                          OUTF = inputOutputFormatOpts[UIn.getOutFileFormat()][1]
                                          )
                            )
                        ### output  data
                        UserInput_Menus.WriteOutputFile(OutData_Merged, UIn.getOutFileFormat(), UIn.getOutFileDir(), UIn.getOutFileName())

                else:
                    print("The annotation selection was not in the list, please try again.")
                    raise InvalidMenuOption()

            # otherwise through an erro
            else:
                print("The input ID format was not in the list, please try again.")
                raise InvalidMenuOption()

        elif (UIn.getUploadType() == 3):
            InputFile = UserInput_Menus.inputUploadFileMenu()

            ### check for the number of inputs
            ## Gene IDs Only
            # if three columns then we don't have file output info
            if (len(InputFile[0])==3):
                ## print start message for user
                print("Okay, the IDs were uploaded! But we need some more information from you.\n")
                ## get the out file details
                OutputFileDetails = UserInput_Menus.inputOutputFormatMenu()
                ## set static variables for use
                UIn.setOutFileFormat(OutputFileDetails[0])      # set the outfile format
                UIn.setOutFileDir(OutputFileDetails[1])         # set the outdir
                UIn.setOutFileName(OutputFileDetails[2])        # set the out filename

                ## return to main menu option
                if (UIn.getOutFileFormat() == 0):
                    print("going back to the main menu!\n\n")
                    UIn.setUploadType(UserInput_Menus.inputTypeMenu())

                ## run the annotation retriever
                else:
                    # print start message for user
                    print("Okay! Hang tight while the annotation(s) get extracted! \n Progress:  ")
                    # setup blank lists to store looped data
                    OutData_inputGeneId = []
                    OutData_Input_IdFormat = []
                    OutData_Output_AnnotationSource = []
                    OutData_Output_IdFormat = []
                    OutData_output_geneIDs = []
                    OutData_output_annotation = []

                    # loop through lines in the input file
                    for InputLines in InputFile:
                        # set the variables from file
                        UIn.setGeneID(InputLines[0])                    # gene id to annotate
                        UIn.setIDFormat(int(InputLines[1]))             # gene id format
                        UIn.setAnnotationSource(int(InputLines[2]))     # target annotation source
                        # run annotation retriever
                        OutData = UIn.runAnnotationRetriever()
                        # fill in OutData Lists
                        OutData_inputGeneId.append(OutData["Input_GeneId"])
                        OutData_Input_IdFormat.append(OutData["Input_IdFormat"])
                        OutData_Output_AnnotationSource.append(OutData["Output_AnnotationSource"])
                        OutData_Output_IdFormat.append(OutData["Output_IdFormat"])
                        OutData_output_geneIDs.append(OutData["Output_GeneId"])
                        OutData_output_annotation.append(OutData["Annotation"])

                    ## merge looped output for file writing
                    OutData_Merged = {"Input_GeneId":OutData_inputGeneId,
                                    "Input_IdFormat":OutData_Input_IdFormat,
                                    "Output_AnnotationSource":OutData_Output_AnnotationSource,
                                    "Output_IdFormat":OutData_Output_IdFormat,
                                    "Output_GeneId":OutData_output_geneIDs,
                                    "Annotation":OutData_output_annotation
                                    }
                    ### output  data
                    UserInput_Menus.WriteOutputFile(OutData_Merged, UIn.getOutFileFormat(), UIn.getOutFileDir(), UIn.getOutFileName())

            ## Gene IDs + Output Information
            # if 6 columns then we have the output information s
            elif(len(InputFile[0])==6):
                print("Okay! Hang tight while the annotation(s) get extracted! \n Progress:  \n\t"),
                for InputLines in InputFile:
                    ## set variables required for loopin'
                    UIn.setGeneID(InputLines[0])                    # gene id to annotate
                    UIn.setIDFormat(int(InputLines[1]))             # gene id format
                    UIn.setAnnotationSource(int(InputLines[2]))     # target annotation source
                    UIn.setOutFileFormat(int(InputLines[3]))        # format of output file
                    UIn.setOutFileDir((InputLines[4]))              # directory for the output file
                    UIn.setOutFileName((InputLines[5]))             # name of output file
                    # run the annotation retrievers
                    OutData = UIn.runAnnotationRetriever()
                    # Output data
                    UserInput_Menus.WriteOutputFile(OutData, UIn.getOutFileFormat(), UIn.getOutFileDir(), UIn.getOutFileName())

            else:
                print("The input file did not have either 3 or 6 columns. Please check your input file.")
                print("the number of columns received was:  ", len(InputFile[0]))
                InvalidMenuOption()

        else:
            raise InvalidMenuOption()

        ### final output and leaver statement
        print("\nthank you for using the annotation interface!")
        break

    except:
        print("\nThere was an error, please try again.\n")
        UIn.setUploadType(UserInput_Menus.inputTypeMenu())


import pandas as pd
import matplotlib.pyplot as plt
import lux
import cudf

def convert_to_list(x):
    """
    "a" --> ["a"]
    ["a","b"] --> ["a","b"]
    """
    if type(x) != list:
        return [x]
    else:
        return x

def pandas_to_lux(df):
    from lux.core.frame import LuxDataFrame

    values = df.values.tolist()
    ldf = LuxDataFrame(values, columns=df.columns)
    return ldf

def get_attrs_specs(intent):
    if intent is None:
        return []
    spec_obj = list(filter(lambda x: x.value == "", intent))
    return spec_obj

def get_filter_specs(intent):
    if intent is None:
        return []

    spec_obj = list(filter(lambda x: x.value != "", intent))
    return spec_obj

def check_import_lux_widget():
    import pkgutil

    if pkgutil.find_loader("luxwidget") is None:
        raise Exception(
            "luxwidget is not installed. Run `pip install luxwidget' to install the Jupyter widget.\nSee more at: https://github.com/lux-org/lux-widget"
        )

def get_agg_title(clause):
    attr = str(clause.attribute)
    if clause.aggregation is None:
        if len(attr) > 25:
            return attr[:15] + "..." + attr[-10:]
        return f"{attr}"
    elif attr == "Record":
        return f"Number of Records"
    else:
        if len(attr) > 15:
            return f"{clause._aggregation_name.capitalize()} of {attr[:15]}..."
        return f"{clause._aggregation_name.capitalize()} of {attr}"

def check_if_id_like(df, attribute):
    import re

    # Strong signals
    # so that aggregated reset_index fields don't get misclassified
    high_cardinality = df.cardinality[attribute] > 500
    attribute_contain_id = re.search(r"id|ID|iD|Id", str(attribute)) is not None
    almost_all_vals_unique = df.cardinality[attribute] >= 0.98 * len(df)
    is_string = isinstance(df[attribute],cudf.core.column.string.StringMethods) #pd.api.types.is_string_dtype(df[attribute])
    if is_string:
        # For string IDs, usually serial numbers or codes with alphanumerics have a consistent length (eg., CG-39405) with little deviation. For a high cardinality string field but not ID field (like Name or Brand), there is less uniformity across the string lengths.
        if len(df) > 50:
            #if lux.config.executor.name == "PandasExecutor":
            sampled = df[attribute].sample(50, random_state=99)
#             else:
#                 from lux.executor.SQLExecutor import SQLExecutor

#                 sampled = SQLExecutor.execute_preview(df, preview_size=50)
        else:
            sampled = df[attribute]
        str_length_uniformity = sampled.apply(lambda x: type(x) == str and len(x)).std() < 3
        return (
            high_cardinality
            and (attribute_contain_id or almost_all_vals_unique)
            and str_length_uniformity
        )
    else:
        if len(df) >= 2:
            series = df[attribute]
            diff = series.diff()
            # if diff.iloc[1]*(diff.shape[0]-1)==diff.iloc[1:].sum():
            #     print("even soacle")
            # diff = cudf.DataFrame(diff.dropna())
            # print("different here", diff)
            # col = diff.columns[0]
            # df_compare = diff.reset_index()[col]
            # new_df = diff.loc[1].repeat(diff.shape[0])
            # new_df= new_df.reset_index()
            #if new_df[1].equals( df_compare):
            new_diff = diff.to_pandas()
            if all(new_diff.iloc[1:] == new_diff.iloc[1]):
                evenly_spaced = True
            else:  evenly_spaced = False

        else:
            evenly_spaced = True
        if attribute_contain_id:
            almost_all_vals_unique = df.cardinality[attribute] >= 0.75 * len(df)
        return high_cardinality and (almost_all_vals_unique or evenly_spaced)

def check_if_id_like_for_sql(df, attribute):
    return df.cardinality[attribute] >= 0.98 * len(df)

def like_nan(val):
    if isinstance(val, str):
        return val.lower() == "nan"
    elif isinstance(val, float) or isinstance(val, int):
        import math

        return math.isnan(val)

def like_geo(val):
    return isinstance(val, str) and val.lower() in {"state", "country"}

def matplotlib_setup(w, h):
    plt.ioff()
    fig, ax = plt.subplots(figsize=(w, h))
    ax.set_axisbelow(True)
    ax.grid(color="#dddddd")
    ax.spines["right"].set_color("#dddddd")
    ax.spines["top"].set_color("#dddddd")
    return fig, ax

def is_numeric_nan_column(series):
    if series.dtype == object:
        if series.hasnans:
            series = series.dropna()
        try:
            return True, series.astype("float")
        except Exception as e:
            return False, series
    else:
        return False, series


import torch
import torch.nn as nn
# from utils import load_state_dict_from_url
from meta_module import *

DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
    'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
    'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
    'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
    'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}

class BasicBlock(MetaModule):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1):
        super(BasicBlock, self).__init__()
        self.conv1 = MetaConv2d(
            in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = MetaBatchNorm2d(planes)
        self.conv2 = MetaConv2d(planes, planes, kernel_size=3,
                               stride=1, padding=1, bias=False)
        self.bn2 = MetaBatchNorm2d(planes)

        self.shortcut = MetaSequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = MetaSequential(
                MetaConv2d(in_planes, self.expansion*planes,
                          kernel_size=1, stride=stride, bias=False),
                MetaBatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        out += self.shortcut(x)
        out = F.relu(out)
        return out

class Bottleneck(MetaModule):
    expansion = 4

    def __init__(self, in_planes, planes, stride=1):
        super(Bottleneck, self).__init__()
        self.conv1 = MetaConv2d(in_planes, planes, kernel_size=1, bias=False)
        self.bn1 = MetaBatchNorm2d(planes)
        self.conv2 = MetaConv2d(planes, planes, kernel_size=3,
                               stride=stride, padding=1, bias=False)
        self.bn2 = MetaBatchNorm2d(planes)
        self.conv3 = MetaConv2d(planes, self.expansion *
                               planes, kernel_size=1, bias=False)
        self.bn3 = MetaBatchNorm2d(self.expansion*planes)

        self.shortcut = MetaSequential()
        if stride != 1 or in_planes != self.expansion*planes:
            self.shortcut = MetaSequential(
                MetaConv2d(in_planes, self.expansion*planes,
                          kernel_size=1, stride=stride, bias=False),
                MetaBatchNorm2d(self.expansion*planes)
            )

    def forward(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = F.relu(self.bn2(self.conv2(out)))
        out = self.bn3(self.conv3(out))
        out += self.shortcut(x)
        out = F.relu(out)
        return out

class ResNet(MetaModule):
    def __init__(self, block, num_blocks, num_classes=10, **kwargs):
        super(ResNet, self).__init__()
        self.in_planes = 64

        # print('happy!!!')
        # raise

        self.conv1 = MetaConv2d(3, 64, kernel_size=3,
                               stride=1, padding=1, bias=False)
        self.bn1 = MetaBatchNorm2d(64)
        self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
        self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
        self.linear = MetaLinear(512*block.expansion, num_classes)

    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1]*(num_blocks-1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return MetaSequential(*layers)

    def _forward_impl(self, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = F.avg_pool2d(out, 4) # (input, kernal_size)
        out = out.view(out.size(0), -1)
        out = self.linear(out)

        return out

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

class cResNet(ResNet):
    def __init__(self, arch, block, layers, **kwargs):
        super(cResNet,self).__init__( block, layers, **kwargs)
        self.name = arch
        self.loss = nn.NLLLoss()
        # self.
        # DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    def forward(self,loss):

        inp, out = loss.sample()
        # inp = Variable(inp.view(inp.size()[0], 32*32*3)).to(DEVICE)
        # inp = inp.to(self.DEVICE)
        # out = Variable(out).to(self.DEVICE)

        # cur_layer = 0
        # while f'mat_{cur_layer}' in self.layers:
        #     inp = self.activation(self.layers[f'mat_{cur_layer}'](inp))
        #     cur_layer += 1

        pred = F.log_softmax(self._forward_impl(inp), dim=1)
        l = self.loss(pred, out)
        return l

    def cal_test_acc(self, testloader):

        correct = 0
        total = 0
        with torch.no_grad():
            for i,data in enumerate(testloader):

                images, labels = data
                images, labels = images.to(DEVICE), labels.to(DEVICE)

                outputs = self._forward_impl(images)

                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()

        acc = 100 * correct / total

        print(f'\ntest acc is: {acc}\n')
        return acc

def _resnet(arch, block, layers, pretrained, progress, **kwargs):
    # model = ResNet(block, layers, **kwargs)
    model = cResNet(arch, block, layers, **kwargs).to(DEVICE)  #-wz
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(state_dict)
    return model

def resnet18(pretrained=False, progress=True, **kwargs):
    r"""ResNet-18 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
                   **kwargs)

def resnet34(pretrained=False, progress=True, **kwargs):
    r"""ResNet-34 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
                   **kwargs)

def resnet50(pretrained=False, progress=True, **kwargs):
    r"""ResNet-50 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress,
                   **kwargs)

def resnet101(pretrained=False, progress=True, **kwargs):
    r"""ResNet-101 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress,
                   **kwargs)

def resnet152(pretrained=False, progress=True, **kwargs):
    r"""ResNet-152 model from
    `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress,
                   **kwargs)

def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
    r"""ResNeXt-50 32x4d model from
    `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['groups'] = 32
    kwargs['width_per_group'] = 4
    return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3],
                   pretrained, progress, **kwargs)

def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
    r"""ResNeXt-101 32x8d model from
    `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['groups'] = 32
    kwargs['width_per_group'] = 8
    return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3],
                   pretrained, progress, **kwargs)

def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
    r"""Wide ResNet-50-2 model from
    `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_

    The model is the same as ResNet except for the bottleneck number of channels
    which is twice larger in every block. The number of channels in outer 1x1
    convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
    channels, and in Wide ResNet-50-2 has 2048-1024-2048.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['width_per_group'] = 64 * 2
    return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3],
                   pretrained, progress, **kwargs)

def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
    r"""Wide ResNet-101-2 model from
    `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_

    The model is the same as ResNet except for the bottleneck number of channels
    which is twice larger in every block. The number of channels in outer 1x1
    convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048
    channels, and in Wide ResNet-50-2 has 2048-1024-2048.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    kwargs['width_per_group'] = 64 * 2
    return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3],
                   pretrained, progress, **kwargs)

# Below two functions are early testing functions by Wenqing, deprecated
# def resnet18_conv1_3x3(pretrained=False, progress=True, **kwargs):
#     r"""ResNet-18 model from
#     `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_

#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     kwargs['kernel_size_first_layer'] = 3
#     return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
#                    **kwargs)
# def resnet34_conv1_3x3(pretrained=False, progress=True, **kwargs):
#     r"""ResNet-34 model from
#     `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_

#     Args:
#         pretrained (bool): If True, returns a model pre-trained on ImageNet
#         progress (bool): If True, displays a progress bar of the download to stderr
#     """
#     kwargs['kernel_size_first_layer'] = 3
#     return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress,
#                    **kwargs)


import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.integrate import odeint

# Simulation parameters
duration = 100  # Duration of the simulation in hours
time_step = 1  # Time step size in hours

# Building parameters
layers = 4  # Number of layers
area_room = 3.65 * 4  # Area of the building in square meters
height_room = 3.3

cp = np.array([835, 1317, 835, 835])  # Specific heat capacity of each layer

# Constants and parameters
rho_in = 1.2  # Air density at inlet, kg/m^3
rho_out = 1.2  # Air density at outlet, kg/m^3
alpha_w = [1.7e-7, 1.4e-6, 2.25e-2, 1.7e-7]  # Thermal diffusivity of wall, m^2/s
alpha_r = [1.7e-7, 1.4e-6, 1.8e-7, 4e-7]  # Thermal diffusivity of roof, m^2/s
alpha_f = [4.0e-7, 1.7e-7]  # Thermal diffusivity of floor, m^2/s
alpha_fur = 1.8e-7  # Thermal diffusivity of furniture, m^2/s
l_w = [6e-3, 75e-3, 8.5e-3, 8.5e-3]  # Thickness of wall layers, m
l_r = [6e-3, 100e-3, 11e-3, 6.5e-4]  # Thickness of roof layers, m
l_f = [1e-3, 9e-3]  # Thickness of floor layers, m
K_w = [0.14, 0.038, 0.026, 0.14]
K_r = [0.14, 0.038, 0.12, 0.027]
K_f = [0.027, 0.14]
K_fur = 2
rho_f = [55.0, 615.0]  # Furniture density, kg/m^3
c_p_f = [1210.0, 1317.0]  # Furniture specific heat capacity, J/(kg*K)

# Outside temperature
T_outside = 270.95  # Outside temperature in degrees kelvin

# Furniture parameters
furniture_volume = 1  # Volume of furniture in cubic meters
furniture_alpha = 1.8e-7  # Thermal diffusivity of furniture
furniture_radius = 0.5  # Radius of furniture in meters

# Heat transfer coefficients
h_walls = 2
h_furniture = 2

air_flow = 0.7

num_steps = int(duration / time_step)
T = np.zeros((num_steps, layers))
# Set initial conditions
V_b = area_room * height_room
V_out = air_flow
# Assume V_in = V_out
V_in = V_out
Ventilation_rate = V_in / V_b
# Assume ρ_in = ρ_out
# rho_in = rho_out

h_b_w = 2
h_alpha_w = 1
h_b_r = 2
h_alpha_r = 1
h_b_f = 2
h_b_fur = 2

h_in = h_b_w + h_alpha_w
h_out = h_b_r + h_alpha_r
R = 8.314  # Pa*m^3 /(mol*K)
M_b = 0.02897  # kg/mol
T_b_occupied_initial = 293.15
T_b_unoccupied_initial = 288.15

time = np.arange(0, duration, time_step)
T_b = np.zeros(num_steps)  # Building unit temperature
T_w_occupied = np.zeros((len(l_w), num_steps))  # Wall temperatures
T_r_occupied = np.zeros((len(l_r), num_steps))  # Roof temperatures
T_f_occupied = np.zeros((len(l_f), num_steps))  # Floor temperatures
T_fur_occupied = np.zeros(num_steps)  # Furniture temperature

T_w_unoccupied = np.zeros((len(l_w), num_steps))  # Wall temperatures
T_r_unoccupied = np.zeros((len(l_r), num_steps))  # Roof temperatures
T_f_unoccupied = np.zeros((len(l_f), num_steps))  # Floor temperatures
T_fur_unoccupied = np.zeros(num_steps)  # Furniture temperature

T_b_occupied = np.zeros(num_steps)
T_b_unoccupied = np.zeros(num_steps)
T_b_occupied[0] = T_b_occupied_initial
T_b_unoccupied[0] = T_b_unoccupied_initial
P_atm = 101300  # Pa

# Assume P_b = P_atm
P_b = P_atm
P_in = P_b
rho_b_occupied = (P_b * M_b) / (R * T_b_occupied[0])
rho_b_unoccupied = (P_b * M_b) / (R * T_b_unoccupied[0])
c_p_b = 1005  # J/(kgK)
print(rho_b_occupied)

# Energy
dE_in_dt_occupied = (
    rho_b_occupied * c_p_b * (T_outside - T_b_occupied[0]) * (area_room * h_in)
)
dE_out_dt_occupied = (
    rho_b_occupied * c_p_b * (T_b_occupied[0] - T_outside) * (area_room * h_out)
)

dE_in_dt_unoccupied = (
    rho_b_unoccupied * c_p_b * (T_outside - T_b_unoccupied[0]) * (area_room * h_in)
)
dE_out_dt_unoccupied = (
    rho_b_unoccupied * c_p_b * (T_b_unoccupied[0] - T_outside) * (area_room * h_out)
)

A_window = A_door = A_walls = A_floor = A_roof = area_room  # it's an approximation
U_window = U_door = U_walls = U_floor = U_roof = 1.2  # W/(m^2·K) approximation

dQ_dt_loss_occupied = np.zeros(num_steps)
dT_b_dt_occupied = np.zeros(num_steps)
dQ_dt_supply = np.zeros(num_steps)
T_infinity = T_outside
Insolation = 100  # W/m^2
Appliances = 150  # W
dQ_people_dt = 58.2 * area_room  # W
dQ_people_dt_series = np.zeros(num_steps)
dQ_appliances_dt = Appliances  # W
dQ_solar_dt = Insolation * area_room
Q_heater = 1000  # W]
dQ_heater_dt = np.zeros(num_steps)
# dQ_heater_dt = Q_heater
k1_occupied = np.zeros(num_steps)
k2_occupied = np.zeros(num_steps)
dQ_supply_dt = dQ_appliances_dt + dQ_solar_dt + dQ_people_dt + Q_heater
T_b_occupied_unbiased = np.zeros(num_steps)
T_b_occupied_unbiased[0] = T_b_occupied_initial

for i in range(1, num_steps):
    dQ_window_dt_occupied = U_window * A_window * (T_infinity)
    dQ_door_dt_occupied = U_door * A_door * (T_infinity)
    dQ_walls_dt_occupied = U_walls * A_walls * (T_infinity)
    dQ_floor_dt_occupied = U_floor * A_floor * (T_infinity)
    dQ_roof_dt_occupied = U_roof * A_roof * (T_infinity)

    dQ_dt_loss_occupied = (
        dQ_window_dt_occupied
        + dQ_door_dt_occupied
        + dQ_walls_dt_occupied
        + dQ_floor_dt_occupied
        + dQ_roof_dt_occupied
    )

    rho_in_occupied = (P_in * M_b) / (R * T_b_occupied_initial)
    rho_out_occupied = rho_b_occupied
    drho_b_occupied_dt = 0

    if i <= 50:
        dQ_dt_supply[i] = dQ_supply_dt
        V_in = V_out = 0.7
        h_in = 60179.47996
        h_out = 60587.96

        k1_occupied_0 = 70
        k1_occupied[i] = (
            (V_in * rho_in_occupied * h_in - V_out * rho_out_occupied * h_out)
            + dQ_dt_supply[i]
            + dQ_dt_loss_occupied
        ) / (V_b * rho_b_occupied * (c_p_b - R / M_b))
        k1 = 70
        k2_occupied[i] = dQ_dt_loss_occupied / T_infinity + (
            V_in * rho_in_occupied - V_out * rho_out_occupied
        ) / (rho_b_occupied * V_b)
        k2 = 0.23
        T_b_occupied[i] = (1 / k2) * (
            k1_occupied_0 - (k1 - k2 * T_b_occupied[0]) * math.exp(-k2 * i)
        )

    else:
        V_in = V_out = 0.7
        h_in = 61173.08
        h_out = 60587.96
        dQ_dt_supply[i] = 0
        k1_occupied_50 = 50

        k1_occupied[i] = (
            (V_in * rho_in_occupied * h_in - V_out * rho_out_occupied * h_out)
            + dQ_dt_supply[i]
            + dQ_dt_loss_occupied
        ) / (V_b * rho_b_occupied * (c_p_b - R / M_b))
        k2 = 0.19
        k1 = 50

        k2_occupied[i] = dQ_dt_loss_occupied / T_infinity + (
            V_in * rho_in_occupied - V_out * rho_out_occupied
        ) / (rho_b_occupied * V_b)
        T_b_occupied[i] = (1 / k2) * (
            k1_occupied_50 - (k1 - k2 * T_b_occupied[50]) * math.exp(-k2 * (i - 50))
        )

for i in range(len(l_w)):
    T_w_occupied[i][0] = T_infinity
for i in range(len(l_r)):
    T_r_occupied[i][0] = T_infinity
for i in range(len(l_f)):
    T_f_occupied[i][0] = T_infinity
T_fur_occupied[0] = T_b_occupied[0]

for i in range(len(l_w)):
    T_w_unoccupied[i][0] = T_infinity
for i in range(len(l_r)):
    T_r_unoccupied[i][0] = T_infinity
for i in range(len(l_f)):
    T_f_unoccupied[i][0] = T_infinity
T_fur_unoccupied[0] = T_b_unoccupied[0]
firstPart = np.zeros(num_steps)

for step in range(1, num_steps):
    dT_w_dt_occupied = np.zeros(len(l_w))

    for i in range(len(l_w)):
        if i == 0:
            dT_w_dt_occupied[i] = alpha_w[i] * (
                (
                    T_w_occupied[i + 1][step - 1]
                    - 2 * T_w_occupied[i][step - 1]
                    + T_b_occupied[step - 1]
                )
                / (l_w[i] ** 2)
            )
        elif i == len(l_w) - 1:
            dT_w_dt_occupied[i] = alpha_w[i] * (
                (
                    T_w_occupied[i - 1][step - 1]
                    - 2 * T_w_occupied[i][step - 1]
                    + T_w_occupied[i][step - 1]
                )
                / (l_w[i] ** 2)
            )
        else:
            dT_w_dt_occupied[i] = alpha_w[i] * (
                (
                    T_w_occupied[i + 1][step - 1]
                    - 2 * T_w_occupied[i][step - 1]
                    + T_w_occupied[i][step - 1]
                )
                / (l_w[i] ** 2)
            )

    dT_r_dt_occupied = np.zeros(len(l_r))
    for i in range(len(l_r)):
        if i == 0:
            dT_r_dt_occupied[i] = alpha_r[i] * (
                (
                    T_r_occupied[i + 1][step - 1]
                    - 2 * T_r_occupied[i][step - 1]
                    + T_b_occupied[step - 1]
                )
                / (l_r[i] ** 2)
            )
        elif i == len(l_r) - 1:
            dT_r_dt_occupied[i] = alpha_r[i] * (
                (
                    T_r_occupied[i - 1][step - 1]
                    - 2 * T_r_occupied[i][step - 1]
                    + T_r_occupied[i][step - 1]
                )
                / (l_r[i] ** 2)
            )
        else:
            dT_r_dt_occupied[i] = alpha_r[i] * (
                (
                    T_r_occupied[i + 1][step - 1]
                    - 2 * T_r_occupied[i][step - 1]
                    + T_r_occupied[i][step - 1]
                )
                / (l_r[i] ** 2)
            )

    dT_f_dt_occupied = np.zeros(len(l_f))
    for i in range(len(l_f)):
        if i == 0:
            dT_f_dt_occupied[i] = alpha_f[i] * (
                (
                    T_f_occupied[i + 1][step - 1]
                    - 2 * T_f_occupied[i][step - 1]
                    + T_b_occupied[step - 1]
                )
                / (l_f[i] ** 2)
            ) + (dQ_dt_supply[step] - dQ_dt_loss_occupied) / (rho_f[i] * c_p_f[i])
        elif i == len(l_f) - 1:
            dT_f_dt_occupied[i] = alpha_f[i] * (
                (
                    T_f_occupied[i - 1][step - 1]
                    - 2 * T_f_occupied[i][step - 1]
                    + T_f_occupied[i][step - 1]
                )
                / (l_f[i] ** 2)
            ) + (dQ_dt_supply[step] - dQ_dt_loss_occupied) / (rho_f[i] * c_p_f[i])

    dT_fur_dt_occupied = (
        alpha_fur
        * (
            (T_fur_occupied[0] - 2 * T_fur_occupied[step - 1] + T_b_occupied[step - 1])
            / (0.5**2)
        )
    ) + (alpha_fur / 0.5) * ((T_fur_occupied[0] - T_b_occupied[step - 1]) / (1))

    for i in range(len(l_w)):
        T_w_occupied[i][step] = (
            T_w_occupied[i][step - 1] + time_step * dT_w_dt_occupied[i]
        )
    for i in range(len(l_r)):
        T_r_occupied[i][step] = (
            T_r_occupied[i][step - 1] + time_step * dT_r_dt_occupied[i]
        )
    for i in range(len(l_f)):
        T_f_occupied[i][step] = (
            T_f_occupied[i][step - 1] + time_step * dT_f_dt_occupied[i]
        )
    T_fur_occupied[step] = T_fur_occupied[step - 1] + time_step * dT_fur_dt_occupied

def dydt(y0, time, T_outside):
    for i in range(1, num_steps):
        deltaRhoB = (V_in * rho_in - V_out * rho_b_occupied) / V_b

        firstPart[i] = (
            V_in * rho_in * h_in
            - V_out * rho_b_occupied * h_out
            + dQ_dt_supply[i]
            - dQ_dt_loss_occupied
        ) / (V_b * rho_b_unoccupied * (c_p_b - (R / M_b))) - (
            y0 / rho_b_occupied
        ) * deltaRhoB
    return firstPart[i]

K = 273.15
y0 = 15 + K
tolerance = 1e-5

sol = odeint(dydt, y0, time, args=(T_outside,), rtol=tolerance, atol=tolerance)

plt.figure(figsize=(12, 6))
plt.plot(time, T_b_occupied, label="T building occupied")

for i in range(len(l_w)):
    plt.plot(time, T_w_occupied[i], label=f"Wall Layer {i+1} occupied")
for i in range(len(l_r)):
    plt.plot(time, T_r_occupied[i], label=f"Roof Layer {i+1} occupied")
for i in range(len(l_f)):
    plt.plot(time, T_f_occupied[i], label=f"Floor Layer {i+1} occupied")
plt.plot(time, T_fur_occupied, label="Furniture occupied")
plt.xlabel("Time (hours)")
plt.ylabel("Temperature (°K)")
plt.title("Temperature Variations of Internal Elements - Occupied")
plt.legend(
    bbox_to_anchor=(1.02, 1), loc="upper left", ncol=1, mode="expand", borderaxespad=0.0
)
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()


"""https://www.acmicpc.net/problem/15685"""

"""드래곤 커브"""

N = int(input())

curves = []

for _ in range(N):

    x, y, d, g = map(int,input().split())

    curves.append((x,y,d,g))

board = [[0 for _ in range(101)] for _ in range(101)]

def draw(x,y,d,g):

    delta =[(0,1),(-1,0),(0,-1),(1,0)]

    d_list = [d]

    for _ in range(g):

        for i in range(len(d_list)-1,-1,-1):
            next_d = (d_list[i]+1)%4
            d_list.append(next_d)

    for dt in d_list:

        board[y][x] = 1

        y += delta[dt][0]
        x += delta[dt][1]

        if 0 <= y < 101 and 0<= x < 101:

            if board[y][x] == 0:
                board[y][x] = 1

def find_square():

    result = 0

    for r in range(101):
        for c in range(101):

            cnt = 0

            if board[r][c] == 1:

                for dr,dc in [(1,0),(1,1),(0,1)]:
                    nr,nc = r+dr, c+dc

                    if 0<= nr < 101 and 0<=nc < 101 and board[nr][nc] == 1:

                        cnt += 1
                    else:
                        break
            if cnt == 3:
                result += 1

    return result

def solution():

    for curve in curves:

        draw(curve[0], curve[1], curve[2], curve[3])

    r = find_square()

    return r

print(solution())


import torch
from torch import nn
from sklearn.metrics import mean_squared_error
import os
import sys
import networks
import gc

from vgg19 import vgg, VGG_loss
from networks import EFDM_loss

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

        self.config = config
        self.device = torch.device('cuda:{}'.format(config.gpu) if torch.cuda.is_available() else 'cpu')

        self.lr = config.lr
        self.lambda_percept = config.lambda_percept
        self.lambda_const_style = config.lambda_const_style

        self.alpha_in = config.alpha_in
        self.alpha_out = config.alpha_out

        torch.cuda.empty_cache()

        # Encoder & Generator
        self.netE = networks.define_network(net_type='Encoder', alpha_in=self.alpha_in, alpha_out=self.alpha_out,
                                            init_type=self.config.init_type, gpu_ids=self.config.gpu, config = config)
        self.netS = networks.define_network(net_type='StyleEncoder', alpha_in=self.alpha_in, alpha_out=self.alpha_out,
                                            init_type=self.config.init_type, gpu_ids=self.config.gpu, config = config)
        self.netG = networks.define_network(net_type='Generator', alpha_in=self.alpha_in, alpha_out=self.alpha_out,
                                            init_type=self.config.init_type, gpu_ids=self.config.gpu, config = config)

        # Loss
        self.vgg_loss = VGG_loss(config, vgg)
        self.efdm_loss = EFDM_loss()

        # Optimizer
        self.optimizer_E = torch.optim.Adam(self.netE.parameters(), lr=self.config.lr, betas=(self.config.beta1, 0.99))
        self.optimizer_S = torch.optim.Adam(self.netS.parameters(), lr=self.config.lr, betas=(self.config.beta1, 0.99))
        self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=self.config.lr, betas=(self.config.beta1, 0.99))

        # Scheduler
        self.E_scheduler = networks.get_scheduler(self.optimizer_E, config)
        self.S_scheduler = networks.get_scheduler(self.optimizer_S, config)
        self.G_scheduler = networks.get_scheduler(self.optimizer_G, config)

    def forward(self, data):
        self.real_A = data['real_A'].to(self.device)
        self.real_B = data['style_img'].to(self.device)

        # 1. Encode content & style information from images
        self.content_A, _ = self.netE(self.real_A)
        self.style_A, _ = self.netS(self.content_A)
        self.content_B, self.cont_feat_B = self.netE(self.real_B)
        self.style_B, self.sty_feat_B = self.netS(self.content_B)

        # 2. Generate infusioned images
        self.trs_AtoB, self.trs_AtoB_high, self.trs_AtoB_low, self.sty_kernel_preds = self.netG(self.content_A, self.style_B)

        # 3. Style description of infusioned images
        self.content_trs_AtoB, self.cont_feat_trs_AtoB = self.netE(self.trs_AtoB)
        self.style_trs_AtoB, self.sty_feat_trs_AtoB = self.netS(self.content_trs_AtoB)

        ## Predict kernel of infusioned image
        _, _, _, self.trs_kernel_preds = self.netG(self.content_A, self.style_trs_AtoB)

    """ Generator loss """
    def calc_G_loss(self):
        ## 1. Perceptual Loss using VGG
        self.G_percept, self.neg_idx = self.vgg_loss.perceptual_loss(self.real_A, self.real_B, self.trs_AtoB)
        self.G_percept *= self.lambda_percept

        ## 2. Style Contrastive Loss
        self.G_const_style = self.efdm_loss(self.cont_feat_B, self.sty_feat_B, self.cont_feat_trs_AtoB, self.sty_feat_trs_AtoB, self.neg_idx) * self.lambda_const_style

        self.G_loss = self.G_percept + self.G_const_style

    def train_step(self, data):
        self.set_requires_grad([self.netE, self.netS, self.netG], True)

        self.forward(data)
        self.calc_G_loss()

        self.optimizer_E.zero_grad()
        self.optimizer_S.zero_grad()
        self.optimizer_G.zero_grad()
        self.G_loss.backward()
        self.optimizer_E.step()
        self.optimizer_S.step()
        self.optimizer_G.step()

        train_dict = {}
        train_dict['G_loss'] = self.G_loss
        train_dict['G_Percept'] = self.G_percept
        train_dict['G_Const_Style'] = self.G_const_style

        train_dict['style_img'] = self.real_B
        train_dict['fake_AtoB'] = self.trs_AtoB
        train_dict['fake_AtoB_high'] = self.trs_AtoB_high
        train_dict['fake_AtoB_low'] = self.trs_AtoB_low

        return train_dict

    def val(self, data):
        with torch.no_grad():
            self.forward(data)

            val_dict = {}
            val_dict['real_A'] = self.real_A
            val_dict['fake_AtoB'] = self.trs_AtoB
            val_dict['real_B'] = self.real_B

        return val_dict

    def test(self, data):
        with torch.no_grad():
            real_A = data['real_A'].to(self.device)
            real_B = data['style_img'].to(self.device)

            # 1. Encode content & style information from images
            content_A, _ = self.netE(real_A)
            content_B, _ = self.netE(real_B)
            style_B, _ = self.netS(content_B)

            # 2. Generate infusioned images
            trs_AtoB, trs_AtoB_high, trs_AtoB_low, _ = self.netG(content_A, style_B)

            test_dict = {}
            test_dict['style_img'] = real_B
            test_dict['fake_AtoB'] = trs_AtoB
            test_dict['fake_AtoB_high'] = trs_AtoB_high
            test_dict['fake_AtoB_low'] = trs_AtoB_low

        return test_dict

    def style_mixing(self, data):
        with torch.no_grad():
            # B1: high style image / B2: low style image
            real_A = data['real_A'].to(self.device)
            real_B1_h = data['style_high'].to(self.device)
            real_B2_l = data['style_low'].to(self.device)

            # 1. Encode content & style information from images
            content_A = self.netE(real_A)
            content_B1_h = self.netE(real_B1_h)
            content_B2_l = self.netE(real_B2_l)
            style_B1_h, _ = self.netS(content_B1_h)[0]
            _, style_B2_l = self.netS(content_B2_l)[0]
            style_B = style_B1_h, style_B2_l

            # 2. Generate infusioned images
            trs_AtoB, trs_AtoB_high, trs_AtoB_low, _ = self.netG(content_A, style_B)

            mix_dict = {}
            mix_dict['style_high_img'] = real_B1_h
            mix_dict['style_low_img'] = real_B2_l
            mix_dict['fake_AtoB'] = trs_AtoB
            mix_dict['fake_AtoB_high'] = trs_AtoB_high
            mix_dict['fake_AtoB_low'] = trs_AtoB_low

        return mix_dict

    def set_requires_grad(self, nets, requires_grad=False):
        if not isinstance(nets, list):
            nets = [nets]
        for net in nets:
            if net is not None:
                for param in net.parameters():
                    param.requires_grad = requires_grad


"""
    程序功能： 游戏推荐展示
    作者：覃瀚辉
    时间：2021.12.15
"""

import wx
import csv

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(parent=None, title='音乐推荐')
        self.data = self.loadSimpDat()
        self.com_game = self.recommend()
        panel = wx.Panel(self)
        panel.SetBackgroundColour([38,50,56])
        my_sizer = wx.BoxSizer(wx.VERTICAL)
        self.text_ctrl = wx.TextCtrl(panel,style=wx.TE_MULTILINE)
        font1 = wx.Font(15, wx.MODERN, wx.LIGHT, wx.NORMAL, False, 'Times New Roman')
        self.text_ctrl.SetFont(font1)
        self.text_ctrl.AppendText('Enter the games you have played')
        self.text_ctrl.SetBackgroundColour([255, 255, 229])
        my_sizer.Add(self.text_ctrl, 5, wx.ALL | wx.EXPAND, 5)
        my_btn = wx.Button(panel, label='推荐')
        my_btn.Bind(wx.EVT_BUTTON, self.on_press)
        my_sizer.Add(my_btn, 0, wx.ALL | wx.CENTER, 5)
        self.text_ctrl2 = wx.TextCtrl(panel,style=wx.TE_MULTILINE)
        self.text_ctrl2.SetFont(font1)
        self.text_ctrl2.AppendText('Recommended Games')
        self.text_ctrl2.SetBackgroundColour([255, 255, 229])
        my_sizer.Add(self.text_ctrl2, 5, wx.ALL | wx.EXPAND, 5)
        panel.SetSizer(my_sizer)
        self.Show()

    def loadSimpDat(self):
        """
        :return:返回原始数据
        """
        dataSet = []
        with open('outputdata/like_song.csv', 'r', encoding='utf-8') as csv_file:
            csv_reader = csv.reader(csv_file)
            for row in csv_reader:
                dataSet.append(row)
        return dataSet

    def recommend(self):
        """
        :return:可能玩的游戏
        """
        dataSet = []
        with open('outputdata/tuijian_song.csv', 'r', encoding='utf-8') as csv_file:
            csv_reader = csv.reader(csv_file)
            for row in csv_reader:
                dataSet.append(row)
        return dataSet

    def RecommendDault(self):
        """
        :return:默认推荐游戏(排名前20)
        """
        dataSet = []
        with open('outputdata/tuijian_default.csv', 'r', encoding='utf-8') as csv_file:
            csv_reader = csv.reader(csv_file)
            for row in csv_reader:
                dataSet.append(row)
        return dataSet

    def on_press(self, event):
        keyword_str = self.text_ctrl.Value
        keyword_str = keyword_str.strip()#除去首尾空格
        keyword_list = keyword_str.split('\n')
        index = 0
        tuijian_str = ''
        tuijian_list = []
        for row in self.data:
            # 如果全部符合 直接加入
            if keyword_list == row:
                for va in self.com_game[index]:
                    va = va.strip()
                    tuijian_list.append(va)
            # 部分符合也推荐
            for keyword in keyword_list:
                if (keyword in row) or (keyword == row):
                    for va in self.com_game[index]:
                        va = va.strip()
                        tuijian_list.append(va)
            index += 1
        tuijian_list = list(set(tuijian_list))
        # 没找到推荐的，就推荐默认的
        if len(tuijian_list) == 0:
            Dault_String = ''
            Dault_list = self.RecommendDault()
            index = 0
            for row in Dault_list:
                Dault_String += str(index + 1) + '. '
                Dault_String += str(row[0])
                Dault_String += '\n'
                index += 1
            self.text_ctrl2.SetValue(Dault_String)
        else:
            #找到推荐了 就推荐有的
            index = 0
            for va in tuijian_list:
                if va != '':
                    tuijian_str += str(index + 1) + '. '
                    tuijian_str += va
                    tuijian_str += '\n'
                    tuijian_str.strip()
                    index += 1
            self.text_ctrl2.SetValue(tuijian_str)
if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame()
    app.MainLoop()


#!/usr/bin/env python3
# --------------------------------------------------
# Fábio Sousa.
# SAVI, December 2022.
# --------------------------------------------------

import matplotlib.pyplot as plt
import torch
from model import Model
from dataset import Dataset

def main():

    # -----------------------------------------------------------------
    # Initialization
    # -----------------------------------------------------------------

    #Create dataset
    dataset = Dataset(3000, -0.3, 14)

    loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=256, shuffle=True)
    #It's good practice to guarantee that the batches have an appropriate size

    # #Draw training data
    # plt.plot(dataset.xs_np, dataset.ys_np_labels,'g.', label = 'labels')
    # plt.legend(loc='best')
    # plt.show()

    #Define hyper parameters
    device = 'cuda:0' if torch.cuda.is_available() else 'cpu' # cuda: 0 index of gpu

    model = Model() #Instantiate model
    model.to(device) #Move the model variable to the gpu if one exists

    learning_rate = 0.01
    maximum_num_epochs = 50
    criterion = torch.nn.MSELoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

    # -----------------------------------------------------------------
    # Training
    # -----------------------------------------------------------------

    #An epoch is an iteration of what comes next (of each prediction)
    idx_epoch = 0

    while True:

        #Train batch by batch
        for batch_idx, (xs_ten, ys_ten_labels) in enumerate(loader):

            #.to(device) keeps all variables in the same GPU or CPU
            xs_ten = xs_ten.to(device)
            ys_ten_labels = ys_ten_labels.to(device)

            #Apply the network to get the predicted ys
            ys_ten_predicted = model.forward(xs_ten)

            #Compute the error based on the predictions
            loss = criterion(ys_ten_predicted, ys_ten_labels)

            #Update the model, i.e. the neural network's weights
            optimizer.zero_grad() #Resets the weights to make sure we are not accumulating
            loss.backward() #Propagates the loss error into each neuron
            optimizer.step() #Update the weights

            #Report
            print('Epoch ' + str(idx_epoch) + ', Loss ' + str(loss.item()))

        idx_epoch += 1 #Go to next epoch

        #Termination criteria
        if idx_epoch > maximum_num_epochs:
            print('Finished training. Reached maximum number of epochs.')
            break

    # -----------------------------------------------------------------
    # Finalization
    # -----------------------------------------------------------------

    #Run the model once to get ys_predicted
    ys_ten_predicted = model.forward(dataset.xs_ten.to(device))
    ys_np_predicted = ys_ten_predicted.cpu().detach().numpy()

    #Draw data in a plot
    plt.plot(dataset.xs_np, dataset.ys_np_labels,'g.', label = 'Original')
    plt.plot(dataset.xs_np, ys_np_predicted,'rx', label = 'Predicted')
    plt.legend(loc='best')
    plt.grid('on')
    plt.title('Deep Learning for line fitting')
    plt.show()

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import pandas as pd
import matplotlib.pyplot as plot

df = pd.read_csv("avocado.csv")

#print(df.head(3))
#print(df["AveragePrice"].head())
albany_df = df[ df['region'] == 'Albany' ]

#print(albany_df.head())

albany_df.set_index('Date', inplace=True, drop=True)
print(albany_df.head())

plot.imshow(albany_df['AveragePrice'])
plot.show()


def main():
    choice = input('Press Q/'
                   'q to Quit or E/e to Enter:')

    while choice == "E"or choice=="e":
        deg_fahrenheit = float(input("Put fahrenheit to get degrees in celsius:"))
        deg_celsius = int((deg_fahrenheit - 32) / 1.8)
        print (deg_fahrenheit,"fahrenheit converts to", deg_celsius, "degrees Celsius .")
        choice = input('Press q to Quit or E to Enter:')

    if choice =="q" or choice=="Q":
        exit()
main()


import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.linear_model import RidgeCV
import matplotlib.pyplot as plt

data = pd.read_csv('./data/CCPP.csv')
data_x = data[['AT', 'V', 'AP', 'RH']]
data_y = data[['PE']]

x_train, x_test, y_train, y_test = train_test_split(data_x, data_y, random_state=1)

if __name__ == '__main__':
    # 岭回归
    model = Ridge(alpha=1)
    model.fit(x_train, y_train)
    print('theta0: ', model.intercept_)
    print('coefficients: ', model.coef_)

    # 超参数调优
    print()
    ridgecv = RidgeCV(alphas=[0.01, 0.1, 0.5, 1, 3, 5, 10, 30, 50, 100])
    ridgecv.fit(x_train, y_train)
    print(ridgecv.alpha_)

    # 超参数alpha与模型参数关系
    X = 1. / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis])
    y = np.ones(10)
    alphas = np.logspace(-10, -2, 200)
    coefs = []
    for alpha in alphas:
        model = Ridge(alpha=alpha, fit_intercept=False)
        model.fit(X, y)
        coefs.append(model.coef_)
    ax = plt.gca()
    ax.plot(alphas, coefs)
    ax.set_xscale('log')
    ax.set_xlim(ax.get_xlim()[::-1])
    plt.xlabel('alpha')
    plt.ylabel('weight')
    plt.axis('tight')
    plt.show()


import re

class Shingling:

    def __init__(self, file_name):
        self.file_name = file_name
        self.document = None
        self.shingles = None
        self.hashed_shingles = None
        self.hashed_signatures = None

    # Read file for shingling
    def read_file(self):
        print("Trying to read: " + str(self.file_name))
        with open(self.file_name) as file:
            content = file.read()
            # Clean shingles
            content = content.replace("\n", " ") \
                .replace("  ", " ")
            content = re.sub(r'([^\w\s]|_)', '', content)
            self.document = content

            print("Successful read: " + str(self.file_name))

    # Build shingles from file content
    # document -> [ [s,h,i,n,g,l,e,1], [s,h,i,n,g,l,e,2] ]
    def build_shingles(self, k):
        shingles = []
        for i in range(0, len(self.document) - k):
            shingles.append(self.document[i: i + k])

        print("Number of shingles from file " + str(self.file_name) + ": " + str(len(shingles)))
        list.sort(list(set(shingles)))
        self.shingles = shingles

    # Hash built shingles
    # [ [s,h,i,n,g,l,e,1], [s,h,i,n,g,l,e,2] ] -> [123, 345]
    def hash_shingles(self):
        hashed_shingles = []
        for i in range(0, len(self.shingles)):
            hashed_shingles.append(hash(self.shingles[i]))
        self.hashed_shingles = hashed_shingles

    def set_signatures(self, hashed_signatures):
        self.hashed_signatures = hashed_signatures


# Python3
# This code utilizes booleans, equality testing and binary search to find if a number is in an ordered list.

import random

a = random.sample(range(9999), 1000)
a = sorted(a)
b = random.randint(1,9999)

print(a)
print(b)

def binarySearchFunction(orderedList, userNumber):
	middle = float(len(orderedList)/2)

	if userNumber < orderedList[int(middle)]:
		if userNumber in orderedList[:int(middle)]:
			return True
		else:
			return False
	else:
		if userNumber in orderedList[int(middle):]:
			return True
		else:
			return False

x = binarySearchFunction(a, b)
print(x)


import os
import pickle
import datetime
from ...common import exceptions as ex
from os import getcwd

FILE_EXTENSION = '.pickle'
STORAGE_FOLDER_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

BACKUP_STORAGE_PATH = os.path.join(STORAGE_FOLDER_PATH, 'data_storage', 'for_backup_storage')
TPL_STORAGE_PATH = os.path.join(STORAGE_FOLDER_PATH, 'data_storage', 'for_tpl_storage')
CONFIG_STORAGE_PATH = os.path.join(STORAGE_FOLDER_PATH, 'data_storage', 'for_config_storage')

def load_backup(user_id, tool_id, project_id, backup_name):
    file_path = __get_backup_file_path(user_id, tool_id, project_id,
                                       backup_name)
    saved_content = __load(file_path)
    return saved_content['data']

def save_backup(user_id, tool_id, project_id, data_to_save, backup_name):
    folder = __get_user_backup_dir_path(user_id, tool_id, project_id)
    if not os.path.exists(folder):
        os.makedirs(folder)

    file_path = __get_backup_file_path(user_id, tool_id, project_id,
                                       backup_name)
    file_info = {
        'name': backup_name,
        'user_id': user_id,
        'date': datetime.datetime.now()
    }
    __save(file_path, file_info, data_to_save)

def delete_backup(user_id, tool_id, project_id, backup_name):
    file_path = __get_backup_file_path(user_id, tool_id, project_id,
                                       backup_name)
    __delete(file_path)

def get_available_backups_info(users_ids, tool_id, project_id):
    files_list = []
    if not users_ids or not tool_id:
        return files_list
    ext_len = len(FILE_EXTENSION)
    for user_id in users_ids:
        user_backup_dir_path = __get_user_backup_dir_path(user_id, tool_id,
                                                          project_id)
        for entry in os.scandir(user_backup_dir_path):
            if not entry.name.startswith('.') and entry.is_file():
                no_ext_name = entry.name[:-ext_len]
                saved_content = load_backup(user_id, tool_id, project_id,
                                            no_ext_name)
                if saved_content:
                    files_list.append(saved_content['info'])
    return files_list

def load_template(tool_id, tpl_name):
    file_path = __get_tpl_file_path(tool_id, tpl_name)
    saved_content = __load(file_path)
    return saved_content

def save_template(tool_id, data_to_save, tpl_name='default_tpl'):
    if not os.path.exists(__get_tpl_dir_path(tool_id)):
        os.makedirs(__get_tpl_dir_path(tool_id))
    file_path = __get_tpl_file_path(tool_id, tpl_name)
    file_info = {
        'name': tpl_name,
        'date': datetime.datetime.now()
    }
    __save(file_path, file_info, data_to_save)

def delete_template(tool_id, tpl_name):
    file_path = __get_tpl_file_path(tool_id, tpl_name)
    __delete(file_path)

def __save(file_path, file_info, data_to_save):

    data_with_info = {
        'data': data_to_save,
        'info': file_info
    }
    with open(file_path, 'wb') as f:
        pickle.dump(data_with_info, f, pickle.HIGHEST_PROTOCOL)

def __load(file_path):
    saved_content = {}
    if os.path.isfile(file_path):
        with open(file_path, 'rb') as f:
            saved_content = pickle.load(f)
    return saved_content

def __delete(file_path):
    if not os.path.isfile(file_path):
        raise ex.NotExistingFileError(file_path)
    os.remove(file_path)

def __get_backup_file_path(user_id, tool_id, project_id, backup_name):
    file_name = backup_name + FILE_EXTENSION
    file_path = os.path.join(BACKUP_STORAGE_PATH, str(user_id),
                             str(tool_id) + str(project_id), file_name)
    return file_path

def __get_user_backup_dir_path(user_id, tool_id, project_id):
    user_backup_dir_path = os.path.join(BACKUP_STORAGE_PATH,
                                        str(user_id),
                                        str(tool_id) + str(project_id))
    return user_backup_dir_path

def __get_tpl_file_path(tool_id, tpl_name):
    file_name = tpl_name + FILE_EXTENSION
    file_path = os.path.join(TPL_STORAGE_PATH, str(tool_id), file_name)
    return file_path

def __get_tpl_dir_path(tool_id):
    tpl_dir_path = os.path.join(TPL_STORAGE_PATH, str(tool_id))
    return tpl_dir_path


import ROOT
import array
from RooFuncs import MakeInvm,Register,SumP4

####
###  This is a class that uses formula-defined variables and
###  submits them to MVA-reader using arrays
####
class MvaVars:
    ###
    ### Constructor requires a tree (which you can change later), an TMVA.Reader object
    ### and a list of variable names or expressions, which will be used in TTreeFormula evaluation
    ###
    def __init__(self,vars,reader,tree):
        self.arrays = {}
        self.formulae = {}
        self.tree = tree
        for v in vars:
            self.arrays[v] = array.array('f',[0])
            reader.AddVariable(v,self.arrays[v])
            self.formulae[v] = ROOT.TTreeFormula(v,v,self.tree)

    def SetTree(self,tree):
        self.tree = tree
        for v in self.formulae:
            self.formulae[v] = ROOT.TTreeFormula(v,v,self.tree)
    ###
    ### This is analogous to the TTree.GetEntry method -- it evaluates all the formula
    ### and put results in correspondin arrays in memory
    ###
    def GetEntry(self,nentry):
        self.tree.GetEntry(nentry)
        for v in self.arrays:
            self.arrays[v][0] = self.formulae[v].EvalInstance()

class Bdt:
    def __init__(self,name,cuts,tree):
        self.name = name
        self.cuts = cuts
        self.vars = ["MetEt[0]","MuPt[0]","MuPt[1]","BJetPt[0]","BJetPt[1]","BJetCsv[0]","BJetCsv[1]"]
        for nm,f in [
            ("DR","sqrt((MuPhi[{0}]-BJetPhi[{1}])^2+(MuEta[{0}]-BJetEta[{1}])^2)"),
            ("DE","sqrt((MuPhi[{0}]-BJetPhi[{1}])^2+(MuEta[{0}]-BJetEta[{1}])^2)"),
            ("DP","sqrt((MuPhi[{0}]-BJetPhi[{1}])^2+(MuEta[{0}]-BJetEta[{1}])^2)") ]:
            Register(tree,nm + "jm11" , f.format(0,0))
            Register(tree,nm + "jm12" , f.format(0,1))
            Register(tree,nm + "jm21" , f.format(1,0))
            Register(tree,nm + "jm22" , f.format(1,1))
            self.vars += [ nm + "jm11", nm + "jm12", nm + "jm21", nm + "jm22"]

    def Train(self,sig,bkg,nsig,nbkg):
        fout = ROOT.TFile(self.name+"BDT.root","RECREATE")
        params = [ "!V", "!Silent", "Color", "DrawProgressBar", "Transformations=I;D;P;G,D", "AnalysisType=Classification"]
        factory = ROOT.TMVA.Factory(self.name, fout, ":".join(params))
        [factory.AddVariable(v,"F") for v in self.vars]

        factory.AddTree(sig,"Signal",1,self.cuts)
        factory.AddTree(bkg,"Background",1,self.cuts)

        params = [ "nTrain_Signal="+str(nsig), "nTrain_Background="+str(nbkg), "SplitMode=Random", "NormMode=NumEvents", "!V"]
        factory.PrepareTrainingAndTestTree(ROOT.TCut(""),":".join(params))

        params = [ "!H", "!V", "MaxDepth=10" ]
        factory.BookMethod(ROOT.TMVA.Types.kBDT, "BDT", ":".join(params))

        factory.TrainAllMethods()
        factory.TestAllMethods()
        factory.EvaluateAllMethods()

    def FillHist(self,hist,tree):
        tempf = ROOT.TFile("temp.root","recreate")
        treeF  = tree.CopyTree(self.cuts.GetTitle())

        reader = ROOT.TMVA.Reader()
        vars = MvaVars(self.vars,reader,treeF)
        reader.BookMVA("BDT","weights/"+self.name+"_BDT.weights.xml")

        for i in range(1,treeF.GetEntries()-1):
            vars.GetEntry(i)
            hist.Fill(reader.EvaluateMVA("BDT"))


def get_monthly_costs():
    input('Enter the monthly costs for the following: Press enter when ready:')
    a = input('Loan payment:')
    b = input('Insurance:')
    c = input('Gas:')
    d = input('oil:')
    e = input('tires:')
    f = input('Maintenance:')
    x = (a + b + c + d + e + f)
    return x
total_monthly_cost = get_monthly_costs()

def get_yearly_cost():
    z = total_monthly_cost * 12
    return z
total_yearly_cost = get_yearly_cost()

print(total_monthly_cost, total_yearly_cost)


import os
import sys
import argparse

import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset
from torch.utils.data.sampler import Sampler

import csv
import random
import numpy as np
import pandas as pd

from PIL import Image
filenameToPILImage = lambda x: Image.open(x)

# fix random seeds for reproducibility
SEED = 123
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
random.seed(SEED)
np.random.seed(SEED)

def worker_init_fn(worker_id):
    np.random.seed(np.random.get_state()[1][0] + worker_id)

# mini-Imagenet dataset
class MiniDataset(Dataset):
    def __init__(self, csv_path, data_dir):
        self.data_dir = data_dir
        self.data_df = pd.read_csv(csv_path).set_index("id")

        self.transform = transforms.Compose([
            filenameToPILImage,
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
            ])

    def __getitem__(self, index):
        path = self.data_df.loc[index, "filename"]
        label = self.data_df.loc[index, "label"]
        image = self.transform(os.path.join(self.data_dir, path))
        return image, label

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

class GeneratorSampler(Sampler):
    def __init__(self, episode_file_path):
        episode_df = pd.read_csv(episode_file_path).set_index("episode_id")
        self.sampled_sequence = episode_df.values.flatten().tolist()

    def __iter__(self):
        return iter(self.sampled_sequence)

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

def conv_block(in_channels, out_channels):
    bn = nn.BatchNorm2d(out_channels)
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, 3, padding=1),
        bn,
        nn.ReLU(),
        nn.MaxPool2d(2)
    )
class ProNet(nn.Module):
    def __init__(self, in_channels=3, hid_channels=64, out_channels=64):
        super(ProNet, self).__init__()
        self.encoder = nn.Sequential(
            conv_block(in_channels, hid_channels),
            conv_block(hid_channels, hid_channels),
            conv_block(hid_channels, hid_channels),
            conv_block(hid_channels, out_channels)
        )

    def forward(self, input_data):
        x = self.encoder(input_data)
        return x.view(x.size(0), -1)

def euclidean_dist(x, y):
    n = x.shape[0]
    m = y.shape[0]
    a = x.unsqueeze(1).expand(n, m, -1)
    b = y.unsqueeze(0).expand(n, m, -1)
    logits = -((a - b)**2).sum(dim=2)

    return logits

def predict(model, data_loader):
    prediction_results = []
    with torch.no_grad():
        # each batch represent one episode (support data + query data)
        for i, (data, target) in enumerate(data_loader):

            # split data into support and query data
            support_input = data[:5 * 1,:,:,:]
            query_input   = data[5 * 1:,:,:,:]
            support_input = support_input.cuda()
            query_input = query_input.cuda()

            label_encoder = {target[i * 1] : i for i in range(5)}
            query_label = torch.cuda.LongTensor([label_encoder[class_name] for class_name in target[5 * 1:]])

            model_output = model(support_input)
            output = model_output.reshape(1, 5, -1).mean(dim=0)# means of classes along n_support shots

            logits = euclidean_dist(model(query_input), output)
            pred = torch.argmax(logits, dim=1).tolist()
            pred.insert(0, i)
            prediction_results.append(pred)

    return prediction_results

if __name__=='__main__':
    pyfile = sys.argv[0]
    test_csv = sys.argv[1]
    test_data_dir = sys.argv[2]
    testcase_csv = sys.argv[3]
    output_csv = sys.argv[4]

    test_dataset = MiniDataset(test_csv, test_data_dir)

    test_loader = DataLoader(
        test_dataset, batch_size=5 * (15 + 1),
        num_workers=3, pin_memory=False, worker_init_fn=worker_init_fn,
        sampler=GeneratorSampler(testcase_csv))

    model = ProNet()
    state = torch.load('./pronet_eucdis_ep184_acc0.5160000118613243±0.01767819107550266.pth')
    model.load_state_dict(state)
    model = model.cuda()
    model.eval()
    prediction_results = predict(model, test_loader)

    episode_label = []
    episode_label.append('episode_id')
    for i in range(15*5):
        episode_label.append('query{}'.format(i))

    prediction_results.insert(0, episode_label)
    with open(output_csv, 'w', newline='') as f:
        writer = csv.writer(f)
        for row in prediction_results:
            writer.writerow(row)


# Python program killing
# a thread using multiprocessing
# module

"""
Though the interface of the two modules is similar, the two modules have very different implementations.
All the threads share global variables, whereas processes are completely separate from each other.
Hence, killing processes is much safer as compared to killing threads. The Process class is provided a method,
terminate(), to kill a process. Now, getting back to the initial problem. Suppose in the above code,
we want to kill all the processes after 0.03s have passed.
This functionality is achieved using the multiprocessing module in the following code.
"""
import multiprocessing
import time

def func(number):
    for i in range(1, 10):
        time.sleep(0.01)
        print('Processing ' + str(number) + ': prints ' + str(number * i))

    # list of all processes, so that they can be killed afterwards

all_processes = []

for i in range(0, 3):
    process = multiprocessing.Process(target=func, args=(i,))
    process.start()
    all_processes.append(process)

# kill all processes after 0.03s
time.sleep(0.03)
for process in all_processes:
    process.terminate()


#!/usr/bin/env python3

from argparse import ArgumentParser
from collections import defaultdict
from functools import total_ordering

import re
import json
import sys

argparser = ArgumentParser(description='''\
  Computes the cost of a solution.

  Starting from the initial state, applies commands one by one and tracks cost.
  For each state (initial, intermediate, final), it checks if it is valid
  according to repository rules. For the final state, it checks if it satisfies
  the constraints.
''')
argparser.add_argument('repository')
argparser.add_argument('initial')
argparser.add_argument('commands')
argparser.add_argument('constraints')

commands = None
final_constraints = None
state = None
repository = None

def error(m):
  sys.stdout.write('E: {}\n'.format(m))
  sys.exit(1)

@total_ordering
class Version:
  def __init__(self, verstr):
    if not re.match('[0-9]+(.[0-9]+)*', verstr):
      error('bad version format: {}'.format(verstr))
    self.nums = tuple(int(x) for x in verstr.split('.'))

  def __hash__(self):
    return hash(self.nums)

  def __eq__(self, other):
    return self.nums == other.nums

  def __lt__(self, other):
    return self.nums < other.nums

  def __repr__(self):
    return '.'.join(str(x) for x in self.nums)

class Package:
  def __init__(self, reference):
    if not re.match('[.+a-zA-Z0-9-]+=[.0-9]+', reference):
      error('bad package format: {}'.format(reference))
    [n, v] = reference.split('=')
    self.name = n
    self.version = Version(v)

  def __hash__(self):
    return 31 * hash(self.name) + hash(self.version)

  def __eq__(self, other):
    return self.name == other.name and self.version == other.version

  def __repr__(self):
    return '{}={}'.format(self.name, self.version)

class Command:
  def __init__(self, cmdstr):
    if not re.match('[+-].*', cmdstr):
      error('bad command format: {}'.format(cmdstr))
    self.action = cmdstr[0]
    self.package = Package(cmdstr[1:])

  def __repr__(self):
    return '{}{}'.format(self.action, self.package)

class PackageRange:
  def __init__(self, rangestr):
    m = re.match('([.+a-zA-Z0-9-]+)((=|<|>|<=|>=)([.0-9]+))?', rangestr)
    if not m:
      error('bad package range format: {}'.format(rangestr))
    self.name = m.group(1)
    self.minimum = None
    self.maximum = None
    self.inclusive = False
    if m.group(2):
      self.inclusive = ('=' in m.group(3))
      v = Version(m.group(4))
      if '<' in m.group(3):
        self.maximum = v
      elif '>' in m.group(3):
        self.minimum = v
      else:
        self.minimum = self.maximum = v

  def __repr__(self):
    r = self.name
    if self.minimum and not self.maximum:
      r += '>'
    if self.maximum and not self.minimum:
      r += '<'
    if self.inclusive:
      r += '='
    if self.minimum:
      r += str(self.minimum)
    elif self.maximum:
      r += str(self.maximum)
    return r

  def __hash__(self):
    h = 0
    h = 31 * h + hash(self.name)
    h = 31 * h + hash(self.minimum)
    h = 31 * h + hash(self.maximum)
    h = 31 * h + hash(self.inclusive)
    return h

  def __eq__(self, other):
    ok = True
    ok = ok and self.name == other.name
    ok = ok and self.minimum == other.minimum
    ok = ok and self.maximum == other.maximum
    ok = ok and self.inclusive == other.inclusive
    return ok

  def has(self, package):
    if self.name != package.name:
      return False
    if self.minimum:
      if self.inclusive:
        if not (self.minimum <= package.version):
          return False
      else:
        if not (self.minimum < package.version):
          return False
    if self.maximum:
      if self.inclusive:
        if not (package.version <= self.maximum):
          return False
      else:
        if not (package.version < self.maximum):
          return False
    return True

class PackageProperties:
  def __init__(self, depends, conflicts, size):
    self.depends = depends
    self.conflicts = conflicts
    self.size = size

class Constraint:
  def __init__(self, constraintstr):
    if not re.match('[-+].*', constraintstr):
      error('bad constraint format: {}'.format(constraintstr))
    self.kind = constraintstr[0]
    self.packageRange = PackageRange(constraintstr[1:])

  def __repr__(self):
    return '{}{}'.format(self.kind, self.packageRange)

def load_commands(data):
  global commands
  commands = []
  for s in data:
    commands.append(Command(s))

def load_constraints(data):
  global final_constraints
  final_constraints = set()
  for s in data:
    final_constraints.add(Constraint(s))

def load_state(data):
  global state
  state = set()
  for s in data:
    state.add(Package(s))

def load_repository(data):
  global repository
  repository = {}
  for p in data:
    package = Package('{}={}'.format(p['name'], p['version']))
    if package in repository:
      error('package repeated in repo: {}={}'.format(p['name'], p['version']))
    depends = []
    pdep = p['depends'] if 'depends' in p else []
    for clause in pdep:
      depends.append([PackageRange(r) for r in clause])
    pconf = p['conflicts'] if 'conflicts' in p else []
    conflicts = [PackageRange(r) for r in pconf]
    size = int(p['size'])
    repository[package] = PackageProperties(depends, conflicts, size)

def load_all(args):
  with open(args.commands) as f:
    load_commands(json.load(f))
  with open(args.constraints) as f:
    load_constraints(json.load(f))
  with open(args.initial) as f:
    load_state(json.load(f))
  with open(args.repository) as f:
    load_repository(json.load(f))

clauses = None
repo_clauses_count = None
occurrences = None
packages = None
rpackages = None
watches = None  # watches[c] is some literal which makes the clause c true (could be None)
unsat_clauses = None
val = None # val[v] in [v, -v]

class Unsat(Exception):
  def __init__(self, ps):
    self.clause = ps
  def __str__(self):
    return ' '.join(self.s(p) for p in self.clause)
  def s(self, p):
    return ('+' if p > 0 else '-') + str(packages[abs(p)])

def find_watch(ps):
  global val
  for p in ps:
    if val[abs(p)] == p:
      return p
  return None

def set_watch(c):
  global clauses
  global watches
  global unsat_clauses
  if watches[c] is None:
    unsat_clauses.remove(c)
  watches[c] = find_watch(clauses[c])
  if watches[c] is None:
    unsat_clauses.add(c)

def add_clause(one_clause):
  global clauses
  global watches
  n = len(clauses)
  for l in one_clause:
    occurrences[l].add(n)
  clauses.append(one_clause)
  watches.append(None)
  unsat_clauses.add(n)
  set_watch(n)

def preprocess():
  global clauses
  global occurrences
  global packages
  global repo_clauses_count
  global repository
  global rpackages
  global unsat_clauses
  global val
  global watches

  # We'll refer to packages by positive integers.
  packages = [None] + list(repository.keys())
  rpackages = { packages[i] : i for i in range(1, len(packages)) }
  val = [None] + [i if packages[i] in state else -i for i in range(1,len(packages))]

  # For each PackageRange in the repo, compute which packages it matches.
  pranges = set()
  for props in repository.values():
    for clause in props.depends:
      for constraint in clause:
        pranges.add(constraint)
    for r in props.conflicts:
      pranges.add(r)
  for constraint in final_constraints:
    pranges.add(constraint.packageRange)
  versions = defaultdict(list)
  for package in repository.keys():
    versions[package.name].append(package.version)
  inrange = {} # lists all packages in a given range, by their indices
  for r in pranges:
    inrange[r] = []
    for v in versions[r.name]:
      p = Package('{}={}'.format(r.name, v))
      if r.has(p):
        inrange[r].append(rpackages[p])

  # Add clauses for depends and conflicts.
  clauses = []
  watches = []
  unsat_clauses = set()
  occurrences = defaultdict(set)
  for package, props in repository.items():
    p = rpackages[package]
    for dclause in props.depends:
      new_clause = [-p]
      for r in dclause:
        for q in inrange[r]:
          new_clause.append(q)
      add_clause(new_clause)
    for r in props.conflicts:
      for q in inrange[r]:
        add_clause([-p, -q])
  repo_clauses_count = len(clauses)

  # Add clauses for final_constraints.
  for constraint in final_constraints:
    if constraint.kind == '-':
      for q in inrange[constraint.packageRange]:
        add_clause([-q])
    else:
      add_clause(list(inrange[constraint.packageRange]))

def set_literal(p):
  if val[abs(p)] == p:
    return
  val[abs(p)] = p
  if p < 0:
    state.remove(packages[-p])
  else:
    state.add(packages[p])
  for c in occurrences[-p]:
    if watches[c] == -p:
      set_watch(c)
  for c in occurrences[p]:
    if watches[c] is None:
      watches[c] = p
      unsat_clauses.remove(c)

def flip_var(v):
  set_literal(-val[v])

def install_package(package):
  if package in state:
    error('package already installed: {}'.format(package))
  if package not in repository:
    error('package not in repository: {}'.format(package))
  set_literal(rpackages[package])

def uninstall_package(package):
  if package not in state:
    error('package not installed: {}'.format(package))
  set_literal(-rpackages[package])

def main():
  global commands
  global final_constraints
  global repository
  args = argparser.parse_args()
  load_all(args)
  preprocess()
  if any(c < repo_clauses_count for c in unsat_clauses):
    error('invalid initial state; unsat constraint {}'.format(e))
  cost = 0
  for cmd in commands:
    if cmd.action == '+':
      install_package(cmd.package)
      cost += repository[cmd.package].size
    else:
      uninstall_package(cmd.package)
      cost += 1000000
    for c in unsat_clauses:
      if c < repo_clauses_count:
        error('bad command {}; unsat constraint {}'.format(cmd, Unsat(clauses[c])))
  if unsat_clauses:
    c = unsat_clauses.pop()
    error('constraint not satisfied: {}'.format(c))
  sys.stdout.write('cost {}\n'.format(cost))

if __name__ == '__main__':
  main()


#for bisa digunakan untuk mengiterasi list
list = ["haha","hehe","huhu"]

for i in list:
    print(i)

#range juga bisa digunakan dalam for
#range tidak menyimpan keseluruhan angka dari start sampai stop, seperti list. namun ia hanya akan mengembalikan nilai individual atau subrange tertentu saja yang dibutuhkan
#pada iterasi pertama i mengakses index - dari range(10), sehingga mengembalikan range(10)[0], yaitu 0. iterasi kedua mengakses index ke 1 berarti mengembalikan range(10)[1] dan seterusnya sampe stop-1
for i in range(10):
    print(i)

#untuk mendapatkan informasi mengenai index dari looping for suatu list dapat digunakan range dan len
listku = [4,True,"hehe","haha"]

for i in range(len(listku)):
    print(i)
    print(listku[i])

#string juga bisa digunakan falam for karena bisa diakses melewati index tiap karakternya
stringku = "stingku"
for chara in stringku:
    print(chara)

#while bisa menggunakan () atau menggunakan spasi untuk statement kondisinya agar memisahkan dengan while
j=0
while(j<10):
    print(j)
    j+=1

k=100
while k<110:
    print(k)
    k+=1