from tkinter import *
from tkinter import messagebox
a = 0.
b = 0.
c = 0.
def fa_jauns():
    messagebox.showinfo("Info","Šeit jāapstrādā komanda")
def fa_autors():
    messagebox.showinfo("Autors","Vilis Vilītis"+"\n"+"12.VI")
def fa_datuievadsa():
    global a
    a = float(input("Ievadiet a:"))
def fa_datuievadsb():
    global b
    b = float(input("Ievadiet b:"))
def fa_datuievadsc():
    global c
    c = float(input("Ievadiet c:"))
def fa_rez():
    global a
    global b
    global c
    print("a=",a," b=",b," c=",c)
    label2 = Label(logs1, text = 'Rezultāts:'+str(a+b+c), fg = 'black',
                  bg = 'white', font = (None, 12), height = 2)
    label2.pack(side = BOTTOM)
# Izveidojam logu
logs1 = Tk()
logs1.title("Mana programma")
# šeit uzlikt logam fona krāsu
logs1.geometry("400x400")
menubar = Menu(logs1) # sagatavo izvēlņu joslu
# Izveido komandas 1
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Jauns", command=fa_jauns)
filemenu.add_command(label="Open", command=fa_jauns)
filemenu.add_command(label="Save", command=fa_jauns)
filemenu.add_command(label="Autors", command=fa_autors)
filemenu.add_separator()
filemenu.add_command(label="Close", command=fa_jauns)
# --- nākamās divas rindiņas ievieto izvēlņu joslā
# iepriekš sagatavoto kaskādi
menubar.add_cascade(label="File", menu=filemenu)
logs1.config(menu=menubar)
# Izveido komandas 2
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Mala a:", command=fa_datuievadsa)
editmenu.add_command(label="Mala b:", command=fa_datuievadsb)
editmenu.add_command(label="Mala c:", command=fa_datuievadsc)
editmenu.add_command(label="Rezultāts", command=fa_rez)
# --- nākamās divas rindiņas ievieto izvēlņu joslā
# iepriekš sagatavoto kaskādi
menubar.add_cascade(label="Edit", menu=editmenu)
logs1.config(menu=menubar)
#messagebox.showinfo("Info","Šī ir vienkāršā info")
#messagebox.showwarning("Ūūū", "Šis ir brīdinājums")
#messagebox.showerror("Alles kaput", "Fatāla kļūda")
label1 = Label(logs1, text = 'Mala a:', fg = 'black',
                  bg = 'white', font = (None, 12), height = 2)
label1.pack(side = TOP)

# Veidojam pogu
poguRamis = Frame(logs1, bg='white')
poga_a = Button(poguRamis, text = 'Mala a:', width = 25, height = 2, command=fa_datuievadsa)
poga_a.grid(row=0, column=0, pady = 10, padx = 25, sticky=W)
poga_b = Button(poguRamis, text = 'Mala b:', width = 25, height = 2, command=fa_datuievadsb)
poga_b.grid(row=1, column=0, pady = 10, padx = 25, sticky=W)
poga_c = Button(poguRamis, text = 'Mala c:', width = 25, height = 2, command=fa_datuievadsc)
poga_c.grid(row=2, column=0, pady = 10, padx = 25, sticky=W)
poguRamis.pack(side=TOP)
# -----
# Datu ievads
#ievadRamis = Frame(logs1, bg='white')
#ievadRamis.Label(logs1, text="First Name").grid(row=0)
#ievadRamis.Label(logs1, text="Last Name").grid(row=1)

#e1 = ievadRamis.Entry(logs1)
#e2 = ievadRamis.Entry(logs1)
#ievadRamis.pack(side=TOP)
logs1.mainloop()


import argparse
import os
import json
from src.plot_utils import plotLightCurve
from src.CNN import classification as CNN
import src.normalizing_flows as NF
import src.nf_metrics as nf_met
import src.cnn_metrics as cnn_met
import sys
import shutil
import numpy as np

def plots(nf):
    passband2name = {0: 'g', 1: 'r'}
    df = nf.df # Accessing the dataframe from NF object
    objects = nf.objects # Accessing unique objects from data
    path = "Nf_run_plots/"
    #creates Nf_run_plots and saves plots at each run
    isExist = os.path.exists(path)
    if isExist:
        shutil.rmtree(path)
    os.makedirs(path)

    for i in range(len(objects)):
        obj_name = objects[i]
        df_obj = df.loc[df['object_id'] == obj_name] # select data for object=object_name
        plotLightCurve(obj_name, df_obj, nf.flux_pred[i], nf.aug_timestamps[i], passband2name)

# Run binary classification
def run_CNN(cnn_params, report_file, nf = 0, og = 0, run_nf = 0):

    X_matrix = []
    y_vector = []
    X_test = []
    y_test = []

    if (not run_nf):

        X_file = os.path.join("data", "images.json")
        y_file = os.path.join("data", "labels.json")
        with open(X_file, 'r') as f:
            X_matrix = json.load(f)
        with open(y_file, 'r') as f:
            y_vector = json.load(f)

    else:
        if og:
            X_file = os.path.join("data", "images.json")
            y_file = os.path.join("data", "labels.json")
            with open(X_file, 'r') as f:
                X_matrix = json.load(f)
            with open(y_file, 'r') as f:
                y_vector = json.load(f)
            X_test = nf.X_matrix
            y_test = nf.y_vector
            X_test = np.array(X_test)
            y_test = np.array(y_test)
            X_test = np.array((X_test - X_test.mean()) / X_test.std(), dtype = np.float32)
        else:
            X_matrix = nf.X_matrix
            y_vector = nf.y_vector

    X_matrix = np.array(X_matrix)
    y_vector = np.array(y_vector)
    # normalize input data
    X_matrix = np.array((X_matrix - X_matrix.mean()) / X_matrix.std(), dtype = np.float32)

    print('Training CNN')
    y_test, y_test_pred = CNN(cnn_params, X_matrix, y_vector, report_file, og, X_test, y_test)

    # Report
    report = cnn_met.gen_report(y_test, y_test_pred)
    print(report)

    original_stdout = sys.stdout
    with open(report_file, 'a') as f:
        sys.stdout = f
        print(report)
        sys.stdout = original_stdout

if __name__ == '__main__':

    # Command line arguments
    parser = argparse.ArgumentParser(description='Classification of Supernovae Light Curves by NF approximation')

    # Default values of parameters are defined
    parser.add_argument('--param', default = 'param/param.json', help='file containing hyperparameters')
    parser.add_argument('-nf', '--nf', help="input number of objects generated by normalizing flows", type = int, default = 0)
    parser.add_argument('-v', '--verbose', help="increase output verbosity", action="store_true")
    parser.add_argument('-p', '--plot', help="generate plots", action="store_true" )
    parser.add_argument('-s', '--shuffle', help="Shuffles the objects generated by Normalizing Flows", action="store_true")
    parser.add_argument('-o', '--og', help="Runs CNN to classify the objects generated by Normalizing Flows", action="store_true")

    args = parser.parse_args()
    num_objects = args.nf

    verbose = args.verbose
    plot = args.plot
    shuffle = args.shuffle
    og = args.og

    # Hyperparameters from json file
    with open(args.param) as paramfile:
        param = json.load(paramfile)

    # Creates a report file
    report_file = 'report.txt'

    if os.path.exists(report_file):
        os.remove(report_file)
    f = open(report_file, 'w')
    f.close()

    cnn_params = param["CNN"]

    # Runs CNN as default
    if (num_objects == 0):
        run_CNN(cnn_params, report_file)
    else:
        # Load data
        nf_params = param["NF"]
        data_dir = 'data/ANTARES_NEW.csv'

        print('Training NF')
        # Run Normalizing Flows to obtain the approximate light curve
        nf = NF.FitNF(data_dir, shuffle, num_objects, nf_params, report_file, verbose)

        metrics = nf_met.generate_NF_report(nf.flux, nf.flux_pred_metrics, nf.flux_err, nf.flux_err_pred_metrics)
        metrics.to_csv('nfmetrics.csv')

        original_stdout = sys.stdout
        with open(report_file, 'a') as f:
            sys.stdout = f
            print(metrics)
            sys.stdout = original_stdout

        if plot:
            plots(nf)

        run_CNN(cnn_params, report_file, nf, og, run_nf = 1)


#
# @lc app=leetcode id=290 lang=python3
#
# [290] Word Pattern
#
# https://leetcode.com/problems/word-pattern/description/
#
# algorithms
# Easy (38.50%)
# Likes:    1869
# Dislikes: 221
# Total Accepted:    255.5K
# Total Submissions: 663.4K
# Testcase Example:  '"abba"\n"dog cat cat dog"'
#
# Given a pattern and a string s, find if s follows the same pattern.
#
# Here follow means a full match, such that there is a bijection between a
# letter in pattern and a non-empty word in s.
#
#
# Example 1:
#
#
# Input: pattern = "abba", s = "dog cat cat dog"
# Output: true
#
#
# Example 2:
#
#
# Input: pattern = "abba", s = "dog cat cat fish"
# Output: false
#
#
# Example 3:
#
#
# Input: pattern = "aaaa", s = "dog cat cat dog"
# Output: false
#
#
# Example 4:
#
#
# Input: pattern = "abba", s = "dog dog dog dog"
# Output: false
#
#
#
# Constraints:
#
#
# 1 <= pattern.length <= 300
# pattern contains only lower-case English letters.
# 1 <= s.length <= 3000
# s contains only lower-case English letters and spaces ' '.
# s does not contain any leading or trailing spaces.
# All the words in s are separated by a single space.
#
#
#

# @lc code=start
class Solution:
    def wordPattern(self, s: str, t: str) -> bool:
        t = t.split()
        if len(s) != len(t) or len(set(s)) != len(set(t)):
            return False
        hashmap = {}
        maphash = {}
        for ss, tt in zip(s, t):
            if ss in hashmap:
                if tt != hashmap[ss]:
                    return False
            hashmap[ss] = tt
            if tt in maphash:
                if ss != maphash[tt]:
                    return True
            maphash[tt] = ss
        return True

# @lc code=end


'''
redo #1
- pay attention to the colon after else
'''

from typing import Optional

