#import pythoncom
import pandas as pd
import csv
from sympy import Line                   # For geometry calculation

#from pkg02.util import *
from pkg01.cad import *

# Class Xs4Xls to prepare X-section data for Output files
class Xs4File:
    def __init__(self, fdir, fxls, fcsv, fxyz):
        self.fdir = fdir
        self.fxls = fxls
        self.fcsv = fcsv
        self.fxyz = fxyz
        self.dtcsv = []
        self.dtxyz = []
        self.dtxls = []

    # Add each X-section data for 3 formats
    def xsAdd(self, xsobj):
        #dicsv, dixyz, dixls = xsobj.dt2csv, xsObj.dt2xyz, xsObj.dt2xls
        for i in xsobj.dt2csv:
            self.dtcsv.append(i)
        for i in xsobj.dt2xyz:
            self.dtxyz.append(i)
        for i in xsobj.dt2xls:
            self.dtxls.append(i)

    def xs_show_csvdata(self):
        print(self.dtcsv)

    def xs_show_xyzdata(self):
        print(self.dtxyz)

    # Writing data to Excel file using Pandas Data Frame
    def xs2File(self, dtenconding):
        dfxls = pd.DataFrame(self.dtxls, columns=['Chainage', 'Offset', 'Elevation', 'Code']) # DataFrame to Excel
        dfcsv = pd.DataFrame(self.dtcsv, columns=['Chainage', 'Offset', 'Elevation', 'Code']) # DataFrame to CSV
        dfxyz = pd.DataFrame(self.dtxyz, columns=['East', 'North', 'Elevation', 'Code']) # DataFrame to CSV

        # Display result of X-section in Offset Elevation format
        print(dfcsv)
        #print(dfxyz)

        """
        with pd.ExcelWriter(self.fdir + self.fout, mode='w') as writer:
            df.to_excel(writer, sheet_name='Offset_Elevation')
        """
        xlsname = self.fdir + self.fxls
        csvname = self.fdir + self.fcsv
        xyzname = self.fdir + self.fxyz

        try:
            writer1 = pd.ExcelWriter(xlsname, mode='w')
            #dfcsv.to_csv(csvname, sep=' ', quoting=csv.QUOTE_MINIMAL, quotechar=' ', index=False)
            #dfxyz.to_csv(xyzname, sep=' ', quoting=csv.QUOTE_MINIMAL, quotechar=' ', index=False)
            dfcsv.to_csv(csvname, encoding='UTF-8', sep=' ', quoting=csv.QUOTE_MINIMAL, quotechar=' ', index=False)
            dfxyz.to_csv(xyzname, encoding='UTF-8', sep=' ', quoting=csv.QUOTE_MINIMAL, quotechar=' ', index=False)
            #dfcsv.to_csv(csvname, encoding=dtenconding, sep=' ', quoting=csv.QUOTE_MINIMAL, quotechar=' ', index=False)
            #dfxyz.to_csv(xyzname, encoding=dtenconding, sep=' ', quoting=csv.QUOTE_MINIMAL, quotechar=' ', index=False)
        except:
            msg = 'Excel File : {} : currently in use!!!'.format(xlsname)
            msg += '\nPlease close it, then process again.'
            warn_message(msg)
            return False
        dfxls.to_excel(writer1, sheet_name='Offset_Elevation')
        writer1.save()
        msg = '>>>> Excel File : {},\n'.format(xlsname)
        msg += '>>>> Csv File : {} & '.format(csvname)
        msg += '{} : have been created.'.format(xyzname)
        show_message(msg)

# X-section class for data manipulation
class XsInfo:
    CHN = []                                                # Initialize variables
    ptc = []
    p1, p2 = [], []
    ofs_ele = []
    enz = []
    num_xs = 0

    def __init__(self, ename, buffer):
        self.ename = ename
        #self.ptc = ptc
        self.buffer = buffer
        self._initsl()
        self.dt2csv = []
        self.dt2xyz = []
        self.dt2xls = []
        #self.dt2enz = []
        XsInfo.num_xs += 1

    # Initialize selection set "SS2"
    def _initsl(self):
        # Add the name "SS2" selection set
        try:
            doc.SelectionSets.Item("SS2").Delete()
        except:
            print("Delete selection failed")

        self.slpts = doc.SelectionSets.Add("SS2")

    # Compute boundary of X-section by buffer distance
    def XsBounds(self):
        self.p1 = self.ename.StartPoint
        self.p2 = self.ename.EndPoint
        self.bounds = line_bounds(self.ename, self.buffer)
        self.pnts = bounds2list(self.bounds)                # compute pnts for SelectByPolygon

    # Select XS point by XS_Line with Xdata attached,
    def getXsPoints(self):
        self.XsBounds()                                     # Compute XS boundary
        self.slpts.Clear()
        p1 = self.p1
        p2 = self.p2
        """
        cmd = 'Zoom W ' + str(p1).replace(" ", "") + ' ' + str(p2).replace(" ", "") + ' '
        cmd = cmd.replace("(", "")
        cmd = cmd.replace(")", "")                          # Create command line
        #cmd = 'Zoom E '             #Example for Zoom Extend
        doc.SendCommand(cmd)                                # Send command to CAD for Zoom window of XS line
        """
        doc.Application.ZoomWindow(pt_vtpt(p1), pt_vtpt(p2))    # Zoom window of XS line in CAD
        ftyp = [0, 8]                                           # Set up filter condition
        ftdt = ["Text", xscode_layer]
        """
        #Example format of pnts for SelectionByPolygon
        #pnts = [0, 0, 0, 750, 750, 0, 550, 900, 0, -180, 120, 0, 0, 0, 0]
        #pnts = vtFloat(pnts)
        """
        pnts = vtFloat(self.pnts)                           # pnts from Xsbounds
        filterType = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_I2, ftyp)
        filterData = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_VARIANT, ftdt)
        self.slpts.SelectByPolygon(6, pnts, filterType, filterData)      # mode = 6, SelectByPolygon
        #doc.SendCommand('regen ')
        doc.Regen(1)                                        # Regenerate drawing
        doc.Utility.Prompt("{0:d} points selected\n".format(self.slpts.count)) # echo to CAD command prompt
        #doc.Utility.Prompt(str(self.slpts.count) + " points selected\n")

    # Calculate offset & elevation of XS points, using XS line and its Xdata
    def calOfsEle(self):
        l1 = Line(self.p1, self.p2)                         # Create Line object for perpendicular
        self.enz = []
        self.ofs_ele = []
        xs_ang = self.ename.Angle
        xdata = self.ename.GetXData(cadapp)                 # Get Xdata from XS_Line
        """
        #Show XS line Xdata content
        #print(xdata)
        #xdata in format : ((1001, 1000, 1005, 1005), ('rtk_xs', 'X81', '3C22', '37E3'))
        #'rtk_xs' is an AppName in ACAD extended data
        """
        self.CHN = xdata[1][1]
        cc = doc.HandleToObject(xdata[1][3])                # Center point entity of X-section
        ptc = cc.InsertionPoint
        self.ptc = ptc
        s1 = l1.perpendicular_segment(ptc)                  # Compute CL point on XS line
        ptc = (float(s1.p2.x), float(s1.p2.y))              # Define CL point format
        for i in self.slpts:
            pt = i.InsertionPoint                           # Get point from Text entity
            s1 = l1.perpendicular_segment(pt)               # Compute point on XS line
            ptx = (float(s1.p2.x), float(s1.p2.y))
            el = pt[2]
            p_code = i.TextString                           # Get Code from Text entity
            di = distance(ptc, ptx)
            ang = angle(ptc, ptx)
            dang = abs(xs_ang - ang)
            if (dang > math.pi * 0.5) and (dang < math.pi * 1.5):
                di = 0 - di
            self.ofs_ele.append([p_code, (di, el)])         # Create list of Offset & Elevation with Code

            ptx = (float(s1.p2.x), float(s1.p2.y), el)      # Set format of ENZ
            #print(p_code, ptx)
            self.enz.append([p_code, ptx])                  # Create list of ENZ with Code
        self.ofs_ele = sort_rtk_x(self.ofs_ele)             # Sorting by Offset distance
        self.enz = sort_rtk_x(self.enz)                     # Sorting by East
        if (xs_ang > math.pi * 0.5) and (xs_ang < math.pi * 1.5):
            self.enz.reverse()

    # Ctreate XS points to Data table
    def xs2DTab(self):
        self.dt2xyz.append([self.CHN, '', '', ''])               # For XYZ file
        i = 0
        self.dt2xls = []                                         # For Excel
        for pt in self.ofs_ele:
            if i == 0:
                #f1.write('      {0:0.0f}     {1:0.3f}    {2}\n'.format(pt[1][0], pt[1][1], pt[0]))
                ofs_ele = ([self.CHN, round(pt[1][0]), pt[1][1], pt[0]])      #Data format for Excel
                self.dt2csv.append(ofs_ele)
                self.dt2xls.append(ofs_ele)
            else:
                #f1.write('           {0:0.0f}     {1:0.3f}    {2}\n'.format(pt[1][0], pt[1][1], pt[0]))
                ofs_ele = (['  ', round(pt[1][0]), pt[1][1], pt[0]])
                self.dt2csv.append(ofs_ele)
                self.dt2xls.append(ofs_ele)
            i += 1
        for pt in self.enz:
            #f2.write('{0:0.3f}   {1:0.3f}   {2:0.3f}   {3}\n'.format(pt[1][0], pt[1][1], pt[1][2], pt[0]))
            enzi = ([round(pt[1][0],3), round(pt[1][1],3), round(pt[1][2],3), pt[0]])
            self.dt2xyz.append(enzi)
            #self.dt2enz.append(enzi[:-1])
        # End for
        # Append '#' end of section
        self.dt2xyz.append(['#', '', '', ''])
        print('Total points = {:d} '.format(i))
        for i in self.slpts:                            # Change color of XS_Code to completed-color
            i.Color = completed_color

        #self.ename.Layer = xsline_completed_layer      # Set XS_Line layer = "XS_Line_Completed"

    # Draw computed points on X-section line
    def drawXSComputed(self, layer):
        if not layerexist(layer):
            doc.Layers.Add(layer)
        ms = doc.ModelSpace
        for pt in self.enz:
            p_pt = ms.AddPoint(pt_vtpt(pt[1]))
            p_pt.Layer = layer

