'''
SCRIPT: ReadStoichiometry
@Authors:
    Alberto Cuoci [1]
    [1]: CRECK Modeling Lab, Department of Chemistry, Materials, and Chemical Engineering, Politecnico di Milano
@Contacts:
    alberto.cuoci@polimi.it
@Additional notes:
    This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
    Please report any bug to: alberto.cuoci@polimi.it
'''

# Import main libraries
import math
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import xml.etree.ElementTree as ET
from scipy.sparse import csr_matrix, find
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
plt.style.use('default')

# Define path to PyTools classes
import sys
sys.path.insert(0, '../src')

# Import PyTools classes
from KineticMechanism import KineticMechanism
from OpenSMOKEppXMLFile import OpenSMOKEppXMLFile
from PolimiSootModule import *
from Utilities import *

# --------------------------------------------------------------------------------------
# Utilities
# --------------------------------------------------------------------------------------

def ReadVectorInt(vector, pos):
    length = int(vector[pos])
    subvector = vector[pos+1:pos+length+1]
    return np.int32(subvector), pos+length+1

def ReadVectorFloat64(vector, pos):
    length = int(vector[pos])
    subvector = vector[pos+1:pos+length+1]
    return np.float64(subvector), pos+length+1

# --------------------------------------------------------------------------------------
# Read kinetic mechanism
# --------------------------------------------------------------------------------------

kin_xml_folder_name="C:\\Users\\acuoci\\Aachen-Data\\Kinetics\\GRI30\\kinetics-GRI30\\"
kinetics = KineticMechanism(kin_xml_folder_name + "kinetics.xml")
kinetics.ReadKinetics(kin_xml_folder_name + "reaction_names.xml")

# --------------------------------------------------------------------------------------
# Import stoichiometry
# --------------------------------------------------------------------------------------

tree = ET.parse(kin_xml_folder_name + "kinetics.xml")
root = tree.getroot()
kinetics_element = root.find('Kinetics')
stoichiometry_element = kinetics_element.find('Stoichiometry')
stoichiometry = (stoichiometry_element.text).split()

# --------------------------------------------------------------------------------------
# Process stoichiometric data
# --------------------------------------------------------------------------------------

pos = 0
numDir1, pos = ReadVectorInt(stoichiometry, pos)
numDir2, pos = ReadVectorInt(stoichiometry, pos)
numDir3, pos = ReadVectorInt(stoichiometry, pos)
numDir4, pos = ReadVectorInt(stoichiometry, pos)
numDir5, pos = ReadVectorInt(stoichiometry, pos)

numRevTot1, pos = ReadVectorInt(stoichiometry, pos)
numRevTot2, pos = ReadVectorInt(stoichiometry, pos)
numRevTot3, pos = ReadVectorInt(stoichiometry, pos)
numRevTot4, pos = ReadVectorInt(stoichiometry, pos)
numRevTot5, pos = ReadVectorInt(stoichiometry, pos)

numRevEq1, pos = ReadVectorInt(stoichiometry, pos)
numRevEq2, pos = ReadVectorInt(stoichiometry, pos)
numRevEq3, pos = ReadVectorInt(stoichiometry, pos)
numRevEq4, pos = ReadVectorInt(stoichiometry, pos)
numRevEq5, pos = ReadVectorInt(stoichiometry, pos)

jDir1, pos = ReadVectorInt(stoichiometry, pos)
jDir2, pos = ReadVectorInt(stoichiometry, pos)
jDir3, pos = ReadVectorInt(stoichiometry, pos)
jDir4, pos = ReadVectorInt(stoichiometry, pos)
jDir5, pos = ReadVectorInt(stoichiometry, pos)
valueDir5, pos = ReadVectorFloat64(stoichiometry, pos)

jDir1 = jDir1-1
jDir2 = jDir2-1
jDir3 = jDir3-1
jDir4 = jDir4-1
jDir5 = jDir5-1

jRevTot1, pos = ReadVectorInt(stoichiometry, pos)
jRevTot2, pos = ReadVectorInt(stoichiometry, pos)
jRevTot3, pos = ReadVectorInt(stoichiometry, pos)
jRevTot4, pos = ReadVectorInt(stoichiometry, pos)
jRevTot5, pos = ReadVectorInt(stoichiometry, pos)
valueRevTot5, pos = ReadVectorFloat64(stoichiometry, pos)

jRevTot1 = jRevTot1-1
jRevTot2 = jRevTot2-1
jRevTot3 = jRevTot3-1
jRevTot4 = jRevTot4-1
jRevTot5 = jRevTot5-1

jRevEq1, pos = ReadVectorInt(stoichiometry, pos)
jRevEq2, pos = ReadVectorInt(stoichiometry, pos)
jRevEq3, pos = ReadVectorInt(stoichiometry, pos)
jRevEq4, pos = ReadVectorInt(stoichiometry, pos)
jRevEq5, pos = ReadVectorInt(stoichiometry, pos)
valueRevEq5, pos = ReadVectorFloat64(stoichiometry, pos)

jRevEq1 = jRevEq1-1
jRevEq2 = jRevEq2-1
jRevEq3 = jRevEq3-1
jRevEq4 = jRevEq4-1
jRevEq5 = jRevEq5-1

changeOfMoles, pos = ReadVectorFloat64(stoichiometry, pos)
explicit_reaction_orders = int(stoichiometry[pos])

# Elementary reactions only
if (explicit_reaction_orders == 0):

    lambda_numDir1 = numDir1;
    lambda_numDir2 = numDir2;
    lambda_numDir3 = numDir3;
    lambda_numDir4 = numDir4;
    lambda_numDir5 = numDir5;

    lambda_numRevEq1 = numRevEq1;
    lambda_numRevEq2 = numRevEq2;
    lambda_numRevEq3 = numRevEq3;
    lambda_numRevEq4 = numRevEq4;
    lambda_numRevEq5 = numRevEq5;

    lambda_jDir1 = jDir1;
    lambda_jDir2 = jDir2;
    lambda_jDir3 = jDir3;
    lambda_jDir4 = jDir4;
    lambda_jDir5 = jDir5;
    lambda_valueDir5 = valueDir5;

    lambda_jRevEq1 = jRevEq1;
    lambda_jRevEq2 = jRevEq2;
    lambda_jRevEq3 = jRevEq3;
    lambda_jRevEq4 = jRevEq4;
    lambda_jRevEq5 = jRevEq5;
    lambda_valueRevEq5 = valueRevEq5;

else:

    sys.exit("Non-elementary reactions cannot be processed")

# --------------------------------------------------------------------------------------
# Reactant side analysis (stoichiometric coefficients)
# --------------------------------------------------------------------------------------

react_species = []
react_reaction = []
react_nu = []