class TreeNode:
    def __init__(self, val, left = None, right = None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def dfs(left, right):
            if left == None  and right == None:
                return True

            if left == None or right == None:
                return False

            is_symmetric = (left.val == right.val and
                            dfs(left.left, right.right) and
                            dfs(left.right, right.left)
                            )
            return is_symmetric

        return(dfs(root.left, root.right))

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(4)
root.right.right = TreeNode(3)

s = Solution()

print(s.isSymmetric(root))


import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import transforms, datasets,models
from collections import OrderedDict
from PIL import Image
def pretrained_model_info(pretrained_name):

    #upload the pretrained model
    x="models."+pretrained_name+"(pretrained=True)"
    #exec("model="+x)
    model = eval(x)
    #print(model)
    #Get keys and values of the model
    list_keys=[]
    list_value=[]
    for key in model.state_dict():
        value = model.state_dict().get(key)
        list_keys.append(key)
        list_value.append(value)

    #Get the last key of the model by eliminating chars after "."
    last_layer_key  = list_keys[-1].split('.')[0]

    #Get size of the input to the classification layer
    for key in list_keys:
        if(key.split('.')[0]==last_layer_key):
            break

    x= model.state_dict().get(key).size()

    #return name of the classifier layer and the size of its input
    return model,last_layer_key,int(x[1])

def building_model(hiden_units,pretrained_name,learning_rate):

    model,key,size = pretrained_model_info(pretrained_name)

    #Defining the classifier
    classifier =  nn.Sequential(OrderedDict([
                          ('fc1', nn.Linear(size, hiden_units)),
                          ('c_relu1', nn.ReLU()),
                          ('c_drop1', nn.Dropout()),
                          ('fc3', nn.Linear(hiden_units, 102)),
                          ('output', nn.LogSoftmax(dim=1))
                          ]))

    #fixing the gradient
    for param in model.parameters():
        param.requires_grad = False

    #replacing the classifier
    x="model."+key+"=classifier"
    exec(x)
    x= "optim.Adam(model."+key+".parameters(), learning_rate)"
    optimizer = eval(x)
    return model,optimizer

def data_preparation(data_dir,train_batch=32,valid_batch=16,test_batch=16):

    train_dir = data_dir + '/train'
    valid_dir = data_dir + '/valid'
    test_dir = data_dir + '/test'

    # Define your transforms for the training, validation, and testing sets
    train_transforms = transforms.Compose([transforms.RandomRotation(30),
                                       transforms.RandomResizedCrop(224),
                                       transforms.RandomHorizontalFlip(),
                                       transforms.ToTensor(),
                                       transforms.Normalize([0.485, 0.456, 0.406],
                                                            [0.229, 0.224, 0.225])])

    test_valid_transforms = transforms.Compose([transforms.Resize(256),
                                      transforms.CenterCrop(224),
                                      transforms.ToTensor(),
                                      transforms.Normalize([0.485, 0.456, 0.406],
                                                           [0.229, 0.224, 0.225])])
    # Load the datasets with ImageFolder
    train_datasets = datasets.ImageFolder(root=train_dir,transform=train_transforms)
    valid_datasets = datasets.ImageFolder(root=valid_dir,transform=test_valid_transforms)
    test_datasets = datasets.ImageFolder(root=test_dir,transform=test_valid_transforms)

    # Using the image datasets and the trainforms, define the dataloaders
    trainloader = DataLoader(train_datasets, batch_size=train_batch, shuffle=True)
    validloader = DataLoader(valid_datasets, batch_size=valid_batch)
    testloader = DataLoader(test_datasets, batch_size=test_batch)

    return train_datasets,trainloader,validloader,testloader

criterion = nn.NLLLoss()

def train(model,train_datasets,trainloader,validloader,testloader,optimizer,device,epochs,hiden_units,pretrained_name,\
          learning_rate,file_path):

    #optimizer = optim.Adam(model.fc.parameters(), learning_rate)
    epochs = epochs
    model.train(True)
    # change to device
    model.to(device)
    print_every = 1
    for e in range(epochs):
        steps = 0
        running_loss = 0
        for ii, (inputs, labels) in enumerate(trainloader):
            steps += 1

            inputs, labels = inputs.to(device), labels.to(device)

            optimizer.zero_grad()

            # Forward and backward passes
            outputs = model.forward(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            running_loss += loss.item()

            if steps % print_every == 0:
                valid_loss,valid_accuracy = valid(model,validloader,device)
                print("Epoch: {}/{}... ".format(e+1, epochs),
                     "Loss: {:.4f}".format(running_loss/print_every))
                running_loss = 0
                print("validation_loss: {:.4f}".format(valid_loss),'validation_accuracy: %d %%' % valid_accuracy)

    save_checkpoint(model,epochs,train_datasets,hiden_units,pretrained_name,learning_rate,file_path)

def valid(model,validloader,device):
    correct = 0
    total = 0
    with torch.no_grad():
        model.train(False)
        model.to(device)
        running_loss = 0
        step=0
        for ii,(inputs,labels) in enumerate(validloader):
            step+=1

            inputs, labels = inputs.to(device), labels.to(device)
            outputs = model.forward(inputs)
            loss = criterion(outputs, labels)
            running_loss += loss.item()

            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()
    #print("Validation_Loss: {:.4f}".format(running_loss/step))
    return running_loss/step,(100 * (correct / total))

def test(model,testloader,device):
    correct = 0
    total = 0
    with torch.no_grad():
        model.eval()
        model.to(device)
        for ii,(inputs,labels) in enumerate(testloader):
            inputs, labels = inputs.to(device), labels.to(device)
            outputs = model(inputs)

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

def save_checkpoint(model,epoch,train_datasets,hiden_units,pretrained_name,learning_rate,filename='new.pkl'):
    state = {
    'hiden_units': hiden_units,
    'pretrained_name': pretrained_name,
    'learning_rate': learning_rate,
    'epoch': epoch,
    'state_dict': model.state_dict(),
    'class_to_idx': train_datasets.class_to_idx
            }
    torch.save(state, filename)

def load_checkpoint(filename='new.pkl'):

    saved = torch.load(filename,lambda storage, loc: storage)

    model,optimizer = building_model(saved['hiden_units'],saved['pretrained_name'],saved['learning_rate'])

    model.load_state_dict(saved['state_dict'])

    return model,saved['class_to_idx']

def process_image(image):
    ''' Scales, crops, and normalizes a PIL image for a PyTorch model,
        returns an Numpy array
    '''
    side = 256
    w,h = image.size
    max_side = max(w,h)
    #plt.imshow(image)

    if(max_side==w):
        ratio = w/h
        x=[int(256*ratio),256]
    else:
        ratio=h/w
        x=[256,int(256*ratio)]

    image = image.resize(x)
    width,height = image.size

    left = (width - 224)/2
    top = (height - 224)/2
    right = (width + 224)/2
    bottom = (height + 224)/2

    image = image.crop((left, top, right, bottom))

    np_image = np.array(image)

    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    np_image = np_image/255
    np_image = (np_image-mean)/std
    np_image = np_image.transpose((2,0,1))

    return np_image

def predict(image_path, model, device,class_to_idx,topk):
    ''' Predict the class (or classes) of an image using a trained deep learning model.
    '''
    with torch.no_grad():
        im = Image.open(image_path)
        input_im = process_image(im)
        model.to(device)
        model.eval()
        input=(torch.from_numpy(input_im)).unsqueeze_(0).float()
        input = input.to(device)

        output=model(input)
        topk, indices = output.topk(topk)

        topk = np.exp(topk.data.cpu().numpy()[0])
        indices = indices.data.cpu().numpy()[0]

        inv_map = {v: k for k, v in class_to_idx.items()}
        classes = [inv_map[x] for x in indices]

        return topk,classes


import ast
import re
import textwrap
from unittest.mock import Mock

from regexploit.bin.regexploit_python_ast import handle_file
from regexploit.found_regex import FoundRegex
from regexploit.languages.python_node_visitor import PythonNodeVisitor

def patterns_from_code(code: str):
    pnv = PythonNodeVisitor()
    code = textwrap.dedent(code)
    pnv.visit(ast.parse(code))
    return pnv.patterns

def test_basic():
    code = """
    MY_RE = "abc+d+"
    def x():
        '''Just*a*docstring*'''
        a = "nostarsorpluses"
        b = "(" + re.sub("aregex", "*****", "notaregex", flags=re.A) + ")"
        return re.compile(b"x*y*z", re.X | re.MULTILINE)
    """
    patterns = patterns_from_code(code)
    assert len(patterns) == 3
    assert patterns[0] == FoundRegex(2, "abc+d+", 0, False)
    assert patterns[1] == FoundRegex(6, "aregex", re.A, True)
    assert patterns[2] == FoundRegex(7, "x*y*z", re.X | re.MULTILINE, True)

def test_file():
    output = Mock(spec=["next"])
    handle_file(__file__, output)
    assert output.next.call_count == 2  # abc+d+, x*y*z, code string errors


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def DFS(self,root,currentPath,target):
        if not root:
            return

        currentPath.append(root)
        if root.val == target:
            return
        elif root.val > target:
            self.DFS(root.left,currentPath,target)
        elif root.val < target:
            self.DFS(root.right,currentPath,target)
        return

    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        currentPath = []
        pathP = []
        pathQ = []
        self.DFS(root,currentPath,p.val)
        pathP = currentPath

        currentPath = []
        self.DFS(root,currentPath,q.val)
        pathQ = currentPath

        if len(pathQ) >= len(pathP):
            smallerPath = pathP
        else:
            smallerPath = pathQ

        for i in range(0,len(smallerPath)):
            if pathP[i].val != pathQ[i].val:
                return pathP[i - 1]
        return smallerPath[len(smallerPath) - 1]


import os
import shutil
from datetime import datetime
import numpy as np

class MiniRNN:
    def __init__(
        self,
        n_hidden_neurons: int,
        train_data: str,
        seq_length=25,
        model_name="miniRNN",
    ) -> None:
        """Initialize Mini RNN for character level generation

        Args:
            n_hidden_neurons (int): Number of Neurons in the hidden layer
            vocab_size (int): Number of unique characters for the RNN to predict
            seq_length (int): number of steps to unroll the RNN for.
                Defaults to 25.
            model_name (str): Model Name. Defaults to miniRNN
        """
        self.data = train_data
        chars = list(set(train_data))
        self.data_size, self.vocab_size = len(train_data), len(chars)

        self.char_to_ix = {ch: i for i, ch in enumerate(chars)}
        self.ix_to_char = {i: ch for i, ch in enumerate(chars)}

        self.seq_length = seq_length
        self.n_hidden_neurons = n_hidden_neurons
        self.model_name = model_name

        # Initialize weights
        self.model_weights = {
            # input -> hidden_state
            "xh": np.random.randn(n_hidden_neurons, self.vocab_size) * 0.01,
            # prev_hidden_state -> next_hidden_state
            "hh": np.random.randn(n_hidden_neurons, n_hidden_neurons) * 0.01,
            # hidden_state -> output
            "hy": np.random.randn(self.vocab_size, n_hidden_neurons) * 0.01,
        }

        # Initialize Biases
        self.model_biases = {
            # input to hidden
            "xh": np.zeros((n_hidden_neurons, 1)),
            # hidden to output
            "hy": np.zeros((self.vocab_size, 1)),
        }

    def calc_gradients(self, inputs: list, targets: list, h_prev):
        """_summary_

        Args:
            inputs (list): _description_
            targets (list): _description_
            h_prev (_type_): _description_
        """
        inputs_x, hidden_states_h, preds_y, probabs_p = {}, {}, {}, {}

        # Last hidden state vars is hprev
        hidden_states_h[-1] = np.copy(h_prev)
        loss = 0

        # forward pass
        for t in range(len(inputs)):
            # one-hot encoding of input
            # create a list of zeros of size: vocab_size
            inputs_x[t] = np.zeros((self.vocab_size, 1))
            # set the index of the char to 1
            inputs_x[t][inputs[t]] = 1

            # calculate the hidden state
            hidden_states_h[t] = np.tanh(
                np.dot(self.model_weights["xh"], inputs_x[t])
                + np.dot(self.model_weights["hh"], hidden_states_h[t - 1])
                + self.model_biases["xh"]
            )

            # calculate the next output
            # unnormalized log probabilities for next chars
            preds_y[t] = (
                np.dot(self.model_weights["hy"], hidden_states_h[t])
                + self.model_biases["hy"]
            )

            # normalized probabilities for next chars
            probabs_p[t] = np.exp(preds_y[t]) / np.sum(np.exp(preds_y[t]))

            # Calculate loss: softmax (cross-entropy loss)
            loss += -np.log(probabs_p[t][targets[t], 0])

        # backward pass: compute gradients going backwards
        # set gradient matrices to be the same size as weights
        dWxh, dWhh, dWhy = (
            np.zeros_like(self.model_weights["xh"]),
            np.zeros_like(self.model_weights["hh"]),
            np.zeros_like(self.model_weights["hy"]),
        )
        # set bias matrices
        dbh, dby = (
            np.zeros_like(self.model_biases["xh"]),
            np.zeros_like(self.model_biases["hy"]),
        )
        # set a dummy dh_next var
        dhnext = np.zeros_like(hidden_states_h[0])

        # Go back every step and calculate grads
        for t in reversed(range(len(inputs))):
            # grad of y
            dy = np.copy(probabs_p[t])
            # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here
            dy[targets[t]] -= 1
            dWhy = np.dot(dy, hidden_states_h[t].T)
            dby += dy
            dh = np.dot(self.model_weights["hy"].T, dy) + dhnext
            dhraw = (
                1 - hidden_states_h[t] * hidden_states_h[t]
            ) * dh  # grad of tanh
            dbh += dhraw
            dWxh += np.dot(dhraw, inputs_x[t].T)
            dWhh += np.dot(dhraw, hidden_states_h[t - 1].T)
            dhnext = np.dot(self.model_weights["hh"].T, dhraw)

        # Clip gradients to mitigate exploding grad problem
        for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
            np.clip(dparam, -5, 5, out=dparam)

        return (
            loss,
            dWxh,
            dWhh,
            dWhy,
            dbh,
            dby,
            hidden_states_h[len(inputs) - 1],
        )

    def sample(self, h: np.array, seed_ix: int, n: int) -> list:
        """_summary_

        Args:
            h (np.array): _description_
            seed_ix (int): _description_
            n (int): _description_

        Returns:
            list: _description_
        """
        x = np.zeros((self.vocab_size, 1))
        x[seed_ix] = 1

        ixes = []
        for _ in range(n):
            # calc hidden state based on x, ws & bh, and prev state 'h'
            h = np.tanh(
                np.dot(self.model_weights["xh"], x)
                + np.dot(self.model_weights["hh"], h)
                + self.model_biases["xh"]
            )

            # calc predictions through the updated hidden state
            y = np.dot(self.model_weights["hy"], h) + self.model_biases["hy"]

            # normalize probabilites
            p = np.exp(y) / np.sum(np.exp(y))

            # TODO: Understand this piece of code.
            ix = np.random.choice(range(self.vocab_size), p=p.ravel())
            x = np.zeros((self.vocab_size, 1))
            x[ix] = 1
            ixes.append(ix)
        return ixes

    def save_model_params(self, model_dir: str, model_iter: int) -> None:
        """Save Model Weights"""

        # Make Dir for the model iteration
        os.makedirs(f"{model_dir}/{model_iter}")

        # Save Model Weights
        for param_name, param in self.model_weights.items():
            with open(
                f"{model_dir}/{model_iter}/weights_{param_name}.npy", "wb"
            ) as f:
                np.save(f, param)

        # Save Model Biases
        for param_name, param in self.model_biases.items():
            with open(
                f"{model_dir}/{model_iter}/biases_{param_name}.npy", "wb"
            ) as f:
                np.save(f, param)

    def load_model_params(self, model_dir=str, model_ckpt="latest") -> None:
        if not os.path.isdir(model_dir):
            print("Model Path doesn't exist")

        model_ckpts = next(os.walk(model_dir))[1]
        if model_ckpt == "latest":
            if "final" in model_ckpts:
                model_ckpt = "final"
            else:
                model_ckpt = max([int(x) for x in model_ckpts])
        else:
            if str(model_ckpt) not in model_ckpts:
                print("Model checkpoint not found!")
                return None

        # Load Weights
        for w_ in list(self.model_weights.keys()):
            with open(f"{model_dir}/{model_ckpt}/weights_{w_}.npy", "rb") as f:
                self.model_weights[w_] = np.load(f)

        # Load Biases
        for b_ in list(self.model_biases.keys()):
            with open(f"{model_dir}/{model_ckpt}/biases_{b_}.npy", "rb") as f:
                self.model_biases[b_] = np.load(f)

    def train(
        self,
        num_epochs: int,
        learning_rate=1e-1,
        checkpoint_range=1000,
        verbose=False,
        save_model=True,
    ) -> None:
        """Train Model

        Args:
            data (str): Data to train upon
            num_epochs (int): Number of epochs to train on
            learning_rate (float): Learning Rate of the model. Defaults to 1e-1.
            checkpoint_range (int): Checkpoint range. Defaults to 100.
            verbose (bool): Whether to print predictions at every checkpoint. Defaults to False.
            save_model_weights (bool): Whether to save model weights. Defaults to True.
        """

        print(f"Data size: {self.data_size}; Vocab Size: {self.vocab_size}")

        # Ensure checkpoints directory exists
        curr_time = datetime.now().strftime("%m_%d_%Y_T_%H_%M_%S")
        if self.model_name == "miniRNN":
            self.model_name += f"_{curr_time}"
        model_dir = f"saved_models/{self.model_name}"

        if os.path.isdir(model_dir):
            # to clear the existing
            shutil.rmtree(model_dir)
        os.makedirs(model_dir)

        p = 0
        # declare memory variables for Adagrad
        mWxh, mWhh, mWhy = (
            np.zeros_like(self.model_weights["xh"]),
            np.zeros_like(self.model_weights["hh"]),
            np.zeros_like(self.model_weights["hy"]),
        )
        mbh, mby = (
            np.zeros_like(self.model_biases["xh"]),
            np.zeros_like(self.model_biases["hy"]),
        )

        # loss at iteration 0
        smooth_loss = -np.log(1.0 / self.vocab_size) * self.seq_length

        print(f"Starting Training. Save Model: {save_model}, ")
        try:
            for epoch in range(num_epochs):
                # prepare inputs (we're sweeping from left to right in steps seq_length long)
                if p + self.seq_length + 1 >= len(self.data) or epoch == 0:
                    hprev = np.zeros(
                        (self.n_hidden_neurons, 1)
                    )  # reset RNN memory
                    p = 0  # go from start of self.data
                inputs = [
                    self.char_to_ix[ch]
                    for ch in self.data[p : p + self.seq_length]
                ]
                targets = [
                    self.char_to_ix[ch]
                    for ch in self.data[p + 1 : p + self.seq_length + 1]
                ]

                # sample from the model now and then
                if epoch % checkpoint_range == 0 and verbose:
                    sample_ix = self.sample(hprev, inputs[0], 200)
                    txt = "".join(self.ix_to_char[ix] for ix in sample_ix)
                    print("-" * 30, f"\n {txt} \n", "-" * 30)

                # forward seq_length characters through the net and fetch gradient
                loss, dWxh, dWhh, dWhy, dbh, dby, hprev = self.calc_gradients(
                    inputs, targets, hprev
                )
                smooth_loss = smooth_loss * 0.999 + loss * 0.001
                if epoch % checkpoint_range == 0:
                    print(f"Iteration: {epoch}; Loss: {smooth_loss}")

                    # Save Model
                    if save_model:
                        self.save_model_params(model_dir, epoch)

                # perform parameter update with Adagrad
                for param, dparam, mem in zip(
                    [
                        self.model_weights["xh"],
                        self.model_weights["hh"],
                        self.model_weights["hy"],
                        self.model_biases["xh"],
                        self.model_biases["hy"],
                    ],
                    [dWxh, dWhh, dWhy, dbh, dby],
                    [mWxh, mWhh, mWhy, mbh, mby],
                ):
                    mem += dparam * dparam
                    param += (
                        -learning_rate * dparam / np.sqrt(mem + 1e-8)
                    )  # adagrad update

                p += self.seq_length  # move self.data pointer
            print("Training Complete.")

        except KeyboardInterrupt:
            print("Halting Training.")

        # Save final weights & biases
        if save_model:
            print("Saving last checkpoint...")
            self.save_model_params(model_dir, "final")

    def predict_sequence(self, input_char: str, generated_str_len=200):
        hprev = np.zeros((self.n_hidden_neurons, 1))  # reset RNN memory

        sample_ix = self.sample(
            hprev, self.char_to_ix[input_char], generated_str_len
        )
        txt = "".join(self.ix_to_char[ix] for ix in sample_ix)
        print("-" * 30, f"\n {txt} \n", "-" * 30)


import logging, os

logger = logging.getLogger('main')
level = logging.getLevelName(os.environ.get('LOG_LEVEL', 'INFO'))
logger.setLevel(level)

# create console handler
ch = logging.StreamHandler()

# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch
ch.setFormatter(formatter)

logger.addHandler(ch)


import sqlite3, config

connection = sqlite3.connect(config.DB_FILE)

cursor = connection.cursor()

cursor.execute(
    """
    CREATE TABLE IF NOT EXISTS school (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    url TEXT NOT NULL
    )
    """
)

cursor.execute(
    """
    CREATE TABLE IF NOT EXISTS location (
    id INTEGER PRIMARY KEY,
    school_id INTEGER,
    city TEXT NOT NULL,
    zipcode TEXT NOT NULL,
    state TEXT NOT NULL,
    region TEXT NOT NULL,
    locale TEXT,
    FOREIGN KEY (school_id) REFERENCES school (id)
    )
    """
)

cursor.execute(
    """
    CREATE TABLE IF NOT EXISTS finance (
    id INTEGER PRIMARY KEY,
    school_id INTEGER,
    year DATE,
    cost4a REAL,
    in_state_tuition REAL,
    out_state_tuition REAL,
    FOREIGN KEY (school_id) REFERENCES school (id)
    )
    """
)

cursor.execute(
    """
    CREATE TABLE IF NOT EXISTS control (
    id INTEGER PRIMARY KEY,
    school_id INTEGER,
    under_investigation BOOLEAN,
    predominant_deg TEXT,
    highest_deg TEXT,
    control TEXT,
    FOREIGN KEY (school_id) REFERENCES school (id)
    )
    """
)

connection.commit()


import datetime
import random
from math import sqrt, log

class Node:

    def __init__(self, move = None, parent = None, state = None, last = None):
        self.move = move
        self.parentNode = parent
        self.children = []
        self.wins = 0
        self.visits = 0
        self.untriedMoves = state.get_moves()
        self.playerJustMoved = last

    def UCTSelectChild(self):
        m = sorted(self.children, key=lambda i: float(i.wins) / float(i.visits) + sqrt(2 * log(float(self.visits)) / float(i.visits)))[-1]
        return m

    def AddChild(self, m, s, last = None):
        new_node = Node(move=m, parent=self, state=s, last=last)
        self.untriedMoves.remove(m)
        self.children.append(new_node)
        return new_node

    def Update(self, result):
        self.visits += 1
        self.wins += result

    def __repr__(self):
        return '[M:' + str(self.move) + ' W/V:' + str(self.wins) + '/' + str(self.visits) + ' U:' + str(self.untriedMoves) + ']'

    def TreeToString(self, indent):
        s = self.a(indent) + str(self)
        for c in self.children:
            s += c.TreeToString(indent + 1)

        return s

    def IndentString(self, indent):
        s = '\n'
        for i in range(1, indent + 1):
            s += '| '

        return s

    def ChildrenToString(self):
        s = ''
        for c in self.children:
            s += str(c) + '\n'

        return s

def think(rootstate, quip):
    rollouts = 0
    who = rootstate.get_whos_turn()
    range = {'blue': 'red',
     'red': 'blue'}
    rootnode = Node(state=rootstate, last=range[who])
    now = datetime.datetime.now()
    while True:
        node = rootnode
        state = rootstate.copy()

        # Select
        while node.untriedMoves == [] and node.children != []:
            node = node.UCTSelectChild()
            state.apply_move(node.move)

        # Expand
        if node.untriedMoves != []:
            m = random.choice(node.untriedMoves)
            w = state.get_whos_turn()
            state.apply_move(m)
            node = node.AddChild(m, state, last=w)

        # Rollout
        while state.get_moves() != []:
            state.apply_move(random.choice(state.get_moves()))

        # Backpropagate
        score = state.get_score()
        rollouts += 1
        while node != None:
            node_score = score[node.playerJustMoved]
            node.Update(node_score)
            node = node.parentNode

        if datetime.datetime.now() - now > datetime.timedelta(seconds = 1):
            break
    quipText = "UCT rollouts per second: " + str(rollouts)
    quip(quipText)
    return sorted(rootnode.children, key=lambda i: i.visits)[-1].move


class Solution:
    def findRightInterval(self, intervals: List[List[int]]) -> List[int]:
        intvl = sorted([(x[0], i) for i, x in enumerate(intervals)], key=lambda x: x[0])

        starts, idx = [x[0] for x in intvl], [x[1] for x in intvl]

        res = []

        for x in intervals:
            pos = bisect.bisect_left(starts, x[1])
            if pos == len(starts):
                res.append(-1)
            else:
                res.append(idx[pos])
        return res


import csv

def read_csv_as_dict(file):
	"""
	[Function] read_csv_as_dict
	Helper function to convert CSV data to array of dictionary.
	The CSV must have headers for this function to work.

	Parameters:
		- file : filename.

	Returns: [List of Dictionary] data
	"""
	datas = []
	with open(file) as csv_file:
		csv_reader = csv.reader(csv_file, delimiter=',')
		line_count = 0
		keys = []
		for row in csv_reader:
			data = {}
			if len(keys) == 0:
				keys = row
			elif len(row) != 0:
				#print(row)
				for i in range(0,len(keys)):
					data[keys[i]]=row[i]
				datas.append(data)
	return datas


import json
from collections import OrderedDict

def buildCommand(jsonFile):
    return json.dumps(clean(json.loads(jsonFile, object_pairs_hook=OrderedDict)))

def clean(x):
    print('...',x)
    print()
    if type(x) is int or type(x) is float:
        return 0
    elif type(x) is str :
        return ""
    elif type(x) is list:
        return []
    elif type(x) is OrderedDict:
        print('this order dict')
        res = OrderedDict()
        for i, j in x.items():
            #처음 x가 들어오면, {}기준으로 짤라서 res가되어 clean함수로 재귀된다.
            res[i] = clean(j)
        return res

jsonFile= "{\"version\": \"0.1.0\",\"command\": \"c:python\",\"args\": [\"app.py\"],\"problemMatcher\": {\"fileLocation\": [\"relative\", \"${workspaceRoot}\"],\"pattern\": {\"regexp\": \"^(.*)+s$\", \"message\": 1}}}"

print(buildCommand(jsonFile))
#여기서는 dump의 개념과, loads()의 개념을 잡을 수 있다.

코드시그널/5. Python/Picturing the Parsibilities/BuildCommand.py


import torch
from torch import nn
from torch import optim
from torch.nn import functional as F

from .deeplab import DeepLab

import lightning.pytorch as pl
from torchmetrics import JaccardIndex

class FocalLoss(nn.Module):
    def __init__(self, alpha=1, gamma=0, ignore_index=255):
        super(FocalLoss, self).__init__()
        self.alpha = alpha
        self.gamma = gamma
        self.ignore_index = ignore_index

    def forward(self, inputs, targets):
        CE_loss = F.cross_entropy(
            inputs, targets, reduction='none', ignore_index=self.ignore_index)
        pt = torch.exp(-CE_loss)
        focal_loss = self.alpha * (1-pt) ** self.gamma * CE_loss
        return focal_loss.mean()

class ModelWrapper(pl.LightningModule):
    def __init__(
        self,
        num_classes,
        epochs: int=1000,
        lr_start=1e-3,
        lr_final=1e-5,
        wd=1e-4,
        alpha=1,
        gamma=0,
        backbone='resnet101',
        output_stride=16):

        super(ModelWrapper, self).__init__()
        self.model = DeepLab(num_classes, backbone=backbone, output_stride=output_stride)
        self.num_classes = num_classes
        self.criterion = FocalLoss(alpha, gamma, ignore_index=255)
        self.train_metric = JaccardIndex(task = 'multiclass', num_classes=num_classes, ignore_index=255, average='macro')
        self.val_metric = JaccardIndex(task = 'multiclass', num_classes=num_classes, ignore_index=255, average='macro')

        self.best_train_pixel_acc = 0
        self.best_val_pixel_acc = 0
        self.best_train_miou = 0
        self.best_val_miou = 0

        self.save_hyperparameters()

    def training_step(self, batch, batch_idx):
        image, label = batch
        out_img = self.model(image)
        loss = self.criterion(out_img, label)
        pred = out_img.max(1)[1]
        pixel_acc = torch.sum(pred == label) / label.numel()
        self.best_train_pixel_acc = max(pixel_acc, self.best_train_pixel_acc)
        self.log("train/loss", loss, sync_dist=True)
        self.log("train/pixel_acc", pixel_acc, sync_dist=True)
        self.log("train/best_pixel_acc", self.best_train_pixel_acc, sync_dist=True)
        self.train_metric.update(pred, label)
        return loss

    def on_train_epoch_end(self):
        # log epoch metric
        miou = self.train_metric.compute()
        self.best_train_miou = max(miou, self.best_train_miou)
        self.log('train/mIoU', miou, sync_dist=True)
        self.log('train/best_mIoU', self.best_train_miou, sync_dist=True)
        self.train_metric.reset()

    def validation_step(self, batch, batch_idx):
        image, label = batch
        out_img = self.model(image)
        loss = self.criterion(out_img, label)
        pred = out_img.max(1)[1]
        pixel_acc = torch.sum(pred == label) / label.numel()
        self.best_val_pixel_acc = max(pixel_acc, self.best_val_pixel_acc)
        self.log("val/loss", loss, sync_dist=True)
        self.log("val/pixel_acc", pixel_acc, sync_dist=True)
        self.log("val/best_pixel_acc", self.best_val_pixel_acc, sync_dist=True)
        self.val_metric.update(pred, label)

    def on_validation_epoch_end(self):
        # log epoch metric
        miou = self.val_metric.compute()
        self.best_val_miou = max(miou, self.best_val_miou)
        self.log('val/mIoU', miou, sync_dist=True)
        self.log('val/best_mIoU', self.best_val_miou, sync_dist=True)
        self.val_metric.reset()

    def test_step(self, batch, batch_idx):
        image, label = batch
        out_img = self.model(image)
        loss = self.criterion(out_img, label)
        pred = out_img.max(1)[1]
        pixel_acc = torch.sum(pred == label) / label.numel()
        self.log("pixel_acc", pixel_acc, sync_dist=True)
        self.val_metric.update(pred, label)

    def on_test_epoch_end(self):
        miou = self.val_metric.compute()
        self.log('mIoU', miou, sync_dist=True)
        self.val_metric.reset()

    def forward(self, batch):
        image, _ = batch
        out_img = self.model(image)
        pred = out_img.max(1)[1]
        return pred

    def configure_optimizers(self):
        optimizer = optim.AdamW(
            params=[
                {'params': self.model.backbone.parameters(), 'lr': 0.1 * self.hparams.lr_start},
                {'params': self.model.ASPP.parameters(), 'lr': self.hparams.lr_start},
                {'params': self.model.decoder.parameters(), 'lr': self.hparams.lr_start},
            ], lr=self.hparams.lr_start, weight_decay=self.hparams.wd)
        scheduler = optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=(self.hparams.lr_final / self.hparams.lr_start) ** (1 / self.hparams.epochs))
        return [optimizer], [scheduler]


''' FCFS Disk Schedulig algorithm in Python
By Yogesh Rana
CISC3320'''

def fcfs(head, requests):
    # Initialize total head movement to 0
    head_movement = 0
    # Loop through list of requests
    for request in requests:
        # if request (i) is not head
        if request != head:
            # print the movement from head to request line
            print(f"Moving header from {head} to ",end="")
            #if head is greater than request
            if head >= request:
                # calculate the difference
                difference = head - request
                # Add the difference to cumulative head_movement
                head_movement += difference
                # Assign a new head as request
                head = request
            # if head is smaller than request
            if head <= request:
                difference = request - head
                head_movement += difference
                head = request
            print(request)
            print(f" head movement for now: {head_movement}")
    return head_movement

if __name__ == "__main__":
    # Total number of cylinders
    num_disk_cylinders = 5000
    # Get the initial header possition from user GIVEN 65
    head = int(input("Enter initial head position: "))
    # Check if the entered head position is with in range of numbers of cylinders
    while not head in range(num_disk_cylinders+1):
        head = int(input("Please enter head position between 0-4999: "))

    request_sequence = [4078, 153, 2819, 3294, 1433, 211, 1594, 2004, 2335,
    2007, 771, 1043, 3950, 2784, 1881, 2931, 3599, 1245, 4086, 520, 3901,
    2866, 947, 3794, 2353, 3970, 3948, 1815, 4621, 372, 2684, 3088, 827,
    3126, 2083, 584, 4420, 1294, 917, 2881, 3659, 2868, 100, 1581, 4581,
    1664, 1001, 1213, 3439, 4706, 4869]
    #sequence = [82,170,43,140,24,16,190]
    # Call the FCFS function
    fcfc_head_movement = fcfs(head, request_sequence)
    print(f"The total number of head movements is : {fcfc_head_movement}")


"""build_pot command for setup.py"""

from __future__  import absolute_import, division, unicode_literals

import os
import glob
from distutils import log
from distutils.core import Command
from distutils.errors import DistutilsOptionError

class build_pot(Command):
    """Distutils command build_pot"""

    description = 'extract strings from python sources for translation'

    # List of options:
    #   - long name,
    #   - short name (None if no short name),
    #   - help string.
    user_options = [('build-dir=', 'd', 'Directory to put POT file'),
                    ('output=', 'o', 'POT filename'),
                    ('lang=', None, 'Comma-separated list of languages '
                                    'to update po-files'),
                    ('no-lang', 'N', "Don't update po-files"),
                    ('english', 'E', 'Regenerate English PO file'),
                   ]
    boolean_options = ['no-lang', 'english']

    def initialize_options(self):
        self.build_dir = None
        self.output = None
        self.lang = None
        self.no_lang = False
        self.english = False

    def finalize_options(self):
        if self.build_dir is None:
            self.build_dir = 'po'
        if not self.output:
            self.output = (self.distribution.get_name() or 'messages')+'.pot'
        if self.lang is not None:
            self.lang = [i.strip() for i in self.lang.split(',') if i.strip()]
        if self.lang and self.no_lang:
            raise DistutilsOptionError("You can't use options "
                "--lang=XXX and --no-lang in the same time.")

    def _force_LF(self, src, dst=None):
        f = open(src, 'rU')
        try:
            content = f.read()
        finally:
            f.close()
        if dst is None:
            dst = src
        f = open(dst, 'wb')
        try:
            f.write(content)
        finally:
            f.close()

    def run(self):
        """Run xgettext for project sources"""
        # project name based on `name` argument in setup() call
        prj_name = self.distribution.get_name()
        # output file
        if self.build_dir != '.':
            fullname = os.path.join(self.build_dir, self.output)
        else:
            fullname = self.output
        log.info('Generate POT file: ' + fullname)
        if not os.path.isdir(self.build_dir):
            log.info('Make directory: ' + self.build_dir)
            os.makedirs(self.build_dir)
        self.spawn(['xgettext',
                    '--keyword=N_',
                    '-p', self.build_dir,
                    '-o', self.output] +
                    glob.glob('cola/*.py') +
                    glob.glob('cola/*/*.py'))
        self._force_LF(fullname)
        # regenerate english PO
        if self.english:
            log.info('Regenerating English PO file...')
            if prj_name:
                en_po = prj_name + '-' + 'en.po'
            else:
                en_po = 'en.po'
            self.spawn(['msginit',
                '--no-translator',
                '-l', 'en',
                '-i', os.path.join(self.build_dir, self.output),
                '-o', os.path.join(self.build_dir, en_po),
                ])
        # search and update all po-files
        if self.no_lang:
            return
        for po in glob.glob(os.path.join(self.build_dir,'*.po')):
            if self.lang is not None:
                po_lang = os.path.splitext(os.path.basename(po))[0]
                if prj_name and po_lang.startswith(prj_name+'-'):
                    po_lang = po_lang[5:]
                if po_lang not in self.lang:
                    continue
            new_po = po + ".new"
            cmd = "msgmerge %s %s -o %s" % (po, fullname, new_po)
            self.spawn(cmd.split())
            # force LF line-endings
            log.info("%s --> %s" % (new_po, po))
            self._force_LF(new_po, po)
            os.unlink(new_po)


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

from openerp import models, fields, api
from openerp.exceptions import ValidationError

class OpHostel(models.Model):
    _name = 'op.hostel'

    name = fields.Char('Name', size=16, required=True)
    capacity = fields.Integer('Hostel Capacity', required=True)
    hostel_room_lines = fields.One2many(
        'op.hostel.room', 'hostel_id', 'Room(s)')

    @api.one
    @api.constrains('hostel_room_lines')
    def _check_hostel_capacity(self):
        if self.capacity <= 0:
            raise ValidationError('Enter proper Hostel Capacity')
        counter = 0.00
        for room in self.hostel_room_lines:
            counter += room.students_per_room
            if counter > self.capacity:
                raise ValidationError('Hostel Capacity Over')

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


#!/usr/bin/env python
import logging
import sys

import ldclient
import pandas as pd
from collections import OrderedDict
import uuid

#root = logging.getLogger()
#root.setLevel(logging.INFO)
#ch = logging.StreamHandler(sys.stdout)
#ch.setLevel(logging.INFO)
#formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#ch.setFormatter(formatter)
#root.addHandler(ch)

if __name__ == "__main__":
  ldclient.set_sdk_key("SDK KEY_Emily's Test Project - Test")

  # load dictionaries with name/sign data
  firstNameMap = { 'a': 'Amethyst', 'b': 'Bold', 'c': 'Curvy', 'd': 'Daring', 'e': 'Electric', 'f': 'Fatal', 'g': 'Grace', 'h': 'Horrendous', 'i': 'Ign', 'j': 'Jolly', 'k': 'Killer', 'l': 'Loud', 'm': 'Magnificent', 'n': 'Nasty', 'o': 'Orange', 'p': 'Plain', 'q': 'Queen', 'r': 'Righteous', 's': 'Saucy', 't': 'Terrifying', 'u': 'Unicorn', 'v': 'Vivacious', 'w': 'Wild', 'x': 'Xanthic', 'y': 'Yummy', 'z': 'Zesty'}
  lastNameMap = {'aries': 'Impulse', 'taurus': 'Bull', 'gemini': 'Twoface', 'cancer': 'Moody','leo': 'Star', 'virgo': 'Flawless', 'libra': 'Flake', 'scorpio': 'Intense','sagittarius': 'Airborne', 'capricorn': 'ambition', 'aquarius': 'Ice','pisces': 'Spacey'}

  # start generator
  playagain = "yes"
  while playagain.lower() == "yes":
    print ("Welcome to the Drag Name Generator!")
    # get user info
    firstname = input("Please enter your first name: ")
    while not firstname.isalpha():
        print ("You typed something wrong!")
        firstname = input("Please enter your first name: ")
    firstnameletter = firstname[:1]
    dragFirstName = firstNameMap[firstnameletter.lower()]

    sign = input("Please enter your astrological sign: ")
    while sign.lower() not in lastNameMap:
        print ("You typed something wrong!")
        sign = input("Please enter your astrological sign: ")
    dragLastName = lastNameMap[sign.lower()]

    # set user info
    user = {
      "key": uuid.uuid4(),
      "firstName": firstname,
      "custom": {
        "astroSign": sign
      }
    }

    # evaluate feature flag
    disable_lastname = ldclient.get().variation("dg-first-name-only", user, False)

    if disable_lastname:
      print("Your Drag First Name is: ", dragFirstName)
    else:
      print("Your Drag Name is: ", dragFirstName," ", dragLastName)

    # check if they want to play again
    playagain = input("Would you like to generate another drag name? Enter ""Yes"" or ""No"": ")
    while playagain.lower() != "yes" and playagain.lower() != "no":
        print ("You typed something wrong!")
        playagain = input("Would you like to generate another drag name? Enter ""Yes"" or ""No"": ")

  ldclient.get().close() # close the client before exiting the program - ensures that all events are delivered


# Error handling
# compile time  or syntax error , logical , run time errors

a = 5 # Normal statement . this has no chance of giving error
b = 0

try:
    print(a/b) # Critical statement
except Exception as e: # If we dono the exception
    print(" Not divisible by 0 - "  , e)
except ValueError as e:
    print("value error ", e) # if we know the exception
finally:
    print("Resource closed") # will get executed if we r getting exceptions are not


import time

import pdfkit
import requests
from PyPDF2 import PdfFileMerger
from bs4 import BeautifulSoup

def get_chapter(bookname,url):
    i = 0
    pdfs = []
    html_template = """
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
        {content}
        </body>
        </html>
        """
    soup = BeautifulSoup(requests.get(url).text, 'html.parser')

    for cursor in soup.find_all( class_='chapter' ):
        i = i+1
        print(cursor.text)
        pdf_name = 'docker'+ str(i) + '.pdf'
        html_name = 'docker'+ str(i) + '.html'
        link = url+cursor.a.get('href')
        time.sleep(2);
        html = get_chapter_text(link)
        html = html_template.format(content = html)
        html = html.encode("utf-8")
        with open( html_name, 'wb') as f:
            f.write(html)
        save_pdf(html_name,pdf_name )
        pdfs.append(pdf_name)

    merge_pdf(bookname, pdfs)

def merge_pdf(bookname,pdfs):
    merger = PdfFileMerger()
    i = 0
    for pdf in pdfs:
        merger.append(open(pdf, 'rb'), import_bookmarks=False)
        print( "Merging " + str(i) + ' files:' + pdf)

        i = i + 1
    output = open(bookname+".pdf", "wb")
    merger.write(output)
    print("Finished!")

def get_chapter_text(url):
    current_soup = BeautifulSoup(requests.get(url).text, 'html.parser')
    content = current_soup.find(class_='search-noresults')
    return(content)

def save_pdf(htmls, file_name):
  """
  save all .html to .pdf
  :param htmls: name of .html files
  :param file_name: name of .pdf files
  """
  options = {
    'page-size': 'Letter',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': "UTF-8",
    'custom-header': [
      ('Accept-Encoding', 'gzip')
    ],
    'cookie': [
      ('cookie-name1', 'cookie-value1'),
      ('cookie-name2', 'cookie-value2'),
    ],
    'outline-depth': 10,
  }
  pdfkit.from_file(htmls, file_name, options=options)

if __name__ == '__main__':
    url = 'https://yeasy.gitbooks.io/docker_practice/content/'
    get_chapter("Docker_all",url)


import sys
sys.path.append('./xsvc')
import xsvc
import json
import datetime
import dateutil.parser

def _adder(request):
    return 100

xs=xsvc.XSVC()
tmpreq={'request':'blp_get_historical_data','params':{'securities':['usdkrw curncy'],'fields':['px_last'],'startdate':'20150601','enddate':'20150701'}}
xs.connect('localhost',2000)
tmp2=json.loads(xs.request(tmpreq))['result'][0]['field_data']

ts={}
for elm in tmp2:
    date=dateutil.parser.parse(elm['date'])
    date_str=date.strftime('%Y-%m-%d')
    ts[date_str]=elm['px_last']

print(ts)
xs.registerService('adder',_adder)
#xsvc.serve()
xs.close()


import datetime
from app import db
from models.logActivity import LogActivity
from sqlalchemy.sql import text

ts = datetime.datetime.utcnow()

class LogActivityService(db.Model):
    __tablename__ = "log_activity"

    def add_log(user_id, activity):
        log = LogActivity(
            user_id = user_id,
            activity = activity,
            created_at = ts,
            deleted_at= None
        )
        db.session.add(log)
        db.session.commit()
        return log


import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
	"""a clss to manage the bullets fired from the shjip"""
	def __init__(self, ai_settings, screen, ship):
		"""make a bullet obj at the ships current position"""
		super().__init__()
		self.screen = screen

		#init bullet rect at (0, 0) and set the correct position.
		#we're drawing it from scratch. we init the rects top left corner to 0,0
		#after init, we update the bullets centerx to be the same as the ships centerx,
		#and the bullets top to the sjhips top to make it look like the bullet
		#emerges from the ship
		self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
		self.rect.centerx = ship.rect.centerx
		self.rect.top = ship.rect.top

		#store the bullets position as a decimal value
		#this is the y value as it moves up the screen
		self.y = float(self.rect.y)

		self.color = ai_settings.bullet_color
		self.speed_factor = ai_settings.bullet_speed_factor

	def update(self):
		"""move the bullet up the screen"""
		#this function is called automatically by the pygame.sprite group object

		#update the y value of the bullet
		#the bullet travels up so we subtract y (pygame inits the upper left corner
		#of the window as 0,0 and the bottom right as positive integers for maxX, maxY.
		# maxX and maxY are whtever size of the screen you config'd) so upward
		#movement means we subtract. this will be in the main loop so it will
		#run a shitload of tiems and move the bullet up. no x coord is needed
		#cuz the bullet travels in a straight line
		self.y -= self.speed_factor

		#update the rect position
		self.rect.y = self.y

	def draw_bullet(self):
		"""draw bullet on the screen"""
		pygame.draw.rect(self.screen, self.color, self.rect)


import math

num=int(input());
mid=[];
result=1000.00;
for i in range(num):
    nums=list(map(int,input().split(",")));
    mid.append(nums);
count=0;
for i in range(len(mid)):
    for j in range(i+1,len(mid)):
        length=pow(abs(mid[i][0]-mid[j][0]),2)+pow(abs(mid[i][1]-mid[j][1]),2);
        center=[(mid[i][0]+mid[j][0])/2,(mid[i][1]+mid[j][1])/2];
        for k in range(j+1,len(mid)):
            length_p=pow(abs(mid[k][0]-center[0]),2)+pow(abs(mid[k][1]-center[1]),2);
            if(length_p==length/4):
                fourth=[(center[0]*2-mid[k][0]),(center[1]*2-mid[k][1])];
                if(fourth in mid):
                    high=pow(abs(mid[i][0]-mid[k][0]),2)+pow(abs(mid[i][1]-mid[k][1]),2);
                    width=pow(abs(mid[i][0]-fourth[0]),2)+pow(abs(mid[i][1]-fourth[1]),2);
                    area=math.sqrt(high*width);
                    if(area<result):
                        result=area;
                        count=1;
if(count==0):
    print("0.0000");
else:
    print("%.4f"%result);


import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

def detect_green_triangle(image, threshold_low, threshold_high):
    # Convert image to HSV color space
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    # Define lower and upper green color thresholds
    lower_green = np.array([threshold_low, 50, 50])
    upper_green = np.array([threshold_high, 255, 255])

    # Create a binary mask of green pixels
    mask = cv2.inRange(hsv, lower_green, upper_green)

    # Apply morphological operations to enhance the mask
    kernel = np.ones((5, 5), np.uint8)
    mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)

    # Find contours in the mask
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Iterate over contours to find the green triangle
    triangle_contour = None
    for cont in contours:
        perimeter = cv2.arcLength(cont, True)
        approx = cv2.approxPolyDP(cont, 0.03 * perimeter, True)
        area = cv2.contourArea(cont)
        if len(approx) == 3 and 300 < area < 2000:
            triangle_contour = approx
            break

    return triangle_contour