"""
#object.Select( Mode , Point1 , Point2 , FilterType , FilterData )
#- Object : Object SelectionSet at The Applies to the this Method,..
#- Mode : selection mode, AcSelect enum, the specific meaning of the table.
#- Point1 : 3-dimensional coordinates.
#- Point2 : 3-dimensional coordinates.
#- FilterType : Group A code Specifying the DXF The type of filter to use.
#- FilterData : at The filter value to ON.
#————————————————
#：https://blog.csdn.net/Hulunbuir/article/details/95446723

#   Mode	            enum	Description
#------------------------------------------
# acSelectionSetWindow	    0	Selects all objects completely inside a rectangular area whose corners are
                                defined by Point1 and Point2.
# acSelectionSetCrossing	1	Selects objects within and crossing a rectangular area whose corners are
                                defined by Point1 and Point2.
# acSelectionSetPrevious	3	Selects the most recent selection set. This mode is ignored if you switch
                                between paper space and model space and attempt to use the selection set.
# acSelectionSetLast	    4	Selects the most recently created visible objects.
# acSelectionSetAll	        5	Selects all objects
#————————————————
#：https://blog.csdn.net/Hulunbuir/article/details/95446723
"""
"""
# Add the name "SS1" selection set
try:
    doc.SelectionSets.Item("SS1").Delete()
except:
    print("Delete selection failed")
slcn = doc.SelectionSets.Add("SS1")
"""

#==========
def create_xs_dtab(doci, proj_params, sta_label):
    global slcn
    global xscode_layer, completed_color, xsline_completed_layer, xscomppoint_layer
    global doc, cadapp, drawxscomppoint
    global data4file

    doc = doci
    workdir = proj_params['WorkDirectory']
    csvfname = proj_params['OutputCsvFile']
    xyzfname = 'xyz_' + csvfname
    xlsfname = proj_params['OutputXlsFile']

    cadapp = proj_params['CadApp']
    xsline_layer = proj_params['XSLineLayer']
    xscode_layer = proj_params['XSCodeLayer']
    completed_color = proj_params['CompletedColor']
    xsline_completed_layer = proj_params['XSLineCompletedLayer']
    Buffer = proj_params['Buffer']
    xscomppoint_layer = proj_params['XSComputedPointLayer']
    drawxscomppoint = proj_params['DrawXSComputedPoint']

    # Add the name "SS1" selection set
    try:
        doc.SelectionSets.Item("SS1").Delete()
    except:
        print("Delete selection failed")
    slcn = doc.SelectionSets.Add("SS1")

    #p1list = []
    #xlsdata = Xs4Xls('d:/TGA_Lisp/', 'xs-03.xlsx')
    #xlsfname = input('Name of Excel file : ')
    #xlsfname = doc.Utility.GetInput()
    try:
        #print('Interact with AutoCAD Window >>>')
        doc.Utility.Prompt('To Extract X-section Data >>>\n')
        #print(dir(doc.Utility))
        #doc.Utility.InitializeUserInput(1)
        keypress = doc.Utility.GetKeyword('Press [Enter] to continue, [Esc] to cancel : ')
        #doc.Regen(1)
        #doc.Application.Update()                                #Redraw CAD window
    except:
        return

    #xlsfdir = 'd:/TGA_Lisp/'                        # Folder for Output Excel file
    #xlsfname = None
    #while not xlsfname:
    #xlsfname = doc.Utility.GetString(1, 'Output Excel file name : ')
    data4file = Xs4File(workdir, xlsfname, csvfname, xyzfname)    # File name from proj_params
    print('>>>X-section extraction start')
    doc.Regen(1)
    # Filtered of Line on layer XS_Line
    ftyp = [0, 8]
    ftdt = ["Line", xsline_layer]                                  # Filter with Line & XS_Line layer

    filterType = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_I2, ftyp)
    filterData = win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_VARIANT, ftdt)

    #slcn.Select(5)
    slcn.Select(5, 0, 0, filterType, filterData)            # Select all with filtering
    print('{:d} X-sections are filtered'.format(slcn.count))

    j = 0
    XsInfo.num_xs = 0           # initialize number of X-section
    for i in range(slcn.count):
        #Ename = slcn[i]
        #print(Ename.GetXData(cadapp))

        xdata = slcn[i].GetXData(cadapp)
        #print(xdata)
        if xdata != (None, None):                       # Xdata 'rtk_xs' attached to X-section line
            CHN = xdata[1][1]
            #cc = doc.HandleToObject(xdata[1][3])
            #ptc = cc.InsertionPoint
            #print('Processing chainage : {}'.format(CHN))
            msg = 'Processing chainage : {}'.format(CHN)
            doc.Utility.Prompt(msg + '\n')          # Echo to CAD command prompt
            statusbox(sta_label, msg)

            #Testing OBJECT
            #XSObj1 = XSInfo(slcn[0], [507063.544, 1860344.719], 10)
            xsObj1 = XsInfo(slcn[i], Buffer)
            """"
            # Try to create Object at once
            if i == 0:
                xsObj1 = XsInfo(slcn[i], Buffer)
            else:
                xsObj1.ename = slcn[i]
            """

            xsObj1.getXsPoints()                                # Call getXsPoints Function

            xsObj1.calOfsEle()                                  # Call calOfsEle Function
            #print(xsObj1.ofs_ele)
            #print(xsObj1.enz)

            #xsObj1.xs2csvFile('d:/TGA_Lisp/', 'xsec-0.csv')     # Call Xs2File by giving Directory & FileName
            xsObj1.xs2DTab()                    # Call xs2DTab
            if drawxscomppoint:                 # Draw computed XS on X-section line
                xsObj1.drawXSComputed(xscomppoint_layer)
            data4file.xsAdd(xsObj1)
            #slcn[i].Layer = 'XS_Line_Completed'                 # change XS_Line to completed
        j += 1
    #for
    msg = '>>>> Total {:d} X-sections extracted.'.format(XsInfo.num_xs)
    doc.Utility.Prompt(msg + '\n')  # Echo to CAD command prompt
    show_message(msg)
    return data4file