count1=0
count2=0
count3=0
count4=0
count5=0
for i in range(kinetics.ns):

    for k in range(numDir1[i]):
        react_species.append(i)
        react_reaction.append(jDir1[count1])
        react_nu.append(1.)
        count1 = count1+1

    for k in range(numDir2[i]):
        react_species.append(i)
        react_reaction.append(jDir2[count2])
        react_nu.append(2.)
        count2 = count2+1

    for k in range(numDir3[i]):
        react_species.append(i)
        react_reaction.append(jDir3[count3])
        react_nu.append(3.)
        count3 = count3+1

    for k in range(numDir4[i]):
        react_species.append(i)
        react_reaction.append(jDir4[count4])
        react_nu.append(0.5)
        count4 = count4+1

    for k in range(numDir5[i]):
        react_species.append(i)
        react_reaction.append(jDir5[count5])
        react_nu.append(valueDir5[count5])
        count5 = count5+1

nur = sparse.coo_matrix((react_nu,(react_reaction,react_species)),shape=(kinetics.nr,kinetics.ns))

# --------------------------------------------------------------------------------------
# Product side analysis (stoichiometric coefficients)
# --------------------------------------------------------------------------------------

react_species = []
react_reaction = []
react_nu = []

count1=0
count2=0
count3=0
count4=0
count5=0
for i in range(kinetics.ns):

    for k in range(numRevTot1[i]):
        react_species.append(i)
        react_reaction.append(jRevTot1[count1])
        react_nu.append(1.)
        count1 = count1+1

    for k in range(numRevTot2[i]):
        react_species.append(i)
        react_reaction.append(jRevTot2[count2])
        react_nu.append(2.)
        count2 = count2+1

    for k in range(numRevTot3[i]):
        react_species.append(i)
        react_reaction.append(jRevTot3[count3])
        react_nu.append(3.)
        count3 = count3+1

    for k in range(numRevTot4[i]):
        react_species.append(i)
        react_reaction.append(jRevTot4[count4])
        react_nu.append(0.5)
        count4 = count4+1

    for k in range(numRevTot5[i]):
        react_species.append(i)
        react_reaction.append(jRevTot5[count5])
        react_nu.append(valueRevTot5[count5])
        count5 = count5+1

nup = sparse.coo_matrix((react_nu,(react_reaction,react_species)),shape=(kinetics.nr,kinetics.ns))

# --------------------------------------------------------------------------------------
# Reactant side analysis (reaction orders)
# --------------------------------------------------------------------------------------

react_species = []
react_reaction = []
react_lambda = []

count1=0
count2=0
count3=0
count4=0
count5=0
for i in range(kinetics.ns):

    for k in range(lambda_numDir1[i]):
        react_species.append(i)
        react_reaction.append(lambda_jDir1[count1])
        react_lambda.append(1.)
        count1 = count1+1

    for k in range(lambda_numDir2[i]):
        react_species.append(i)
        react_reaction.append(lambda_jDir2[count2])
        react_lambda.append(2.)
        count2 = count2+1

    for k in range(lambda_numDir3[i]):
        react_species.append(i)
        react_reaction.append(lambda_jDir3[count3])
        react_lambda.append(3.)
        count3 = count3+1

    for k in range(lambda_numDir4[i]):
        react_species.append(i)
        react_reaction.append(lambda_jDir4[count4])
        react_lambda.append(0.5)
        count4 = count4+1

    for k in range(lambda_numDir5[i]):
        react_species.append(i)
        react_reaction.append(lambda_jDir5[count5])
        react_lambda.append(lambda_valueDir5[count5])
        count5 = count5+1

lambdar = sparse.coo_matrix((react_lambda,(react_reaction,react_species)),shape=(kinetics.nr,kinetics.ns))

# --------------------------------------------------------------------------------------
# Product side analysis (reaction orders)
# --------------------------------------------------------------------------------------

react_species = []
react_reaction = []
react_lambda = []

count1=0
count2=0
count3=0
count4=0
count5=0
for i in range(kinetics.ns):

    for k in range(lambda_numRevEq1[i]):
        react_species.append(i)
        react_reaction.append(lambda_jRevEq1[count1])
        react_lambda.append(1.)
        count1 = count1+1

    for k in range(lambda_numRevEq2[i]):
        react_species.append(i)
        react_reaction.append(lambda_jRevEq2[count2])
        react_lambda.append(2.)
        count2 = count2+1

    for k in range(lambda_numRevEq3[i]):
        react_species.append(i)
        react_reaction.append(lambda_jRevEq3[count3])
        react_lambda.append(3.)
        count3 = count3+1

    for k in range(lambda_numRevEq4[i]):
        react_species.append(i)
        react_reaction.append(lambda_jRevEq4[count4])
        react_lambda.append(0.5)
        count4 = count4+1

    for k in range(lambda_numRevEq5[i]):
        react_species.append(i)
        react_reaction.append(lambda_jRevEq5[count5])
        react_lambda.append(lambda_valueRevEq5[count5])
        count5 = count5+1

lambdap = sparse.coo_matrix((react_lambda,(react_reaction,react_species)),shape=(kinetics.nr,kinetics.ns))

# Final checks (to be removed)
diff_nur = nur - kinetics.nur
print(diff_nur)
diff_nup = nup - kinetics.nup
print(diff_nup)
diff_lambdar = lambdar - kinetics.nur
print(diff_lambdar)
#diff_lambdap = lambdap - kinetics.nup
#print(diff_lambdap)

# Final output (to be removed)
#for j in range(kinetics.nr):
#    indices1 = sparse.find(kinetics.nup.getrow(j))[1]
#    indices2 = sparse.find(nup.getrow(j))[1]
#    print(indices1, indices2)


import random
import sys
import numpy as np

from tqdm import tqdm
import cv2
import os

from skimage.util import random_noise
from skimage import img_as_ubyte

def __augment(img):
    options = [
        'gaussian',
        'poisson',
        's&p',
    ]
    option = random.choice(options)
    noise_img = (random_noise(img, mode=option))
    noise_img = img_as_ubyte(noise_img)
    return np.array(noise_img)

def load_dataset(augment=False):
    """
    load original dataset from data/BigCats
    :return: a list containing the bag of words model and the associated labels
    """
    path_data = f'data{os.sep}BigCats{os.sep}'
    os.chdir(f'{os.path.split(__file__)[0]}{os.sep}..{os.sep}..')
    # retrieve class labels (and clean the list)
    classes = list(filter(None, [x[0].replace(f'data{os.sep}BigCats{os.sep}', '') for x in os.walk(path_data)]))
    if not classes:
        sys.exit("Data could not be loaded, most likely a path mismatch")

    dataset = []
    for c in classes:
        filenames = next(os.walk(f'{path_data}{os.sep}{c}'), (None, None, []))[2]
        # Mac os creates this file.
        filenames.remove('.DS_Store')
        for img in filenames:
            image = cv2.imread(f'{path_data}{os.sep}{c}{os.sep}{img}')
            dataset.append([image, classes.index(c)])
            # augment data
            if random.random() < 0.2 and augment:
                dataset.append([__augment(image), classes.index(c)])
    # turn into greyscale:
    dataset = __convert_to_greyscale(dataset)
    # load features
    dataset = __extract_features(dataset)

    return dataset