def update_threshold_low(val):
    global threshold_low
    threshold_low = val

def update_threshold_high(val):
    global threshold_high
    threshold_high = val

def on_button_press(event):
    # Check if the left mouse button was clicked
    if event.button == 1:
        # Get the current image coordinates
        x, y = int(event.xdata), int(event.ydata)

        # Check if the click is within the image boundaries
        if 0 <= x < image.shape[1] and 0 <= y < image.shape[0]:
            # Display the coordinates
            print("Clicked image coordinates: ({}, {})".format(x, y))

# Load the image
image = cv2.imread(r'C:\Users\rasmu\OneDrive\Skrivebord\CDIO\RobotProject\CDIO-RobtoScripts\ArucoTet\Chessimages\4.jpg')

# Create a figure and axes for plotting
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.2)

# Create sliders for threshold values
ax_threshold_low = plt.axes([0.25, 0.1, 0.5, 0.03])
slider_threshold_low = widgets.Slider(ax_threshold_low, 'Threshold Low', 0, 255, valinit=100)
slider_threshold_low.on_changed(update_threshold_low)

ax_threshold_high = plt.axes([0.25, 0.05, 0.5, 0.03])
slider_threshold_high = widgets.Slider(ax_threshold_high, 'Threshold High', 0, 255, valinit=200)
slider_threshold_high.on_changed(update_threshold_high)

