from nn.network import *
from nn.part1 import *
from nn.part2 import *

class LayOutPlan(Scene):
    def construct(self):
        title = TextMobject("Plan")
        title.scale(1.5)
        title.to_edge(UP)
        h_line = Line(LEFT, RIGHT).scale(SPACE_WIDTH - 1)
        h_line.next_to(title, DOWN)

        items = BulletedList(
            "Recap",
            "Intuitive walkthrough",
            "Derivatives in \\\\ computational graphs",
        )
        items.to_edge(LEFT, buff = LARGE_BUFF)
        self.add(items)

        rect = ScreenRectangle()
        rect.scale_to_fit_width(2*SPACE_WIDTH - items.get_width() - 2)
        rect.next_to(items, RIGHT, MED_LARGE_BUFF)

        self.play(
            Write(title),
            ShowCreation(h_line),
            ShowCreation(rect),
            run_time = 2
        )
        for i in range(len(items)):
            self.play(items.fade_all_but, i)
            self.dither(2)

class TODOInsertFeedForwardAnimations(TODOStub):
    CONFIG = {
        "message" : "Insert Feed Forward Animations"
    }

class TODOInsertStepsDownCostSurface(TODOStub):
    CONFIG = {
        "message" : "Insert Steps Down Cost Surface"
    }

class TODOInsertDefinitionOfCostFunction(TODOStub):
    CONFIG = {
        "message" : "Insert Definition of cost function"
    }

class TODOInsertGradientNudging(TODOStub):
    CONFIG = {
        "message" : "Insert GradientNudging"
    }

class InterpretGradientComponents(GradientNudging):
    CONFIG = {
        "network_mob_config" : {
            "layer_to_layer_buff" : 3,
        },
        "stroke_width_exp" : 2,
        "n_decimals" : 6,
        "n_steps" : 3,
        "start_cost" : 3.48,
        "delta_cost" : -0.21,
    }
    def construct(self):
        self.setup_network()
        self.add_cost()
        self.add_gradient()
        self.change_weights_repeatedly()
        self.ask_about_high_dimensions()
        self.circle_magnitudes()
        self.isolate_particular_weights()
        self.shift_cost_expression()
        self.tweak_individual_weights()

    def setup_network(self):
        self.network_mob.scale(0.55)
        self.network_mob.to_corner(UP+RIGHT)
        self.color_network_edges()

    def add_cost(self):
        rect = SurroundingRectangle(self.network_mob)
        rect.highlight(RED)
        arrow = Vector(DOWN, color = RED)
        arrow.shift(rect.get_bottom())
        cost = DecimalNumber(self.start_cost)
        cost.highlight(RED)
        cost.next_to(arrow, DOWN)

        cost_expression = TexMobject(
            "C(", "w_0, w_1, \\dots, w_{13{,}001}", ")", "="
        )
        for tex in "()":
            cost_expression.highlight_by_tex(tex, RED)
        cost_expression.next_to(cost, DOWN)
        cost_group = VGroup(cost_expression, cost)
        cost_group.arrange_submobjects(RIGHT)
        cost_group.next_to(arrow, DOWN)

        self.add(rect, arrow, cost_group)

        self.set_variables_as_attrs(
            cost, cost_expression, cost_group,
            network_rect = rect
        )

    def change_weights_repeatedly(self):
        decimals = self.grad_vect.decimals
        grad_terms = self.grad_vect.contents
        edges = VGroup(*reversed(list(
            it.chain(*self.network_mob.edge_groups)
        )))
        cost = self.cost

        for x in range(self.n_steps):
            self.move_grad_terms_into_position(grad_terms.copy())
            self.play(*self.get_weight_adjustment_anims(edges, cost))
            self.play(*self.get_decimal_change_anims(decimals))

    def ask_about_high_dimensions(self):
        grad_vect = self.grad_vect

        words = TextMobject(
            "Direction in \\\\ ${13{,}002}$ dimensions?!?")
        words.highlight(YELLOW)
        words.move_to(grad_vect).to_edge(DOWN)
        arrow = Arrow(
            words.get_top(),
            grad_vect.get_bottom(),
            buff = SMALL_BUFF
        )

        randy = Randolph()
        randy.scale(0.6)
        randy.next_to(words, LEFT)
        randy.shift_onto_screen()

        self.play(
            Write(words, run_time = 2),
            GrowArrow(arrow),
        )
        self.play(FadeIn(randy))
        self.play(randy.change, "confused", words)
        self.play(Blink(randy))
        self.dither()
        self.play(*map(FadeOut, [randy, words, arrow]))

    def circle_magnitudes(self):
        rects = VGroup()
        for decimal in self.grad_vect.decimals:
            rects.add(SurroundingRectangle(VGroup(*decimal[-4:])))
        rects.highlight(WHITE)

        self.play(LaggedStart(ShowCreation, rects))
        self.play(FadeOut(rects))

    def isolate_particular_weights(self):
        vect_contents = self.grad_vect.contents
        w_terms = self.cost_expression[1]

        edges = self.network_mob.edge_groups
        edge1 = self.network_mob.layers[1].neurons[3].edges_in[0].copy()
        edge2 = self.network_mob.layers[1].neurons[9].edges_in[15].copy()
        VGroup(edge1, edge2).set_stroke(width = 4)
        d1 = DecimalNumber(3.2)
        d2 = DecimalNumber(0.1)
        VGroup(edge1, d1).highlight(YELLOW)
        VGroup(edge2, d2).highlight(MAROON_B)
        new_vect_contents = VGroup(
            TexMobject("\\vdots"),
            d1, TexMobject("\\vdots"),
            d2, TexMobject("\\vdots"),
        )
        new_vect_contents.arrange_submobjects(DOWN)
        new_vect_contents.move_to(vect_contents)

        new_w_terms = TexMobject(
            "\\dots", "w_n", "\\dots", "w_k", "\\dots"
        )
        new_w_terms.move_to(w_terms, DOWN)
        new_w_terms[1].highlight(d1.get_color())
        new_w_terms[3].highlight(d2.get_color())

        for d, edge in (d1, edge1), (d2, edge2):
            d.arrow = Arrow(
                d.get_right(), edge.get_center(),
                color = d.get_color()
            )

        self.play(
            FadeOut(vect_contents),
            FadeIn(new_vect_contents),
            FadeOut(w_terms),
            FadeIn(new_w_terms),
            edges.set_stroke, LIGHT_GREY, 0.35,
        )
        self.play(GrowArrow(d1.arrow))
        self.play(ShowCreation(edge1))
        self.dither()
        self.play(GrowArrow(d2.arrow))
        self.play(ShowCreation(edge2))
        self.dither(2)

        self.cost_expression.remove(w_terms)
        self.cost_expression.add(new_w_terms)
        self.set_variables_as_attrs(
            edge1, edge2, new_w_terms,
            new_decimals = VGroup(d1, d2)
        )

    def shift_cost_expression(self):
        self.play(self.cost_group.shift, DOWN+0.5*LEFT)

    def tweak_individual_weights(self):
        cost = self.cost
        cost_num = cost.number
        edges = VGroup(self.edge1, self.edge2)
        decimals = self.new_decimals
        changes = (1.0, 1./32)
        wn = self.new_w_terms[1]
        wk = self.new_w_terms[3]

        number_line_template = NumberLine(
            x_min = -1,
            x_max = 1,
            tick_frequency = 0.25,
            numbers_with_elongated_ticks = [],
            color = WHITE
        )
        for term in wn, wk, cost:
            term.number_line = number_line_template.copy()
            term.brace = Brace(term.number_line, DOWN, buff = SMALL_BUFF)
            group = VGroup(term.number_line, term.brace)
            group.next_to(term, UP)
            term.dot = Dot()
            term.dot.highlight(term.get_color())
            term.dot.move_to(term.number_line.get_center())
            term.dot.save_state()
            term.dot.move_to(term)
            term.dot.set_fill(opacity = 0)

        groups = [
            VGroup(d, d.arrow, edge, w)
            for d, edge, w in zip(decimals, edges, [wn, wk])
        ]
        for group in groups:
            group.save_state()

        for i in range(2):
            group1, group2 = groups[i], groups[1-i]
            change = changes[i]
            edge = edges[i]
            w = group1[-1]
            added_anims = []
            if i == 0:
                added_anims = [
                    GrowFromCenter(cost.brace),
                    ShowCreation(cost.number_line),
                    cost.dot.restore
                ]
            self.play(
                group1.restore,
                group2.fade, 0.7,
                GrowFromCenter(w.brace),
                ShowCreation(w.number_line),
                w.dot.restore,
                *added_anims
            )
            for x in range(2):
                func = lambda a : interpolate(
                    cost_num, cost_num-change, a
                )
                self.play(
                    ChangingDecimal(cost, func),
                    cost.dot.shift, change*RIGHT,
                    w.dot.shift, 0.25*RIGHT,
                    edge.set_stroke, None, 8,
                    rate_func = lambda t : wiggle(t, 4),
                    run_time = 2,
                )
                self.dither()
            self.play(*map(FadeOut, [w.dot, w.brace, w.number_line]))

    ######

    def move_grad_terms_into_position(self, grad_terms):
        cost_expression = self.cost_expression
        w_terms = self.cost_expression[1]
        points = VGroup(*[
            VectorizedPoint()
            for term in grad_terms
        ])
        points.arrange_submobjects(RIGHT)
        points.replace(w_terms, dim_to_match = 0)

        grad_terms.generate_target()
        grad_terms.target[len(grad_terms)/2].rotate(np.pi/2)
        grad_terms.target.arrange_submobjects(RIGHT)
        grad_terms.target.scale_to_fit_width(cost_expression.get_width())
        grad_terms.target.next_to(cost_expression, DOWN)

        words = TextMobject("Nudge weights")
        words.scale(0.8)
        words.next_to(grad_terms.target, DOWN)

        self.play(
            MoveToTarget(grad_terms),
            FadeIn(words)
        )
        self.play(
            Transform(
                grad_terms, points,
                remover = True,
                submobject_mode = "lagged_start",
                run_time = 1
            ),
            FadeOut(words)
        )

    def get_weight_adjustment_anims(self, edges, cost):
        start_cost = cost.number
        target_cost = start_cost + self.delta_cost
        w_terms = self.cost_expression[1]

        return [
            self.get_edge_change_anim(edges),
            LaggedStart(
                Indicate, w_terms,
                rate_func = there_and_back,
                run_time = 1.5,
            ),
            ChangingDecimal(
                cost,
                lambda a : interpolate(start_cost, target_cost, a),
                run_time = 1.5
            )
        ]


from django.views.generic import TemplateView, FormView, RedirectView
from django.db.models import Q
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib.auth import get_user_model
from django.contrib.auth import get_user_model

from cbvmixins.mixins import LoginRequiredMixin

from confirmemail.forms import ConfirmForm
from confirmemail.models import Confirm

class ConfirmView(LoginRequiredMixin, FormView):
    """Confirmation's form of email."""
    template_name = 'confirmemail/index.jinja'
    form_class = ConfirmForm
    success_url = reverse_lazy('confirmemail:status',
        kwargs={'status': 'confirm'})

    def dispatch(self, request, *args, **kwargs):
        """..."""
        # Confirmed.
        Client = get_user_model()
        key = kwargs.get('key', None)

        if (key):
            try:
                #..
                confirm = Confirm.objects.get(Q(key=key))
                user_id = confirm.user.id
                user_email = confirm.email
                confirm.delete()

                Client = get_user_model()
                client = Client.objects.get(id=user_id)
                client.email = user_email
                client.save()

                return HttpResponseRedirect(reverse('confirmemail:status',
                    kwargs={'status': 'success'}))
            except Confirm.DoesNotExist:
                return HttpResponseRedirect(reverse('confirmemail:status',
                    kwargs={'status': 'badkey'}))
            except Confirm.MultipleObjectsReturned:
                Confirm.objects.filter(Q(key=key)).delete()
                return HttpResponseRedirect(reverse('confirmemail:status',
                    kwargs={'status': 'repeat'}))

        return super(ConfirmView, self).dispatch(request, *args, **kwargs)

    def get_form_kwargs(self):
        """Initial form."""
        kwargs = super(ConfirmView, self).get_form_kwargs()
        kwargs['request'] = self.request

        return kwargs

    def form_valid(self, form):
        """..."""
        response = super(ConfirmView, self).form_valid(form)
        form.save()
        return response