def __convert_to_greyscale(dataset):
    """
    Converts all images in the raw dataset into greyscale, since sift operates on greyscale
    :return: a list containing all greyscale images and the associated labels
    """
    greyscale_dataset = []
    for image, label in dataset:
        try:
            greyscale_dataset.append([cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), label])
        except Exception as e:
            print(e)

    return greyscale_dataset

def __extract_features(dataset):
    """
    extracts the keypoints and descriptors from the greyscale images using sift
    :return: a list containing all sift descriptors
    """
    sift = cv2.SIFT_create()
    feature_dataset = []
    print('Loading data:')
    for image, label in tqdm(dataset):
        kp, des = sift.detectAndCompute(image, None)
        des = random.sample(list(des), 245)
        feature_dataset.append([des, 245, label])

    return feature_dataset


# https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

from typing import List
"""
Time O(n)
Space O(1)
"""

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        prices_length= len(prices)
        max_profit=0

        for i in range(1, prices_length):
            if prices[i] > prices[i-1]:
                max_profit = prices[i] - prices[i-1] + max_profit

        return max_profit


import logging
import os

DEFAULT_LOGGING_LEVEL = os.environ.get("LOGGING_LEVEL", "INFO")

class Logging:
    """
    Singleton for logging.

    This eases the retrieval of loggers with a uniform format for all the library.
    """

    def __init__(self, level=DEFAULT_LOGGING_LEVEL):
        self._level = level
        self._handlers = [logging.StreamHandler()]
        self._formatter = logging.Formatter('[%(levelname)-2s %(threadName)s] %(asctime)s - %(name)s - %(message)s ')
        self._loggers = {}

        for handler in self._handlers:
            handler.setFormatter(self._formatter)
            handler.setLevel(self._level)

    def get_logger(self, logger_name):
        logger = self._loggers.get(logger_name)

        if logger is None:
            logger = logging.getLogger(logger_name)
            logger.setLevel(self._level)

            for handler in self._handlers:
                logger.addHandler(handler)

        self._loggers[logger_name] = logger
        return logger

    def set_level(self, new_level):
        for handler in self._handlers:
            handler.setLevel(new_level)

        for logger in self._loggers.values():
            logger.setLevel(new_level)

    def add_file_handler(self, filename):
        file_handler = logging.FileHandler(filename)
        file_handler.setLevel(self._level)
        file_handler.setFormatter(self._formatter)
        self._handlers.append(file_handler)

        for logger in self._loggers.values():
            logger.addHandler(file_handler)

poktbot_logging = Logging()


import numpy as np
import pandas as pd
from scipy.sparse.linalg import svds
from scipy.sparse import csc_matrix

users=pd.read_json("data/customers.json")
users.columns = ["user_id",'username']

products=pd.read_json("data/products.json")
products.columns = ["product_id","product_name","price"]

ratings=pd.read_json("data/ratings.json")
ratings.drop("CreateDate",inplace = True, axis=1)
ratings.columns = ["user_id","product_id","rating"]
ratings = ratings.drop_duplicates(['user_id', 'product_id'])

pivot_ratings = ratings.pivot(index='user_id', columns='product_id',values='rating')
# Process NaN values
avg_ratings = pivot_ratings.mean(axis = 1)
# User's pivot
user_ratings_centered  = pivot_ratings.sub(avg_ratings, axis=0)
user_ratings_centered.fillna(0, inplace = True)

user_ratings_centered_sparse = csc_matrix(user_ratings_centered)
# Decompose the matrix
U, sigma, Vt = svds(user_ratings_centered_sparse)
sigma = np.diag(sigma)
recalculated_ratings = np.dot(np.dot(U,sigma), Vt)
recalculated_ratings = recalculated_ratings + avg_ratings.values.reshape(-1,1)

pred_SVC = pd.DataFrame(recalculated_ratings,
                        index=pivot_ratings.index,
                        columns=pivot_ratings.columns)
def recommend(user_id):
    recommend_products = []
    user_ratings = pred_SVC.loc[user_id,:].sort_values(ascending=False)
    products_idxs = user_ratings.index.tolist()
    for idx in products_idxs:
        product = products[products["product_id"] == idx]
        product= {
            "product_id": product["product_id"].values[0],
            "product_name": product["product_name"].values[0],
            "price": product["price"].values[0]
        }
        recommend_products.append(product)

    user = users[users['user_id'] == user_id]
    userName = user['username'].values[0]
    userId = user["user_id"].values[0]
    print("User id: {} Username: {} /n".format(userId, userName))
    print(recommend_products[:10])
    return recommend_products

recommend(103904)


from django.urls import path

from .views import DashboardView, ProfileView, SettingView, ReportHistoryView

app_name = "doctor"

urlpatterns = [
    path('doctor/dashboard/', DashboardView, name="dashboard"),

    path('doctor/report/history/', ReportHistoryView, name="report-history"),

    path('doctor/profile/', ProfileView.as_view(), name="profile"),

    path('doctor/setting/', SettingView.as_view(), name="setting"),
]


#!/usr/bin/python

#################
# Imports
import os
import time
import datetime
import time
from datetime import datetime as dt
from time import strftime
import pDBIconnect
import decimal
import pandas as pd

def nowTime():
    nowstrt = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")
    return nowstrt
pd.set_option('display.max_rows', None)

#SQL select
mrxSelect = '''
select distinct TransactionType,Instrument,PlInstrument
from MR_PositionsAttributes
where ReportDate>=convert(varchar,dateadd(dd,-1,getdate()),112) --and TransactionType like '%uture%'
and isnull(Underlying,'')=''
and TransactionType not in('Cross Rate Swap','IR Swap','FRA')
            '''

#Variables
MxList = []
MxlistSecond = []
MxPortfolio = []
body = ''

ExctMX = pDBIconnect.dbi_connect_Michelangelo_mrxrecon(mrxSelect)
# for item in ExctMX:
#     MxList.append(str(item[0]))

for item in ExctMX:
    MxList.append(str(item[0]))
for item in ExctMX:
    MxlistSecond.append(str(item[1]))
for item in ExctMX:
    MxPortfolio.append(str(item[2]))

#Creating table through module Pandas
dataframe = pd.DataFrame({'TransactionType': MxList,
                   'Instrument': MxlistSecond,
                   'PlInstrument': MxPortfolio,
                   })

if len(MxList) != 0:
    print ("\nStatus:CRITICAL\n")
    print(dataframe)
else:
    print ("OK\n")

if len(MxList) != 0:
    print("\nComment:\nPl's check setup of the instrument and GRDBMAP table ")

print("\nTIMESTAMP:\n" + nowTime())
print("/mrx/share/scripts/check_PositionsAttributes.py\n")


from io import StringIO
from copy import deepcopy

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if not args and not kwargs:  # empty call
            if cls not in cls._instances:
                cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        else:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

    def clear(cls):
        try:
            del cls._instances[cls]
        except KeyError:
            pass

class ConfigurationError(Exception):
    pass

_DEFAULT_VALUE = object()