# Detect the green triangle with initial threshold values
threshold_low = slider_threshold_low.val
threshold_high = slider_threshold_high.val
triangle_contour = detect_green_triangle(image, threshold_low, threshold_high)

# Plot the image with detected triangle
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Green Triangle Detection')
plt.axis('off')

# Connect mouse click event handler
cid = fig.canvas.mpl_connect('button_press_event', on_button_press)

# Display the plot
plt.show()

# Disconnect mouse click event handler
fig.canvas.mpl_disconnect(cid)


#-*-coding:utf-8-*-
import numpy as np
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
from sklearn.model_selection import train_test_split,KFold
import datetime

tt = pd.read_csv('final_train.csv')
area = tt['area_id']
#tt['answer'] = tt['answer'] -1
answer=tt[['answer']]

del tt['answer']
del tt['area_id']
#tt.replace(np.inf,np.nan,inplace=True)
#tt.replace(-np.inf,np.nan,inplace=True)
tt.replace(np.inf,100000,inplace=True)
tt.replace(-np.inf,-100000,inplace=True)
tt.fillna(tt.mean(),inplace=True)

x_train, x_test, y_train, y_test=train_test_split(tt, answer, test_size=0.1, random_state=8)
features1 = x_train.values
features2 = x_test.values

answer1 = y_train.answer.values
answer2 = y_test.answer.values