# To create Files of X-section
def create_xs_file(rtkencoding):
    if data4file:
        data4file.xs2File(rtkencoding)                       # Call data4file.xs2File -> Data to Files
        if not layerexist(xsline_completed_layer):
            doc.Layers.Add(xsline_completed_layer)
        for si in slcn:
            si.Layer = xsline_completed_layer               # change XS_Line to completed
    else:
        msg = 'Please run [eXtract XS] before this!'
        show_message(msg)


from Manager import Manager
import os
import argparse
import ConfigWriter
import json
parser = argparse.ArgumentParser()
parser.add_argument("-Config_Path", help=f"Input a string in the form 'relative/path/to/Config.json' With the settings to run the display on")
def clearConsole():
    try:
        os.system('cls')
    except:
        try:
            os.system('clear')
        except:
            pass
def start(workingDir, configPath):
    manager = Manager(workingDir, configPath)
    manager.start()

if __name__ == '__main__':
    workingDirectory = os.path.abspath("Display Working Directory")
    defaultConfigPath = os.path.join(workingDirectory, "Config.json")
    defaultBackupConfigPath = os.path.join(workingDirectory, "Config_backup.json")
    args = parser.parse_args()
    if args.Config_Path is None:
        print("Config_Path argument not passed in.")
        # No Config Path detected. Check for one
        foundConfigs = []
        for path in [path for path in [os.path.join(workingDirectory, x) for x in os.listdir(workingDirectory)] if os.path.exists(path) and os.path.isfile(path) and path.lower().endswith(".json")]:
            # A config has been found.
            try:
                config = Manager.loadConfig(path)
                if isinstance(config, dict) and False not in [prop.value in config for prop in ConfigWriter.ConfigProps]:
                    foundConfigs.append((path, config))
            except:
                continue
        configPathMap = {}
        if len(foundConfigs) > 0:
            fileListString = '\n'.join([found[0] for found in foundConfigs])
            print(f"Config file{'s' if len(foundConfigs) > 1 else ''} have been detected in \n{fileListString}")
            index = 1
            for path, config in foundConfigs:
                configPathMap[index] = path
                configStr = json.dumps(config).replace("None", "'Auto'")
                print(f"{index}. Config settings for {path}\n{configStr}")
                index += 1
        keys = list(configPathMap)
        keys.sort()
        options = [
            "{0}. Use Config: {1}".format(key, configPathMap[key])
            for key in keys
        ]
        options.append(f"{len(options) + 1}. Create Configuration")
        options.append(f"{len(options) + 1}. Quit")
        while True:
            try:
                choice = int(input("Please select a configuration option.\n{0}\n".format("\n".join(options))).replace(" ", ""))
                if choice in list(range(1, len(options) + 1)):
                    break
            except:
                print("Invalid input. Must be number between {0} and {1}".format(1, len(options)))
        if choice in configPathMap:
            configPath = configPathMap[choice][0]
            start(workingDirectory, configPath)
        elif choice == len(options) - 1:
            # Create config
            configPath = defaultConfigPath
            ConfigWriter.createConfigCommandLine(configPath)
            start(workingDirectory, configPath)
    else:
        # Config file has been passed in
        start(workingDirectory, args.Config_Path)


import numpy as np

def loadAirfoil(file='/Users/gakki/Dropbox/thesis/surface_flow_sort.csv'):
    info = np.loadtxt(file, delimiter=',', skiprows=1)
    num_nodes = info.__len__()
    info[:, 0] = np.arange(num_nodes)

    turning_point_id = num_nodes // 2

    force_dict = {}
    force_dict['GLOBALIDX'] = np.array(info[:, 0], dtype=int)
    force_dict['X'] = info[:, 1]
    force_dict['Y'] = info[:, 2]
    force_dict['PRESS'] = info[:, 3]
    force_dict['PRESSCO'] = info[:, 4]
    force_dict['MACHNUM'] = info[:, 5]

    airfoil = {}
    airfoil['x_bot'] = force_dict['X'][:turning_point_id]
    airfoil['y_bot'] = force_dict['Y'][:turning_point_id]
    airfoil['p_bot'] = force_dict['PRESS'][:turning_point_id]
    airfoil['x_top']= force_dict['X'][turning_point_id:][::-1]
    airfoil['y_top'] = force_dict['Y'][turning_point_id:][::-1]
    airfoil['p_top'] = force_dict['PRESS'][turning_point_id:][::-1]
    airfoil['num_data'] = num_nodes
    airfoil['turning_point'] = num_nodes//2
    return airfoil


# -*- coding: utf-8 -*-
from easynav.views import GenericView
from django.conf.urls.defaults import patterns,url

def MakePattern(menuItem):
    ur = menuItem.url

    if ur == "/":
        ur=""
    else:
        if ur[0] == "/" and len(ur)>1:
            ur = ur[1:]
        if len(ur)>1 and ur[-1] != "/":
            ur+="/"

    return patterns('',url(
                r'^%s$' % ur,
                GenericView.as_view(),
                kwargs={"slug": menuItem.slug,},
                name="easynav-%s" % menuItem.slug
                ))


from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Comment
from django.views import generic
from .forms import CommentForm, PostForm, ImageForm
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.contrib.auth.models import User
from .forms import UserRegistrationForm

class PostList(generic.ListView):
    queryset = Post.objects.order_by('-created_on')
    template_name = 'index.html'
    context_object_name = 'data'
    paginate_by = 5

class PostRead(generic.DetailView):
    model = Post
    template_name = 'index_read.html'

def news(request):
    return render(request, 'news.html')