class Configuration(metaclass=Singleton):
    def __init__(self):
        self.initial_configurations_dict = dict()
        self.configurations_dict = dict()
        self.simulation_data = list()
        self.simulation_number = None

    def reset_to_original_configurations(self):
        self.configurations_dict = deepcopy(self.initial_configurations_dict)

    def __getitem__(self, key):
        # import inspect
        # print (inspect.getframeinfo(inspect.currentframe().f_back)[2])
        if key in self.configurations_dict:
            return self.configurations_dict[key]
        else:
            raise ConfigurationError("{} not found".format(key))

    def __setitem__(self, key, value):
        self.configurations_dict[key] = value

    def get(self, key, default=_DEFAULT_VALUE):
        try:
            return self.configurations_dict[key]
        except KeyError:
            if default is _DEFAULT_VALUE:
                raise
            else:
                return default

    def load_configuration_for_simulation(self, simulation):
        self.simulation_data = sorted(simulation.data)
        self.load_configurations_from_dict(simulation.configurations_dict)

    def load_configurations_from_dict(self, configurations_dict):
        self.configurations_dict = configurations_dict
        self.initial_configurations_dict = deepcopy(self.configurations_dict)

    def __str__(self):
        values_str_io = StringIO()
        print("Configurations:", end="\n", file=values_str_io)
        for (key, value) in sorted(self.configurations_dict.items()):
            value_string = ""
            if type(value) is dict:
                for (secondary_key, secondary_value) in self.configurations_dict[key].items():
                    value_string += (len(key) + 2) * " " + "{}: {}\n".format(secondary_key,
                                                                             secondary_value)  # manual justification
                value_string = value_string.strip()
            else:
                value_string = str(value)
            print("{}: {}".format(key, value_string), end="\n", file=values_str_io)

        return values_str_io.getvalue().strip()

    def clear(self):
        self.__init__()


from tempfile import TemporaryDirectory
import popxl
import numpy as np
from popxl_addons.layers import Linear
from popxl_addons.module import Module
from popxl_addons.task_session import TaskSession
import os
import glob

class MockModel(Module):
    def __init__(self):
        super().__init__()
        self.l1 = Linear(30)
        self.l2 = Linear(10)
        self.l3 = Linear(2)

    def build(self, x: popxl.Tensor):
        x = self.l1(x)
        x = self.l2(x)
        x = self.l3(x)
        return x

def build_session():
    ir = popxl.Ir()

    with ir.main_graph:
        x = popxl.constant(np.random.rand(100))
        facts, g = MockModel().create_graph(x)
        vars = facts.init()
        (x,) = g.bind(vars).call(x)

    session = TaskSession(inputs=[], outputs=[], state=vars, ir=ir, device_desc="ipu_hw")
    return session

def test_save_load_ckpt():
    with TemporaryDirectory() as ckpt_dir:
        session = build_session()

        with session:
            session.run()
            session.save_checkpoint(ckpt_dir)

        files = glob.glob(os.path.join(ckpt_dir, "model", "*.npz"))
        assert len(files) == len(
            session.state.keys_flat()
        ), f"expected {len(session.state.keys_flat())} found {len(files)}"
        session2 = build_session()
        try:
            session2.load_checkpoint(ckpt_dir, report_missing="error")
        except ValueError as e:
            assert e is None

def test_missing_key():
    with TemporaryDirectory() as ckpt_dir:
        session = build_session()

        with session:
            session.run()
            session.save_checkpoint(ckpt_dir)

        files = glob.glob(os.path.join(ckpt_dir, "model", "*.npz"))
        assert len(files) == len(
            session.state.keys_flat()
        ), f"expected {len(session.state.keys_flat())} found {len(files)}"
        os.remove(os.path.join(ckpt_dir, "model", "l2.weight.npz"))

        session2 = build_session()
        try:
            session2.load_checkpoint(ckpt_dir, report_missing="error")
        except ValueError as e:
            print(e)
            assert e is not None

def test_missing_session_info_json():
    with TemporaryDirectory() as ckpt_dir:
        session = build_session()
        with session:
            session.run()
            session.save_checkpoint(ckpt_dir)

        os.remove(os.path.join(ckpt_dir, "session_info.json"))

        session2 = build_session()
        session2.load_checkpoint(ckpt_dir, report_missing="error")
        assert True

if __name__ == "__main__":
    test_save_load_ckpt()
    test_missing_key()


from django.shortcuts import render
from portfolio.models import MyApp

# Create your views here.
def home(request):
    # name = "John"
    all_apps = MyApp.objects.all()
    context = {
        'my_apps': all_apps
    }
    return render(request, 'website/index.html', context)


import os
from datetime import datetime
from typing import Any, Dict, List, Tuple, Union
from uuid import uuid4

import sqlalchemy as sa
from sqlalchemy.orm import Session, aliased
from sqlalchemy.sql import label

from umeta import config, core, generators, models, sources

def get_buckets(db: Session, s: config.Source) -> List[models.Object]:
    source = (
        db.query(models.Source).filter(models.Source.name == s.name).first()
    )
    if source is None:
        raise ValueError(f'source {s.name} not in database')
    buckets = (
        db.query(models.Object)
        .filter(models.Object.source_id == source.id)
        .all()
    )
    return (
        source,
        buckets,
    )

def get_path(db: Session, obj: models.Object) -> core.Object:
    obj_model = obj
    key = []
    while obj_model.parent_id is not None:
        key.append(obj_model.name)
        obj_model = obj_model.parent
    return core.Object(
        key=os.sep.join(reversed(key)),
        bucket=obj_model.name,
        type=obj.type,
        modified=obj.modified,
        size=obj.size,
    )

def get_nodes(db: Session, root: models.Object, modified: datetime = None):
    hierarchy = (
        db.query(models.Object, sa.literal(0).label('level'))
        .filter(models.Object.parent_id == root.id)
        .cte(name="hierarchy", recursive=True)
    )
    parent = aliased(hierarchy, name="p")
    children = aliased(models.Object, name="c")
    hierarchy = hierarchy.union_all(
        db.query(children, (parent.c.level + 1).label("level")).filter(
            children.parent_id == parent.c.id
        )
    )
    q = db.query(models.Object, hierarchy.c.level).select_entity_from(
        hierarchy
    )
    if modified:
        q = q.filter(models.Object.modified >= modified)
    return q.all()

def index_source(db: Session, s: config.Source, reindex: models.Reindex):
    parent_cache = {}
    for i, obj in enumerate(sources.get_module(s.type).index(s)):
        if obj.key is not None:
            upsert_object(db, obj, parent_cache, reindex)
        yield i
    reindex.ended = datetime.utcnow()
    reindex.status = models.ReindexStatus.succeeded
    db.add(reindex)
    db.commit()