class StatusView(LoginRequiredMixin, TemplateView):
    """..."""
    template_name = 'confirmemail/status.jinja'
    available_status_list = (
        'confirm', # Confirm email message.
        'badkey',  # Incorrect activation key.
        'success', # Activation was successful.
        'repeat',  # Retry email confirm.
    )

    def get_context_data(self, **kwargs):
        """Show page with the status or 404."""
        status = kwargs.get('status', None)
        if not status or status not in self.available_status_list:
            raise Http404()

        # Display status page.
        context = super(StatusView, self).get_context_data(**kwargs)
        context['status'] = status
        return context


import os
import tkinter
from tkinter import *
from PyPDF2 import PdfFileReader #PDF
import comtypes.client #DOCX
import win32api # install pypiwin32, PyMuPDF, python-pptx, python-docx
from docx import Document
from docx.enum.text import WD_COLOR_INDEX
from pptx import Presentation
import xlsxwriter #EXCEL
from xlsxwriter.utility import xl_rowcol_to_cell
import xlrd
import fitz # PDF

def init(window):
    window.title("Best File Search")
    window.geometry("700x640")
    window.resizable(False, False)

    # Configure Widgets
    frame.place(x=300, y=78)  # set for fileList(Listbox) scrollbar
    frame2.place(x=300, y=412)
    scrollbar.configure(command=fileList.yview)
    fileList.configure(yscrollcommand=scrollbar.set)
    scrollbar2.configure(command=fileList.yview)
    openedFileList.configure(yscrollcommand=scrollbar.set)
    backgroundlabel.configure(image=backgroundimage)
    bClear.configure(command=buttonClear)
    bOpen.configure(command=buttonOpen)
    btnSearch.configure(command=executeSearchButton)
    bClearTwo.configure(command=buttonClearTwo)
    # Place Widgets
    # labelsearchtext.place(x=40, y=80)
    # labledesiredpath.place(x=40, y=230)
    desiredpath.place(x=130, y=250)
    searchText.place(x=41, y=125)
    # searchedFileName.place(x=300, y=30)
    # openedFileName.place(x=300, y=380)
    btnSearch.place(x=170, y=110, width=50, height=50)
    bClear.place(x=620, y=385, width=50, height=20)
    bClearTwo.place(x=565,y=50, width=50, height=20)
    bOpen.place(x=620, y=50, width=50, height=20)

def buttonClear():
    openedFileList.delete(0, END)

def buttonClearTwo():
    fileList.delete(0, END)

def buttonOpen():
    value = fileList.get(fileList.curselection()[0])
    #os.startfile(value)

    searchInput = searchText.get()

    ext = os.path.splitext(value)[-1]
    pathExceptExt = os.path.splitext(value)[0]

    if ext == ".pptx":
        powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
        powerpoint.Visible = 1

        Filename = value
        deck = powerpoint.Presentations.Open(Filename)
        deck.SaveAs(pathExceptExt + ".pdf", 32)  # formatType = 32 for ppt to pdf

        value2 = pathExceptExt + ".pdf"
        doc = fitz.open(value2)
        pdf = PdfFileReader(value2)
        saveNumPages = pdf.getNumPages()

        for i in range(saveNumPages):
            page = doc[i]
            text_instances = page.searchFor(searchInput)

            for inst in text_instances:
                highlight = page.addHighlightAnnot(inst)
        doc.save(pathExceptExt + "_modified.pdf", garbage=4, deflate=True, clean=True)
        os.startfile(pathExceptExt + "_modified.pdf")

    elif ext == ".txt":
        with open(value, mode='r', encoding='utf-8') as fo:
            textthis = fo.read()

        with open(pathExceptExt + ".html", "w") as e:
            if searchInput in textthis:
                e.write("
" + textthis.replace(searchInput, '{}'.format(
                    searchInput)) + "

\n")
        os.startfile(pathExceptExt + ".html")
    elif ext == ".xlsx":

        wbk = xlsxwriter.Workbook(value)
        wks = wbk.add_worksheet()
        myPath = value

        cell_format = wbk.add_format()
        cell_format.set_bg_color('yellow')
        for sh in xlrd.open_workbook(myPath).sheets():
            for row in range(sh.nrows):
                for col in range(sh.ncols):
                    mycell = sh.cell(row, col)
                    if mycell.value == searchInput:
                        wks.write(xl_rowcol_to_cell(row, col), searchInput, cell_format)
                    else:
                        wks.write(xl_rowcol_to_cell(row, col), mycell.value)
        wbk.close()
        os.startfile(value)
    elif ext == ".docx":
        document = Document(value)

        for para in document.paragraphs:
            start = para.text.find(searchInput)
            if start > -1:
                pre = para.text[:start]
                post = para.text[start + len(searchInput):]
                para.text = pre
                para.add_run(searchInput)
                para.runs[1].font.highlight_color = WD_COLOR_INDEX.YELLOW
                para.add_run(post)
        document.save(pathExceptExt + "_modified.docx")
        os.startfile(pathExceptExt + "_modified.docx")

    elif ext == ".pdf":

        doc = fitz.open(value)
        for i in range(10):
            try:
                    page = doc[i]

                    text_instances = page.searchFor(searchInput)

                    for inst in text_instances:
                        highlight = page.addHighlightAnnot(inst)

            except IndexError:
                break
        doc.save(pathExceptExt + "_mod.pdf", garbage=4, deflate=True, clean=True)
        os.startfile(pathExceptExt + "_mod.pdf")

    openedFileList.insert(END, value)

# Determine whether there are specific strings in some files such as .txt, .docx, .pptx files
# then insert their path and name to the list
def searchDir(root_folder, searchInput):

    #exceptFolderList = [ "AppData", "WINDOWS", "Windows", "Program Files (x86)", "Program Files"]

    try:
        filenames = os.listdir(root_folder)

        for filename in filenames:
            full_filename = os.path.join(root_folder, filename)

            if os.path.isdir(full_filename):
                if filename == "AppData" or filename == "WINDOWS" or filename == "Windows" or filename == "Program Files (x86)" or filename == "Program Files":
                    pass
                else:
                    searchDir(full_filename, searchInput)

            else:
                ext = os.path.splitext(full_filename)[-1]
                #Search TXT files
                if ext == ".pdf":
                    try:
                        doc = fitz.open(full_filename)
                        page = doc[0]
                        text_instances = page.searchFor(searchInput)
                        if text_instances:
                            print(full_filename)
                            fileList.insert(END, full_filename)
                            break
                    except:
                        pass

                elif ext == ".txt":
                    try:
                        fo = open(full_filename, 'r', encoding='utf-8', errors='ignore')

                        if searchInput in fo.read():
                            print(full_filename)
                            fileList.insert(END, full_filename)
                            break
                    except:
                        pass

                elif ext == ".docx":
                    try:
                        print(full_filename)
                        document = Document(full_filename)

                        for para in document.paragraphs:
                            if searchInput in para.text:
                                fileList.insert(END, full_filename)
                                break
                    except:
                        pass
                elif ext == ".xlsx":
                    try:
                        print(full_filename)
                        wbk = xlsxwriter.Workbook(full_filename)
                        wks = wbk.add_worksheet()

                        myPath = full_filename
                        for sh in xlrd.open_workbook(myPath).sheets():
                            for row in range(sh.nrows):
                                for col in range(sh.ncols):
                                    myCell = sh.cell(row, col)
                                    if myCell.value == searchInput:
                                        fileList.insert(END, full_filename)
                                        break
                                break
                    except:
                        pass
                elif ext == ".pptx":
                    try:
                        print(full_filename)
                        prs = Presentation(full_filename)
                        for slide in prs.slides:
                            for shape in slide.shapes:
                                if hasattr(shape, "text"):
                                    if searchInput in shape.text:
                                        fileList.insert(END, full_filename)
                                    break
                            break
                    except:
                        pass

    except PermissionError:
        pass

# Search User's HDD. Send the information of HDD and filetypes.
def searchInfo():
    searchInput = searchText.get()
    HDD_List = []

    for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
        # insert the name of HDDs to the ListBox to display them for User to see.
        onlyHDDname = drive.split(":")
        desiredpath.delete(0, END)
        HDD_List.append(onlyHDDname[0])

        for i in HDD_List[0:]:
            desiredpath.insert(END, i + " ")

        # Specify the file_type.
        print("Finding files")
        searchDir(drive, searchInput)

# Execute Search Button
def executeSearchButton():
    searchInfo()

window = Tk()
C = Canvas(window, bg="blue", height=250)
backgroundimage = PhotoImage(file="image.png")
backgroundlabel = Label(window)
backgroundlabel.pack()

frame = Frame(window)
frame2 = Frame(window)

bOpen = tkinter.Button(window, text="open")
bClear = tkinter.Button(window, text="Clear")
bClearTwo = tkinter.Button(window, text="Clear")
btnSearch = tkinter.Button(window, text="search")
labelsearchtext = tkinter.Label(window, text="Enter text")
labledesiredpath = tkinter.Label(window, text="Searched HDD")
openedFileName = tkinter.Label(window, text="Opened Files")
searchedFileName = tkinter.Label(window, text="Searched Files")

fileList = Listbox(frame, width=50, height=17)
fileList.pack(side='left', fill='y')
scrollbar = Scrollbar(frame, orient=VERTICAL)
scrollbar.pack(side="right", fill="y")
scrollbar2 = Scrollbar(frame2, orient=VERTICAL)
scrollbar2.pack(side="right", fill="y")

openedFileList = Listbox(frame2, width=50)
openedFileList.pack(side='left', fill='y')
fileList.pack(side='left', fill='y')
desiredpath = tkinter.Listbox(window, width=10, height=5)
searchText = tkinter.Entry(window, width=16)

#fileList.bind('<<ListboxSelect>>', openFile)
#fileList.bind('<Double-Button>', buttonOpen)
openedFileList.bind('<Double-Button>', buttonOpen)
# initialise and run main loop
init(window)
mainloop()

Best-File-Search-master/Best File Search/Best File Search.py


l1=eval(input())
l2=eval(input())
l1=list(reversed(l1))
l2=list(reversed(l2))
length=max(len(l1),len(l2))
result=0
for i in range(length):
    temp=int(pow(-2,i))
    if i<len(l1):
        result=result+l1[i]*temp
    if i<len(l2):
        result+=l2[i]*temp
print(result)


from __future__ import absolute_import, division, print_function

import tensorflow as tf
from tensorflow.keras import Model, layers
import numpy as np
import matplotlib.pyplot as plt
from timer import timer
from load_basic import DATA_FOLDER, EXPER_FOLDER, DATA_SIZE, NET_NAME
from read_data import ideal_data_generator, exper_data_generator, DATA_FEATURES, EXPER_FEATURES

learning_rate  = 1e-3
batch_size     = 1
epoch          = 1
training_steps = DATA_SIZE*epoch
display_step   = 1
print(training_steps)

num_features =  DATA_FEATURES # number of wave length separate.
print("data features: ", num_features)

#  num_hidden_1 = 512 # 1st layer num features.
#  num_hidden_2 = 128 # 2nd layer num features (the latent dim).
#  num_hidden_3 = 32
#  num_hidden_4 = 1

train_size = int(0.8*DATA_SIZE)
#  test_size = int(0.3*DATA_SIZE)

dataset = tf.data.Dataset.from_generator(
    ideal_data_generator,
    (tf.float32, tf.float32, tf.float32),
    (tf.TensorShape(None), tf.TensorShape(None), tf.TensorShape(None))
)

train_set = dataset.take(train_size)
test_set  = dataset.skip(train_size)

train_set = train_set.shuffle(train_size).repeat(epoch).batch(batch_size).prefetch(epoch)

class ConvNet(Model):
    # Set layers.
    def __init__(self):
        super().__init__()
        # Convolution Layer with 32 filters and a kernel size of 5.
        self.flatten = layers.Flatten()

        # Fully connected layer.
        self.fc2 = layers.Dense(2048)
        #  self.fc1 = layers.Dense(1313)
        self.fc0 = layers.Dense(512)
        # Apply Dropout (if is_training is False, dropout is not applied).
        self.dropout = layers.Dropout(rate=0.5)

        # Output layer, class prediction.
        self.out = layers.Dense(1)

    # Set forward pass.
    def call(self, x, is_training=False):
        x = tf.reshape(x, [-1, DATA_FEATURES, 1])
        #  x = self.conv1(x)
        #  x = self.conv2(x)
        #  x = self.conv3(x)
        #  x = self.conv4(x)
        #  x = self.conv5(x)
        #  x = self.conv6(x)
        #  x = self.conv7(x)
        #  x = self.conv8(x)
        #  x = self.conv9(x)
        #  x = self.conv10(x)
        #  x = self.conv11(x)
        #  x = self.conv12(x)
        #  x = self.conv13(x)
        #  x = self.conv14(x)
        #  x = self.conv15(x)
        x = self.flatten(x)
        x = self.fc2(x)
        #  x = self.fc1(x)
        x = self.fc0(x)
        x = self.dropout(x, training=is_training)
        x = self.out(x)
        #  if not is_training:
        #      # tf cross entropy expect logits without softmax, so only
        #      # apply softmax when not training.
        #      x = tf.nn.softmax(x)
        return x