def add_comment(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.for_post = post
            comment.save()
            return redirect('postRead', pk=post.pk)
    else:
        form = CommentForm()
    return render(request, 'indexComment.html', {'form': form})

@login_required
def comment_remove(request, pk):
    comment = get_object_or_404(Comment, pk=pk)
    comment.delete()
    return redirect('postRead', pk=comment.for_post.pk)

@login_required
def post_remove(request, pk):
    Post = get_object_or_404(Post, pk=pk)
    post.delete()
    return redirect('index', pk=post.pk)

@login_required
def post_edit(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.created_on = timezone.now()
            post.save()
            return redirect('postRead', pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, 'post_edit.html', {'form': form})

def register(request):
    if request.method == 'POST':
        user_form = UserRegistrationForm(request.POST)
        if user_form.is_valid():
            new_user = user_form.save(commit=False)
            new_user.set_password(user_form.cleaned_data['password'])
            new_user.save()
            return render(request, 'register_done.html', {'new_user': new_user})
    else:
        user_form = UserRegistrationForm()
    return render(request, 'register.html', {'user_form': user_form})

def Log(request):
	redirect('/')

def Logout(request):
	pass

@login_required
def image_upload_view(request):
    """Process images uploaded by users"""
    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            # Get the current instance object to display in the template
            img_obj = form.instance
            return render(request,'index.html', {'img_obj': img_obj})
    else:
        form = ImageForm()
    return render(request, 'add_image.html', {'form': form})

# Create Post with image
@login_required
def post_new(request):
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            img_obj = form.instance
            image =  img_obj

            post.save()
            return redirect('postRead', pk=post.pk)

    else:
        form = PostForm()
    return render(request, 'post_edit.html', {'form': form})

def news(request):
    return render(request, 'news.html')

def about_blog(request):
    return render(request, 'about_blog.html')


import decimal
import uuid

from flask_sqlalchemy import SQLAlchemy

from src.shared.global_db import GlobalDB

db = SQLAlchemy()

class Product(db.Model):
    id = db.Column(db.String, unique=True, primary_key=True, default=uuid.uuid4)
    name = db.Column(db.String(80), nullable=False)
    stock = db.Column(db.Integer, nullable=False, default=0)
    price = db.Column(db.Numeric(10, 2), nullable=False)

class ShoppingCart(db.Model):
    id = db.Column(db.String, unique=True, primary_key=True, default=uuid.uuid4)
    products = db.relationship('ProductsInShoppingCart', back_populates='shopping_cart')
    coupon_id = db.Column(db.Integer, db.ForeignKey('coupon.id'), nullable=True)

    def show_items(self):
        items = []
        for p in self.products:
            product = GlobalDB.instance().db.session.query(Product) \
                .filter(Product.id == p.product_id).first()
            items.append(
                {
                    "product_id": p.product_id,
                    "name": product.name,
                    "quantity": p.quantity,
                    "price": product.price,
                    "subtotal": decimal.Decimal(
                        product.price * decimal.Decimal(p.quantity)
                    ).quantize(decimal.Decimal('0.01'))
                }
            )
        return items

    def subtotal(self):
        total = decimal.Decimal(0)
        for i in self.show_items():
            total += i['subtotal']
        return total

    def discount(self):
        if self.coupon_id is not None:
            coupon = GlobalDB.instance().db.session.query(Coupon).\
                filter(Coupon.id == self.coupon_id).first()
            return ((coupon.discount_percentage * self.subtotal()) / decimal.Decimal(100)).\
                quantize(decimal.Decimal('0.01'))
        return '0'

    def total(self):
        total = decimal.Decimal(0)
        for i in self.show_items():
            total += i['subtotal']
        total -= decimal.Decimal(self.discount())
        return total.quantize(decimal.Decimal('0.01'))

class ProductsInShoppingCart(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    quantity = db.Column(db.Integer, nullable=False, default=1)
    product_id = db.Column('product_id', db.String, db.ForeignKey('product.id'))
    shopping_cart_id = db.Column('shopping_cart_id', db.String, db.ForeignKey('shopping_cart.id'))
    product = db.relationship("Product")
    shopping_cart = db.relationship("ShoppingCart", back_populates="products")

class Coupon(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(80), nullable=False)
    discount_percentage = db.Column(db.Numeric(10, 2), nullable=False)
    is_valid = db.Column(db.Boolean, default=False, nullable=False)


import logging

from django.core.exceptions import ObjectDoesNotExist
from rest_framework.permissions import (DjangoModelPermissions,
                                        DjangoObjectPermissions)

logger = logging.getLogger(__name__)

def log_result(func):
    '''
    A decorator to automatically log the arguments and the results of calls
    to has_permission and has_object_permission.
    '''
    def wrapper(self, request, *args):
        result = func(self, request, *args)

        class_name = self.__class__.__name__
        func_name = func.__name__
        logger.debug('%s.%s path=%s method=%s user=%s result=%s',
                     class_name, func_name, request.path, request.method, request.user, result)
        return result

    return wrapper

class HasModelPermission(DjangoModelPermissions):

    perms_map = {
        'GET': ['%(app_label)s.view_%(model_name)s'],
        'OPTIONS': ['%(app_label)s.view_%(model_name)s'],
        'HEAD': ['%(app_label)s.view_%(model_name)s'],
        'POST': ['%(app_label)s.add_%(model_name)s'],
        'PUT': ['%(app_label)s.change_%(model_name)s'],
        'PATCH': ['%(app_label)s.change_%(model_name)s'],
        'DELETE': ['%(app_label)s.delete_%(model_name)s'],
    }

    @log_result
    def has_permission(self, request, view):
        return super().has_permission(request, view)

    @log_result
    def has_object_permission(self, request, view, obj):
        if not (request.user and request.user.is_authenticated):
            return False

        # has_object_permission needs to follow has_permission
        return self.has_permission(request, view)

class HasObjectPermission(DjangoObjectPermissions):

    perms_map = {
        'GET': ['%(app_label)s.view_%(model_name)s_object'],
        'OPTIONS': ['%(app_label)s.view_%(model_name)s_object'],
        'HEAD': ['%(app_label)s.view_%(model_name)s_object'],
        'POST': ['%(app_label)s.add_%(model_name)s_object'],
        'PUT': ['%(app_label)s.change_%(model_name)s_object'],
        'PATCH': ['%(app_label)s.change_%(model_name)s_object'],
        'DELETE': ['%(app_label)s.delete_%(model_name)s_object'],
    }

    @log_result
    def has_permission(self, request, view):
        if not (request.user and request.user.is_authenticated):
            return False

        # check if this is a detail view (retrieve, update, partial_update, destroy) or not (list, create)
        if view.detail:
            # for retrieve, update, partial_update, or destroy return True
            # the permission will be checked on object level (in the next step)
            return True
        else:
            try:
                # for list or create we need to check the permission object from the view
                # and check that the user has the correct permission on this object
                permission_object = view.get_list_permission_object()
                return super().has_object_permission(request, view, permission_object)
            except ObjectDoesNotExist:
                # return False if the database query fails
                return False
            except AttributeError:
                # return True if the function is not defined in the view
                # the permission will be checked on object level (in the next step)
                return True

    @log_result
    def has_object_permission(self, request, view, obj):
        # get the permission object from the view
        try:
            permission_object = view.get_detail_permission_object(obj)
            return super().has_object_permission(request, view, permission_object)
        except ObjectDoesNotExist:
            # return False if the database query fails
            return False
        except AttributeError:
            # just take the input obj if the function is not defined in the view
            return super().has_object_permission(request, view, obj)


# General
import os
import numpy as np
from dotenv import load_dotenv; load_dotenv()
from typing import Optional
from utils.json_utils import load_json, dump_json

# Timing
from codetiming import Timer
from tqdm import tqdm

# NLP
import regex as re

# Constants
MATCHES_PER_YEAR_ENOUGH_THRESHOLD = 100_000
DATA_MFD_PATH = os.getenv('DATA_MFD_PATH')
DATA_LEMMATIZED_PATH = os.getenv('DATA_LEMMATIZED_PATH')
DATA_COUNTS_PATH = os.getenv('DATA_COUNTS_PATH')

w2f: dict[str, list[str]] = load_json(f'{DATA_MFD_PATH}/w2f_pl.json') #type:ignore

def get_w_re(w: str) -> re.Pattern[str]:
    pat = r'\b' + w.replace('*', r'\w*') + r'\b'
    return re.compile(pat)

def load_w2re() -> dict[str, re.Pattern[str]]:
    w2re = {w: get_w_re(w) for w in sorted(w2f)}
    return w2re

def count_lemmas(re_w: re.Pattern[str], text_lemmas: str) -> int:
    return len(re_w.findall(text_lemmas))

def initialize_counts() -> dict[str, int]:
    return {w:0 for w in sorted(w2f)}# | {'total_lemmas': 0, 'total_matches': 0}

def compute_counts_sum(counter: dict[str, int]) -> int:
    return int(np.sum([counter[w] for w in w2f]))

def main() -> None:
    w2re = load_w2re()
    batches: list[tuple[str, str]] = [(f'{DATA_LEMMATIZED_PATH}/{d}', d.replace('.json', '')) for d in sorted(os.listdir(DATA_LEMMATIZED_PATH))]
    periods = sorted(dict.fromkeys([b[1].split('b')[0] for b in batches]))
    period2batches: dict[str, list[tuple[str, str]]] = {p: [b for b in batches if p in b[1]] for p in periods}

    start_i = 0
    end_i = None
    if end_i is None:
        end_i = len(batches)

    t = Timer()
    for i, (period_name, period_batches) in enumerate(sorted(period2batches.items())[start_i:end_i], start_i):
        t.start()
        #
        print(f'[{str(i).zfill(2)}/{len(periods)}] | Processing period {period_name} | {len(period_batches)} batch{"es" if len(period_batches) > 1 else ""}')

        counts = initialize_counts()
        total_lemmas = 0
        total_matches = 0
        for batch_path, batch_name in tqdm(period_batches):
            batch_lemmas: list[str] = load_json(batch_path) #type:ignore
            batch_lemmas_str = ' '.join(batch_lemmas)
            # print(f'Batch {batch_name} | Length: {len(batch_lemmas)} lemmas')

            for w, re_w in w2re.items():
                counts[w] += count_lemmas(re_w, batch_lemmas_str)
            total_lemmas += len(batch_lemmas)
            total_matches += compute_counts_sum(counts)
            # print(f'{total_matches = } ({100*(total_matches/MATCHES_PER_YEAR_ENOUGH_THRESHOLD):.2f} %)')
            # if total_matches > MATCHES_PER_YEAR_ENOUGH_THRESHOLD:
            #     break

        results = dict(period=period_name,
                       counts=counts,
                       total_lemmas=total_lemmas,
                       total_matches=total_matches)
        save_path = f'{DATA_COUNTS_PATH}/{period_name}.json'
        dump_json(results, save_path)
        #
        t.stop()

if __name__ == '__main__':
    main()


import sqlite3
import matplotlib.pyplot as plt
import numpy as np

dbname = "Record.sqlite3"
conn = sqlite3.connect(dbname)
c = conn.cursor()

# データを取り出す
Japanese_select = "select mark from Japanese"
Math_select = "select mark from Math"
English_select = "select mark from English"

Japanese = c.execute(Japanese_select).fetchall()
Math = c.execute(Math_select).fetchall()
English = c.execute(English_select).fetchall()

# 総和
print("=== sum ===")
print("Japanese:" + str(np.sum(Japanese)))
# print("Math:" + str(np.sum(Math)))
print("English:" + str(np.sum(English)))
# 平均
print("=== average ===")
print("Japanese:" + str(np.average(Japanese)))
# print("Math:" + str(np.average(Math)))
print("English:" + str(np.average(English)))
# 分散
print("=== var ===")
print("Japanese:" + str(np.var(Japanese)))
print("English:" + str(np.var(English)))

def mark(subject):
    all = []
    for i in range(len(subject)):
        all.append(subject[i][0])
    return all

# 点数のタプル
points = (mark(Japanese),mark(English))
# 箱ひげ図
fig, ax = plt.subplots()

bp = ax.boxplot(points)
# データ名
ax.set_xticklabels(['Japanese', 'English'])

plt.title('Japanese & English Box Plot')
# ラベル名
plt.xlabel('subject')
plt.ylabel('points')
# Y軸のメモリの長さ
plt.ylim([0,100])
plt.grid()

# 描画
plt.show()

conn.close() # 閉じる


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

@author: Maurizio Ferrari Dacrema
"""

import numpy as np
from RecSysFramework.Recommender.DataIO import DataIO
from RecSysFramework.Utils import check_matrix

class Recommender(object):
    """Abstract Recommender"""

    RECOMMENDER_NAME = "Recommender_Base_Class"

    def __init__(self, URM_train):

        super(Recommender, self).__init__()

        self.URM_seen = None

        self.URM_train = check_matrix(URM_train.copy(), 'csr', dtype=np.float32)
        self.URM_train.eliminate_zeros()

        self.n_users, self.n_items = self.URM_train.shape
        self.verbose = True

        self.filterTopPop = False
        self.filterTopPop_ItemsID = np.array([], dtype=np.int)

        self.items_to_ignore_flag = False
        self.items_to_ignore_ID = np.array([], dtype=np.int)

        self._cold_user_mask = np.ediff1d(self.URM_train.indptr) == 0
        self._cold_users = np.arange(self.n_users)[self._cold_user_mask]

        if self._cold_user_mask.any():
            self._print("URM Detected {} ({:.2f} %) cold users.".format(
                self._cold_user_mask.sum(), self._cold_user_mask.sum()/self.n_users*100))

        self._cold_item_mask = np.ediff1d(self.URM_train.tocsc().indptr) == 0
        self._cold_items = np.arange(self.n_items)[self._cold_item_mask]

        if self._cold_item_mask.any():
            self._print("URM Detected {} ({:.2f} %) cold items.".format(
                self._cold_item_mask.sum(), self._cold_item_mask.sum()/self.n_items*100))

    def _get_cold_user_mask(self):
        return self._cold_user_mask

    def _get_cold_users(self):
        return self._cold_users

    def _get_cold_item_mask(self):
        return self._cold_item_mask

    def _get_cold_items(self):
        return self._cold_items

    def _print(self, string):
        if self.verbose:
            print("{}: {}".format(self.RECOMMENDER_NAME, string))

    def fit(self):
        pass

    def get_URM_train(self):
        return self.URM_train.copy()

    def set_URM_seen(self, URM_seen):
        self.URM_seen = URM_seen.tocsr().astype(np.bool).astype(np.float32)

    def set_URM_train(self, URM_train_new, **kwargs):

        assert self.URM_train.shape == URM_train_new.shape, \
            "{}: set_URM_train old and new URM train have different shapes".format(self.RECOMMENDER_NAME)

        if len(kwargs) > 0:
            self._print("set_URM_train keyword arguments not supported "
                        "for this recommender class. Received: {}".format(kwargs))

        self.URM_train = check_matrix(URM_train_new.copy(), 'csr', dtype=np.float32)
        self.URM_train.eliminate_zeros()

        self._cold_user_mask = np.ediff1d(self.URM_train.indptr) == 0

        if self._cold_user_mask.any():
            self._print("Detected {} ({:.2f} %) cold users.".format(
                self._cold_user_mask.sum(), self._cold_user_mask.sum()/len(self._cold_user_mask)*100))

    def set_items_to_ignore(self, items_to_ignore):
        self.items_to_ignore_flag = True
        self.items_to_ignore_ID = np.array(items_to_ignore, dtype=np.int)

    def reset_items_to_ignore(self):
        self.items_to_ignore_flag = False
        self.items_to_ignore_ID = np.array([], dtype=np.int)

    #########################################################################################################
    ##########                                                                                ##########
    ##########                     COMPUTE AND FILTER RECOMMENDATION LIST                          ##########
    ##########                                                                                ##########
    #########################################################################################################

    def _remove_TopPop_on_scores(self, scores_batch):
        scores_batch[:, self.filterTopPop_ItemsID] = -np.inf
        return scores_batch

    def _remove_custom_items_on_scores(self, scores_batch):
        scores_batch[:, self.items_to_ignore_ID] = -np.inf
        return scores_batch

    def _remove_seen_on_scores(self, user_id, scores_batch):

        if self.URM_seen is not None:
            urm = self.URM_seen
        else:
            urm = self.URM_train

        if len(scores_batch.shape) == 1:
            seen = urm.indices[urm.indptr[user_id]:urm.indptr[user_id + 1]]
            scores_batch[seen] = -np.inf
        else:
            seen = urm[user_id, :]
            seen.data -= np.inf
            scores_batch += seen

        return scores_batch

    def _compute_item_score(self, user_id_array, items_to_compute=None):
        """

        :param user_id_array:       array containing the user indices whose recommendations need to be computed
        :param items_to_compute:    array containing the items whose scores are to be computed.
                                        If None, all items are computed, otherwise discarded items will have as score -np.inf
        :return:                    array (len(user_id_array), n_items) with the score.
        """
        raise NotImplementedError("BaseRecommender: compute_item_score not assigned for current recommender, unable to compute prediction scores")

    def _compute_item_score_postprocess_for_cold_users(self, user_id_array, item_scores):
        """
        Remove cold users from the computed item scores, setting them to -inf
        :param user_id_array:
        :param item_scores:
        :return:
        """

        cold_users_batch_mask = self._get_cold_user_mask()[user_id_array]

        # Set as -inf all cold user scores
        if np.any(cold_users_batch_mask):
            item_scores[cold_users_batch_mask, :] -= np.inf

        return item_scores

    def _compute_item_score_postprocess_for_cold_items(self, item_scores):
        """
        Remove cold items from the computed item scores, setting them to -inf
        :param item_scores:
        :return:
        """

        cold_items = self._get_cold_items()

        # Set as -inf all cold items scores
        if len(cold_items) > 0:
            item_scores[:, cold_items] -= np.inf

        return item_scores

    def recommend(self, user_id_array, cutoff=None, remove_seen_flag=True, items_to_compute=None,
                  remove_top_pop_flag=False, remove_custom_items_flag=False, return_scores=False, filter_at_recommendation=False):

        # If is a scalar transform it in a 1-cell array
        if np.isscalar(user_id_array):
            user_id_array = np.atleast_1d(user_id_array)
            single_user = True
        else:
            single_user = False

        if cutoff is None:
            cutoff = self.URM_train.shape[1] - 1

        if not filter_at_recommendation:
            rec_items_to_compute = None
        else:
            rec_items_to_compute = items_to_compute
        # Compute the scores using the model-specific function
        # Vectorize over all users in user_id_array
        scores_batch = self._compute_item_score(user_id_array, items_to_compute=rec_items_to_compute)

        if remove_seen_flag:
            scores_batch = self._remove_seen_on_scores(user_id_array, scores_batch)

        # Sorting is done in three steps. Faster then plain np.argsort for higher number of items
        # - Partition the data to extract the set of relevant items
        # - Sort only the relevant items
        # - Get the original item index
        # relevant_items_partition = (-scores_user).argpartition(cutoff)[0:cutoff]
        # relevant_items_partition_sorting = np.argsort(-scores_user[relevant_items_partition])
        # ranking = relevant_items_partition[relevant_items_partition_sorting]
        #
        # ranking_list.append(ranking)

        if remove_top_pop_flag:
            scores_batch = self._remove_TopPop_on_scores(scores_batch)

        if remove_custom_items_flag:
            scores_batch = self._remove_custom_items_on_scores(scores_batch)

        scores_batch = np.array(scores_batch)
        ranking_list = [None] * len(user_id_array)

        # Remove from the recommendation list any item that has a -inf score
        # Since -inf is a flag to indicate an item to remove

        if items_to_compute is not None:
            if not isinstance(items_to_compute, list):
                items_to_compute = [items_to_compute]

        for user_index in range(len(user_id_array)):

            sb = scores_batch[user_index, :]
            if items_to_compute is not None:
                sb = sb[items_to_compute[user_index]]

            # relevant_items_partition is block_size x cutoff
            len_to_order = min(cutoff, sb.shape[-1])
            relevant_items_partition = sb.argpartition(-len_to_order, axis=-1)[-len_to_order:]

            # Get original value and sort it
            # [:, None] adds 1 dimension to the array, from (block_size,) to (block_size,1)
            # This is done to correctly get scores_batch value as [row, relevant_items_partition[row,:]]
            relevant_items_partition_original_value = sb[relevant_items_partition]
            relevant_items_partition_sorting = np.argsort(-relevant_items_partition_original_value, axis=-1, kind="stable")
            user_recommendation_list = relevant_items_partition[relevant_items_partition_sorting]

            user_item_scores = sb[user_recommendation_list]
            not_inf_scores_mask = np.logical_not(np.isinf(user_item_scores))

            ranking_list[user_index] = user_recommendation_list[not_inf_scores_mask].tolist()
            if items_to_compute is not None:
                ranking_list[user_index] = items_to_compute[user_index][ranking_list[user_index]]

        # Return single list for one user, instead of list of lists
        if single_user:
            ranking_list = ranking_list[0]
            scores_batch = scores_batch[0]

        if return_scores:
            return ranking_list, scores_batch

        return ranking_list

    #########################################################################################################
    ##########                                                                                ##########
    ##########                                LOAD AND SAVE                                        ##########
    ##########                                                                                ##########
    #########################################################################################################

    def save_model(self, folder_path, file_name=None):
        raise NotImplementedError("Recommender: save_model not implemented")

    def load_model(self, folder_path, file_name=None):

        if file_name is None:
            file_name = self.RECOMMENDER_NAME

        self._print("Loading model from file '{}'".format(folder_path + file_name))

        dataIO = DataIO(folder_path=folder_path)
        data_dict = dataIO.load_data(file_name=file_name)

        for attrib_name in data_dict.keys():
             self.__setattr__(attrib_name, data_dict[attrib_name])

        self._print("Loading complete")


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""TransactionKeyValue links Transactions and Keys and Values objects."""
from peewee import ForeignKeyField, CompositeKey
from .base import DB
from .utils import index_hash, unicode_type
from .projects import Projects
from .analytical_tools import AnalyticalTools
from ..rest.orm import CherryPyAPI

class AToolProject(CherryPyAPI):
    """
    TransactionKeyValue attributes are foreign keys.

    Attributes:
        +-------------------+-------------------------------------+
        | Name              | Description                         |
        +===================+=====================================+
        | project           | Link to the Projects model          |
        +-------------------+-------------------------------------+
        | analytical_tool   | Link to the AnalyticalTools model   |
        +-------------------+-------------------------------------+
    """

    project = ForeignKeyField(Projects, backref='atools')
    analytical_tool = ForeignKeyField(AnalyticalTools, backref='projects')

    # pylint: disable=too-few-public-methods
    class Meta:
        """PeeWee meta class contains the database and the primary key."""

        database = DB
        primary_key = CompositeKey('analytical_tool', 'project')
    # pylint: enable=too-few-public-methods

    def to_hash(self, **flags):
        """Convert the object to a hash."""
        obj = super(AToolProject, self).to_hash(**flags)
        obj['_id'] = index_hash(unicode_type(self.__data__['project']),
                                int(self.__data__['analytical_tool']))
        obj['project'] = unicode_type(self.__data__['project'])
        obj['analytical_tool'] = int(self.__data__['analytical_tool'])

        return obj

    def from_hash(self, obj):
        """Convert the hash into the object."""
        super(AToolProject, self).from_hash(obj)
        self._set_only_if('project', obj, 'project',
                          lambda: Projects.get(Projects.id == obj['project']))
        self._set_only_if('analytical_tool', obj, 'analytical_tool',
                          lambda: AnalyticalTools.get(
                              AnalyticalTools.id == obj['analytical_tool']))

    @classmethod
    def where_clause(cls, kwargs):
        """Where clause for the various elements."""
        where_clause = super(AToolProject, cls).where_clause(kwargs)
        attrs = ['project', 'analytical_tool']
        return cls._where_attr_clause(where_clause, kwargs, attrs)


import random
import time

import numpy as np
import torch
import torchvision
from torchvision import transforms

import matplotlib.pyplot as plt
import random
from model import Model

SAVE_MODEL_PATH = "checkpoint/best_accuracy.pth"

def train(opt):
    device = torch.device("cuda:0" if opt.use_gpu and torch.cuda.is_available() else "cpu")
    print("device:", device)

    model = Model().to(device)
    criterion = torch.nn.CrossEntropyLoss().to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=opt.lr)

    # data preparation
    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
    trainset = torchvision.datasets.MNIST(root="./data", train=True, transform=transform, download=True)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=opt.batch_size)
    testset = torchvision.datasets.MNIST(root="./data", train=False, transform=transform, download=True)
    testloader = torch.utils.data.DataLoader(testset, batch_size=opt.batch_size)

    # training epoch loop
    best_eval_acc = 0
    start = time.time()
    for ep in range(opt.num_epoch):
        avg_loss = 0
        model.train()
        print(f"{ep + 1}/{opt.num_epoch} epoch start")

        # training mini batch
        for i, (imgs, labels) in enumerate(trainloader):
            imgs, labels = imgs.to(device), labels.to(device)

            preds = model(imgs)
            loss = criterion(preds, labels)

            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            avg_loss += loss.item() #ortalama kayıp hesaplama

            if i > 0 and i % 100 == 0:
                print(f"loss:{avg_loss / 100:.4f}") # 100 adımda bir kaybı yazdırma
                avg_loss = 0

        # doğrulama
        if ep % opt.valid_interval == 0: #doğrulama ne zaman yapılacak
            tp, cnt = 0, 0
            model.eval()
            for i, (imgs, labels) in enumerate(testloader):
                imgs, labels = imgs.to(device), labels.to(device)
                with torch.no_grad(): #eğitim verileri korunuyor
                    preds = model(imgs)
                preds = torch.argmax(preds, dim=1)
                tp += (preds == labels).sum().item()
                cnt += labels.shape[0]
            acc = tp / cnt
            print(f"eval acc:{acc:.4f}")

            # modelin kaydedilmesi
            if acc > best_eval_acc:
                best_eval_acc = acc
                torch.save(model.state_dict(), SAVE_MODEL_PATH)

        print(f"{ep + 1}/{opt.num_epoch} epoch finished. elapsed time:{time.time() - start:.1f} sec")

    print(f"training finished. best eval acc:{best_eval_acc:.4f}")

random_seed = random.randint(1, 1000)

if __name__ == "__main__":

    # Argümanların belirlenmesi
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--manual_seed", type=int, default=1111, help="random seed setting")
    parser.add_argument("--batch_size", type=int, default=64, help="batch size")
    parser.add_argument("--num_epoch", type=int, default=10, help="number of epochs to train")
    parser.add_argument("--valid_interval", type=int, default=1, help="validation interval")
    parser.add_argument("--lr", type=float, default=1e-4, help="learning rate")
    parser.add_argument("--use_gpu", action="store_true", help="use gpu if available")
    opt = parser.parse_args()
    print("args", opt)

    opt.manual_seed = random_seed
    # set seed
    random.seed(opt.manual_seed)
    np.random.seed(opt.manual_seed)
    torch.manual_seed(opt.manual_seed)
    torch.cuda.manual_seed(opt.manual_seed)

    # training
    train(opt)

####################################python your_script.py --num_epoch 50
##########

    # Örnek tahminler

    device = torch.device("cuda:0" if opt.use_gpu and torch.cuda.is_available() else "cpu")

    model = Model().to(device)
    model.load_state_dict(torch.load(SAVE_MODEL_PATH))
    model.eval()

    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
    # testset = torchvision.datasets.MNIST(root="./data", train=False, transform=transform, download=True)
    # testloader = torch.utils.data.DataLoader(testset, batch_size=1)

    # Test veri setini karıştırma
    testset = torchvision.datasets.MNIST(root="./data", train=False, transform=transform, download=True)
    indices = list(range(len(testset)))
    random.shuffle(indices)

# Karıştırılmış veri setini kullanarak DataLoader oluşturma
    batch_size = 1
    testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, sampler=torch.utils.data.SubsetRandomSampler(indices))

    with torch.no_grad():
        for images, labels in testloader:
            images = images.to(device)
            labels = labels.to(device)

            outputs = model(images)
            predicted = torch.argmax(outputs.data, dim=1)

            pred = predicted[0].item()
            label = labels[0].item()
            print("Predicted:", pred)
            print("Actual:", label)
            break

        image = images[0].cpu().numpy()
        image = image * 0.5 + 0.5
        plt.imshow(np.squeeze(image), cmap='gray')
        plt.show()