def get_parent(
    db: Session, obj: core.Object, cache: Dict[str, models.Object],
) -> models.Object:
    """
    get parent node of obj
        get_parent('/foo/bar.txt') -> Object(name=foo)
        get_parent('/bar') -> Object(name=None, bucket=bucket)
    """
    path = obj.key
    if path is None:
        raise ValueError(f'Cannot get parent of bucket {obj.key} {obj.bucket}')
    parent_name = os.path.dirname(path)
    if parent_name == '':
        return (
            db.query(models.Object)
            .filter(
                sa.and_(
                    models.Object.name == obj.bucket,
                    models.Object.parent_id == None,
                )
            )
            .first()
        )
    cache_key = f'{obj.bucket}/{parent_name}'
    if cache_key in cache:
        return cache[cache_key]
    grandparent = get_parent(
        db, core.Object(key=parent_name, bucket=obj.bucket), cache=cache
    )
    if grandparent is None:
        return None
    parent = (
        db.query(models.Object)
        .filter(
            sa.and_(
                models.Object.name == os.path.basename(parent_name),
                models.Object.parent_id == grandparent.id,
            )
        )
        .first()
    )
    if parent is None:
        return None
    else:
        cache[cache_key] = parent
        return parent

def upsert_object(
    db: Session,
    obj: core.Object,
    parent_cache: Dict[str, models.Object],
    reindex: models.Reindex,
    source: models.Source = None,
) -> models.Object:
    is_bucket = obj.key is None

    name = obj.bucket if is_bucket else os.path.basename(obj.key)
    parent_id = None if is_bucket else get_parent(db, obj, parent_cache).id

    if parent_id is None and not is_bucket:
        raise ValueError(
            f'cannot create object without existing parent {obj.key}'
        )

    obj_model: models.Object = db.query(models.Object).filter(
        sa.and_(
            models.Object.name == name, models.Object.parent_id == parent_id,
        )
    ).first()

    revised = False
    if not obj_model:
        # need to create model
        # TODO: check for copy or move
        obj_model = models.Object(
            name=name,
            parent_id=parent_id,
            type=obj.type,
            size=obj.size,
            modified=obj.modified,
            reindex=reindex,
            seen_reindex=reindex,
            source=source,
        )
        revised = True
        db.add(obj_model)
        if obj.type == core.ObjectType.directory:
            db.flush()
    elif (
        obj.type != obj_model.type
        or obj.modified != obj_model.modified
        or obj.size != obj_model.size
    ):
        obj_model.type = obj.type
        obj_model.size = obj.size
        obj_model.modified = obj.modified
        obj_model.reindex = reindex
        revised = True
    if revised:
        revision = models.Revision(object=obj_model)
        db.add(revision)
    obj_model.seen_reindex = reindex
    db.add(obj_model)
    return obj_model

def get_or_create(db: Session, model: object, defaults=None, **kwargs):
    existing = db.query(model).filter_by(**kwargs).first()
    if existing:
        return existing, False
    else:
        params = dict(**kwargs)
        params.update(defaults or {})
        instance = model(**params)
        db.add(instance)
        return instance, True

def latest_object_revision(db: Session, obj: models.Object) -> models.Revision:
    result = (
        db.query(models.Revision, sa.sql.func.max(models.Revision.created))
        .filter(models.Revision.object_id == obj.id)
        .group_by(models.Revision.object_id)
        .first()
    )
    return result[0]

def generate(
    db: Session, s: config.Source
) -> List[List[Tuple[str, models.Object, List[models.Object]]]]:

    source, buckets = get_buckets(db, s)
    for name in s.generators:
        generator_module = generators.get_module(name)
        generator_module_version = generator_module.Version
        generator_model = models.Generator(
            name=name, version=generator_module_version, source=source,
        )
        db.add(generator_model)
        db.commit()
        previous_generator: models.Generator = (
            db.query(models.Generator)
            .filter(
                sa.and_(
                    models.Generator.name == name,
                    models.Generator.version == generator_module_version,
                    models.Generator.status == core.GeneratorStatus.succeeded,
                )
            )
            .order_by(models.Generator.created.desc())
            .first()
        )

        modified_since = 0
        if previous_generator:
            modified_since = int(
                datetime.timestamp(previous_generator.created)
            )

        try:
            for b in buckets:
                nodes = get_nodes(db, b, modified_since)
                for node, _ in nodes:
                    # TODO: if type of node is directory, pass children to checker as well.
                    derivs = generator_module.check(node, None)
                    if derivs is not None:
                        filtered = filter_outdated(
                            db, generator_model, node, derivs
                        )
                        for der_model, dependency_models in filtered:
                            yield (generator_module, node, der_model, dependency_models)

            generator_model.status = core.GeneratorStatus.succeeded
            generator_model.ended = datetime.utcnow()
            db.add(generator_model)
            db.commit()
        except:
            db.rollback()
            generator_model.ended = datetime.utcnow()
            generator_model.status = core.GeneratorStatus.failed
            db.add(generator_model)
            db.commit()
            raise Exception(f'generation exception for source {name}')

def create_dependencies(
    db: Session, derivative: models.Derivative, revisions: List[models.Revision]
) -> List[models.Dependency]:
    ret = []
    for rev in revisions:
        new_dep = models.Dependency(
            revision=rev, derivative=derivative,
        )
        db.add(new_dep)
        ret.append(new_dep)
    return ret

def filter_outdated(
    db: Session,
    generator: models.Generator,
    primary: models.Object,
    derivatives: List[core.Derivative],
) -> List[Tuple[models.Derivative, List[models.Dependency]]]:
    """
    returns only the outdated derivatives.
    """
    for der in derivatives:
        der_model, created = get_or_create(
            db,
            models.Derivative,
            name=der.name,
            type=der.type,
            generator_id=generator.id,
            object_id=primary.id,
        )

        if created:  # this is a new derivative, so create all dependencies
            latest_dep_revisions = [
                latest_object_revision(db, dep) for dep in der.dependencies
            ]
            dependency_models = create_dependencies(
                db, der_model, latest_dep_revisions
            )
            yield (der_model, dependency_models)

        else:  # check the revision versions of the existing dependencies
            known_deps: List[models.Dependency] = (
                db.query(models.Dependency)
                .filter(models.Dependency.derivative_id == der_model.id)
                .all()
            )

            known_dep_revisions_set = set(
                [dep.revision_id for dep in known_deps]
            )
            latest_dep_revisions = []
            latest_dep_revisions_set = set()

            for dep in der.dependencies:
                latest = latest_object_revision(db, dep)
                latest_dep_revisions_set.add(latest.id)
                latest_dep_revisions.append(latest)

            if known_dep_revisions_set != latest_dep_revisions_set:
                # destroy all known, and replace with new ones.
                for dep in known_deps:
                    db.delete(dep)
                dependency_models = create_dependencies(
                    db, der_model, latest_dep_revisions
                )
                yield (der_model, dependency_models)

def recompute(
    db: Session,
    outdated_deriv: models.Derivative,
    outdated_deps: List[models.Dependency],
):
    [db.delete(dep) for dep in outdated_deps]
    new_deps


import pygame
import numpy as np
from astar_point_rigid import *
import time

def triangleCoordinates(start, end, triangleSize = 5):

    rotation = (math.atan2(start[1] - end[1], end[0] - start[0])) + math.pi/2
    # print(math.atan2(start[1] - end[1], end[0] - start[0]))
    rad = math.pi/180

    coordinateList = np.array([[end[0],end[1]],
                              [end[0] + triangleSize * math.sin(rotation - 165*rad), end[1] + triangleSize * math.cos(rotation - 165*rad)],
                              [end[0] + triangleSize * math.sin(rotation + 165*rad), end[1] + triangleSize * math.cos(rotation + 165*rad)]])

    return coordinateList