# Build neural network model.
conv_net = ConvNet()

# Cross-Entropy Loss.
# Note that this will apply 'softmax' to the logits.

def lossfunc(pred, ori):
    return tf.reduce_mean(tf.pow(ori-pred, 2))
    #  cp = tf.math.abs(tf.subtract(pred, ori))
    #  return tf.reduce_mean(tf.cast(cp, tf.float32))

# Accuracy metric.
def accuracy(y_pred, y_true):
    # Predicted class is the index of highest score in prediction vector (i.e. argmax).
    correct_prediction = tf.math.abs(tf.subtract(y_pred, y_true))
    return 1-tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Stochastic gradient descent optimizer.
optimizer = tf.optimizers.Adam(learning_rate)

# Optimization process.
def run_optimization(x, y):
    # Wrap computation inside a GradientTape for automatic differentiation.
    with tf.GradientTape() as g:
        # Forward pass.
        pred = conv_net(x, is_training=True)
        # Compute loss.
        loss = lossfunc(pred, y)

    # Variables to update, i.e. trainable variables.
    trainable_variables = conv_net.trainable_variables

    # Compute gradients.
    gradients = g.gradient(loss, trainable_variables)

    # Update W and b following gradients.
    optimizer.apply_gradients(zip(gradients, trainable_variables))

if __name__=="__main__":
    LOSS = []
    ACC = []
    # Run training for the given number of steps.
    for step, (v, r, batch_x) in enumerate(train_set.take(training_steps), 1):
        # Run the optimization to update W and b values.
        run_optimization(batch_x, v)

        if step % display_step == 0:
            pred = conv_net(batch_x)
            loss = lossfunc(pred, v)
            LOSS.append(loss)
            #  acc = accuracy(pred, v)
            #  ACC.append(acc)
            #  print("step: %i, loss: %f, accuracy: %f" % (step, loss, acc))
            print("step: %i, loss: %f" % (step, loss))

    plt.plot(LOSS)
    plt.show()
    plt.plot(np.log(LOSS))
    plt.show()
    #  plt.plot(ACC)
    #  plt.show()
    # Test model on validation set.
    #  pred = conv_net(x_test)
    conv_net.save_weights(NET_NAME)
    #
    #  new_model = ConvNet()
    #  new_model.load_weights('testSave')
    #  pred = new_model(x_test)
    #  print("Test Accuracy2: %f" % accuracy(pred, y_test))

#
#  #  Visualize predictions.
#  import matplotlib.pyplot as plt
#
#
#  # Predict 5 images from validation set.
#  n_images = 5
#  test_images = x_test[:n_images]
#  predictions = conv_net(test_images)
#
#  # Display image and model prediction.
#  for i in range(n_images):
#      plt.imshow(np.reshape(test_images[i], [28, 28]), cmap='gray')
#      plt.show()
#      print("Model prediction: %i" % np.argmax(predictions.numpy()[i]))
#


from threading import Thread, Lock
from PyQt5.QtCore import QObject, pyqtSignal
from time import sleep
from events import RefreshEvent, ExplodeEvent, MoveEvent
from parameters import Parameter
from collections import namedtuple
from random import random, choice

class Bomb(Thread, QObject):

    refresh_bomb = pyqtSignal(RefreshEvent)
    set_explosion = pyqtSignal(ExplodeEvent)

    def __init__(self, parent, bomber, _id, _map, x_block, y_block, enemies, *args, **kwargs):
        Thread.__init__(self, *args, **kwargs)
        QObject.__init__(self)

        self.refresh_bomb.connect(parent.refresh_bomb)
        self.set_explosion.connect(parent.set_explosion)

        self.id = _id
        self.map = _map
        self.x_block = x_block
        self.y_block = y_block
        self.parent = parent
        self.bomber = bomber
        self.enemies = enemies
        self._pause = False
        self.explosions = []
        self.alive = True

    def run(self):
        self.map.edit.acquire()
        self.map.blocks[self.y_block][self.x_block] = 'B'
        self.map.edit.release()

        count = 0
        while count < 10:
            while self._pause:
                sleep(0.25)
            else:
                sleep(0.25)
                self.refresh_bomb.emit(RefreshEvent(self.id, 'refresh'))
                count += 1
        self.refresh_bomb.emit(RefreshEvent(self.id, 'kill'))
        self.map.remove(self.x_block, self.y_block)
        self.explode()

    def explode(self):
        self.bomber.current_bombs -= 1

        self.set_explosion.emit(ExplodeEvent(self.x_block, self.y_block, 'center', 'center', Explosion.id))
        _id = Explosion.id

        if self.bomber.x // 30 == self.x_block and self.bomber.y // 30 == self.y_block:
            self.bomber.life -= 1 # Agregar parte de abajo del bomber

        Explosion.id_lock.acquire()
        Explosion.id += 1
        Explosion.id_lock.release()

        if self.map.blocks[self.y_block - 1][self.x_block] != 'X':
            explosion = Explosion('north', self.parent, self.bomber, self.map, self.x_block, self.y_block - 1, self.enemies)
            self.explosions.append(explosion)
            explosion.start()
        if self.map.blocks[self.y_block + 1][self.x_block] != 'X':
            explosion = Explosion('south', self.parent, self.bomber, self.map, self.x_block, self.y_block + 1, self.enemies)
            self.explosions.append(explosion)
            explosion.start()
        if self.map.blocks[self.y_block][self.x_block + 1] != 'X':
            explosion = Explosion('west', self.parent, self.bomber, self.map, self.x_block + 1, self.y_block, self.enemies)
            self.explosions.append(explosion)
            explosion.start()
        if self.map.blocks[self.y_block][self.x_block - 1] != 'X':
            explosion = Explosion('east', self.parent, self.bomber, self.map, self.x_block - 1, self.y_block, self.enemies)
            self.explosions.append(explosion)
            explosion.start()

         # Se eliminan las explosiones que teminaron
        while self.explosions:
            self.explosions = [explosion for explosion in self.explosions if explosion.alive]
            sleep(0.1)
        self.set_explosion.emit(ExplodeEvent(_type='kill', _id=_id))
        self.alive = False

    def pause(self, state):
        self._pause = state
        for explosion in self.explosions:
            explosion.paused = state

class Explosion(Thread, QObject):

    set_explosion = pyqtSignal(ExplodeEvent)
    kill_enemy = pyqtSignal(MoveEvent)
    id = 0
    id_lock = Lock()
    set_lock = Lock()
    block = namedtuple('ExplosionBlock', 'id x y')

    def __init__(self, direction, parent, bomber, _map, x, y, enemies, *args, **kwargs):
        Thread.__init__(self, *args, **kwargs)
        QObject.__init__(self)
        self.direction = direction
        self.x = x
        self.y = y
        self.map = _map
        self.bomber = bomber
        self.explosions = []
        self.enemies = enemies
        self.did_damage = False
        self.parent = parent
        self.alive = True
        self.paused = False

        self.set_explosion.connect(parent.set_explosion)
        self.kill_enemy.connect(enemies.kill)

    def run(self):
        counter = 0
        while counter < Parameter.explosion_radius:
            while self.paused:
                sleep(0.1)
            else:
                if counter > 0:
                    for explosion in self.explosions:
                        self.set_lock.acquire()
                        self.set_explosion.emit(ExplodeEvent(_type='root', direction=self.direction, _id=explosion.id))
                        self.set_lock.release()
                # Explosion hacia arriba.
                if self.direction == 'north':
                    block = self.map.blocks[self.y - counter][self.x]
                    x = self.x
                    y = self.y - counter
                if self.direction == 'south':
                    block = self.map.blocks[self.y + counter][self.x]
                    x = self.x
                    y = self.y + counter
                if self.direction == 'east':
                    block = self.map.blocks[self.y][self.x - counter]
                    x = self.x - counter
                    y = self.y
                if self.direction == 'west':
                    block = self.map.blocks[self.y][self.x + counter]
                    x = self.x + counter
                    y = self.y
                if block == '0':
                    self.set_lock.acquire()
                    self.set_explosion.emit(ExplodeEvent(x, y, 'arm', self.direction, self.id))
                    self.set_lock.release()
                    self.explosions.append(self.block(self.id, x, y))
                    self.id_lock.acquire()
                    Explosion.id += 1
                    self.id_lock.release()
                if block == 'J':
                    self.bomber.life -= 1
                    break
                if block == 'G':
                    self.bomber.score += Parameter.ENEMY_SCORE
                    self.kill_enemy.emit(MoveEvent(x=x, y=y))
                    break
                if block == 'H':
                    self.bomber.score += Parameter.ENEMY_SCORE
                    self.kill_enemy.emit(MoveEvent(x=x, y=y))
                    break
                if block == 'P':
                    self.map.remove(x, y)
                    self.bomber.score += Parameter.WALL_SCORE
                    self.set_explosion.emit(ExplodeEvent(x, y, 'delete', self.direction, self.id))
                    wall = DestroyedWall(self.parent, self.map, x, y)
                    wall.start()
                    break
                sleep(0.1)
                counter += 1
        for explosion in self.explosions:
            self.set_lock.acquire()
            self.set_explosion.emit(ExplodeEvent(_type='kill', _id=explosion.id))
            self.set_lock.release()
        self.alive = False

class DestroyedWall(Thread, QObject):

    set_power = pyqtSignal(ExplodeEvent)
    set_wall = pyqtSignal(ExplodeEvent)

    def __init__(self, parent, _map, x, y, *args, **kwargs):
        """
        :param parent: QWidget
        :param _map: list[list]
        :param x: int (block)
        :param y: int (block)
        :param args:
        :param kwargs:
        """
        Thread.__init__(self, *args, **kwargs)
        QObject.__init__(self)
        self.x = x
        self.y = y
        self.map = _map
        self.id = '{},{}'.format(str(self.x),str(self.y))
        self.set_power.connect(parent.set_power)
        self.set_wall.connect(parent.set_wall)

    def run(self):
        self.set_wall.emit(ExplodeEvent(x=(self.x * 30), y=(self.y * 30), _type='create', direction='1', _id=self.id))
        sleep(0.05)
        for i in range(2, 6):
            self.set_wall.emit(ExplodeEvent(_type='refresh', direction=str(i), _id=self.id))
            sleep(0.05)
        self.set_wall.emit(ExplodeEvent(_type='kill', _id=self.id))
        if random() <= 0.3:
            power = choice(list(Parameter.POWERS.keys()))
            self.map.add('W{}'.format(Parameter.POWERS[power]), self.x, self.y)
            self.set_power.emit(ExplodeEvent(x=(self.x * 30), y=(self.y * 30), _type='create', direction=power,
                                             _id=self.id))


d = len(sigma)
P = matrix(sigma)
q = matrix(np.zeros(d, float))
A = matrix([
    np.ones(d, float).tolist(), r_i.tolist()
    ]).trans()
b = matrix([1.0, float(rho)])
##########################################################
# Se define la restricción para cuando las ventas en corto
# están permitidas
##########################################################
diagonal = np.zeros((d, d), float)
np.fill_diagonal(diagonal, -1.0)

G = matrix(diagonal)
h = matrix(np.zeros(d, float))
##########################################################
# Se revisa la condición de Ventas en corto para asignar
# valores a G y h
##########################################################
if Ventas_en_corto == True:
    G = None
    h = None
else:
    G = G
    h = h


import cv2, os
import numpy as np

from PIL import Image

recognizer = cv2.face.LBPHFaceRecognizer_create()
path='dataSet'