rf = RandomForestClassifier(n_estimators=100,bootstrap = True, oob_score = True, criterion = 'gini',
                            n_jobs=-1,random_state=8)

start = datetime.datetime.now()
rf.fit(features1,answer1)
end = datetime.datetime.now()
print('user %d seconds'%(end - start).seconds)
print('oob_score:\t',rf.oob_score_)
print ("Accuracy:\t", (answer2 == rf.predict(features2)).mean())
print ("Total Correct:\t", (answer2 == rf.predict(features2)).sum())


import bpy
import random
import mathutils
import sys

import os

sys.path.append(os.getcwd())

from math_utilities import Math_Utilities
from tscn import TSCN
from materials import Material

class Convert_Particles():

    def __init__(self):
        self.math = Math_Utilities()
        self.depg = bpy.context.evaluated_depsgraph_get()
        self.blend_filename = os.path.basename(bpy.data.filepath)

        self.tscn = TSCN()

        self.material = Material()
        self.material_indices = {}

        self.blend_particle_dict = {"Emitter Objects" : {}}

    def deselect_all(self):
        for obj in bpy.context.scene.objects:
            obj.select_set(False)

    def export_object(self, obj, project_dir):

        bpy.context.scene.collection.objects.link(obj)

        obj.select_set(True)

        mat = mathutils.Matrix( [ [1, 0, 0, 0],
                                [0, 1, 0, 0],
                                [0, 0, 1, 0],
                                [0, 0, 0, 1] ])

        obj.matrix_world = mat
        bpy.ops.export_scene.obj(filepath=f"{project_dir}/{obj.name}.obj", use_selection=True, use_triangles=True, use_normals=True)
        obj.select_set(False)

        bpy.context.scene.collection.objects.unlink(obj)

    def convert(self, project_dir):

        self.material.get_all_objects_materials(project_dir)

        self.deselect_all()

        temp_objects = []

        for obj in bpy.context.scene.objects:

            for modifier in obj.modifiers:
                if modifier.type == "PARTICLE_SYSTEM":

                    # Object Has Particle System
                    # Get Object properties

                    # Get Object 3D Transform
                    obj_scale = obj.scale
                    obj_location = obj.location
                    obj_rotation = obj.rotation_euler

                    obj_s = self.math.S3D(obj_scale[0], obj_scale[2], obj_scale[1])
                    obj_r = self.math.R(obj_rotation[0], obj_rotation[2], obj_rotation[1])
                    obj_t = self.math.T(obj_location[0], obj_location[2], obj_location[1])

                    obj_transform = self.math.to_str(self.math.transform(obj_r, obj_s, obj_t))

                    # Other
                    obj_name = obj.name

                    self.blend_particle_dict["Emitter Objects"][obj_name] = {"Transform" : obj_transform, "Particle Objects" : {}}

                    # Get Object Particle Systems
                    obj_particle_systems = obj.evaluated_get(self.depg).particle_systems

                    for particle_system_idx, particle_system in enumerate(obj_particle_systems):

                        # Get particle system properties
                        num_of_particles = len(particle_system.particles)
                        particle_system_name = particle_system.name
                        particle_system_settings = particle_system.settings
                        particle_system_objects_dict = {}

                        # Get Particle Objects
                        if particle_system_settings.render_type == "COLLECTION":

                            for particle_obj_idx, particle_obj in enumerate(particle_system_settings.instance_collection.objects):

                                self.export_object(particle_obj, project_dir)

                                particle_system_objects_dict[particle_system_idx + particle_obj_idx] = {"Object" : particle_obj, "Random Weight" : 1, "Scale" : particle_obj.dimensions}

                                self.blend_particle_dict["Emitter Objects"][obj_name]["Particle Objects"][particle_obj.name] = particle_system_objects_dict

                        elif particle_system_settings.render_type == "OBJECT":

                            particle_obj_idx = 0
                            particle_obj = particle_system_settings.instance_object

                            self.export_object(particle_obj, project_dir)

                            particle_system_objects_dict[particle_system_idx + particle_obj_idx] = {"Object" : particle_obj, "Random Weight" : 1, "Scale" : particle_obj.dimensions}

                            self.blend_particle_dict["Emitter Objects"][obj_name]["Particle Objects"][particle_obj.name] = particle_system_objects_dict

                        particle_indices = []
                        particle_index_weights = []

                        for key, val in particle_system_objects_dict.items():

                            if not val['Object'].name in temp_objects:

                                self.tscn.add_ext_resource(f"{val['Object'].name}.obj", "ArrayMesh")

                                # ob_material = [mk for mk, mv in self.material.materials_dict.items() if mv["Object"] == val['Object'].name]
                                # if len(ob_material) > 0:
                                #     self.tscn.add_ext_resource(f"{ob_material[0]}.tres", "Material")

                                temp_objects += [val['Object'].name]

                            particle_indices += [key]
                            particle_index_weights += [val['Random Weight']]

                        particle_transforms_dict = {}
                        # Loop Through all Particles
                        for particle in particle_system.particles:

                            particle_obj_id = random.choices(particle_indices, weights=particle_index_weights, k=1)[0]

                            particle_obj = particle_system_objects_dict[particle_obj_id]
                            particle_obj_scale = particle_obj['Scale']

                            particle_loc = particle.location
                            particle_rot = particle.rotation.to_euler()

                            particle_r = self.math.Ry(particle_rot[2])
                            particle_s = self.math.S3D(particle.size * particle_obj_scale[0],
                                                       particle.size * particle_obj_scale[2],
                                                       particle.size * particle_obj_scale[1])
                            particle_t = self.math.T(particle_loc[0], 0.0, particle_loc[1])

                            particle_transform = self.math.to_str(self.math.transform(particle_r,
                                                                                particle_s,
                                                                                particle_t))

                            if not particle_obj_id in particle_transforms_dict:
                                #particle_transforms_dict[particle_obj_id] = []
                                particle_transforms_dict[particle_obj_id] = particle_transform
                            else:
                                particle_transforms_dict[particle_obj_id] += particle_transform

                        k = 0
                        for key, val in particle_transforms_dict.items():

                            sub_res_properties = {}
                            sub_res_properties["transform_format"] = 1
                            sub_res_properties["instance_count"] = int(len(val) / 12)
                            sub_res_properties["mesh"] = f"ExtResource( {particle_system_idx + k + 1} )"
                            sub_res_properties["transform_array"] = f"PoolVector3Array( {', '.join(val)} )"

                            self.tscn.add_sub_resource(res_type="MultiMesh", res_properties=sub_res_properties)

                            k += 1

                    break

            ob_material = [mk for mk, mv in self.material.materials_dict.items() if mv["Object"] == obj.name]
            if len(ob_material) > 0:
                self.tscn.add_ext_resource(f"{ob_material[0]}.tres", "Material")

        self.tscn.add_node(node_name=f"{os.path.splitext(self.blend_filename)[0]}", node_type="Spatial", node_parent=None, node_properties=None)

        print(self.blend_particle_dict["Emitter Objects"])

        current_obj = 1
        for key, val in self.blend_particle_dict["Emitter Objects"].items():
            ob_name = key
            ob_transform = val['Transform']
            ob_particle_objects = val["Particle Objects"]

            ob_materials = [mk for mk, mv in self.material.materials_dict.items() if mv["Object"] == ob_name]

            node_properties = {}
            node_properties["transform"] = f"Transform( {', '.join(ob_transform)} )"

            ob_material_name = bpy.context.scene.objects[key].active_material.name
            node_properties['material_override'] = f"ExtResource( {self.tscn.get_ext_resource_by_name(ob_material_name) + 1} )"

            self.tscn.add_node(node_name=ob_name, node_type="Spatial", node_parent=".", node_properties=node_properties)

            #print(ob_particle_objects)

            i = 0
            for k, v in ob_particle_objects.items():

                part_node_properties = {}
                part_node_properties['multimesh'] = f"SubResource( {current_obj + i} )"

                print("k", k)

                print(len(ob_materials))

                #if len(ob_materials) > 0:
                part_ob_material_name = bpy.context.scene.objects[k].active_material.name
                part_node_properties['material_override'] = f"ExtResource( {self.tscn.get_ext_resource_by_name(part_ob_material_name) + 1} )"

                part_ob_name = k

                self.tscn.add_node(node_name=part_ob_name, node_type="MultiMeshInstance", node_parent=ob_name, node_properties=part_node_properties)

                i += 1

            current_obj += 1

        self.tscn.write(f"{project_dir}/test.tscn")