###################################################
#                  Parameters
###################################################
clearance = radius = 0
print('Enter Type of robot\n 1 -> point robot \n 2 -> rigid robot \
        \n Enter number :')

robotType = int(input())

if(robotType == 2):
    print("Enter cleareance")
    clearance = int(input())
    print("Enter radius")
    radius = int(input())

print('Enter step size of the robot')
stepSize = int(input())
print('Enter start location s1')
s1 = int(input())
print('Enter start location s2')
s2 = 200-int(input())

print('Enter goal location g1')
g1 = int(input())
print('Enter goal location g2')
g2 = 200-int(input())

# Start time of simulation
startTime = time.time()

# Step size of movement
threshDistance = stepSize

# Angle between actions
threshAngle = 30

res = 1  #resolution of grid
scale = 3 #scale of grid

startPosition = np.round((np.array([s1,s2]))/res)
goalPosition = np.round((np.array([g1,g2]))/res)
startOrientation = 0

pygame.init()

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

size_x = math.ceil(300)
size_y = math.ceil(200)
gameDisplay = pygame.display.set_mode((size_x*scale,size_y*scale))

############################################################
#                 Display Obstacles
############################################################
circlePts = [225,50,25]

polygonPts =  np.array([[20,120],[25,185],[75,185],[100,150],[75,120],[50,150]])
polygonPts[:,1] = (size_y - polygonPts[:,1])

rhombusPts = np.array([[225,10],[200,25],[225,40],[250,25]])
rhombusPts[:,1] = (size_y - rhombusPts[:,1])

ellipsePts = np.array([110,80,80,40])

X =           np.array([95+10*math.cos(math.radians(60)), 95-75*math.cos(math.radians(30))+10*math.cos(math.radians(60)), 95-75*math.cos(math.radians(30)), 95])
Y = size_y -  np.array([30+10*math.sin(math.radians(60)), 30+75*math.sin(math.radians(30))+10*math.sin(math.radians(60)), 30+75*math.sin(math.radians(30)), 30])
rectPts = np.column_stack((X,Y))

pygame.draw.circle(gameDisplay, red, (circlePts[0]*scale,circlePts[1]*scale), circlePts[2]*scale)
pygame.draw.polygon(gameDisplay,red,scale*polygonPts)
pygame.draw.polygon(gameDisplay,red,scale*rhombusPts)
pygame.draw.ellipse(gameDisplay,red,scale*ellipsePts)
pygame.draw.polygon(gameDisplay,red,scale*rectPts)

############################################################
#          Draw Explored Nodes and solution path
############################################################
nodesExplored = {}
q = []

if(not isSafe(startPosition,res,clearance+radius) or not isSafe(goalPosition,res,clearance+radius)):
    basicfont = pygame.font.SysFont(None, 48)
    text = basicfont.render('Start or goal position must be in a valid workspace', True, (255, 0, 0), (255, 255, 255))
    textrect = text.get_rect()
    textrect.centerx = gameDisplay.get_rect().centerx
    textrect.centery = gameDisplay.get_rect().centery

    gameDisplay.blit(text, textrect)
    pygame.display.update()
    pygame.time.delay(2000)

else:
    print('Exploring nodes...')
    success,solution = generatePath(q,startPosition,startOrientation,goalPosition,nodesExplored,threshDistance,threshAngle,clearance+radius)

    #############################################
    #      Drawing
    #############################################
    if(success):
        print('Optimal path found')
        endTime= time.time()
        print("Total time taken for exploring nodes "+ str(endTime-startTime) +" seconds.")
        draw = True
        while draw:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

            #draw nodesExplored
            for s in nodesExplored:
                if(nodesExplored[s].parent):
                    pt = nodesExplored[s].state[0:2]
                    ptParent = nodesExplored[s].parent.state[0:2]
                    x,y = pt*scale*res
                    x2,y2 = ptParent*scale*res

                    #draw explored nodes
                    pygame.draw.line(gameDisplay,white,(x2,y2),(x,y),1)
                    # pygame.draw.circle(gameDisplay,green,(int(x),int(y)),4)
                    # pygame.draw.circle(gameDisplay,green,(int(x2),int(y2)),2)
                    triangle = triangleCoordinates([x2,y2],[x,y],5)
                    pygame.draw.polygon(gameDisplay, green,[tuple(triangle[0]),tuple(triangle[1]),tuple(triangle[2])])

                #draw start and goal locations
                pygame.draw.rect(gameDisplay,blue,(startPosition[0]*res*scale,startPosition[1]*res*scale, \
                                 res*scale,res*scale))

                pygame.draw.circle(gameDisplay,blue,(int(goalPosition[0]*res*scale),int(goalPosition[1]*res*scale)), \
                                  math.floor(3*1.5*res*scale))

                pygame.draw.rect(gameDisplay,white,(goalPosition[0]*res*scale,goalPosition[1]*res*scale, \
                                 res*scale,res*scale))

                pygame.display.update()

            # draw solution path
            for i in range(len(solution)-1,-1,-1):
                pt = solution[i][0:2]
                x,y = pt[0]*scale*res,pt[1]*scale*res
                pygame.draw.circle(gameDisplay,red,(int(x),int(y)),4)
                pygame.display.update()
            pygame.time.delay(4000)
            draw = False

    else:
        basicfont = pygame.font.SysFont(None, 48)
        text = basicfont.render('Path can\'t be generated', True, (255, 0, 0), (255, 255, 255))
        textrect = text.get_rect()
        textrect.centerx = gameDisplay.get_rect().centerx
        textrect.centery = gameDisplay.get_rect().centery

        gameDisplay.blit(text, textrect)
        pygame.display.update()
        pygame.time.delay(2000)

pygame.quit()


import os
import shutil
import sys
import datetime
import json

dateconvert = {
    1: "Jan",
    2: "Feb",
    3: "Marc",
    4: "Apr",
    5: "Maj",
    6: "Jun",
    7: "Jul",
    8: "Aug",
    9: "Szept",
    10: "Okt",
    11: "Nov",
    12: "Dec"
}

def prepare():
    root = ""

    if len(sys.argv) > 1:
        root = sys.argv[1]
    else:
        while not os.path.exists(root) and not os.path.isdir(root):
            root = input("Adj egy helyes elérési mappát: ")

    with open("settings.txt","r") as f:
        settings = json.load(f)

    sorting(root,settings["subfold"],settings["delpar"])