# Modulos do MicroPython
from machine import Pin, I2C

from time import sleep
from json import dumps, loads

# Modulos de Ligação á Internet
from wlan_manager import WLAN_Manager
from mqtt_manager import MQTT_Manager

# Modulos de Ligação ao Hardware
from board_manager import *
from sensor_manager import Sensor_BME280
from sensor_manager import Sensor_BH1750

# Ligação à Internet
wlan_client = WLAN_Manager() # Cliente para ligar ao Wireless
#wlan_client.setup("ATLANTICO", "oceno12")
mqtt_client = MQTT_Manager() # Cliente para ligar ao Servidor de Mensagens

# Ligação ao Hardware
i2c = I2C(scl=Pin(D1), sda=Pin(D2)) # Protocolo de Comunicação I2C
sensor1 = Sensor_BME280(i2c, 118)   # Ligação ao sensor 1
sensor2 = Sensor_BH1750(i2c, 35)    # Ligação ao sensor 2

# Função para tratar das quedas de ligação à Internet
def reconnect():
  print("WiFi Connection")
  wlan_client.start()
  for i in range(30):
    if wlan_client.check(): break
    print(".", end="")
    sleep(1)
  sleep(5)
  success = wlan_client.check() and mqtt_client.check()
  if success:
    mqtt_client.broker.subscribe(TOPIC_SUB)
  return success