def getImagesAndLabels(path):
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
    faces = []
    IDs = []
    for imagePath in imagePaths:
        faceImg = Image.open(imagePath).convert('L')
        faceNp = np.array(faceImg,'uint8')
        ID=int(os.path.split(imagePath)[-1].split('.')[1])
        faces.append(faceNp)
        IDs.append(ID)
        cv2.imshow("traning",faceNp)
        cv2.waitKey(10)
    return faces, IDs

faces, IDs = getImagesAndLabels(path)
#trainning
recognizer.train(faces, np.array(IDs))
if not os.path.exists('recognizer') :
    os.makedirs('recognizer')
recognizer.save('recognizer/trainningData.yml')
cv2.destroyAllWindows()


from velociraptor.observations.objects import ObservationalData

import unyt
import numpy as np
import os
import sys

# Exec the master cosmology file passed as first argument
with open(sys.argv[1], "r") as handle:
    exec(handle.read())

# Cosmologies
h_obs = 0.7
h_sim = cosmology.h

input_filename = "../raw/Tremonti_2004_ascii.txt"
delimiter = "\t"

output_filename = "Tremonti2004_Data.hdf5"
output_directory = "../"

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

# Read the data
raw = np.loadtxt(input_filename, delimiter=delimiter)
M_star = 10 ** raw[:, 0] * unyt.Solar_Mass * (h_sim / h_obs) ** -2
Z_median = raw[:, 3] * unyt.dimensionless  # 12 + log(O/H)
Z_lo = raw[:, 2] * unyt.dimensionless  # 12 + log(O/H)
Z_hi = raw[:, 4] * unyt.dimensionless  # 12 + log(O/H)

# Define the scatter as offset from the mean value
y_scatter = unyt.unyt_array((Z_median - Z_lo, Z_hi - Z_median))

# Meta-data
comment = (
    "Data obtained assuming a Kroupa IMF and h=0.7. "
    f"h-corrected for SWIFT using cosmology: {cosmology.name}. "
    "The metallicity is expressed as 12 + log10(O/H). "
    "In these units the solar metallicity is 8.69."
    "The error bars given the 16th and 84th percentile of the distribution."
)
citation = "Tremonti et al. (2004) (SDSS)"
bibcode = "2004ApJ...613..898T"
name = "Stellar mass - Gas phase metallicity relation"
plot_as = "line"
redshift = 0.1
h = h_sim

# Write everything
processed = ObservationalData()
processed.associate_x(
    M_star, scatter=None, comoving=True, description="Galaxy Stellar Mass"
)
processed.associate_y(
    Z_median, scatter=y_scatter, comoving=True, description="Gas phase metallicity"
)
processed.associate_citation(citation, bibcode)
processed.associate_name(name)
processed.associate_comment(comment)
processed.associate_redshift(redshift)
processed.associate_plot_as(plot_as)
processed.associate_cosmology(cosmology)

output_path = f"{output_directory}/{output_filename}"

if os.path.exists(output_path):
    os.remove(output_path)

processed.write(filename=output_path)


from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^search$', views.search, name='search'),
    url(r'^result$', views.result, name='result'),
    url(r'^entries$', views.show_entries, name='show'),
    url(r'^entries/new$', views.create_article, name='new'),
    url(r'^entries/(?P<daily_id>[0-9]+)$', views.detail, name='detail'),
    url(r'^entries/(?P<daily_id>[0-9]+)/edit$', views.edit, name='edit'),
    url(r'^entries/(?P<daily_id>[0-9]+)/delete$', views.delete, name='delete'),
    url(r'^users$', views.show_users, name='show_users'),
    url(r'^users/(?P<user_id>[0-9]+)$', views.show_user_page, name='show_user_page'),
]


from privacy_evaluator.attacks.property_inference_attack import PropertyInferenceAttack
from privacy_evaluator.classifiers.classifier import Classifier
from privacy_evaluator.utils.data_utils import (
    dataset_downloader,
    new_dataset_from_size_dict,
)
from privacy_evaluator.utils.trainer import trainer
from privacy_evaluator.models.tf.cnn import ConvNet

def test_property_inference_attack():
    train_dataset, test_dataset = dataset_downloader("CIFAR10")
    input_shape = test_dataset[0][0].shape
    num_elements_per_classes = {0: 1000, 1: 1000}
    num_classes = len(num_elements_per_classes)

    train_set = new_dataset_from_size_dict(train_dataset, num_elements_per_classes)

    model = ConvNet(num_classes, input_shape)
    trainer(train_set, num_elements_per_classes, model)

    # change pytorch classifier to art classifier
    target_model = Classifier._to_art_classifier(model, num_classes, input_shape)

    attack = PropertyInferenceAttack(target_model, train_dataset)
    attack.attack()


"""
decision tree
"""
import math
from collections import Counter, defaultdict
import numpy as np
from typing import NamedTuple, Any
import matplotlib.pyplot as plt

# NamedTuple 을 상속받는 클래스 선언
class Candidate(NamedTuple):
    level: str
    lang: str
    tweet: bool
    phd: bool
    result: bool = None  # 기본값 쓸 수 있다! (클래스 선언 방식의 장점!)

def uncertainty(p):
    """
    엔트로피 : 불확실성의 정도 0 < p <= 1
    확률 p=0이면, 사건이 항상 발생하지 않는다라고 확신 -> 불확실성 0
    확률 p=1이면, 사건이 항상 발생한다고 확신 -> 불확실성 1
    확률 0 < p < 1이면, 사건이 발생할 수도, 발생하지 않을 수도 있다 -> 불확실성이 있다.
     """
    # math.log(p, base=2) -> log_2 가 밑수
    # 1보다 작은 로그는 음수에 -을 붙여서 양수로 만든다
    return -p * math.log(p, 2)

def entropy(class_probabilities):
    """
    주어진 확률들의 리스트에 대해서 엔트로피를 계산
    E = sum(i) [uncertainty(p_i)] = -p_1 * log(p_1) - p_2 * log(p_2) * ...
    E = 모든 경우에 대한 불확실성 = 각 사건에 대한 불확실성 + 각 사건에 대한 불확실성 + ...
    가장 불확실성이 큰 경우 : 50%, 50% -> 엔트로피 max (최댓값)
    """
    ent = 0
    for p in class_probabilities:
        if p != 0:
            ent += uncertainty(p)
            # 만약 p=0이면 log(p)를 계산할 때 Error 가 발생
        # 더하지 않는 건, 더하기 0과 같으므로, else 부분은 없어도 되~
    return ent

def binary_entropy(p):
    """사건이 두 가지인 경우, 사건이 일어날 확률 p, 사건이 일어나지 않을 확률 1-p
    두가지만 더하면 된다"""
    return uncertainty(p) + uncertainty(1-p)

def class_probabilities(labels):
    """"""
    total_count = len(labels)
    counts = Counter(labels)  # 갯수, {label1: x개, label2: y개.. } -> dict 와 비슷
    print(counts)
    probabilities = []
    for count in counts.values():
        p = count / total_count  # 각 레이블의 확률
        probabilities.append(p)
    return probabilities
#
# def class_probabilities(labels):
#     total_count = len(labels)
#     counts = Counter(labels)  # 갯수, {label1: x개, label2: y개.. } -> dict 와 비슷
#     print(counts)
#     pass

def partition_by(dataset, attr_name):
    """NamedTuple 들의 리스트로 이루어진 dataset 을 NamedTuple 의 특정 attribute 로 partitioning"""
    # list 를 value 로 갖는 dict 만듬
    # 전체적 흐름 : 지원자 1 row 가 senior 그룹에 들어감. (맞다면), 아니면 그룹 만들어 들어감
    partitions = defaultdict(list)
    for sample in dataset:
        # 지원자 1 row 추출
        # sample.attr_name 은 글자 그대로 인식함
        # sample 의 getattr 함수에 지정된 attr_name(ex_level) 으로 준다. defaultdict 의 key 로 준다.
        key = getattr(sample, attr_name)
        # dict 의 키로 사용하여 sample 을 value 에 저장(새로 생성)
        partitions[key].append(sample)
    return partitions

# defaultdict : dictionary 에 기본값을 정의하고, 키값이 없더라도 에러를 출력하지 않고 기본값을 출력한다.

def partition_entropy_by(dataset, by_partition, by_entropy):
    """
    attr_name 으로 분리된 각 파티션에서 label_name 의 엔트로피를 각각 계산하고, 파티션 내에서의 엔트로피 * 파티션의 비율들의 합을 리턴
    dataset : 데이터 전체
    by_partition : patitioning 을 나눌 컬럼명(특성)
    by_entropy : 합격 불합격 결과(엔트로피를 계산할 컬럼명)

    과정
    : attr_name 이 예를 들어 level 일 때, level 이 Junior 일 때, 합격할 확률의 엔트로피를 구한다.
    level 이 mid 일 때, 합격할 확률의 엔트로피를 구한다.
    level 이 Senior 일 때, 합격할 확률의 엔트로피를 구한다.
    """
    # partition 을 나눔
    partitions = partition_by(dataset, by_partition)
    # label(class) 별 확률을 계산하기 위해서 각 label 들의 리스트 만들기
    labels = []
    for partition in partitions.values():  # partition 갯수 만큼 반복
        values = []
        for sample in partition:  # 부분집합인 partition 안의 sample 들(candidate)의 갯수 - 원소 1개 만큼 반복
            values.append(getattr(sample, by_entropy))
        labels.append(values)  # [Junior 의 T, F, T, F], [Senior 의 T, F, T, F]..
    print(labels)  # [[t,f,t,f], [..], [..] ..] 위의 리스트를 모아 하나의 리스트로!
    # 각 파티션이 차지하는 비율을 계산하고, 각 파티션에서의 엔트로피에 그 비율을 곱해주기 위해서
    total_count = sum(len(label) for label in labels)
    # 함수 안에도 for 문 쓸 수 있음
    # labels 은 리스트를 3개 가지고 있음, 실제로는 5 + 5 + 5 = 15개이다.
    # 따라서 for 문 :  [[t,f,t,f], [..], [..] ..] 안의 [t,f,t,f] 에서의 label 의 갯수 계산
    ent = 0
    for label in labels:
        # 파티션이 가지고 있는 [t,f,t,f] 에서 확률 계산 (ex_P(t) = 1/2, P(f) = 1/2)
        cls_prob = class_probabilities(label)  # 파티션의 엔트로피 계산
        part_ent = entropy(cls_prob)
        ent += part_ent * len(label) / total_count  # 파티션 내에서의 엔트로피 * 파티션의 비율들의 합
    return ent

# 데이터 타입을 먼저 지정해준다
class Leaf(NamedTuple):  # NamedTuple 을 상속받는 클래스
    value: Any  # 어떤 타입이든 올 수 있다는 뜻, 합격 불합격 저장 용도로 사용

class Split(NamedTuple):
    # 무엇으로 가지를 치는지 attribute 이름이 있어야 해요
    attribute: str  # 트리에서 가지(branch)가 나눠지는 기준 : key 값은 무조건 문자열 ex_level
    subtree: dict  # 중간에 있는 tree (ex_senior 의 subtree)

# predict 함수
def predict(model, sample):
    """sample을 model(의사결정나무)에 적용했을 때, 예측 결과를 리턴"""
    # 기본원리 : leaf type 이 들어오면 우리가 예측을 멈춘다!
    if isinstance(model, Leaf):
        # model 이 최종 노드인 Leaf 타입이면, Leaf 가 가지고 있는 value (값) 을 리턴
        return model.value

    # model이 아닌 경우에는 가지를 따라 내려가야 하기 때문에
    # sample(ex_candidate) 이 attribute(ex_level) 로 가지고 있는 값을 찾아서, 해당 가지로 내려감
    subtree_key = getattr(sample, model.attribute)  # sample 의 attribute 의 값을 찾는다.
    # ex_model.attribute 가 level 이라면 sample 의 값인 ex_'Senior' 값이 나온다.
    print('subtree_key : ', subtree_key)

    # model 이 가지고 있는 subtree (ex_'Senior'라는 subtree 로 다시 간다)
    subtree = model.subtree[subtree_key]
    return predict(subtree, sample)  # 재귀함수 : (ex_ Senior)