def sorting(root,subfold,delpar):

    files = os.listdir(root)

    if subfold:

        for file in files:

            if os.path.isdir(f"{root}/{file}"):
                subsorting(root,f"/{file}",delpar)

            else:
                modtime = os.path.getmtime(root + "/" + file)
                moddate = datetime.datetime.fromtimestamp(modtime)
                sortfolder = f"{root}/{moddate.year}/{dateconvert[int(moddate.month)]}"

                if not os.path.exists(f"{root}/{moddate.year}"):
                    os.mkdir(f"{root}/{moddate.year}")

                if not os.path.exists(sortfolder):
                    os.mkdir(sortfolder)
                os.rename(root + "/" + file, sortfolder + "/" + file)
    else:

        for file in files:
            if not os.path.isdir(f"{root}/{file}"):

                modtime = os.path.getmtime(root + "/" + file)
                moddate = datetime.datetime.fromtimestamp(modtime)
                sortfolder = f"{root}/{moddate.year}/{dateconvert[int(moddate.month)]}"

                if not os.path.exists(f"{root}/{moddate.year}"):
                    os.mkdir(f"{root}/{moddate.year}")

                if not os.path.exists(sortfolder):
                    os.mkdir(sortfolder)

                os.rename(root + "/" + file, sortfolder + "/" + file)

    if delpar and subfold:
        check = os.listdir(root)
        for i in check:
            if "20" not in i:
                shutil.rmtree(root+"/"+i)

    return

def subsorting(root,path,delpar):
    files = os.listdir(root+path)

    for file in files:

        if os.path.isdir(f"{root + path}/{file}"):
            subsorting(root,f"{path}/{file}",delpar)
        else:
            modtime = os.path.getmtime(root+path+"/"+file)
            moddate = datetime.datetime.fromtimestamp(modtime)

            if delpar:

                sortfolder = f"{root}/{moddate.year}/{dateconvert[int(moddate.month)]}"

                if not os.path.exists(f"{root}/{moddate.year}"):
                    os.mkdir(f"{root}/{moddate.year}")
            else:

                sortfolder = f"{root+path}/{moddate.year}/{dateconvert[int(moddate.month)]}"

                if not os.path.exists(f"{root + path}/{moddate.year}"):
                    os.mkdir(f"{root+path}/{moddate.year}")

            if not os.path.exists(sortfolder):
                os.mkdir(sortfolder)

            os.rename(root+path+"/"+file,sortfolder+"/"+file)
    return

if __name__ == "__main__":
    prepare()


from collections import defaultdict

def solve(program):

    painted_hull = {}
    x, y = 0, 0
    dx, dy = 0, 1
    painting = True

    def input_func():
        print(f"get_color({x}, {y}) : {get_color(x, y)}")
        return get_color(x, y)

    def output_func(value):
        nonlocal x, y, dx, dy, painting
        if painting:
            print(f"Painting ({x}, {y}) : {value}")
            painted_hull[(x, y)] = value
        else:
            if value == 0:
                print(f"Turning left")
                dx, dy = -dy, dx
            else:
                print(f"Turning right")
                dx, dy = dy, -dx
            x += dx
            y += dy

            show_hull()
            # input()

        painting = not painting

    def get_color(x, y):
        if (x, y) in painted_hull:
            return painted_hull[(x, y)]
        else:
            return 1

    def show_hull():
        if len(painted_hull) == 0:
            print('')
            return

        min_x = min(x for x, y in painted_hull)
        max_x = max(x for x, y in painted_hull)
        min_y = min(y for x, y in painted_hull)
        max_y = max(y for x, y in painted_hull)

        s = '\n'.join(''.join('\u2588' if get_color(x, y) == 1 else ' ' for x in range(min_x, max_x + 1)) for y in reversed(range(min_y, max_y + 1)))
        print(s)
        print()

    execute(program, input_func=input_func, output_func=output_func)

    return len(painted_hull)

"""
Operations :
    1 a b c     add             a + b -> c
    2 a b c     multiply        a * b -> c
    3 a         input           input -> a
    4 a         output          a -> output
    5 a b       jump-if-true    (a != 0) => b -> instruction pointer
    6 a b       jump-if-false   (a == 0) => b -> instruction pointer
    7 a b c     less than       (a < b) -> c
    8 a b c     equals          (a == b) -> c
    9 a         change base     relative_base += a
   99           halt
"""
NUMBER_OF_OPERANDS = {1: 3,
                      2: 3,
                      3: 1,
                      4: 1,
                      5: 2,
                      6: 2,
                      7: 3,
                      8: 3,
                      9: 1,
                      99: 0}

def default_input():
    return int(input("Need input: "))

def execute(program_, input_func=default_input, output_func=print):

    program = defaultdict(int)
    for index, value in enumerate(program_):
        program[index] = value

    relative_base = 0

    def get_value(flag_, index_):
        if flag_ == 0:
            return program[index_]
        elif flag_ == 1:
            return index_
        elif flag_ == 2:
            return program[relative_base + index_]
        else:
            raise RuntimeError(f"Unknown flag {flag_} in get_value({flag_}, {index_})")

    def set_value(flag_, index_, value_):
        if flag_ == 0:
            program[index_] = value_
        elif flag_ == 1:
            raise RuntimeError(f"Cannot set to value in set_value({flag_}, {index_}, {value_})")
        elif flag_ == 2:
            program[relative_base + index_] = value_
        else:
            raise RuntimeError(f"Unknown flag {flag_} in set_value({flag_}, {index_}, {value_})")

    instruction_pointer = 0
    while True:
        flags_, op = divmod(program[instruction_pointer], 100)
        instruction_pointer += 1

        values, flags = [], []
        for i in range(NUMBER_OF_OPERANDS[op]):
            values.append(program[instruction_pointer])
            flags_, flag = divmod(flags_, 10)
            flags.append(flag)
            instruction_pointer += 1

        if op == 1:
            a, b, c = values
            fa, fb, fc = flags
            set_value(fc, c, get_value(fa, a) + get_value(fb, b))
        elif op == 2:
            a, b, c = values
            fa, fb, fc = flags
            set_value(fc, c, get_value(fa, a) * get_value(fb, b))
        elif op == 3:
            (a,) = values
            (fa,) = flags
            set_value(fa, a, input_func())
        elif op == 4:
            (a,) = values
            (fa,) = flags
            output_func(get_value(fa, a))
        elif op == 5:
            a, b = values
            fa, fb = flags
            if get_value(fa, a) != 0:
                instruction_pointer = get_value(fb, b)
        elif op == 6:
            a, b = values
            fa, fb = flags
            if get_value(fa, a) == 0:
                instruction_pointer = get_value(fb, b)
        elif op == 7:
            a, b, c = values
            fa, fb, fc = flags
            set_value(fc, c, 1 if (get_value(fa, a) < get_value(fb, b)) else 0)
        elif op == 8:
            a, b, c = values
            fa, fb, fc = flags
            set_value(fc, c, 1 if (get_value(fa, a) == get_value(fb, b)) else 0)
        elif op == 9:
            (a,) = values
            (fa,) = flags
            relative_base += get_value(fa, a)
        elif op == 99:
            return
        else:
            raise RuntimeError("Something went wrong")

if __name__ == "__main__":
    with open('input.txt', 'r') as input_file:
        program = list(map(int, input_file.readline().split(',')))
    print(solve(program))


import sklearn.svm
import ProtModel
import numpy as np
import sys