s=input()
s=s[1:len(s)-1]
sl=s.split(',')
numlist=[]
for i in sl:
    numlist.append(int(i))
t=int(input())
n=numlist.count(t)
if(n==0):
    print(-1)
else:
    print(numlist.index(t))


import os
import argparse
import numpy as np
import torch
import pandas as pd
import data
import setGPU

from robustbench.data import load_cifar10, load_cifar10c
from robustbench.utils import clean_accuracy

from resnet import ResNet18
from models.c_models import PreActResNet18

def corr_eval(x_corrs, y_corrs, model):
    model.eval()
    res = np.zeros((5, 15))
    for i in range(1, 6):
        for j, c in enumerate(data.corruptions):
            res[i-1, j] = clean_accuracy(model, x_corrs[i][j].cuda(), y_corrs[i][j].cuda())
            print(c, i, res[i-1, j])

    return res

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--batch_size', default=128, type=int)
    parser.add_argument('--data_dir', default='./data', type=str)
    parser.add_argument('--checkpoint', default='', type=str)
    parser.add_argument('--us_gpu', action='store_true')
    parser.add_argument('--output', default='output.csv', type=str)
    parser.add_argument('--only_clean', action='store_true')
    parser.add_argument('--n_samples', default=1000, type=int)
    return parser.parse_args()