# Função para tratar as mensagens recebidas
def mqtt_callback(topic, msg):
  print('MSG! Topic:{}; Data{}'.format(topic, msg))

# Topicos para enviar e receber mensagens
PREFIX = "Atlantico"
TOPIC_SUB = "/".join( [PREFIX, mqtt_client.get_topic("control"), "#"] )
TOPIC_PUB = "/".join( [PREFIX, mqtt_client.get_topic("status") ] )
mqtt_client.broker.set_callback(mqtt_callback)

DELAY = 5 * 1000 # DELAY in milliseconds

sucess = reconnect()
while True:
  sucess = mqtt_client.check_msg()
  if not sucess:
    sucess = mqtt_client.check()
    if not sucess:
      sucess = reconnect()

  sensor1.read()
  sensor2.read()
  t = sensor1.values_dict["t"]
  p = sensor1.values_dict["p"]
  l = sensor2.values_dict["lux"]

  values = {"t": t, "p": p, "l": l}
  data = dumps( values )
  print(msg)
  mqtt_client.send(TOPIC_PUB, data)
  sleep( DELAY )


# -*- coding: utf-8 -*-
"""
Created on Sat Sep 15 14:10:36 2018
@title：读Excel数据
@author: ff7f
"""
import xlrd
test = 1
if test:
    xlsfile = "test.xls"