def build_tree(dataset, by_splits, target):
    print('\n>> building tree.. ')
    print(f'dataset len : {len(dataset)} = {dataset}')
    print(f'by_split : {by_splits}, target : {target}')
    # dataset (data), by_splits (tree 나누는 기준), target(결과)

    # target 의 갯수를 셈 by Counter 객체 생성 Counter : {True: x, False: y}
    target_counts = Counter(getattr(sample, target)
                            for sample in dataset)  # 리스트로 만들어진 True, False 갯수를 센다. (counter 객체 dict 타입 리턴)
    print('target_counts : ', target_counts)  # dict 에서는 key:value 가 1개의 data, 그래서 dict 의 length 는 2

    # Counter 의 length 가 1개이면
    # leaf 가 될 수 있는 상태란? target 갯수, 즉 Counter 의 length 가 1개인 상태 - Leaf 생성하고 종료
    if len(target_counts) == 1:
        keys = list(target_counts.keys())
        # = [k for k in target_counts.keys()] -> [] 연산자 사용 불가.. why? keys() 는 generator 객체이므로,,
        # target_counts.keys() generator (반복문 안에서 리스트를 만들어주는 객체)이므로 리스트를 먼저 만들어 주어야 함 -> 리스트 함수 쓰면 됨
        result = keys[0]
        leaf = Leaf(result)
        print('leaf : ', leaf)
        return leaf

    # tree 의 depth 가 깊어져서 더이상 서브 트리를 나눌 기준이 없을 때 (ex_ 4가지 기준 모두 씀)
    # by_splits = []일때, 원소가 없으면 False
    # if len(by_splits) == 0:
    if not by_splits:
        return Leaf(list(target_counts.keys())[0])  # leaf node 를 무조건 리턴

    # Counter 의 length 가 1이 아니면, 파티션을 나눌 수 있음.
    # by_splits(가지 나누는 기준)의 각 변수로 파티션을 나눔.
    # 각 파티션별 엔트로피(level 로 나눴을 때 엔트로피.. )를 계산해서 가장 낮은 엔트로피 변수를 선택
    # best_splilter = min(by_splits, key=partition_entropy_by())
    # partition_entropy_by()를 key= 에 바로 못쓰는 이유
    # 파라미터 1개밖에 못주기 때문, by_splits 는 key 의 함수(dataset, ..)에 파라미터로 주는데, partition_entropy_by()는 파라미터 3개이다.
    # (ex_ sorted(list, key=lambda x: len(x)) # 리스트의 문자열 1개가 x가 되어서 글자 수 세고 글자수 기준으로 정렬 - 파라미터 1개만 된다)
    # 어디다 넣어야 할 지 알려주기 위해서 partition_entropy_by()를 호출할 수 있는 wrapper 함수(helper 함수)를 작성

    # wrapper 함수(helper 함수)
    # 내부함수(자신의 바깥쪽에 선언된 변수를 모두 가져다 쓸 수 있다 - ??? ctrl + 클릭으로 확인)
    def splitted_entropy(split_attr):
        print('split_attr = ', split_attr)
        # 파라미터 3개 중 1개를 딱 정해준다.(split_attr) / build_tree 의 파라미터 dataset, target 이 자동으로 파라미터로 들어간다 - ???)
        result = partition_entropy_by(dataset, split_attr, target)
        print('splitted entropy = ', result)
        return result

    best_splilter = min(by_splits, key=splitted_entropy)
    print('best_spliter : ', best_splilter)

    # 선택된 변수(entropy 최솟값을 주는 변수)로 Split 객체를 생성 - 첫번째 가지를 치자!
    partitions = partition_by(dataset, best_splilter)
    print('partitions : ', partitions)

    # partition 을 만든 이유 : 나눠준 candidate 들을 key 값(ex_level)의 value 들을 부분집합으로 만들어주기 위해서!
    # 각 부분집합들은 또다른 가지의 dataset 이 된다.
    # 선택한 변수를 제외한 나머지 변수들로 sub tree 를 만듬
    # branch 기준 리스트에서 선택된 변수 제거
    new_split = [x for x in by_splits
                 if x != best_splilter]  # best_spliter 와 다른 새로운 split 기준 리스트 생성
    print(f'제거 후 by_splits : {by_splits}, new_splits : {new_split}')

    # subtree 생성
    subtree = {k: build_tree(subset, new_split, target)  # 재귀함수로 가지 밑 다른 트리를 만듬 *by_splits 전의 변수 없어진 상태
               for k, subset in partitions.items()}
    # 해석 : {'Senior' - key ! : [Candidate(level='Senior', ..), ...- value 는 원소 5개짜리 부분집합

    # Split 객체를 생성하여 리턴
    return Split(best_splilter, subtree)

# leaf 하고 나서 다시 올라가는데 왜 올라가지? 다시 올라가서 재귀함수인가?
# 같은 depth 에서는 같은 기준으로 나누게 하기 위하여 new_split 을 써야 한다. (근데 다시 올라가는 거 모르겠음)

if __name__ == '__main__':
    candidates = [Candidate('Senior', 'Java', False, False, False),
                  Candidate('Senior', 'Java', False, True, False),
                  Candidate('Mid', 'Python', False, False, True),
                  Candidate('Junior', 'Python', False, False, True),
                  Candidate('Junior', 'R', True, False, True),
                  Candidate('Junior', 'R', True, True, False),
                  Candidate('Mid', 'R', True, True, True),
                  Candidate('Senior', 'Python', False, False, False),
                  Candidate('Senior', 'R', True, False, True),
                  Candidate('Junior', 'Python', True, False, True),
                  Candidate('Senior', 'Python', True, True, True),
                  Candidate('Mid', 'Python', False, True, True),
                  Candidate('Mid', 'Java', True, False, True),
                  Candidate('Junior', 'Python', False, True, False)]

# decision tree = 스무고개
# 첫 질문이 제일 중요하다! (확률적 - 엔트로피 개념 파악하기)
# 질문 순서에 따라 decision tree 갯수 엄청 많아져~
# 그런데 트리 크기가 짧은게 꼭 좋은 건 아니다 -> 다른 데이터에 예측력이 떨어질 수 있다.

    # 엔트로피 : 질문을 선택하는 기준
    # uncertainty 함수 그래프
    x_pts = np.linspace(0.0001, 0.9999, 100)  # 시작값, 끝값, 그사이를 나누는 값
    y_pts = [uncertainty(p) for p in x_pts]
    plt.plot(x_pts, y_pts)
    plt.xlim(0.0)  # 0 <= x 그 밑은 그리지 않는다.
    plt.ylim(0.0)  # 0 <= y 그 밑은 그리지 않는다.
    plt.title('-p * log(p)')
    plt.show()
    # 해석
    # 엔트로피는 불확실성! https://web.mit.edu/16.unified/www/FALL/thermodynamics/notes/node56.html
    # 확률 1 = 모두 발생하는 경우, 불확실성이 없다. 확실하게 정해져 있으므로
    # 확률 0 = 발생하지 않는 경우, 불확실성이 없다. 확실하게 정해져 있으므로

    # binary entropy graph
    x_pts = np.linspace(0.0001, 0.9999, 100)
    y_pts = [binary_entropy(p) for p in x_pts]
    plt.plot(x_pts, y_pts)
    plt.xlim(0)
    plt.axvline(0.5)
    plt.ylim(0)
    plt.show()
    # 0.5 일때 가장 불확실성이 커진다. 소금물100% + 맹물 100% = 50%, 50%으로 불확실성이 가장 커지는 방향으로 변화한다.

    # entropy 함수 테스트
    # 확률 1개, p=1
    rain_prob = [1]  # 내일 비올확률 1 (확률 1개)
    ent = entropy(rain_prob)
    print('entropy = ', ent)  # binary entropy 의 그래프의 최솟값 0

    # 확률 2개, p1=0.5, p2=0.5 (p1+p2=1)
    rain_prob = [0.5, 0.5]
    ent = entropy(rain_prob)
    print('entropy = ', ent)  # binary entropy 의 그래프의 최댓값 1

    # 확률 2개, p1=0.9, p2=0.1 (p1+p2=1) 비가 올 확률 90%
    rain_prob = [0.9, 0.1]
    ent = entropy(rain_prob)
    print('entropy = ', ent)  # entropy 0.47

# decision tree = 스무고개에서의 엔트로피 활용
# E(level), E(lang), E(mid) .. 계산 -> 엔트로피가 가장 낮은 질문을 첫번째로 삼는다.
# 2번째 질문 -> partitioning group 1 을 다시 partitioning 하여 엔트로피를 계산한다.

    # class_probabilities 함수 테스트
    level = ['junior', 'senior', 'mid', 'junior']
    cls_prob = class_probabilities(level)
    print(cls_prob)

    # 실전!
    # 전체 집합을 나누는 기준(Partitioning) 에 따라 엔트로피가 달라질 수 있다.
    # 함수 만듬
    partition_by_level = partition_by(candidates, 'level')
    print('partitioning by level: \n', partition_by_level)
    partition_by_tweets = partition_by(candidates, 'tweet')
    print('partitioning by tweets: \n', partition_by_tweets)

    # partition entropy by 함수 테스트
    # 전체 지원자들을 level 로 partition 을 나눠서 result 의 엔트로피를 계산하자~
    ent_level = partition_entropy_by(candidates, 'level', 'result')
    print(f'entropy partitioned by level : {ent_level}')
    # 결과 : [[False, False, True, True, True], [True, True, True, True], [True, True, False, True, False]]
    ent_lang = partition_entropy_by(candidates, 'lang', 'result')
    print(f'entropy partitioned by lang : {ent_lang}')
    ent_tweets = partition_entropy_by(candidates, 'tweet', 'result')
    print(f'entropy partitioned by tweets : {ent_tweets}')
    ent_phd = partition_entropy_by(candidates, 'phd', 'result')
    print(f'entropy partitioned by phd : {ent_phd}')

    """ 결과 해석 - 불확실성이 적은 질문을 먼저 던지는 것이 좋다. 즉 엔트로피가 가장 적은 것부터 트리를 그리자.
    [[False, False, False, True, True], [True, True, True, True], [True, True, False, True, False]] : 파티션
    Counter({False: 3, True: 2}) : 1번의 FALSE 3, 3 엔트로피 계산 * 비율 곱하여 더한다.
    Counter({True: 4})           : 2번의 TRUE 4
    Counter({True: 3, False: 2}) : 3번의
    entropy partitioned by level : 0.6935361388961919

    [[False, False, True], [True, True, False, True, True, True, False], [True, False, True, True]]
    Counter({False: 2, True: 1})
    Counter({True: 5, False: 2}) : 확실성 더 높다. 엔트로피 더 낮다.
    Counter({True: 3, False: 1})
    entropy partitioned by lang : 0.8601317128547441  불확실성이 더 많아 전체 엔트로피 더 커질 수 밖에 없다.

    [[False, False, True, True, False, True, False], [True, False, True, True, True, True, True]]
    Counter({False: 4, True: 3}) : 불확실성 크다
    Counter({True: 6, False: 1}) : 불확실성 상대적으로 적다
    entropy partitioned by tweets : 0.7884504573082896

    [[False, True, True, True, False, True, True, True], [False, False, True, True, True, False]]
    Counter({True: 6, False: 2})
    Counter({False: 3, True: 3})
    entropy partitioned by phd : 0.8921589282623617  --> 박사학위가 엔트로피가 제일 크다.
    """

    # test - 자료구조를 만들고 있다!
    hire_tree = Split(
        'level',                                          # branch 나누는 기준 : root node
        {
            'Senior': Split(                              # 첫번째 가지
                'tweet',
                {True: Leaf(True), False: Leaf(False)}),  # subtree
            'Mid': Leaf(True),  # 전부 합격인 leaf 노드
            'Junior': Split(
                 'phd',
                 {True: Leaf(False), False: Leaf(True)})
        }
    )

    # 두번째 그림도 만들어보기 (노트 필기)

    # predict test
    print(hire_tree)
    candidate_1 = Candidate('Senior', 'Java', False, False, False)
    result = predict(hire_tree, candidate_1)
    print(result)

    candidate_2 = Candidate('Mid', 'Python', False, False, True)
    result = predict(hire_tree, candidate_2)
    print(result)

    # built tree 함수 테스트
    tree = build_tree(candidates, ['level', 'lang', 'tweet', 'phd'], 'result')
    print(tree)  # 최소 엔트로피로 이루어진 tree 를 출력한다.

    # pip install graphviz


import time;
import random;
import _thread;
import RPi.GPIO as GPIO;
from MCP3008 import MCP3008;

GPIO.setmode(GPIO.BOARD);
GPIO.setwarnings(False);

#Base colors
rot = (255,0,0);
grün = (0,255,0);
blau = (0,0,255);
magenta = (255,0,255);
gelb = (255,255,0);
türkis = (0,255,255);
weiss = (255,255,255);
aus = (0,0,0);
global f_manager;
f_manager = [rot,grün,blau,magenta,gelb,türkis,weiss];