corruptions = ["shot_noise", "motion_blur", "snow", "pixelate",
               "gaussian_noise", "defocus_blur", "brightness", "fog",
               "zoom_blur", "frost", "glass_blur", "impulse_noise", "contrast",
               "jpeg_compression", "elastic_transform"]

def main():
    args = get_args()
    device = "cuda"
    #os.environ["CUDA_VISIBLE_DEVICES"] = str("6")
    x_clean, y_clean = load_cifar10(n_examples=args.n_samples, data_dir=args.data_dir)

    mu = torch.tensor([0.485, 0.456, 0.406], dtype=torch.float, device=device).unsqueeze(-1).unsqueeze(-1)
    std = torch.tensor([0.229, 0.224, 0.225], dtype=torch.float, device=device).unsqueeze(-1).unsqueeze(-1)

    models_info = [["FrankWolfe", "nets/cifar_adv_training_attack-frank_eps-0.005.pth", "dict", None],
#                ["Wass 0.01", "models/cifar_adv_training_attack-l1wass_eps-0.01_epoch-30.pth", "dict", None],
#                ["Wass 0.005", "models/cifar_adv_training_attack-l1wass_eps-0.005_epoch-30.pth", "dict", None],
#                ["Wass 0.002", "models/cifar_adv_training_attack-l1wass_eps-0.002_epoch-30.pth", "dict", None],
                #  ["Wass 0.005", "models/cifar_frank_eps-0.005_epoch-30.pth", "dict", None],
                 ["Wass 0.001", "nets/cifar_frank_eps-0.001_epoch-30.pth", "dict", None],
                #  ["Wass 0.001 (60ep)", "models/cifar_frank_eps-0.001_epoch-60-c.pth", "dict", None],
                 ["Wass 0.001 (150ep)", "nets/cifar_frank_eps-0.001_epoch-150.pth", "dict", None],
                 ["Revnet 0.00025", "nets/cifar_revnet_eps-0.00025_alpha-0.01_epoch-30.pth", "dict", None],
                 ["Revnet 0.004", "nets/cifar_revnet_eps-0.004_alpha-0.01_epoch-30.pth", "dict", None],
                 ["Revnet 0.016", "nets/cifar_revnet_eps-0.016_alpha-0.01_epoch-30.pth", "dict", None],
                 #  ["Wass 0.00075", "models/cifar_frank_eps-0.00075_epoch-30.pth", "dict", None],
                #  ["Wass 0.0005", "models/cifar_frank_eps-0.0005_epoch-30.pth", "dict", None],
                #  ["Wass 0.0001", "models/cifar_frank_eps-0.0001_epoch-30.pth", "dict", None],
#                ["Wass 0.0008 (a,51ep)", "models/cifar_l1wass_eps-0.0008_alpha-0.005_epoch-51.pth", "dict", None],
#                ["Wass 0.01 (2)", "models/cifar_adv_training_attack-l1wass_eps-0.01_epoch-20.pth", "dict", None],
#                ["Wass 0.001 (2)", "models/cifar_adv_training_attack-l1wass_eps-0.001_epoch-20.pth", "dict", None],
#                ["Wass 0.0005 (2)", "models/cifar_adv_training_attack-l1wass_eps-0.0005_epoch-20.pth", "dict", None],
                ["L2", "nets/l2-at-eps=0.1-cifar10.pt", "pre", None],
                ["Standard", "nets/cifar_vanilla.pth", "net", None]]

    def print_info(name, elems):
        print("{} \t".format(name.ljust(20)), end="")
        for i in elems:
            print("{} \t".format(i.ljust(15)), end="")
        print()

    prnt = []
    for model in models_info:
        if model[2] == "dict":
            model[-1] = ResNet18().cuda()
            ckpt = torch.load(model[1])
            model[-1].load_state_dict(ckpt["model_state_dict"])
            model[-1].eval()
        elif model[2] == "net":
            model[-1] = ResNet18().cuda()
            ckpt = torch.load(model[1])
            if "net" in ckpt.keys():
                for key in ckpt["net"].keys():
                    assert "module" in key
                ckpt["net"] = dict((key[7:], value) for key, value in ckpt["net"].items())
                model[-1].load_state_dict(ckpt["net"])
            model[-1].eval()
        elif model[2] == "pre":
            model[-1] = PreActResNet18(n_cls=10, model_width=64, cifar_norm=True).cuda()
            model[-1].load_state_dict(torch.load(model[1])['last'])
            model[-1].eval()
        prnt += [model[0]]
    print_info("Corruption", prnt)

    prnt = []
    acc_cln = [0 for i in models_info]
    for i, model in enumerate(models_info):
        net = model[-1]
        if model[2] == "pre":
            acc_cln[i] = clean_accuracy(net, x_clean.cuda(), y_clean.cuda())
        elif model[2] == "dict" or model[2] == "net":
            acc_cln[i] = clean_accuracy(net, ((x_clean.cuda() - mu) / std), y_clean.cuda())
        prnt += ["{:.4f}".format(acc_cln[i])]
    print()
    print_info("Clean", prnt)

    mean_acc = [[0 for i in models_info] for j in range(6)]
    tot_mean = [0 for i in models_info]
    cnt = 0
    for corr in corruptions:
        print()
        for i in range(1,6):
            x_corr, y_corr = load_cifar10c(n_examples=args.n_samples, severity=i, corruptions=(corr,), data_dir=args.data_dir)
            cnt += 1

            prnt = []
            acc_corr = [0 for i in models_info]
            for j, model in enumerate(models_info):
                net = model[-1]
                if model[2] == "pre":
                    acc_corr[j] = clean_accuracy(net, x_corr.cuda(), y_corr.cuda())
                elif model[2] == "dict" or model[2] == "net":
                    acc_corr[j] = clean_accuracy(net, ((x_corr.cuda() - mu) / std), y_corr.cuda())
                mean_acc[i][j] += acc_corr[j]
                tot_mean[j] += acc_corr[j]
                prnt += ["{:.4f}".format(acc_corr[j])]
            print_info("{} {}".format(corr, i), prnt)

    for i in range(1,6):
        prnt = []
        for acc in mean_acc[i]:
            prnt += ["{:.4f}".format(acc / cnt * 5)]
        print()
        print_info("Average {}".format(i), prnt)

    prnt = []
    for acc in tot_mean:
        prnt += ["{:.4f}".format(acc / cnt)]
    print()
    print_info("Total Average", prnt)

    # if args.only_clean:
    #     return

    # x_corrs, y_corrs, _, _ = data.get_cifar10_numpy()

    # corr_res_last = corr_eval(x_corrs, y_corrs, model)
    # corr_data_last = pd.DataFrame({i+1: corr_res_last[i, :] for i in range(0, 5)}, index=data.corruptions)
    # corr_data_last.loc['average'] = {i+1: np.mean(corr_res_last, axis=1)[i] for i in range(0, 5)}
    # corr_data_last['avg'] = corr_data_last[list(range(1,6))].mean(axis=1)
    # corr_data_last.to_csv(args.output)
    # print(corr_data_last)

if __name__ == "__main__":
    main()


class Solution(object):
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        sign = 1 if x >= 0 else -1

        x = abs(x)

        ret = sign * int(str(x)[::-1])

        if ret > 2 ** 31 - 1 or ret < -2 ** 31:
            return 0
        else:
            return ret


from cryptography.fernet import Fernet, base64, InvalidSignature, InvalidToken
import hashlib
from django.contrib.auth.hashers import make_password, PBKDF2PasswordHasher, BasePasswordHasher, get_random_string
import logging

log = logging.getLogger(__name__)
import requests

class JsonApi(object):

    @classmethod
    def get(cls, base_url, api_url):
        url = '{}{}'.format(base_url, api_url)
        data = {}
        response = None
        try:
            response = requests.get(url)
            response.raise_for_status()
            data = response.json()
        except Exception as exc:
            log.warning('GET failed: {} - {}'.format(url, exc))
            if response is not None and hasattr(response, 'content'):
                log.warning('RESPONSE {}'.format(response.content))
        finally:
            return data

    @classmethod
    def post(cls, base_url, api_url, data):
        url = '{}{}'.format(base_url, api_url)
        response_data = {}
        response = None
        try:
            response = requests.post(url, json=data)
            response.raise_for_status()
            if response.status_code == 201:
                log.info('Peer {} accepted block.'.format(base_url))
            if not len(response.content):
                if response.status_code == 304:
                    log.warning('Peer {}: unable to accept block.'.format(base_url))
            else:
                response_data = response.json()
        except Exception as exc:
            log.warning('POST failed: {} - {}'.format(url, exc))
            if response is not None and hasattr(response, 'content'):
                log.warning('RESPONSE {}'.format(response.content))
        finally:
            return response_data


from __future__ import division, print_function, absolute_import
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

from tensorflow.examples.tutorials.mnist import input_data

# fashion_mnist = keras.datasets.fashion_mnist
# (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# mnist = fashion_mnist.read_data_sets()

data = input_data.read_data_sets('data/fashion',
                                 source_url='http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/', one_hot=True)

lr = 0.001 #change to adaptive
num_steps = 1200
batch_size = 1000
display_step = 60

#parameter
num_input = 784
num_classes = 10
dropout = 1.0
lossarr = []
accarr = []

#graph input
X = tf.placeholder(tf.float32, [None, num_input])
print(X)
Y = tf.placeholder(tf.float32, [None, num_classes])
prob = tf.placeholder(tf.float32)

#define layer methods