else:
    xlsfile = "records.xls"
book = xlrd.open_workbook(xlsfile)
for sheet in book.sheets():
    print(f'>>> 工作表名：{sheet.name}')
sheet = book.sheet_by_index(0)
print(f'>>> 解析Excel工作表({sheet.name})数据...')
students = []
for i in range(sheet.nrows):
    row = sheet.row_values(i)[1:]
    if i==1:
        classtime = row[2]
    elif i==2:
        classplace = row[2]
    elif i==3:
        cno, cnum = row[2].split('-')
        cname, tname = row[10], row[23]

    elif i in [4,5]:
        continue
    elif i >= 6:
        row[0], row[1] = int(row[0]), int(row[1])
        students.append((row[1],row[2],row[3]))
    print(i, end=' ')
    for n,cell in enumerate(row):
        if cell:
            print(cell, end=' ')
    print('')

# 解析基本数据data=(上课时间,上课地点,课号,课序号,课程名,上课教师,上课班级)
sclass = row[3]
data = (classtime, classplace, cno, cnum, cname, tname, sclass)

import sqlite3
import os
def parse_excel():
    # 创建数据库，解析Excel电子表格数据
    dbname = 'student.db'
    if os.path.exists(dbname):
        os.remove(dbname)
    # 创建教师表t
    create_table_teacher = """
        create table if not exists t(
            tno     char(10) primary key,
            tname   char(10),
            title   char(10))"""

    # 创建学生表s
    create_table_student = """
        create table if not exists s(
            sno     char(10) primary key,
            sname   char(10),
            age     smallint,
            sex     char(2),
            sclass  char(10))"""

    # 创建课程表c
    create_table_course = """
        create table if not exists c(
            cno        char(10) primary key,
            cname      char(20),
            class_hour smallint
            )"""

    # 创建授课表sh(schedules)
    create_table_schedules = """
        create table if not exists sh(
            tno        char(10),
            tname      char(10),
            cno        char(10),
            cnum       char(5),
            classtime  text,
            classplace text,
            sclass     char(10)
            )"""

    # 创建选课表sc
    create_table_sc = """
        create table if not exists sc(
            sno   char(10),
            cno   char(10),
            score smallint)"""

    # 创建记录表rec(records)
    create_table_records = """
        create table if not exists rec(
            sno    char(10) primary key,
            cno    char(10),
            cnum   char(5),
            cdate  date,
            state  char(1)
            )"""

    # 查询创建的表
    select_tables = """select name from sqlite_master where type='table'"""

    # 插入数据
    insert_student = """insert into s(sno,sname,sclass) values(?,?,?)"""
    insert_schedules = """insert into sh(tname,cno,cnum,classtime,classplace,sclass) values(?,?,?,?,?,?)"""
    insert_teacher = """insert into t(tno,tname) values(?,?)"""
    insert_course = """insert into c(cno,cname) values(?,?)"""

    # 查询插入的数据
    select_course = """select * from c"""   # 查询课程
    select_teacher = """select * from t"""  # 查询教师
    select_student = """select * from s"""  # 查询学生

    # 创建数据库
    try:
        con = sqlite3.connect(dbname)
        cur = con.cursor()
        # 创建表
        cur.execute(create_table_teacher)
        cur.execute(create_table_student)
        cur.execute(create_table_course)
        cur.execute(create_table_schedules)
        cur.execute(create_table_sc)
        cur.execute(create_table_records)

        # 查询已创建的表
        cur.execute(select_tables)
        tables = []
        for table in cur.fetchall():
            tables.append(table[0])
        print(f'>>> 确认已经创建的表：{tables}')
        print('#教师表t, 学生表s, 课程表c, 授课表sh, 选课表sc, 教学记录表rec')

        # 插入数据
        print('>>> 插入解析数据..')
        cur.execute(insert_course,(cno, cname))    # 插入课程
        cur.execute(insert_teacher,('t1',tname))   # 插入教师
        for s in students:                         # 插入学生
            cur.execute(insert_student, s)

        # 查询课程
        print('>>> 查询数据..')
        cur.execute(select_course)
        courses = cur.fetchall()
        print(f'>>> 课程记录：{courses}')

        #查询教师
        cur.execute(select_teacher)
        teachers = cur.fetchall()
        print(f'>>> 教师记录：{teachers}')

        # 查询学生
        cur.execute(select_student)
        sel_students = cur.fetchall()
        print(f'>>> 学生记录\n{sel_students}')
    except Exception as e:
        print(e)
    finally:
        cur.close()
        con.commit()
        con.close()