#Mode Konfig
global Mode_At_Moment;
Mode_At_Moment = 3;
Mode_Qnt = 10;

#OutEnFade
global out_en_duty;
out_en_duty = 0;

#LED Konfig
led_ges = 320;
rgb_values = 3;
global LED_Values;
LED_Values = [[255]*rgb_values for i in range(led_ges)];
LED_Count = [[0]*rgb_values for i in range(led_ges)];
LED_Lookup = [[0]*256 for i in range(256)];
global Mode_Keeper;
Mode_Keeper = [[0] for i in range(Mode_Qnt)];
global Threads_Qnt;
Threads_Qnt = 2;
global Threads_Done;
Threads_Done = 0;

i_differenz = 0;

for i in range(256):
  for j in range(256):
    i_differenz += i/255;

    if i_differenz >= 1:
      LED_Lookup[i][j] = 1;
      i_differenz -= 1;

LED_Values[0][0] = 255;
LED_Values[0][1] = 0;
LED_Values[0][2] = 0;
LED_Values[1][0] = 0;
LED_Values[1][1] = 255;
LED_Values[1][2] = 0;
LED_Values[2][0] = 0;
LED_Values[2][1] = 0;
LED_Values[2][2] = 255;
LED_Values[3][0] = 255;
LED_Values[3][1] = 255;
LED_Values[3][2] = 255;

#GPIO zuweisen
#outs
data_1 = 11;
data_2 = 12;
data_3 = 18;
data_4 = 22;
write_1 = 7;
write_2 = 33;
write_3 = 35;
write_4 = 36;
show_1 = 15;
show_2 = 29;
show_3 = 31;
show_4 = 32;
reset = 16;
out_en = 13;
#ins
Button_1 = 40;

#GPIO definieren
#DATA-1
GPIO.setup(data_1,GPIO.OUT);
GPIO.output(data_1,0);
#DATA-12
GPIO.setup(data_2,GPIO.OUT);
GPIO.output(data_2,0);
#DATA-3
GPIO.setup(data_3,GPIO.OUT);
GPIO.output(data_3,0);
#DATA-4
GPIO.setup(data_4,GPIO.OUT);
GPIO.output(data_4,0);
#WRITE-1
GPIO.setup(write_1,GPIO.OUT);
GPIO.output(write_1,0);
#WRITE-2
GPIO.setup(write_2,GPIO.OUT);
GPIO.output(write_2,0);
#WRITE-3
GPIO.setup(write_3,GPIO.OUT);
GPIO.output(write_3,0);
#WRITE-4
GPIO.setup(write_4,GPIO.OUT);
GPIO.output(write_4,0);
#SHOW-1
GPIO.setup(show_1,GPIO.OUT);
GPIO.output(show_1,0);
#SHOW-2
GPIO.setup(show_2,GPIO.OUT);
GPIO.output(show_2,0);
#SHOW-3
GPIO.setup(show_3,GPIO.OUT);
GPIO.output(show_3,0);
#SHOW-4
GPIO.setup(show_4,GPIO.OUT);
GPIO.output(show_4,0);
#RESET
GPIO.setup(reset,GPIO.OUT);
GPIO.output(reset,1);
#OUTPUT_EN
GPIO.setup(out_en,GPIO.OUT);
#GPIO.output(out_en,0);
out_en_fade = GPIO.PWM(out_en,100)
out_en_fade.start(out_en_duty);

#BUTTON-IN
GPIO.setup(Button_1,GPIO.IN)

#Funktionen
def set_data(pin,val):

  GPIO.output(pin,val);

def OutputThread(von,bis,pin,s_pin,w_pin):

  global LED_Values;

  counter = 0

  while True:

    LED = bis;

    while (LED >= von):

      rgb = rgb_values;

      while (rgb > 0):

        rgb -= 1;

        set_data(pin, LED_Lookup[LED_Values[LED][rgb]][counter]);

        write_data(w_pin);

        time.sleep(0.0001);

      LED -= 1;

    show_data(s_pin);

    if counter == 255:

      counter = 0;

    else:

      counter += 1;

def write_data(pin):

  GPIO.output(pin,0);
  GPIO.output(pin,1);

def show_data(pin):

  GPIO.output(pin,1);
  GPIO.output(pin,0);

def reset_all():

  GPIO.output(reset,0);
  GPIO.output(reset,1);

def set_color_in_array(color):

  for LED in range(led_ges):
    for RGB_Val in range(len(color)):
      LED_Values[LED][RGB_Val] = color[RGB_Val];

def Auto_Flash(myMode):
  global Mode_At_Moment;
  global f_manager;
  while myMode == Mode_At_Moment:
    set_color_in_array(f_manager[random.randint(0,len(f_manager)-1)]);
    time.sleep(3);

def Auto_Fade(myMode):
  global Mode_At_Moment;
  global f_manager;
  set_color_in_array(f_manager[random.randint(0,len(f_manager)-1)]);
  while myMode == Mode_At_Moment:
    for dc in range(0, 101, 5):
      out_en_fade.ChangeDutyCycle(dc)
      out_en_duty = dc;
      time.sleep(0.1)
    time.sleep(0.5);
    set_color_in_array(f_manager[random.randint(0,len(f_manager)-1)]);
    for dc in range(100, -1, -5):
      out_en_fade.ChangeDutyCycle(dc)
      out_en_duty = dc;
      time.sleep(0.1)
    time.sleep(2);

def Strobo(myMode):
  global Mode_At_Moment;
  set_color_in_array(weiss)
  while myMode == Mode_At_Moment:
    out_en_fade.ChangeDutyCycle(100);
    out_en_duty == 100;
    time.sleep(0.1);
    out_en_fade.ChangeDutyCycle(0);
    out_en_duty == 0;
    time.sleep(0.1);

def look_for_new_Mode():
  while True:
    global Mode_At_Moment;
    if Mode_At_Moment == 0:
      set_color_in_array(aus);
    elif Mode_At_Moment == 1:
      set_color_in_array(rot);
    elif Mode_At_Moment == 2:
      set_color_in_array(grün);
    elif Mode_At_Moment == 3:
      set_color_in_array(blau);
    elif Mode_At_Moment == 4:
      set_color_in_array(magenta);
    elif Mode_At_Moment == 5:
      set_color_in_array(gelb);
    elif Mode_At_Moment == 6:
      set_color_in_array(türkis);
    elif Mode_At_Moment == 7:
      set_color_in_array(weiss);
    elif Mode_At_Moment == 8:
     Auto_Flash(8);
    elif Mode_At_Moment == 9:
     Auto_Fade(9);
    elif Mode_At_Moment == 10:
      Strobo(10);

def update_Mode():
  global Mode_At_Moment;
  while True:
    if GPIO.input(Button_1) == 1:
      if Mode_At_Moment + 1 <= Mode_Qnt:
        Mode_At_Moment += 1;
      else:
        Mode_At_Moment = 0;
      print(Mode_At_Moment);
      time.sleep(0.5);

reset_all();

_thread.start_new_thread(look_for_new_Mode,())
_thread.start_new_thread(update_Mode,())
_thread.start_new_thread(OutputThread,(0,159,data_1,show_1,write_1,))
_thread.start_new_thread(OutputThread,(160,319,data_2,show_2,write_2,))
#_thread.start_new_thread(OutputThread,(160,239,data_3,show_3,write_3,))
#_thread.start_new_thread(OutputThread,(240,319,data_4,show_4,write_4,))


m = []
o = input()

for i in range(0, 12):
    n = []
    for j in range(0, 12):
        x = float(input())
        n.append(x)
    m.append(n)

s = 0
c = 1
for i in range(0, 11):
    for j in range(c, 12):
        s += m[i][j]
    c += 1
if o == 'S':
    print('{:.1f}'.format(s))
elif o == 'M':
    print('{:.1f}'.format(s / 66))


# -*- coding:utf-8 -*-
__author__ = "Alex Li"

import socket ,os,time
server = socket.socket()
server.bind(('localhost',9999) )

server.listen(10)

while True:
    conn, addr = server.accept()
    print("new conn:",addr)
    while True:
        print(u"等待新指令")
        data = conn.recv(1024)
        if not data:
            print(u"客户端已断开")
            break
        print(u"执行指令:",data)
        cmd_res = os.popen(data.decode()).read()
        #接受字符串，执行结果也是字符串
        print(u"before send",len(cmd_res))
        if len(cmd_res) ==0:
            cmd_res = "cmd has no output..."

        conn.send( str(len(cmd_res.encode())).encode("utf-8")    )
        #先发大小给客户端
        #time.sleep(0.5)
        client_ack = conn.recv(1024)
        conn.send(cmd_res.encode("utf-8"))
        print(u"send done")
        #os.path.isfile()
        #os.stat(u"sock")
server.close()

import hashlib
m = hashlib.md5()


# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import numpy as np
import math
from functools import reduce
from mindspore.ops import prim_attr_register, PrimitiveWithInfer
from mindspore import Tensor
from mindspore._checkparam import ParamValidator as validator
from mindspore._checkparam import Rel, check_bool, check_int_positive, twice
from mindspore.common import dtype as mstype
class Cus_Conv2D(PrimitiveWithInfer):
    r"""
    Applies 2D convolution for the input.

    Input is typically of shape :math:`(N, C, H, W)`, where :math:`N` is batch size and :math:`C` is channel number.
    For each batch of shape :math:`(C, H, W)` the formula (given mode 1) is defined as:

    .. math::
        out_j = \sum_{i=0}^{C_{in} - 1} ccor(W_{ij}, X_i) + b_j,

    where :math:`ccor` is cross correlation operator, :math:`C_{in}` is the input channel number, :math:`j` ranges
    from :math:`0` to :math:`C_{out} - 1`, :math:`W_{ij}` corresponds to i-th channel of the j-th filter and
    :math:`out_{j}` corresponds to the j-th channel of the output.

    The first introduction can be found in paper `Gradient Based Learning Applied to Document Recognition
    <http://vision.stanford.edu/cs598_spring07/papers/Lecun98.pdf>`_.

    More detailed introduction can be found here: http://cs231n.github.io/convolutional-networks/.

    Args:
        out_channel (int): The dimensionality of the output space.
        kernel_size (Union[int, tuple[int]]): The kernel size of the 2D convolution.
        mode (int): 0 Math convolutiuon, 1 cross-correlation convolution ,
                       2 deconvolution, 3 depthwise convolution. Default: 1.
        pad_mode (str): "valid", "same", "pad" the mode to fill padding. Default: "valid".
        pad (int): The pad value to fill. Default: 0.
        stride (int): The stride to apply conv filter. Default: 1.
        dilation (int): Specifying the dilation rate to use for dilated convolution. Default: 1.
        group (int): Split input into groups. Default: 1.

    Returns:
        Tensor, the value that applied 2D convolution.

    Inputs:
        - **input** (Tensor) - Tensor of shape :math:`(N, C_{in}, H_{in}, W_{in})`.

    Outputs:
        Tensor of shape :math:`(N, C_{out}, H_{out}, W_{out})`.
    """

    @prim_attr_register
    def __init__(self,
                 out_channel,
                 kernel_size,
                 mode=1,
                 pad_mode="valid",
                 pad=0,
                 stride=1,
                 dilation=1,
                 group=1):
        """init Conv2D"""
        self.init_prim_io_names(inputs=['x', 'w'], outputs=['output'])
        self.kernel_size = kernel_size
        self.kernel_size = validator.check_type('kernel_size', kernel_size, (int, tuple))
        if isinstance(self.kernel_size, int):
            self.kernel_size = (self.kernel_size, self.kernel_size)
        validator.check_integer('length of kernel_size', len(self.kernel_size), 2, Rel.GE)
        validator.equal('type of pad', type(pad), 'not bool', not isinstance(pad, bool))
        validator.equal('type of pad', type(pad), 'int', isinstance(pad, int))
        self.pad_mode = validator.check_string('pad_mode', pad_mode, ['valid', 'same', 'pad'])
        self.pad = validator.check_pad_value_by_mode(self.__class__.__name__, pad_mode, pad)
        if self.pad_mode == 'pad':
            validator.check_integer('pad', self.pad, 0, Rel.GE)

        self.mode = validator.check_integer('mode', mode, 1, Rel.EQ)
        self.add_prim_attr('data_format', "NCHW")
        self.out_channel = validator.check_integer('out_channel', out_channel, 0, Rel.GT)
        self.group = validator.check_integer('group', group, 0, Rel.GT)
        self.dilation = validator.check_integer('dilation', dilation, 1, Rel.GE)
        validator.check_type('kernel_size', kernel_size, [int, tuple])
        if isinstance(kernel_size, int) and kernel_size < 1:
            raise ValueError('Attr \'kernel_size\' of \'Conv2D\' Op passed '
                             + str(self.kernel_size)+', should be a int or tuple and equal to or greater than 1.')
        if isinstance(kernel_size, tuple) and (len(kernel_size) != 2 or
                                               (not isinstance(kernel_size[0], int)) or
                                               (not isinstance(kernel_size[1], int)) or
                                               kernel_size[0] < 1 or kernel_size[1] < 1):
            raise ValueError('Attr \'kernel_size\' of \'Conv2D\' Op passed '
                             + str(self.kernel_size)+', should be a int or tuple and equal to or greater than 1.')
        self.stride = validator.check_integer('stride', stride, 1, Rel.GE)
        from .cus_conv2d_impl import Cus_Conv2D

    def infer_shape(self, x_shape, w_shape):
        validator.check_integer("weight_shape", len(w_shape), 4, Rel.EQ)
        validator.check_integer("x_shape", len(x_shape), 4, Rel.EQ)
        validator.check_param_equal("x_shape[1]", x_shape[1] // self.group, "w_shape[1]", w_shape[1])
        validator.check_param_equal('out_channel', self.out_channel, 'w_shape[0]', w_shape[0])
        validator.check_param_equal('kernel_size', self.kernel_size, 'w_shape[2:4]', tuple(w_shape[2:4]))

        kernel_size_h = w_shape[2]
        kernel_size_w = w_shape[3]

        if self.pad_mode == "valid":
            h_out = math.ceil((x_shape[2] - kernel_size_h + 1) / self.stride)
            w_out = math.ceil((x_shape[3] - kernel_size_w + 1) / self.stride)
            pad_top, pad_bottom, pad_left, pad_right = 0, 0, 0, 0
        elif self.pad_mode == "same":
            h_out = math.ceil(x_shape[2] / self.stride)
            w_out = math.ceil(x_shape[3] / self.stride)

            pad_needed_h = max(0, (h_out - 1) * self.stride + kernel_size_h - x_shape[2])
            pad_top = math.floor(pad_needed_h / 2)
            pad_bottom = pad_needed_h - pad_top

            pad_needed_w = max(0, (w_out - 1) * self.stride + kernel_size_w - x_shape[3])
            pad_left = math.floor(pad_needed_w / 2)
            pad_right = pad_needed_w - pad_left
        elif self.pad_mode == 'pad':
            pad_top, pad_bottom, pad_left, pad_right = self.pad, self.pad, self.pad, self.pad

            h_out = 1 + (x_shape[2] + 2 * self.pad - kernel_size_h - (kernel_size_h - 1) * (self.dilation - 1)) \
                    / self.stride
            w_out = 1 + (x_shape[3] + 2 * self.pad - kernel_size_w - (kernel_size_w - 1) * (self.dilation - 1)) \
                    / self.stride
            h_out = math.floor(h_out)
            w_out = math.floor(w_out)

        self.pad_list = [pad_top, pad_bottom, pad_left, pad_right]
        self.add_prim_attr('pad_list', (pad_top, pad_bottom, pad_left, pad_right))

        out_channel = self.out_channel
        out_shape = [x_shape[0], out_channel, h_out, w_out]
        return out_shape

    def infer_dtype(self, x_dtype, w_dtype):
        args = {'x_dtype': x_dtype, 'w_dtype': w_dtype}
        validator.check_type_same(args, [mstype.int8, mstype.int32, mstype.float16, mstype.float32])
        return x_dtype


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 13:00:07 2020

Package to make face masks manually with 1s and 0s for a control volume.
Includes masks for rho points, control volume edges on rho points.
For faces on U and V points, a grid shift will be applied

@author: Jasen
"""

import numpy as np
import GridShift_3D as GridShift

def NearestIndex(RomsNC, latbounds, lonbounds) :
    """
    Finds indices of control volume given bounds on lat and lon

    Parameters
    ----------
    RomsNC : TYPE NetCDF file
        NetCDF file that contains ROMS output.
    latbounds : list
        Contains the min and max latitude (deg. N) for the control volume.
    lonbounds : list
        Contains the min and max longitdue (deg. E) for the control volume..

    Returns
    -------
    dictionary of indices of control volume.

    """
    #indices of latbounds
    idx_lat0 = np.argmin(np.abs(RomsNC.variables['lat_rho'][:, 0] - latbounds[0]))
    if idx_lat0.size > 1:
        idx_lat0 = idx_lat0[0]

    idx_lat1 = np.argmin(np.abs(RomsNC.variables['lat_rho'][:, 0] - latbounds[1]))
    if idx_lat1.size > 1:
        idx_lat1 = idx_lat1[0]

    #indices of lonbounds
    idx_lon0 = np.argmin(np.abs(RomsNC.variables['lon_rho'][0, :] - lonbounds[0]))
    if idx_lon0.size > 1:
        idx_lon0 = idx_lon0[0]

    idx_lon1 = np.argmin(np.abs(RomsNC.variables['lon_rho'][0, :] - lonbounds[1]))
    if idx_lon1.size > 1:
        idx_lon1 = idx_lon1[0]

    idx = {"lat0" : idx_lat0, "lat1" : idx_lat1, \
           "lon0" : idx_lon0, "lon1" : idx_lon1}

    return idx

def RhoMask(RomsNC, RhoIdx) :
    """
    Parameters
    ----------
    RomsNC : TYPE NetCDF file
        NetCDF file that contains ROMS output.
    RhoIdx : TYPE dictionary
        Contains index of vertices of control volume on rho points

    Returns
    -------
    3D array (depth, lat, lon) of ones within control volume and 0 for mask

    """
    #make array of zeros the same size as variable
    A_shape = RomsNC.variables['salt'][:].shape
    Mask_Array = np.zeros((A_shape[1], A_shape[2], A_shape[3]))

    Mask_Array[:, RhoIdx['lat0']:RhoIdx['lat1'], RhoIdx['lon0']:RhoIdx['lon1']] = 1

    return Mask_Array

def FaceMask(RomsNC, RhoIdx, MaskRho) :
    """
    Parameters
    ----------
    RomsNC : NetCDF4 file
        Contains loaded ROMS output.
    RhoIdx : TYPE dictionary
        Contains index of vertices of control volume on rho points
    MaskRho : TYPE Array
        Array of mask on rho points

    Returns
    -------
    NorthFace, WestFace, SouthFace, EastFace, ON RHO POINTS.

    """
    #empty mask
    MaskRho[:] = 0

    #north mask on rho points
    NorthRho = MaskRho
    NorthRho[:, RhoIdx['lat1'], RhoIdx['lon0']:RhoIdx['lon1']] = 1

    #north mask on v points
    NorthV = GridShift.Rho_to_Vpt(NorthRho)

    #south mask on rho points
    SouthRho = MaskRho
    SouthRho[:, RhoIdx['lat0'], RhoIdx['lon0']:RhoIdx['lon1']] = 1

    #south mask on v points
    SouthV = GridShift.Rho_to_Vpt(SouthRho)

    #east mask on rho points
    EastRho = MaskRho
    EastRho[:, RhoIdx['lat0']:RhoIdx['lat1'], RhoIdx['lon1']] = 1

    #shift to u points
    EastU = GridShift.Rho_to_Upt(EastRho)

    #west mask on rho points
    WestRho = MaskRho
    WestRho[:, RhoIdx['lat0']:RhoIdx['lat1'], RhoIdx['lon0']] = 1

    #shift to v points
    WestU = GridShift.Rho_to_Upt(WestRho)

    return NorthV, WestU, SouthV, EastU


'''
## iam_user_attach_policy
What it does: Attaches a policy (passed in as a variable) to the user
Usage: AUTO: iam_user_attach_policy policy_arn=<policy_arn>
Limitations: none
Examples:
    AUTO: iam_user_attach_policy policy_arn=arn:aws:iam::aws:policy/AlexaForBusinessFullAccess
    AUTO: iam_user_attach_policy policy_arn=arn:aws:iam::621958466464:policy/sumo_collection
    AUTO: iam_user_attach_policy policy_arn=arn:aws:iam::$ACCOUNT_ID:policy/sumo_collection
'''

import boto3
from botocore.exceptions import ClientError

#Poll the account and check if the provided policy exists.
def check_for_policy(iam_client,policy_arn):
    found_policy = False
    try:
        #Check to see if the policy exists in the account currently
        get_policy_response = iam_client.get_policy(PolicyArn=policy_arn)

        if get_policy_response['ResponseMetadata']['HTTPStatusCode'] < 400:
            text_output =  "IAM policy exists in this account.\n"
            found_policy = True

    except ClientError as e:
        error = e.response['Error']['Code']
        if error == 'NoSuchEntity':
            text_output = "The policy %s does not exist. Please check and try again.\n" % policy_arn
        else:
            text_output = "Unexpected error: %s \n" % e

    return text_output,found_policy

#Create attach the policy to the group
def add_policy_to_user(iam_client,user,policy_arn):
    try:
        attach_policy_response = iam_client.attach_user_policy(
            UserName=user,
            PolicyArn=policy_arn
        )

        text_output = "Policy attached to user: \" %s \"\n" % user

    except ClientError as e:
            text_output = "Unexpected error: %s \n" % e

    return text_output

### Update user - core method
def run_action(boto_session,rule,entity,params):
    text_output = ""
    account_id = entity['accountNumber']
    user = entity['name']

    iam_client = boto_session.client('iam')

    # Get the policy_arn from the params
    usage = "Usage: AUTO: iam_user_attach_policy policy_arn=<policy_arn>\n Examples: \nAUTO: iam_user_attach_policy policy_arn=arn:aws:iam::aws:policy/AlexaForBusinessFullAccess\nAUTO: iam_user_attach_policy policy_arn=arn:aws:iam::621958466464:policy/sumo_collection\niam_user_attach_policy policy_arn=arn:aws:iam::$ACCOUNT_ID:policy/sumo_collection\n"
    if len(params) == 1:
        try:
            key_value = params[0].split("=")
            key = key_value[0]
            value = key_value[1]

            if key == "policy_arn":
                if "arn:aws:iam::aws:policy" in value:
                    policy_arn = value
                    text_output = text_output + "AWS Managed policy specified for attachment\nARN: %s \n" % value

                elif "$ACCOUNT_ID" in value:
                    # Look for "$ACCOUNT_ID" and replace it with the current account number
                    account_id = entity['accountNumber']
                    policy_arn = value.replace("$ACCOUNT_ID", account_id)
                    text_output = text_output + "Policy ARN that we're attaching to the user: %s \n" % policy_arn

                else:
                    policy_arn = value
                    text_output = text_output + "Policy ARN specified for attachment: %s \n" % value

            else:
                text_output = text_output + "Params don't match expected values. Exiting.\n" + usage
                return text_output

        except:
            text_output = text_output + "Params handling error. Please check params and try again.\n" + usage
            return text_output

    else:
        text_output = "Wrong amount of params inputs detected. Exiting.\n" + usage
        return text_output

    ## Check and add the policy to the user
    try:
        function_output, found_policy = check_for_policy(iam_client,policy_arn)
        text_output = text_output + function_output

        if found_policy:
            text_output = text_output + add_policy_to_user(iam_client,user,policy_arn)
        else:
            return text_output

    except ClientError as e:
        text_output = "Unexpected error: %s \n" % e

    return text_output


import numpy as np

from dnn.image import DilatedCNNExtractor
from data import fetch

import os, sys, random, glob

import IPython

from keras.preprocessing.image import ImageDataGenerator

import keras
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.layers import Input, Dense, Dropout, Activation, Flatten, Reshape
from keras.layers import Conv2D, MaxPooling2D, GlobalMaxPooling2D, UpSampling2D

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

import random

input_img = Input((128, 128, 3))
x = Conv2D(16, (3, 3), padding='same', activation='relu') (input_img)
x = Conv2D(16, (3, 3), padding='same', activation='relu') (x)
x = Dropout(rate=0.1) (x)
x = MaxPooling2D((2, 2)) (x)

x = Conv2D(32, (3, 3), padding='same', activation='relu') (x)
x = Conv2D(32, (3, 3), padding='same', activation='relu') (x)
x = Dropout(rate=0.1) (x)
x = MaxPooling2D((2, 2)) (x)

x = Conv2D(64, (3, 3), padding='same', activation='relu') (x)
x = Conv2D(64, (3, 3), padding='same', activation='relu') (x)
x = Dropout(rate=0.1) (x)
x = MaxPooling2D((2, 2)) (x)

x = Conv2D(128, (3, 3), padding='same', activation='relu') (x)
x = Conv2D(128, (3, 3), padding='same', activation='relu') (x)
x = Dropout(rate=0.1) (x)
x = MaxPooling2D((2, 2)) (x)

x = Conv2D(64, (3, 3), padding='same', activation='relu') (x)
x = Conv2D(32, (3, 3), padding='same', activation='relu') (x)
x = Dropout(rate=0.1) (x)
x = MaxPooling2D((2, 2)) (x)

x = Conv2D(32, (3, 3), padding='same', activation='relu') (x)
x = Conv2D(16, (3, 3), padding='same', activation='relu') (x)

x = Flatten() (x)

x = Dense(128, activation='sigmoid')(x)
x = Dense(1)(x)

model = Model(input_img, x)
model.compile(loss='mean_squared_error', optimizer='adadelta', metrics=['mape'])

model.summary()

augment = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=180,  # randomly rotate images in the range (degrees, 0 to 180)
        width_shift_range=0.15,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.15,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=True,  # randomly flip images
        vertical_flip=True)  # randomly flip images

def datagen():
    while True:
        for file_name in glob.glob("results/slides_cache*.npz"):
            slide_data = np.load(file_name)["data"].tolist()

            X = []
            Y = []

            for slide_info in slide_data:
                case = slide_info[1].get('case', None)
                if case is None: continue
                days_to_death = fetch.days_to_death(case)

                if days_to_death is None: continue
                if not days_to_death:
                    days_to_death = 3000
                days_to_death /= 3000.0
                days_to_death += 1.0

                X.append(slide_info[0])
                Y.append(days_to_death)

            X = np.concatenate(X)
            Y = np.array(Y)
            Y = np.repeat(Y, 24)

            print (X.shape, Y.shape)
            X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.1)

            aug = augment.flow(X, Y)

            for i, (x, y) in enumerate(aug):
                yield x, y
                if i == 120:
                    break

model.fit_generator(datagen(), samples_per_epoch=120, epochs=10)

IPython.embed()


#!/usr/bin/env python
#     Copyright 2013, Kay Hayen, mailto:kay.hayen@gmail.com
#
#     Part of "Nuitka", an optimizing Python compiler that is compatible and
#     integrates with CPython, but also works on its own.
#
#     Licensed under the Apache License, Version 2.0 (the "License");
#     you may not use this file except in compliance with the License.
#     You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#     Unless required by applicable law or agreed to in writing, software
#     distributed under the License is distributed on an "AS IS" BASIS,
#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#     See the License for the specific language governing permissions and
#     limitations under the License.
#

import os, subprocess

for document in ( "README.txt", "Developer_Manual.rst", "Changelog.rst" ):
    assert 0 == subprocess.call(
        "rst2pdf %(document)s" % {
            "document" : document
        },
        shell = True
    )

if not os.path.exists( "man" ):
    os.mkdir( "man" )

assert 0 == subprocess.call( "help2man -n 'the Python compiler' --no-discard-stderr --no-info --include doc/nuitka-man-include.txt ./bin/nuitka >doc/nuitka.1", shell = True )
assert 0 == subprocess.call( "help2man -n 'the Python compiler' --no-discard-stderr --no-info ./bin/nuitka-python >doc/nuitka-python.1", shell = True )

for manpage in ( "doc/nuitka.1", "doc/nuitka-python.1" ):
    manpage_contents = open( manpage ).readlines()
    new_contents = []
    mark = False

    for count, line in enumerate( manpage_contents ):
        if mark:
            line = ".SS " + line + ".BR\n"
            mark = False
        elif line == ".IP\n" and manpage_contents[ count + 1 ].endswith( ":\n" ):
            mark = True
            continue

        if line == r"\fB\-\-g\fR++\-only" + "\n":
            line = r"\fB\-\-g\++\-only\fR" + "\n"

        new_contents.append( line )

    open( manpage, "w" ).writelines( new_contents )

assert 0 == subprocess.call( "man2html doc/nuitka.1 >doc/man-nuitka.html", shell = True )
assert 0 == subprocess.call( "man2html doc/nuitka-python.1 >doc/man-nuitka-python.html", shell = True )

def getFile( filename ):
    return open( filename ).read()

contents = getFile( "doc/man-nuitka.html" )
new_contents = contents[ : contents.rfind( "
" ) ] + contents[ contents.rfind( "" ) : ]
assert new_contents != contents
contents = new_contents
new_contents = contents[ : contents.rfind( 'Index' ) ] + contents[ contents.rfind( '
' ) : ]
assert new_contents != contents
open( "doc/man-nuitka.html", "w" ).write( new_contents )

contents = getFile( "doc/man-nuitka-python.html" )
new_contents = contents[ : contents.rfind( "
" ) ] + contents[ contents.rfind( "" ) : ]
assert new_contents != contents
contents = new_contents
new_contents = contents[ : contents.rfind( 'Index' ) ] + contents[ contents.rfind( '
' ) : ]
assert new_contents != contents

open( "doc/man-nuitka-python.html", "w" ).write( new_contents )


#You are given an array (which will have a length of at least 3, but could be very large) containing integers.
# The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N.
# Write a method that takes the array as an argument and returns this "outlier" N.
#Examples
#[2, 4, 0, 100, 4, 11, 2602, 36]
#Should return: 11 (the only odd number)

#[160, 3, 1719, 19, 11, 13, -21]
#Should return: 160 (the only even number)

def find_outlier(integers1):
    only_odd = [num for num in integers1 if num % 2 == 1]
    only_even=[num for num in integers1 if num%2!=1]
    if len(only_odd)==1:
        return only_odd[0]
    else:
        return only_even[0]

print(find_outlier([160, 3, 1719, 19, 11, 13, -21]))


from flask import Flask, render_template, request, redirect
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
import time
import warnings
import os

app = Flask(__name__)

main_list = ['radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean', 'compactness_mean',
 'concavity_mean', 'concave points_mean', 'symmetry_mean', 'fractal_dimension_mean', 'radius_se',
 'perimeter_se', 'texture_se', 'area_se', 'smoothness_se', 'compactness_se', 'concavity_se', 'concave points_se',
 'symmetry_se', 'fractal_dimension_se', 'radius_worst', 'texture_worst', 'perimeter_worst', 'area_worst', 'smoothness_worst',
 'compactness_worst', 'concavity_worst', 'concave points_worst', 'symmetry_worst', 'fractal_dimension_worst']

def getContext(list_of_parameters, test_case = None):

	data = pd.read_csv('data.csv', index_col=False)
	#print(data)
	data['diagnosis'] = data['diagnosis'].apply(lambda x: '1' if x == 'M' else '0')
	data = data.set_index('id')
	#del data['Unnamed: 32']
	data = data.drop(list_of_parameters, axis=1)
	#print(data)

	my_path = os.path.dirname(__file__)
	#print(my_path)
	my_file = 'static/plot1.png'
	i_s =0
	data.plot(kind='density', subplots=True, layout=(5,7), sharex=False, legend=False,fontsize=1)
	if os.path.isfile(os.path.join(my_path, my_file)):
		print("Yes")
		os.remove(os.path.join(my_path, my_file))
		i_s = 1
		my_file = 'static/plot13.png'
	plt.savefig(os.path.join(my_path, my_file))

	from matplotlib import cm as cm
	fig = plt.figure()
	ax1 = fig.add_subplot(111)
	cmap = cm.get_cmap('jet', 30)
	cax = ax1.imshow(data.corr(), interpolation="none", cmap=cmap)
	ax1.grid(True)
	plt.title('Breast Cancer Attributes Correlation')
	# Add colorbar, make sure to specify tick locations to match desired ticklabels
	fig.colorbar(cax, ticks=[.75,.8,.85,.90,.95,1])
	my_file = 'static/plot2.png'
	if os.path.isfile(os.path.join(my_path, my_file)):
		print("Yes")
		os.remove(os.path.join(my_path, my_file))
		my_file = 'static/plot24.png'
	plt.savefig(os.path.join(my_path, my_file))

	Y = data['diagnosis'].values
	X = data.drop(['diagnosis'], axis=1).values
	#print(X)
	X_train, X_test, Y_train, Y_test = train_test_split (X, Y, test_size = 0.20, random_state=11)

	# prepare the model
	with warnings.catch_warnings(): warnings.simplefilter("ignore")
	scaler = StandardScaler().fit(X_train)
	X_train_scaled = scaler.transform(X_train)
	model = SVC(C=2.0, kernel='rbf')
	start = time.time()
	model.fit(X_train_scaled, Y_train)
	end = time.time()
	#print( "Run Time: %f" % (end-start))

	# estimate accuracy on test dataset
	with warnings.catch_warnings(): warnings.simplefilter("ignore")

	X_test_scaled = scaler.transform(X_test)
	predictions = model.predict(X_test_scaled)
	if test_case is not None:
		test_case_scaled = scaler.transform(test_case)
		p = model.predict(test_case_scaled)
		#print("+++++++++++"+p)
		if p == '1':
			#print("Malignant")
			p = "Malignant"
		else:
			#print("Benign")
			p = "Benign"
	else:
		p=0

	#print("Accuracy score %f" % accuracy_score(Y_test, predictions))
	accu = round(accuracy_score(Y_test, predictions),4)*100
	x= classification_report(Y_test, predictions, output_dict=True)
	precision_1 = x['0']['precision']
	recall_1 = x['0']['recall']
	f1_1 = round(x['0']['f1-score'],2)
	sc_1 = x['0']['support']

	precision_2 = x['1']['precision']
	recall_2 = x['1']['recall']
	f1_2 = round(x['1']['f1-score'],2)
	sc_2 = x['1']['support']

	y= confusion_matrix(Y_test, predictions)
	v_11 = y[0][0]
	v_10 = y[0][1]
	v_01 = y[1][0]
	v_00 = y[1][1]

	return {
	'precision_1':round(precision_1,3),
	'precision_2':round(precision_2,3),
	'recall_1':round(recall_1,3),
	'recall_2':round(recall_2,3),
	'f1_1':f1_1,
	'f1_2':f1_2,
	'sc_1':sc_1,
	'sc_2':sc_2,
	'accuracy':accu,
	'v_11':v_11,
	'v_10':v_10,
	'v_01':v_01,
	'v_00':v_00,
	'i_s':i_s,
	'p':p,
	}

@app.route('/index.html')
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/team.html')
def team():
    return render_template('team.html')

@app.route('/pulse.html')
def pulse():
    return render_template('pulse.html')

@app.route('/contact.html')
def contact():
    return render_template('contact.html')

@app.route('/files.html', methods=['POST'])
def files():
	z = request.form.getlist('options')
	y=[]
	for i in z:
		if request.form.get(i):
			y.append(float(request.form.get(i)))
	print(y)

	x = list(set(main_list) - set(z))
	#x.append('diagnosis')
	#print(x)
	print("length of z: ",len(z))
	print("length of y: ",len(y))
	if len(y) != 0:
		if len(y) == len(z):
			print("++++++++++1")
			context = getContext(x,[y])
		else:
			print("++++++++++2")
			return redirect('pulse.html')
	else:
		print("++++++++++3")
		context = getContext(x)
	return render_template('files.html', context=context)

@app.after_request
def add_header(response):
    # response.cache_control.no_store = True
    response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '-1'
    return response

if __name__ == "__main__":
	app.static_folder = 'static'
	app.config["CACHE_TYPE"] = "null"
	app.run()


# -*- coding: utf-8 -*-
from setuptools import find_packages, setup

with open("README.md") as f:
    readme = f.read()

with open("LICENSE") as f:
    license = f.read()

setup(
    name="maodevice",
    version="1.0",
    description="Python 3.7 package to control MAO devices",
    long_description=readme,
    author="Project MAO Contributors",
    author_email="tueda1207@gmail.com",
    url="https://github.com/mao-wfs/maodevice",
    license=license,
    packages=find_packages(exclude=("docs", "tests")),
    install_requires=["pyserial>=3.4"],
)