class SVM(ProtModel.Model):   #classe per modello SVM, estende classe astratta modello generico e utilizza la classe SVC di SkLearn

    def __init__(self, C, G):
        self.C=C
        self.G=G

    def train(self,datat):  #train the model given a training(labelled) set
        self.datat=datat
        train_set = []
        train_cla=[]
        positions = [x - (17 // 2) for x in range(17)]
        for id in datat:
            for index in range(len(datat[id]['prof'])):
                coded_seq = []
                for p in positions:
                    if index + p < 0 or index + p >= len(datat[id]['prof']):
                        coded_seq.extend(0 for x in range(21))
                    else:
                        coded_seq.extend(datat[id]['prof'][index + p])
                train_set.append(coded_seq)
                train_cla.append(datat[id]['SVMclass'][index])
        #print(self.C,self.gamma)
        #C=self.C
        #gamma=self.gamma
        #print(self.C,self.G)
        mo = sklearn.svm.SVC(C=self.C, kernel='rbf', gamma=self.G)
        #mo = sklearn.svm.SVC( kernel='rbf')
        #print(mo.C,mo.gamma)
        mo.fit(train_set, train_cla)
        #print('---train----')
        print(mo)
        self.model=mo

    def predicta(self,datap):  #predict an unknown set
        self.datap = datap
        positions = [x - (17 // 2) for x in range(17)]
        self.prediction=[]
        for id in datap:
            test_set = []
            prot=ProtModel.Prot(id,datap[id]['seq'],datap[id]['str'])
            for index in range(len(datap[id]['prof'])):
                coded_seq = []
                for p in positions:
                    if index + p < 0 or index + p >= len(datap[id]['prof']):
                        coded_seq.extend(0 for x in range(21))
                    else:
                        coded_seq.extend(datap[id]['prof'][index + p])
                test_set.append(coded_seq)
            #print('---predict----')
            #print(self.model.C,self.model.gamma)
            #print(self.model)
            predicted_structure = self.model.predict(test_set)
            temp=''
            for p in predicted_structure:
                if p == 1:
                    temp=temp+'H'
                elif p== 2:
                    temp=temp+'E'
                elif p==3:
                    temp=temp+'-'
            prot.predicted_structure=temp

            self.prediction.append(prot)

    def GetPred(self):   #return the prediction
        return self.prediction

        #kernel


"""
This program lists all the active courses as well
as courses with an assignment group containing "Ungraded"

This is useful for configuring the Redis db (See README.md)
"""

import os

import dotenv
from canvasapi import Canvas

dotenv.load_dotenv()

canvas_url = 'https://moravian.instructure.com/'
canvas_token = os.environ['CANVAS_TOKEN']

canvas = Canvas(canvas_url, canvas_token)

print('Current Courses:')
for course in canvas.get_courses():
    print('{}: {}'.format(course.id, course.name))

print('\n\nUngraded Assignment Groups:')
# 2020 course ids
course_ids = [14245, 14692, 13514, 13520]

for course_id in course_ids:
    course = canvas.get_course(course_id)
    for group in course.get_assignment_groups():
        if 'Ungraded' in group.name:
            print('{}:{}'.format(course_id, group.id))


from sklearn.svm import SVC
import pandas as pd
from sklearn.metrics import accuracy_score
import pickle

train = pd.read_csv("./mnist/train.csv")
valid = pd.read_csv("./mnist/t10k.csv")

train_label = train.iloc[:, 0] #모든행에 1번쨰 열
train_data = train.iloc[:, 1:] #모든 행에 2번째 ㅇ열부터 끝까지

valid_label = train.iloc[:, 0] #모든행에 1번쨰 열
valid_data = train.iloc[:, 1:] #모든 행에 2번째 ㅇ열부터 끝까지

model = SVC()
model.fit(train_data, train_label)
result = model.predict(valid_data)
score = accuracy_score(result, valid_label)

print(score)
#모델을 파일 형태로 저장하기 위해
f = open("./mnist_model.pkl", "wb")
pickle.dump(model, f)
f.close()


from typing import Optional

from .AircraftData import AircraftData
from src.pyLiveKML.KML.GeoCoordinates import GeoCoordinates
from src.pyLiveKML.KML.KML import AltitudeMode
from src.pyLiveKML.KML.KMLObjects.IconStyle import IconStyle
from src.pyLiveKML.KML.KMLObjects.Placemark import Placemark
from src.pyLiveKML.KML.KMLObjects.Point import Point
from src.pyLiveKML.KML.KMLObjects.Style import Style

class AircraftPosition(Placemark):
    @property
    def heading(self) -> Optional[float]:
        return self._styles[0].icon_style.heading

    @property
    def coordinates(self) -> GeoCoordinates:
        return self.geometry.coordinates

    def __init__(self, data: AircraftData):
        altitude_mode = (
            AltitudeMode.CLAMP_TO_GROUND
            if data.coordinates.alt is None
            else AltitudeMode.ABSOLUTE
        )
        point = Point(coordinates=data.coordinates, altitude_mode=altitude_mode)
        style = Style(
            icon_style=IconStyle(
                icon='http://maps.google.com/mapfiles/kml/shapes/track.png',
                heading=data.heading,
            )
        )
        Placemark.__init__(self, geometry=point, inline_style=style)
        self.timestamp = data.timestamp
        self.speed = data.speed


# -*- coding: utf-8 -*-
from five import grok
from jowent.bannerviewlet import MessageFactory as _
from jowent.bannerviewlet.behaviors.bannerimage import IBannerImage
from jowent.bannerviewlet.interfaces import IBannerViewletSettings
from plone.namedfile.interfaces import INamedBlobImageField
from plone.registry.interfaces import IRegistry
from z3c.form import validator
from zope.component import getUtility
from zope.interface import Invalid

class ImageDimensionsValidator(validator.FileUploadValidator):

    def validate(self, value):
        super(ImageDimensionsValidator, self).validate(value)

        if value:
            # See: plone.namedfile.file.NamedBlobImage
            width, height = value.getImageSize()

            registry = getUtility(IRegistry)
            settings = registry.forInterface(IBannerViewletSettings)

            # For the time being, ignore settings.validation_policy and
            # go with an *exact* Dimensions check
            if (width != settings.required_width or
                height != settings.required_height):
                raise Invalid(_(u"image_wrong_dimensions",
                        default=u"Image has wrong dimensions - it should be ${required_height} x ${required_width} pixels (h x w)"
                              ", but is ${actual_height} x ${actual_width}",
                        mapping={"required_height": settings.required_height,
                                 "required_width": settings.required_width,
                                 "actual_height": height,
                                 "actual_width": width}))

            # Lastly check filesize
            if value.getSize() > (settings.max_filesize * 1024):
                raise Invalid(_(u"image_too_large",
                            default=u"Image filesize is too large. Maximum permitted: ${max_filesize}KB",
                            mapping={"max_filesize": settings.max_filesize}))

validator.WidgetValidatorDiscriminators(ImageDimensionsValidator,
                                        context=IBannerImage,
                                        field=IBannerImage['banner_image'])
grok.global_adapter(ImageDimensionsValidator)