def conv2dp(x, W, b, strides = 1):
    x = tf.nn.conv2d(x, W, strides=[1,strides,strides,1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def conv2dnp(x, W, b,strides=1):
    x = tf.nn.conv2d(x, W, strides=[1,strides,strides,1], padding='VALID')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def maxpool2d(x, k=2):
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1,k,k,1],
                          padding='SAME')

#model
def conv_net(x, weights, biases, dropout):
    x = tf.reshape(x, shape=[-1, 28, 28, 1])

    #Convolution_1
    conv1 = conv2dnp(x, weights['wc1'], biases['bc1'])
    #Pool_1
    conv1 = maxpool2d(conv1, k=2)

    #Convolution_2
    conv2 = conv2dp(conv1, weights['wc2'], biases['bc2'])
    #Pool_2
    conv2 = maxpool2d(conv2, k=2)

    #FCL_1
    fc1 = tf.reshape(conv2, [-1, weights['wfc1'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['wfc1']), biases['bfc1'])
    fc1 = tf.nn.relu(fc1)
    # Apply Dropout
    fc1 = tf.nn.dropout(fc1, dropout)

    #FCL_2
    # fc2 = tf.reshape(fc1, [-1, weights['wfc2'].get_shape().as_list()[0]])
    fc2 = tf.add(tf.matmul(fc1, weights['wfc2']), biases['bfc2'])
    fc2 = tf.nn.relu(fc2)
    fc2 = tf.nn.dropout(fc2, dropout)

    # #FCL_3
    # fc3 = tf.reshape(fc2, [-1, 50])
    # fc3 = tf.add(tf.matmul(fc3, weights['wfc3']), biases['bfc3'])
    # fc3 = tf.nn.softmax(fc3)
    # fc3 = tf.nn.dropout(fc3, dropout)

    # Output, class prediction
    out = tf.add(tf.matmul(fc2, weights['out']), biases['out'])
    return out

weights = {
    # 5x5 conv, 1 input, 3 outputs
    'wc1': tf.get_variable('WC1', shape = (5, 5, 1, 3), initializer = tf.contrib.layers.xavier_initializer()),
    # 3x3 conv, 3 inputs, 3 outputs
    'wc2': tf.get_variable('WC2', shape = (3, 3, 3, 3), initializer = tf.contrib.layers.xavier_initializer()),
    # fully connected, 108 inputs, 100 outputs
    'wfc1': tf.get_variable('WFC1', shape=(108, 100), initializer= tf.contrib.layers.xavier_initializer()),
    # fully connected, 100 inputs, 50 outputs
    'wfc2': tf.get_variable('WFC2', shape=(100, 50), initializer= tf.contrib.layers.xavier_initializer()),
    # fully connected, 50 inputs, 10 outputs
    # 'wfc3': tf.Variable(tf.random_normal([50, 10])),
    # 10 inputs, 10 outputs (class prediction)
    'out': tf.get_variable('WOUT', shape = (50, num_classes)),
}

biases = {
    'bc1': tf.get_variable('BC1', shape = (3), initializer= tf.zeros_initializer()),
    'bc2': tf.get_variable('BC2', shape = (3), initializer= tf.zeros_initializer()),
    'bfc1': tf.get_variable('BFC1', shape = (100), initializer= tf.zeros_initializer()),
    'bfc2': tf.get_variable('BFC2', shape = (50), initializer= tf.zeros_initializer()),
    # 'bfc3': tf.Variable(tf.random_normal([10])),
    'out': tf.get_variable('BOUT', shape = (num_classes), initializer= tf.zeros_initializer()),
}
# Construct model
logits = conv_net(X, weights, biases, prob)
logits = tf.nn.dropout(logits, dropout)
prediction = tf.nn.softmax(logits)

# Define loss and optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=lr)
train_op = optimizer.minimize(loss_op)

# Evaluate model
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Initialize the variables (i.e. assign their default value)
init = tf.global_variables_initializer()

with tf.Session() as sess:

    # Run the initializer
    sess.run(init)

    for step in range(1, num_steps+1):
        batch_x, batch_y = data.train.next_batch(batch_size)
        batch_x = batch_x.reshape(-1, num_input)
        batch_y = batch_y.reshape(-1, num_classes)
        # Run optimization op (backprop)
        sess.run(train_op, feed_dict={X:batch_x, Y: batch_y, prob: dropout})
        if step % display_step == 0 or step == 1:
            # Calculate batch loss and accuracy
            loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x,
                                                                 Y: batch_y,
                                                                prob: 1 })
            lossarr.append(loss)
            accarr.append(acc)
            print("Step " + str(step) + ", Minibatch Loss= " + \
                  "{:.4f}".format(loss) + ", Training Accuracy= " + \
                  "{:.3f}".format(acc))

    print("Optimization Finished!")

    # Calculate accuracy for 10000 Fashion MNIST test images
    print("Testing Accuracy:", \
        sess.run(accuracy, feed_dict={X: data.test.images[:10000],
                                      Y: data.test.labels[:10000],
                                      prob: 1}))
    #saving model over here
    # savedmodel = tf.train.Saver()
    # savedmodel.save(sess, './model.ckpt')

    plt.plot(lossarr)
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.show()

    plt.plot(accarr)
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.show()

# print(graphing.history.keys())
# # summarize graphing for accuracy
# # plt.plot(graphing.history['loss_op'])
# # plt.title('model accuracy')
# # plt.ylabel('accuracy')
# # plt.xlabel('epoch')
# # plt.legend(['train', 'test'], loc='upper left')
# # plt.show()
#  summarize graphing for loss
# plt.plot('loss_op')
# # plt.plot(graphing.history['val_loss'])
# plt.title('model loss')
# plt.ylabel('loss')
# plt.xlabel('epoch')
# plt.legend(['train', 'test'], loc='upper left')
# plt.show()
#gittutend


from django.http import HttpResponse
from datetime import date, time, datetime
from django.template import Template, Context
from App1.models import *
def saludo(request):
	return HttpResponse("Hola Django - Coder")

def quien_soy(request):
    return HttpResponse("Mi nombre es Mariana, tengo 34 años, tengo dos hijos y un marido hermoso")
def diadehoy(request):
    dia= date.today()
    documentoDeTexto= f" Hoy es día:
{dia}"
    return HttpResponse(documentoDeTexto)
def nombredeltipo(self, nombre):
    docdetexto= f"Mi nombre es

 {nombre}"
    return HttpResponse(docdetexto)
def pruebaTemplate(request):
    nom= "Pedrito"
    ap= "Urzua"
    diaDeFabr= datetime.today
    diccionario= {"nombre":nom, "apellido": ap, "dia":diaDeFabr}

    miHtml= open("H:/Mi unidad/data/python/dj_proy_1/prueba1/plantillas/template1.html")
    plantilla= Template(miHtml.read())
    miHtml.close()
    miContexto= Context(diccionario)
    documento=plantilla.render(miContexto)
    return HttpResponse(documento)

def curso1(request):
    curso1= curso(nombre="SQL",comision=1)
    curso1.save()
    documentoDeTexto= f"----> Curso: {curso1.nombre} Comision: {curso1.comision}"
    return HttpResponse(documentoDeTexto)
def alumnos1(request):
    alumnos1= estudiantes(nombre="Pedro", apellido= "urzua", email= 'pedro@gmail.com')
    alumnos1.save()
    diccionario= {"nombre":alumnos1.nombre, "apellido":alumnos1.apellido, "Correo":alumnos1.email}
    miHtml= open("H:/Mi unidad/data/python/dj_proy_1/prueba1/plantillas/template2.html")
    plantilla= Template(miHtml.read())
    miHtml.close()
    miContexto= Context(diccionario)
    documento=plantilla.render(miContexto)
    return HttpResponse(documento)
def entregable1(request):
    entregable1= entregable(nombre= "pedrourzua", fechaDeEntrega="2023-01-23", entregado= False)
    entregable1.save()
    docdetext= f"El alumno {entregable1.nombre} entrego la prueba: {entregable1.entregado} el dia:{entregable1.fechaDeEntrega}"
    return HttpResponse(docdetext)


import pytest
from pytest_httpx import HTTPXMock

from plurk import AsyncClient
from plurk.models import UserSearchResp

FAKE_APP_CREDENTIALS = ('fake_app_key', 'fake_app_secret')

@pytest.mark.asyncio
async def test_search(httpx_mock: HTTPXMock, user_search_resp_fixture):
    resp_json = user_search_resp_fixture.dict_original()
    httpx_mock.add_response(
        status_code=200,
        json=resp_json,
    )
    async with AsyncClient(*FAKE_APP_CREDENTIALS) as client:
        user_search_resp = await client.user_search.search('')
    assert isinstance(user_search_resp, UserSearchResp)
    assert user_search_resp_fixture.dict_original() == resp_json


def insert_sort(input_list):

  for i in range(1, len(input_list)):
    key = input_list[i]
    j = i - 1
    while input_list[j] > key and j >= 0:   # compare element must use key not input_list[i]
      input_list[j + 1] = input_list[j]
      j -= 1
    input_list[j + 1] = key
  return input_list

import random
# print(insert_sort([random.randrange(60) for i in range(20)]))

## Dynamic Programming Rod-cut problem ##
price = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30]

def max(l, r):
  if l < r:
    return r
  else:
    return l

def cut_rod_recur(p, n):
  if n == 0:
    return 0
  q = -1
  for i in range(1, n + 1):
    # every loop record current max q and return back to original problem when loop terminates
    q = max(q, p[i] + cut_rod_recur(p, n - i))
  return q

def cut_rod_top_down(p, n, revenue):
  if revenue[n] >= 0:
    return revenue[n]
  elif n == 0:
    return 0
  else:
    q = -1
    for i in range(1, n + 1):
      q = max(q, p[i] + cut_rod_top_down(p, n - i, revenue))
  revenue[n] = q
  return q

# print(cut_rod_top_down(price, 10, [-1]*11))

## The difference between top-down approach is bottom-up approach has less cost of recursive calls
def cut_rod_bottom_up(p, n, revenue):
  revenue[0] = 0
  for i in range(1, n + 1):
    q = -1
    for j in range(1, i + 1):
      q = max(q, p[j] + revenue[i-j])
    revenue[i] = q
  return revenue[n]

# print(cut_rod_bottom_up(price, 10, [-1]*11))
# import timeit
# t = timeit.timeit("cut_rod_bottom_up([0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30], 10, [-1]*11)", "from __main__ import cut_rod_bottom_up", number=100)
# print("it takes %f secs" % t)
def cut_rod_bottom_up_extend(p, n):
  revenue = [-1]*(n+1)
  revenue[0] = 0
  length = [0]*(n+1)
  for i in range(1, n + 1):
    q = -1
    for j in range(1, i + 1):
      if q < p[j] + revenue[i-j]:
        q = p[j] + revenue[i-j]
        length[i] = j
    revenue[i] = q
  return revenue, length

def print_cut_rod(p, n):
  r, l = cut_rod_bottom_up_extend(p, n)
  while n > 0:
    print(l[n])
    n = n - l[n]

# print_cut_rod(price, 7)

def binary_search(order_list, item):
  low = 0
  high = len(order_list) - 1
  found = False
  while low <= high and not found:
    mid = (low + high) // 2
    if order_list[mid] == item:
      found = True
    elif order_list[mid] < item:
      low = mid + 1
    elif order_list[mid] > item:
      high = mid - 1
  return found

# print(binary_search([1, 3, 5, 7, 9, 11, 13], 8))