# main
parse_excel()


from KTBC import KTBC
import numpy as np
import numpy.linalg as nla
import matplotlib.pyplot as plt

def fixedFixedPlot(differential_equation,force_vec,xi,xf,h,mesh_density,should_I_plot=True):

    # independent vector for differential equation
    u_ind_vec = np.linspace(xi,xf,mesh_density)

    # difference equation solution
    K = h**2*KTBC('K',h-1)                  # this line calls the KTBC function
    soln = nla.solve(K,force_vec)
    soln = np.insert(soln,0,0)
    soln = np.insert(np.zeros(1),0,soln)
    soln_ind_vec = np.linspace(xi,xf,h+1)

    # plots
    if (should_I_plot == True):
        plt.plot(u_ind_vec,u(u_ind_vec)) # plot differential equation
        plt.plot(soln_ind_vec,soln) # plot difference equation

    return soln_ind_vec, soln, u_ind_vec, u(u_ind_vec)


import unittest
from pygromos.simulations.hpc_queuing.submission_systems.submission_job import Submission_job

class test_queuing_system(unittest.TestCase):
    file_class = Submission_job

    def test_construct_min(self):
        sub_job = self.file_class(command='echo " WUHAHAHA"')
        assert isinstance(sub_job, self.file_class)

    def test_construct_full(self):
        sub_job = self.file_class(
            command='echo " WUHAHAHA"',
            jobName="test_job",
            start_job=1,
            end_job=10,
            jobLim=20,
            outLog="/dev/null/out.log",
            errLog="/dev/null/err.log",
            queue_after_jobID=1,
            post_execution_command='echo " WUHAHAHA2"',
            submit_from_dir=".",
            sumbit_from_file=True,
        )
        assert isinstance(sub_job, self.file_class)

    def test_acces(self):
        sub_job = self.file_class(command='echo " WUHAHAHA"', queue_after_jobID=1)
        id = sub_job.queue_after_jobID
        assert isinstance(id, int)
        assert id == 1
        assert sub_job.command == 'echo " WUHAHAHA"'


import requests

class Gists():

  def __init__(self, usuario):
    self._usuario = usuario

  def requisicao_api(self):
    resposta = requests.get(
      f'https://api.github.com/users/{self._usuario}/gists')
    if resposta.status_code == 200:
      return resposta.json()
    else:
      return resposta.status_code

  def get_gists(self):  # faltando forks
    lista = []
    dados_api = self.requisicao_api()
    if type(dados_api) is not int:
      for i in range(len(dados_api)):
        texto = dados_api[i]['description'].split('-')
        tag = texto[0].strip()
        description = texto[1].strip()
        autor = dados_api[i]['owner']['login']
        url = dados_api[i]['html_url']
        lista.append([tag, description, autor, url])
      return lista
    else:
      return dados_api

  """
  Recebe: uma lista com títulos de gists
  Retorna: lista de tags extraídas dos títulos do gists """

  def get_tags(self, lista):
    tags = []
    for i in lista:
      tags.append(i[0])
    return tags

gists = Gists('eder-projetos-dev')

gists_list = gists.get_gists()

tags = gists.get_tags(gists_list)
""" Obtendo a quantidade e o nome das tags
Recebe: lista de tags
Retorna: dicionário com a contagem e o nome das tags """

def count_tags(tags):
  tags_set = set(tags)  # obtendo tags únicas
  tags_dic = {}  # key=contagem e value=tag
  for tag in tags_set:
    tags_dic.update({tag: tags.count(tag)})
  return tags_dic

tags_dic = count_tags(tags)
""" Menu com as tags em ordem de contagem
Recebe: tags_dic
Retorna: menu_tags """

def menu_tags(tags_dic):
  menu_tags = []  # menu apresenta tags em ordem de contagem
  for k, v in sorted(tags_dic.items(), reverse=True):
    menu_tags.append(k)
  return menu_tags

""" Filtrar gists
Recebe: Lista de gists e aplica filtro por tag
Retorna: Lista com os gists encontrados """

def filtro_tag(gists_list, tag):
  resultado = []
  for gist in gists_list:
    if gist[0] == tag:
      resultado.append(gist)
  return resultado


import numpy as np

from ...control_system.parameter_dae import LinearParameterControlSystem
from ...multilevel_object import local_object_factory
from ...variables import NullVariables
from . import AutomaticLocalConstraint
from . import Constraint
from .lqr import LQRConstraint

class ParameterLQRConstraint(Constraint):
    """Constraint implementation for linear quadratic optimal control problems
    depending on multiple levels of variables."""
    def __init__(self, higher_level_variables, local_level_variables,
                 parameter_dae_control: LinearParameterControlSystem,
                 initial_value: np.ndarray):
        lower_level_variables = NullVariables()
        super().__init__(lower_level_variables, higher_level_variables,
                         local_level_variables)
        if not isinstance(parameter_dae_control, LinearParameterControlSystem):
            raise TypeError(parameter_dae_control)
        self._parameter_dae = parameter_dae_control

        self._dae = parameter_dae_control
        self._initial_value = initial_value

    @property
    def control_system(self) -> LinearParameterControlSystem:
        return self._dae

    @property
    def initial_value(self) -> np.ndarray:
        return self._initial_value

class AutomaticLocalLQRConstraint(AutomaticLocalConstraint, LQRConstraint):
    def __init__(self, global_object: ParameterLQRConstraint, *args, **kwargs):
        self._global_object = global_object
        local_control_dae = global_object.control_system.get_localized_object()
        local_initial_value = global_object.localize_method(
            global_object.initial_value)
        LQRConstraint.__init__(self, local_control_dae, local_initial_value)

local_object_factory.register_localizer(ParameterLQRConstraint,
                                        AutomaticLocalLQRConstraint)