"""
Generic interchange document structures.
"""

STYLE_TYPE_INT = 'int'
STYLE_TYPE_FLOAT = 'float'
STYLE_TYPE_CDATA = 'cdata'
STYLE_TYPE_BOOLEAN = 'boolean'
STYLE_TYPES = (
    STYLE_TYPE_INT,
    STYLE_TYPE_FLOAT,
    STYLE_TYPE_CDATA,
    STYLE_TYPE_BOOLEAN
)

class Style(object):
    def __init__(self, types):
        object.__init__(self)
        self.name = None
        self.source = None
        self.__settings = {}
        self.__types = types
        for key, val in types.items():
            assert (isinstance(key, str)
                ), "key '{0}' not string".format(key)
            if isinstance(val, str):
                assert (val in STYLE_TYPES
                    ), "key '{0}' type '{1}' not valid".format(key, val)
            else:
                assert (hasattr(val, '__iter__') and callable(getattr(val, '__iter__'))
                    ), "key '{0}' type '{1}' not list".format(key, val)
                # FIXME Assert entries in type are strings

    def get_setting(self, name):
        if name in self.__settings:
            return self.__settings[name]
        if name in self.__types:
            return None
        raise Exception("bad setting name: {0}".format(str(name)))

    def set_setting(self, name, value):
        if name in self.__types:
            t = self.__types[name]
            if t == STYLE_TYPE_INT:
                value = int(value)
            elif t == STYLE_TYPE_FLOAT:
                value = float(value)
            elif t == STYLE_TYPE_CDATA:
                value = str(value)
            elif t == STYLE_TYPE_BOOLEAN:
                value = bool(value)
            else:
                value = str(value).lower()
                if value not in t:
                    raise Exception("Bad setting value for name {0}: {1}".format(
                        str(name), value))
            self.__settings[name] = value
        raise Exception("bad setting name: {0}".format(str(name)))

    def defaults(self, default_settings):
        for key, val in default_settings.iteritems():
            self.set_setting(key, val)

    def keys(self):
        return self.__types.keys()

    def __getitem__(self, key):
        return self.get_setting(key)

    def __setitem__(self, name, value):
        self.set_setting(name, value)

    def __str__(self):
        return "Style({0}: {1})".format(self.name, self.__settings)

class BlockStyle(Style):
    def __init__(self):
        # All size measurements in mm
        Style.__init__(self, {
            'margin-left': STYLE_TYPE_FLOAT,
            'margin-right': STYLE_TYPE_FLOAT,
            'margin-top': STYLE_TYPE_FLOAT,
            'margin-bottom': STYLE_TYPE_FLOAT,
            'page-break': STYLE_TYPE_BOOLEAN,
            'h-align': ["center", "left", "right", "justify"],
            'border-left-width': STYLE_TYPE_INT,
            'border-right-width': STYLE_TYPE_INT,
            'border-top-width': STYLE_TYPE_INT,
            'border-bottom-width': STYLE_TYPE_INT
        })

class TextStyle(Style):
    def __init__(self):
        Style.__init__(self, {
            'italic': STYLE_TYPE_BOOLEAN,
            'bold': STYLE_TYPE_BOOLEAN,
            'underline': STYLE_TYPE_BOOLEAN,
            'strikethrough': STYLE_TYPE_BOOLEAN,
            'all-caps': STYLE_TYPE_BOOLEAN,
            'small-caps': STYLE_TYPE_BOOLEAN,
            'v-align': ['sup', 'sub', 'normal'],
            'size': STYLE_TYPE_INT,
            'font': ['sans', 'serif', 'mono', 'normal'],
            'color': STYLE_TYPE_CDATA,
            'background-color': STYLE_TYPE_CDATA
        })

class ContentObj(object):
    def __init__(self):
        object.__init__(self)
        self.source = None

    def get_text(self):
        raise NotImplementedError()

class Div(ContentObj):
    """A block spacing object."""
    def __init__(self):
        ContentObj.__init__(self)
        self.style = BlockStyle()
        self.is_section = False

    def get_children(self):
        raise NotImplementedError()

    def get_text(self):
        ret = ""
        for ch in self.get_children():
            ret += ch.get_text()
        return ret

class SideBar(Div):
    """A side section of content."""
    def __init__(self):
        Div.__init__(self)
        self.divs = []

    def get_children(self):
        return self.divs

class SeparatorLine(Div):
    """A single line separating parts of a chapter."""
    def __init__(self):
        Div.__init__(self)

    def get_children(self):
        return []

class Para(Div):
    def __init__(self):
        Div.__init__(self)
        self.spans = []

    def add_span(self, span):
        assert isinstance(span, Span), "not a span: {0}".format(span)
        self.spans.append(span)

    def get_children(self):
        return self.spans

    def __str__(self):
        spanstxt = u"["
        visited = False
        for spn in self.spans:
            if visited:
                spanstxt += u", "
            else:
                visited = True
            spanstxt += repr(spn)
        spanstxt += u"]"
        return u"Para(Style: {0}; spans: {1})".format(
            self.style, spanstxt)

class TableRow(Div):
    def __init__(self):
        Div.__init__(self)
        self.cells = []

    def add_cell(self, cell):
        assert isinstance(cell, Div)
        self.cells.append(cell)

    def get_children(self):
        return self.cells

class Table(Div):
    def __init__(self):
        Div.__init__(self)
        self.header = None
        self.rows = []

    def set_header(self, header):
        assert header is None or isinstance(header, TableRow)
        self.header = header

    def add_row(self, row):
        assert isinstance(row, TableRow)
        self.rows.append(row)

    def get_children(self):
        ret = [self.header]
        ret.extend(self.rows)
        return ret

class Span(ContentObj):
    """A inline object.  Contained in a Div"""
    def __init__(self):
        ContentObj.__init__(self)
        self.style = TextStyle()

    def get_text(self):
        return ""

class Text(Span):
    def __init__(self):
        Span.__init__(self)
        self.text = ""

    def get_text(self):
        return self.text

    def __str__(self):
        return u"Text(Style: {0}, text: '{1}')".format(
            self.style, self.text)

class SpecialCharacter(Text):
    def __init__(self):
        Text.__init__(self)
        self.html = ""
        self.is_whitespace = False

class Correction(Span):
    def __init__(self, original):
        Span.__init__(self)
        self.original = original
        self.text = ""

class Media(Span):
    def __init__(self, filename):
        Span.__init__(self)
        assert filename.find('.') >= 0
        self.filename = filename
        self.ext = filename[filename.rindex('.')+1:]

    def get_mimetype(self):
        raise NotImplementedError()

    def save_as(self, dest_stream):
        raise NotImplementedError()

class Image(Media):
    def __init__(self, filename):
        Media.__init__(self, filename)
        assert filename.find('.') >= 0
        self.filename = filename
        self.ext = filename[filename.rindex('.')+1:]

    def get_mimetype(self):
        return "image/{0}".format(self.ext)

    def save_as(self, dest_stream):
        raise NotImplementedError()

class Section(Div):
    def __init__(self, index):
        Div.__init__(self)
        self.is_section = True
        self.index = index
        self.is_toc = False
        self.is_book = False

    def get_children(self):
        raise NotImplementedError()

class Chapter(Section):
    def __init__(self, name, index):
        Section.__init__(self, index)
        self.name = name
        self.divs = []

    def add_div(self, div):
        assert isinstance(div, Div)
        self.divs.append(div)

    def get_children(self):
        return self.divs

class TOC(Section):
    def __init__(self, index, depth_index_func):
        Section.__init__(self, index)
        self.is_toc = True
        self.title_div = None
        if depth_index_func is not None:
            assert callable(depth_index_func)
        self.depth_index_func = depth_index_func

        # Should be a list of block styles,
        # one per depth of the TOC
        self.line_div_styles = []

        # A list of nodes
        self.section_tree = []

    def get_children(self):
        ret = []
        if self.title_div is not None:
            ret.append(self.title_div)

        ret.extend(self.section_tree)

        return ret

    def set_chapters(self, chapters):
        self.section_tree = self.__chapter_builder(chapters, 0)

    def __chapter_builder(self, sections, depth):
        order = []
        index = 0
        for ch in sections:
            if isinstance(ch, Chapter):
                index += 1
                order.append(self.__create_entry(ch, depth, index))
                kids = self.__chapter_builder(ch.get_children(), depth + 1)
                if len(kids) > 0:
                    order.extend(kids)
        return order

    def __create_entry(self, ch, depth, index):
        assert isinstance(ch, Chapter)
        prefix = None
        if self.depth_index_func is not None:
            prefix = self.depth_index_func(depth, index)
        d = TocRow(ch, depth, index, prefix)
        if depth > len(self.line_div_styles):
            d.style = self.line_div_styles[-1]
        else:
            d.style = self.line_div_styles[depth]
        return d

class TocRow(Div):
    def __init__(self, chapter, depth, index, prefix):
        Div.__init__(self)
        self.name = chapter.name
        self.prefix = prefix or ""
        self.depth = depth
        self.index = index

        self.text = Text()
        self.text.text = self.prefix + self.name

    def get_children(self):
        return [self.text]

class MetaData(object):
    def __init__(self):
        object.__init__(self)
        self.author_first = ""  # (includes middle name / initial)
        self.author_last = ""
        self.year = ""
        self.cover = None  # Image
        self.title = ""
        self.description = ""
        self.isbn_10 = ""
        self.isbn_13 = ""
        self.language = "en"
        self.subtitles = []

    def set_cover(self, cover):
        assert isinstance(cover, Image)
        self.cover = cover

    def as_dict(self):
        return {
            "author_first": self.author_first,
            "author_last": self.author_last,
            "year": self.year,
            "title": self.title,
            "description": self.description,
            "isbn_10": self.isbn_10,
            "isbn_13": self.isbn_13,
            "language": self.language,
            "subtitles": self.subtitles
        }


import risar
import math
import random
from PyQt5.QtWidgets import QMessageBox

class Ball:
    def __init__(self, color):
        self.x, self.y = risar.nakljucne_koordinate()
        self.speed_x = random.randrange(-5, 5)
        self.speed_y = math.sqrt((5 * 5) - self.speed_x * self.speed_x)
        self.color = color
        self.width = 10
        self.krog = risar.krog(self.x, self.y, self.width, self.color, 2)
        self.exploded = False
        self.time = 4
        self.dead = False

    def set_pos(self, x, y):
        self.x = x
        self.y = y
        self.krog.setPos(x, y)

    def set_width(self, width):
        self.width = width
        self.krog.setRect(-width, -width, width * 2, width * 2)

    def set_color(self, r, g, b):
        self.krog.setBorder(risar.barva(r, g, b))

    def explode(self, exploading):
        if not self.exploded:
            self.exploded = True
            self.set_width(30)
            c = self.krog.pen().color().lighter()
            c.setAlpha(192)
            self.krog.setBrush(c)
            exploading.append(self)

    def update(self, time, exploading, dead):
        if self.dead:
            return

        if self.exploded:
            self.time -= time
            if self.time < 0:
                self.krog.hide()
                self.dead = True
                dead[0] += 1
                exploading.remove(self)
        else:
            self.x += self.speed_x
            self.y += self.speed_y

            if self.x - self.width < 0:
                self.speed_x *= -1
                self.x = self.width
            if self.x + self.width > risar.maxX-1:
                self.speed_x *= -1
                self.x = risar.maxX-1 - self.width
            if self.y - self.width < 0:
                self.speed_y *= -1
                self.y = self.width
            if self.y + self.width > risar.maxY-1:
                self.speed_y *= -1
                self.y = risar.maxY-1 - self.width

            self.set_pos(self.x, self.y)

    def collide(self, ball):
        if self.dead or ball.dead:
            return False

        d_x = self.x - ball.x
        d_y = self.y - ball.y
        d = math.sqrt(pow(d_x, 2) + pow(d_y, 2))
        if d < self.width + ball.width:
            return True
        else:
            return False

tick = 0.02

exploding = []
zoge = []
for i in range(30):
    zoge.append(Ball(risar.nakljucna_barva()))

cursor = Ball(risar.barva(255, 255, 255))
cursor.set_width(30)
stopped = False

running = True
dead = [0]
while running:
    for zoga in zoge:
        zoga.update(tick, exploding, dead)

    if risar.klik:
        stopped = True
        cursor.explode(exploding)
        risar.klik = False

    if stopped:
        cursor.update(tick, exploding, dead)
        if len(exploding) > 0:
            for e in exploding:
                for zoga in zoge:
                    if zoga.collide(e):
                        zoga.explode(exploding)
        else:
            QMessageBox.information(None, "Konec", "Uničenih " + str(dead[0]) + " od 30")
            running = False
            break
    else:
        mouse_pos = risar.miska
        cursor.set_pos(mouse_pos[0], mouse_pos[1])

    risar.obnovi()
    risar.cakaj(tick)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File Name:    偏微分方程模拟扩散.py
Author:       Liheng-Chan
Email:        202111081084@mail.bnu.edu.cn
Time:         2023/5/21
"""

import matplotlib.pyplot as plt
import numpy as np
import random
from PIL import Image

def my_laplacian(In):
    Out = -1.0 * In + 0.20*(np.roll(In,1,axis=1)+np.roll(In,-1,axis=1)+np.roll(In,1,axis=0)+np.roll(In,-1,axis=0) ) + \
          0.05*(np.roll(np.roll(In,1,axis=0),1,axis=1)+np.roll(np.roll(In,-1,axis=0),1,axis=1)+np.roll(np.roll(In,1,axis=0),-1,axis=1)+np.roll(np.roll(In,-1,axis=0),-1,axis=1))
    return Out

def load_image(file_path, width):
    image = Image.open(file_path).convert("L")  # Convert to grayscale
    image = image.resize((width, width), Image.ANTIALIAS)
    image_array = np.array(image, dtype=float) / 255.0
    return image_array

if __name__=="__main__":
    f = 0.055       #进料率
    k = 0.062       #去除率
    da = 1.0          #U的扩散率
    db = 0.5        #V的扩散率
    width = 128     #网格大小
    dt = 0.25       #每进行一需要0.25秒
    stoptime = 100.0 #自定义模拟时间

    image_file = "C:/image/image6.png"  # Replace with your image file path

    B = load_image(image_file, width)
    A = np.ones((width, width), dtype=float)
    t = 0

    nframes = 1

    while t < stoptime:
        anew = A + (da*my_laplacian(A) - A*(B*B) + f*(1-A))*dt
        bnew = B + (db*my_laplacian(B) + A*(B*B) - (k+f)*B)*dt

        A = anew
        B = bnew
        t += dt
        nframes += 1

    fig, ax0 = plt.subplots()
    f = ax0.pcolor(B)
    fig.colorbar(f, ax=ax0)

    plt.show()

偏微分方程模拟扩散final.py


from pyb import Pin
from time import sleep_ms, sleep_us

D1 = Pin(5, Pin.OUT)
D2 = Pin(4, Pin.OUT)
D3 = Pin(0, Pin.OUT)
D4 = Pin(2, Pin.OUT)

#steps of revolution = 4096, 8*512
seq = [[0,0,0,1],
       [0,0,1,1],
       [0,0,1,0],
       [0,1,1,0],
       [0,1,0,0],
       [1,1,0,0],
       [1,0,0,0],
       [1,0,0,1]]

def rotate(RPM, angle):
    if(RPM > 20):
        print("RPM should less than 20")
        return
    delay = int(60*1000*1000/4096/RPM)
    steps = int(512*abs(angle)/360)
    if angle < 0:
        direction = -1
    else:
        direction = 1
    for i in range(steps):
        for step in seq[::direction]:
            set_step(step)
            sleep_us(delay)

def set_step(step):
    D1.value(int(step[0]))
    D2.value(int(step[1]))
    D3.value(int(step[2]))
    D4.value(int(step[3]))

for i in range(1):
    rotate(20, 360)

#


from collections import deque

N, M = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    G[a - 1].append(b - 1)
    G[b - 1].append(a - 1)

dist = [None] * N
q = deque()
q.append(0)
dist[0] = 0
vs = []
while len(q) > 0:
    v = q.popleft()
    vs.append(v)
    for u in G[v]:
        if dist[u] is not None:
            continue
        dist[u] = dist[v] + 1
        q.append(u)

dp = [0] * N
dp[0] = 1
for v in vs:
    for u in G[v]:
        if dist[u] == dist[v] + 1:
            dp[u] += dp[v]
print(dp[N - 1] % (10**9 + 7))


class Solution:
    def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:
        count = [1]*n
        res = [0]*n
        trees = collections.defaultdict(set)
        for i,j in edges:
            trees[i].add(j)
            trees[j].add(i)
        def dfs(root, pre):
            for i in trees[root]:
                if i!=pre:
                    dfs(i, root)
                    count[root] += count[i]
                    res[root] += res[i] + count[i]
        def dfs2(root, pre):
            for i in trees[root]:
                if i!=pre:
                    res[i] = res[root] - count[i] + n - count[i]
                    dfs2(i, root)
        dfs(0,-1)
        dfs2(0,-1)
        return res


from collections import defaultdict

class Polynomials:
    def __init__(self, equation):
        self.coefs = defaultdict(float)
        parsed_equation = self.parse_equation(equation)
        for exp, coef in parsed_equation.items():
            self.coefs[exp] += coef

    def parse_equation(self, equation):
        equation = equation.replace(' ', '')
        terms = equation.split('+')
        coefs = defaultdict(float)
        for term in terms:
            if '-' in term:
                subterms = term.split('-')
                for subterm in subterms:
                    if subterm:
                        coef, exp = subterm.split('x^')
                        coefs[int(exp)] += float(coef)
            else:
                if term:
                    coef, exp = term.split('x^')
                    coefs[int(exp)] += float(coef)
        return coefs

    def add_term(self, term, sign):
        if not term:
            coef = 0
            exp = 0
        elif "x" not in term:
            coef = float(term) * sign
            exp = 0
        else:
            if 'x^' in term:
                term = term.replace("x^", "")
                exp = int(term)
                coef = sign
            elif 'x' in term:
                if term == 'x':
                    coef = 1
                    exp = 1
                elif term == '-x':
                    coef = -1
                    exp = 1
                else:
                    if 'x' in term:
                        coef = float(term.split('x')[0])
                        exp = 1
                    else:
                        coef = float(term)
                        exp = 0
        if exp in self.coefs:
            self.coefs[exp] += coef
        else:
            if coef==1:
                self.coefs[exp] = 1
            elif coef==-1:
                self.coefs[exp] = -1
            else:
                self.coefs[exp] = coef

    # a function to add two polynomials

    def __add__(self, other):
        new_coefs = defaultdict(float)
        for exp, coef in self.coefs.items():
            new_coefs[exp] += coef
        for exp, coef in other.coefs.items():
            new_coefs[exp] += coef
        return Polynomials(new_coefs)

    def __sub__(self, other):
        result = Polynomials("")
        result.coefs = self.coefs.copy()
        for exp, coef in other.coefs.items():
            if exp in result.coefs:
                result.coefs[exp] -= coef
            else:
                result.coefs[exp] = -coef
        return result

    def __mul__(self, other):
        result = Polynomials("")
        for exp1, coef1 in self.coefs.items():
            for exp2, coef2 in other.coefs.items():
                new_exp = exp1 + exp2
                new_coef = coef1 * coef2
                if new_exp in result.coefs:
                    result.coefs[new_exp] += new_coef
                else:
                    result.coefs[new_exp] = new_coef
        return result

    def __str__(self):
        polynomial = ''
        for exp, coef in sorted(self.coefs.items(), key=lambda x: x[0], reverse=True):
            if coef==0:
                continue
            if exp == 0:
                if coef == 1:
                    polynomial += '+1'
                elif coef == -1:
                    polynomial += '-1'
                else:
                    polynomial += f'{coef}'
            elif exp == 1:
                if coef == 1:
                    polynomial += '+x'
                elif coef == -1:
                    polynomial += '-x'
                elif coef > 0:
                    polynomial += f'+{coef}x'
                else:
                    polynomial += f'{coef}x'
            else:
                if coef == 1:
                    polynomial += f'+x^{exp}'
                elif coef == -1:
                    polynomial += f'-x^{exp}'
                elif coef > 0:
                    polynomial += f'+{coef}x^{exp}'
                else:
                    polynomial += f'{coef}x^{exp}'
        return polynomial

    def derivative(self):
        result = Polynomials("")
        for exp, coef in self.coefs.items():
            if exp != 0:
                new_exp = exp - 1
                new_coef = coef * exp
                result.coefs[new_exp] = new_coef
        return result

    def integral(self):
        result = Polynomials("")
        for exp, coef in self.coefs.items():
            new_exp = exp + 1
            new_coef = coef / (new_exp)
            result.coefs[new_exp] = new_coef
        return result


from tkinter import  *

def on_clik():
    print(chk1.get(), chk2.get(), chk3.get())

root = Tk()
root.option_add("*font" , "impact 30")
chk1 = BooleanVar()
chk2 = BooleanVar()
chk3 = BooleanVar()
Label(root , text = "You Interest" ,bg = "gold").pack()
Checkbutton(root, text = "music" , variable = chk1).pack(anchor = W)
Checkbutton(root, text = "Book" , variable = chk2).pack(anchor = W)
Checkbutton(root, text = "Movie" , variable = chk3).pack(anchor = W)
Button(root , text = "submit" , command = on_clik).pack()

root.mainloop()


import random

bokstavar = ["a","b","c","d"]

class Bokstav:
    def __init__ (self, bokstav):
        self.bokstav = bokstav
    def printInfo (self):
        print(self.bokstav)
    def fao_bokstav (self):
        return self.bokstav

liste = []
checkList = set()

while len(liste) <= 3:
    liste.append(Bokstav(bokstavar[random.randint(0,3)]))
    if liste[-1].fao_bokstav() in checkList:
        print("Fins frå før")
        liste.pop(-1)
    checkList.add(liste[-1].fao_bokstav())

for objekt in liste:
   objekt.printInfo()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 19:34:02 2019

@author: jimmy
"""

def read_data():
    train = pd.read_csv('data/jinnan_round1_train_20181227.csv', encoding = 'gb18030').\
rename({'样本id':'id','收率':'target'},axis=1).pipe(filter_outlier)
    test = pd.read_csv('data/FuSai.csv', encoding = 'gb18030').\
        rename({'样本id':'id','收率':'target'},axis=1)
    optimize = pd.read_csv('data/optimize.csv', encoding = 'gb18030').\
        rename({'样本id':'id','收率':'target'},axis=1)

    testA = pd.read_csv('data/jinnan_round1_testA_20181227.csv', encoding = 'gb18030').\
        rename({'样本id':'id','收率':'target'},axis=1)
    testB = pd.read_csv('data/jinnan_round1_testB_20190121.csv', encoding = 'gb18030').\
        rename({'样本id':'id','收率':'target'},axis=1)
    testC = pd.read_csv('data/jinnan_round1_test_20190201.csv', encoding = 'gb18030').\
        rename({'样本id':'id','收率':'target'},axis=1)

    ansA = pd.read_csv('data/jinnan_round1_ansA_20190125.csv', encoding = 'gb18030',header=None).\
        rename({0:'id',1:'target'},axis=1)
    ansB = pd.read_csv('data/jinnan_round1_ansB_20190125.csv', encoding = 'gb18030',header=None).\
        rename({0:'id',1:'target'},axis=1)
    ansC = pd.read_csv('data/jinnan_round1_ans_20190201.csv', encoding = 'gb18030',header=None).\
        rename({0:'id',1:'target'},axis=1)
    unique1_map,unique2_map,unique3_map = get_maps(train)

    A = pd.merge(testA,ansA,on='id',how='left').pipe(filter_outlier)
    B = pd.merge(testB,ansB,on='id',how='left').pipe(filter_outlier)
    C = pd.merge(testC,ansC,on='id',how='left').pipe(filter_outlier)

    train_data = pd.concat([train,A,B,C],axis=0,ignore_index=True)
    test_data = test

    return train_data,test_data,optimize


from openprocurement.api.validation import validate_cpv_group
from schematics.exceptions import ValidationError
from openprocurement.api.utils import get_now
from openprocurement.tender.core.constants import CPV_ITEMS_CLASS_FROM

class TenderCPVItemsValidate(object):
    def __init__(self, tender):
        self.context = tender

    def __call__(self, cls, data, items):
        cpv_336_group = items[0].classification.id[:3] == "336" if items else False
        if (
            not cpv_336_group
            and (data.get("revisions")[0].date if data.get("revisions") else get_now()) > CPV_ITEMS_CLASS_FROM
            and items
            and len(set([i.classification.id[:4] for i in items])) != 1
        ):
            raise ValidationError(u"CPV class of items should be identical")
        else:
            validate_cpv_group(items)


from matplotlib.figure import Figure
import numpy as np
import pickle
import matplotlib
import matplotlib.pyplot as plt
import string
import random

def compare_plot(x1: np.ndarray, y1: np.ndarray, x2: np.ndarray, y2: np.ndarray,
                 xlabel: str, ylabel: str, title: str, label1: str, label2: str) -> Figure:
    """Funkcja służąca do porównywania dwóch wykresów typu plot.
    Szczegółowy opis w zadaniu 3.

    Parameters:
    x1(np.ndarray): wektor wartości osi x dla pierwszego wykresu,
    y1(np.ndarray): wektor wartości osi y dla pierwszego wykresu,
    x2(np.ndarray): wektor wartości osi x dla drugiego wykresu,
    y2(np.ndarray): wektor wartości osi x dla drugiego wykresu,
    xlabel(str): opis osi x,
    ylabel(str): opis osi y,
    title(str): tytuł wykresu ,
    label1(str): nazwa serii z pierwszego wykresu,
    label2(str): nazwa serii z drugiego wykresu.

    Returns:
    matplotlib.pyplot.figure: wykres zbiorów (x1,y1), (x2,y2) zgody z opisem z zadania 3
    """
    try:
        if (x1.shape != y1.shape or min(x1.shape) == 0 or x2.shape != y2.shape or min(x2.shape) == 0):
                return None
        fig , ax = plt.subplots()
        ax.plot(x1,y1,'b',label = label1, linewidth = 4)
        ax.plot(x2,y2,'r',label = label2, linewidth = 2)
        ax.legend()
        ax.set( xlabel = xlabel , ylabel = ylabel, title = title ,)
        # fig.show()
        return fig
    except:
        return None

def parallel_plot(x1:np.ndarray,y1:np.ndarray,x2:np.ndarray,y2:np.ndarray,
                  x1label:str,y1label:str,x2label:str,y2label:str,title:str,orientation:str):
    """Funkcja służąca do stworzenia dwóch wykresów typu plot w konwencji subplot wertykalnie lub chorycontalnie.
    Szczegółowy opis w zadaniu 5.

    Parameters:
    x1(np.ndarray): wektor wartości osi x dla pierwszego wykresu,
    y1(np.ndarray): wektor wartości osi y dla pierwszego wykresu,
    x2(np.ndarray): wektor wartości osi x dla drugiego wykresu,
    y2(np.ndarray): wektor wartości osi x dla drugiego wykresu,
    x1label(str): opis osi x dla pierwszego wykresu,
    y1label(str): opis osi y dla pierwszego wykresu,
    x2label(str): opis osi x dla drugiego wykresu,
    y2label(str): opis osi y dla drugiego wykresu,
    title(str): tytuł wykresu,
    orientation(str): parametr przyjmujący wartość '-' jeżeli subplot ma posiadać dwa wiersze albo '|' jeżeli ma posiadać dwie kolumny.

    Returns:
    matplotlib.pyplot.figure: wykres zbiorów (x1,y1), (x2,y2) zgody z opisem z zadania 5
    """
    try:
        if (x1.shape != y1.shape or  min(x1.shape)==0 or x2.shape != y2.shape or  min(x2.shape)==0 or (orientation not in ['|','-'])):
            return None
        subplot_arg : str = "21" if orientation == '|' else "12"
        fig : Figure
        if orientation == '|' :
            fig = plt.figure(figsize=(8,24))
        else:
            fig = plt.figure(figsize=(24,8))

        ax1 = plt.subplot(int(subplot_arg + "1"))
        ax1.plot(x1,y1)
        ax1.set(xlabel = x1label, ylabel=y1label)
        ax2 = plt.subplot(int(subplot_arg + "2"))
        ax2.plot(x2 , y2)
        ax2.set(xlabel = x2label , ylabel = y2label)
        fig.suptitle(title , fontsize = 32)
        # fig.show()

    except:
        return None

def log_plot(x:np.ndarray,y:np.ndarray,xlabel:np.ndarray,ylabel:str,title:str,log_axis:str):
    """Funkcja służąca do tworzenia wykresów ze skalami logarytmicznymi.
    Szczegółowy opis w zadaniu 7.

    Parameters:
    x(np.ndarray): wektor wartości osi x,
    y(np.ndarray): wektor wartości osi y,
    xlabel(str): opis osi x,
    ylabel(str): opis osi y,
    title(str): tytuł wykresu ,
    log_axis(str): wartość oznacza:
        - 'x' oznacza skale logarytmiczną na osi x,
        - 'y' oznacza skale logarytmiczną na osi y,
        - 'xy' oznacza skale logarytmiczną na obu osiach.

    Returns:
    matplotlib.pyplot.figure: wykres zbiorów (x,y) zgody z opisem z zadania 7
    """
    try:
        if (x.shape != y.shape or  min(x.shape)==0 or (log_axis not in ['x','y','xy'])):
            return None
        fig , ax = plt.subplots()
        if log_axis == 'x' :
            ax.set(xscale = "log")
        elif log_axis == 'y':
            ax.set(yscale = "log")
        else:
            ax.set(xscale = "log" , yscale = "log")

        ax.plot(x,y)
        ax.set(xlabel = xlabel, ylabel=ylabel)
        ax.set_title(title)
        # fig.show()
    except:
        return None


import matplotlib.pyplot as plt
import pickle
import click
import os.path
import math

@click.command()
@click.argument('in-file')
@click.argument('out-dir')
def main(in_file, out_dir):
    with open(in_file, 'rb') as f:
        images = pickle.load(f)

    print("Writing {} images to disk.".format(len(images)))

    num_digits = int(math.log(len(images), 10)) + 1
    for n, image in enumerate(images[::100]):
        fig = plt.figure()

        for i in range(16):
            fig.add_subplot(4, 4, i + 1)
            plt.imshow(image[i], cmap='gray')

        plt.savefig(os.path.join(out_dir, "fig_{:0{}}.png".format(n, num_digits)))

if __name__ == '__main__':
    main()


# Yuchen Shi
# ITP 115, Spring 2018
# Assignment A9
# yuchensh@usc.edu

class Animal(object):
    def __init__(self, hungerValue, happinessValue, healthValue, energyValue, ageValue, nameValue, speciesValue):
        self.hunger=hungerValue
        self.happiness=happinessValue
        self.health=healthValue
        self.energy=energyValue
        self.age=ageValue
        self.name=nameValue
        self.species=speciesValue

    def play(self):
        if self.happiness>90:
            self.happiness=100
        else:
            self.happiness = self.happiness+10

        if self.hunger>95:
            self.hunger=100
        else:
            self.hunger = self.hunger+5

    def feed(self):
        if self.hunger<10:
            self.hunger=0
        else:
            self.hunger = self.hunger-10

    def giveMedicine(self):
        if self.happiness<20:
            self.happiness=0
        else:
            self.happiness=self.happiness-20
        if self.health>80:
            self.health=100
        else:
            self.health=self.health+20

    def sleep(self):
        if self.energy>80:
            self.energy=100
        else:
            self.energy=self.energy+20

        self.age=self.age+1

    def __str__(self):
        msg = "Name: " + self.name + " the " + self.species
        msg += "\nHealth: " + str(self.health)
        msg += "\nHappiness: " + str(self.happiness)
        msg += "\nHunger: " + str(self.hunger)
        msg += "\nEnergy: " + str(self.energy)
        msg += "\nAge: " + str(self.age)
        return msg

def loadAnimals(fileName):
    animalList=[]
    fileIn=open(fileName, "r")
    for line in fileIn:
        line=line.strip()
        delimiter=","
        dataList=line.split(delimiter)
        hungerValue=int(dataList[0])
        happinessValue=int(dataList[1])
        healthValue=int(dataList[2])
        energyValue=int(dataList[3])
        ageValue=int(dataList[4])
        nameValue=dataList[5]
        speciesValue=dataList[6]
        animal=Animal(hungerValue, happinessValue, healthValue, energyValue, ageValue, nameValue, speciesValue)
        animalList.append(animal)

    return animalList

def displayMenu():
    print("\n1) Play\n2) Feed\n3) Give Medicine\n4) Sleep\n5) Print an Animal's stats\n6) View All Animals\n7) Exit\n")

def selectAnimal(animalList):
    print("1) Ollie the Bunny\n2) Murdock the French Bulldog\n3) Socks the Cat\n4) Peewee the Turtle\n5) Milo the Labrador\n")
    selection=int(input("Please select an animal from the list (enter the 1-5): "))
    while selection not in [1, 2, 3, 4, 5]:
        selection=int(input("Invalid input, please try again!\n\nPlease select an animal from thew list (enter the 1-5): "))
    return animalList[selection-1]

def main():
    animalList=loadAnimals("animals.csv")
    print("Welcome to the Animal Daycare! Here is what we can do:")
    selection=1
    while selection !=7:
        displayMenu()
        selection=int(input("Please make a selection: "))
        while selection not in [1, 2, 3, 4, 5, 6, 7]:
            print("*Invalid selection, please try again.")
            displayMenu()
            selection=int(input("Please make a selection: "))
        if selection == 6:
            for animal in animalList:
                print(animal)
                print("********************************")
        elif selection == 1:
            animal=selectAnimal(animalList)
            animal.play()
            print("You played with " + animal.name + " the " + animal.species + "!")
        elif selection == 2:
            animal=selectAnimal(animalList)
            animal.feed()
            print("You fed " + animal.name + " the " + animal.species + "!")
        elif selection == 3:
            animal=selectAnimal(animalList)
            animal.giveMedicine()
            print("You gave " + animal.name + " the " + animal.species + " some medicine!")
        elif selection == 4:
            animal=selectAnimal(animalList)
            animal.sleep()
            print(animal.name + " the "+ animal.species + " took a nap!")
        elif selection == 5:
            animal=selectAnimal(animalList)
            print(animal)
            print("********************************")
    print("Goodbye!")

main()


from itertools import count

f = open("mbox-short.txt")
emaildic = dict()
bigNum = 0
bigEmail = None

#open the text file and read each line starting with 'From'
for lines in f:
    if lines.startswith('From '):
        #take the 2nd WORD from each line and save as variable email
        #split each line by spacing to seperate out the words, if not, [1] will specify the 'r' in 'From'
        email = lines.split()[1]
        #assign the value of emaildic[] to either email:0+1 or email:x+1
        emaildic[email] = emaildic.get(email , 0) + 1

#for each value in the dic, if the new value is bigger than none, it becomes the new big value
        for emails , emailNum in emaildic.items():
            if emailNum > bigNum:
                bigNum = emailNum
                bigEmail = emails

if bigNum > 0:
    print(bigEmail, bigNum)
else:
    print(bigNum , "emails found")


from dataloader import Dataloader, RE_Dataset
import argparse
from model import Model
import pytorch_lightning as pl
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import ModelCheckpoint, LearningRateMonitor
import os
from sklearn.model_selection import StratifiedKFold
import pandas as pd
from omegaconf import OmegaConf
from transformers import set_seed
import math
from utils import validate_conf

if __name__ == "__main__":
    conf = OmegaConf.load("./config.yaml")

    # conf validation
    validate_conf(conf)

    # seed 고정
    if conf.params.seed > 0:
        set_seed(conf.params.seed)

    # k-fold 여부에 따라 step 수가 달라짐.
    if conf.params.use_stratified_kfold:
        train_df = pd.read_csv(conf.path.origin_train_path)  # 학습 데이터

        # ((num_folds-1) x num_folds) 를 곱해줘야 함.
        # 총 스텝 수 = 학습 데이터 개수 / 배치사이즈 x max_epoch / ((num_folds-1) x num_folds)
        total_steps = math.ceil(
            (len(train_df) // conf.params.batch_size)
            * conf.params.max_epoch
            * ((conf.params.num_folds - 1) / conf.params.num_folds)
        )

    else:
        train_df = pd.read_csv(conf.path.train_path)  # 학습 데이터
        # 총 스텝 수 = 학습 데이터 개수 / 배치사이즈 x max_epoch
        total_steps = (len(train_df) // conf.params.batch_size) * conf.params.max_epoch

    # warmup_ratio 가 음수가 아닌 경우에만 warmup_staps 를 overwrite 합니다.
    if conf.params.warmup_ratio > 0.0:  # float라서 등호(=) 주의
        conf.params.warmup_steps = int(total_steps * conf.params.warmup_ratio)

    model = Model(
        model_name=conf.model_name,
        lr=conf.params.learning_rate,
        num_labels=conf.params.num_labels,
        warmup_steps=conf.params.warmup_steps,
        max_training_step=total_steps,
        loss_type=conf.params.loss_type,
        classifier=conf.params.classifier,
        lr_decay=conf.params.lr_decay,
    )

    wandb_logger = WandbLogger(
        project=conf.params.project_name, name=conf.params.test_name
    )

    checkpoint_callback = ModelCheckpoint(
        monitor="val_micro_f1",
        dirpath="./ckpt",
        filename="roberta-large-emb-lr_sched-{epoch:02d}-{val_micro_f1:.2f}",
        save_top_k=1,
        mode="max",
    )

    lr_monitor = LearningRateMonitor(logging_interval="step")

    os.makedirs("./ckpt", exist_ok=True)

    # StratifiedKFold 사용할 경우
    if conf.params.use_stratified_kfold:
        num_folds = conf.params.num_folds
        skf = StratifiedKFold(
            n_splits=num_folds, shuffle=True, random_state=42
        )  # StratifiedKFold 객체 선언

        train_dataset = pd.read_csv(conf.path.origin_train_path)
        indices = list(range(len(train_dataset)))
        labels = train_dataset["label"].values
        folds = list(
            skf.split(indices, labels)
        )  # labels 를 보고 분포에 맞게 skf 객체가 indices를 나눠준다 (train_index, val_index) 형태로 반환

        # k-fold 만큼 반복
        for fold, (train_index, val_index) in enumerate(folds):
            print(f"Training Fold {fold + 1}/{num_folds}")

            # fold 별로 trainer, dataloader 객체를 새로 만들어준다
            trainer = pl.Trainer(
                accelerator="gpu",
                max_epochs=conf.params.max_epoch,
                log_every_n_steps=1,
                logger=wandb_logger,
                callbacks=[checkpoint_callback, lr_monitor],
            )

            fold_dataloader = Dataloader(
                model_name=conf.model_name,
                batch_size=conf.params.batch_size,
                shuffle=conf.params.shuffle,
                origin_train_path=conf.path.origin_train_path,
                train_path=None,  # StratifiedKFold 시엔 None
                dev_path=None,  # StratifiedKFold 시엔 None
                test_path=None,  # StratifiedKFold 시엔 None
                predict_path=None,  # StratifiedKFold 시엔 None
                emb=conf.params.emb,
                use_stratified_kfold=conf.params.use_stratified_kfold,
                train_indices=train_index,
                val_indices=val_index,
                only_entity=False,  # CoRE predict 시에만 True
            )

            trainer.fit(model=model, datamodule=fold_dataloader)

    else:
        trainer = pl.Trainer(
            accelerator="gpu",
            max_epochs=conf.params.max_epoch,
            log_every_n_steps=1,
            logger=wandb_logger,
            callbacks=[checkpoint_callback, lr_monitor],
        )

        dataloader = Dataloader(
            model_name=conf.model_name,
            batch_size=conf.params.batch_size,
            shuffle=conf.params.shuffle,
            origin_train_path=None,  # StratifiedKFold 시엔 None
            train_path=conf.path.train_path,
            dev_path=conf.path.dev_path,
            test_path=conf.path.test_path,
            predict_path=conf.path.predict_path,
            emb=conf.params.emb,
            use_stratified_kfold=None,  # StratifiedKFold 시엔 None
            train_indices=None,  # StratifiedKFold 시엔 None
            val_indices=None,  # StratifiedKFold 시엔 None
            only_entity=False,  # CoRE predict 시에만 True
        )

        trainer.fit(model=model, datamodule=dataloader)


import numpy
import matplotlib.pyplot
import multiprocessing
import random
import warnings
import time
import centroid_dictionary_builder as cdb
import KTester as kt

alpha = 0.001

def calculate_z(data_array_i, neuron_weights):
    dot_product = -numpy.dot(data_array_i, neuron_weights)
    z_value = 1 / (1 + numpy.exp(dot_product))
    return z_value

def calculate_neuron_weights(data_array_i, neuron_weights, error):
    neuron_weights = neuron_weights + alpha * error * data_array_i
    return neuron_weights

warnings.filterwarnings('ignore')
#numpy.set_printoptions(suppress=True)

if __name__ == "__main__":

    with open('../100centroids/data_array_100centroids.npy', 'rb') as opened_file:
        letter_array = numpy.load(opened_file)

    with open('../100centroids/nonletter_labeled_data_100centroids.npy', 'rb') as opened_file:
        non_letter_array = numpy.load(opened_file)

    letter_centroid_data = letter_array[:,-1] #get centroid labels for datasets
    non_letter_centroid_data = non_letter_array[:,-1]

    #half the letter data by truncating half of each letter's data set
    #letter_centroid_data = numpy.reshape(letter_centroid_data, (62, int(len(letter_centroid_data) / 62)))
    #letter_centroid_data = letter_centroid_data[:,:-int((len(letter_centroid_data[0])/2))]
    #letter_centroid_data = numpy.ndarray.flatten(letter_centroid_data)

    #put 8x8 samples back into 32x32 images
    letter_centroid_data = numpy.reshape(letter_centroid_data,(int(len(letter_centroid_data)/16), 16))
    non_letter_centroid_data = numpy.reshape(non_letter_centroid_data, (int(len(non_letter_centroid_data) / 16), 16))

    # put letter/nonletter centroid data through translator
    letter_data = cdb.build_translated_letter_centroid_labels(letter_centroid_data)
    non_letter_data = cdb.build_translated_letter_centroid_labels(non_letter_centroid_data)

    data_array = numpy.concatenate((letter_data, non_letter_data), axis=0)

    Bias = numpy.full((len(data_array),1), 1)

    Class_one = numpy.full((len(letter_data), 1), 1)
    Class_two = numpy.full((len(non_letter_data), 1), 0)
    Classes = numpy.concatenate((Class_one, Class_two), axis=0)

    #concatenate Bias and Classes to a super letter_array
    data_array = numpy.concatenate((Bias, data_array), axis=1)
    data_array = numpy.concatenate((data_array, Classes), axis=1)

    #shuffle data array for training
    indexArray = list(range(numpy.size(data_array, 0)))
    random.shuffle(indexArray)
    data_array = data_array[indexArray]

    #letter_array = letter_array[:25000]

    #Code to count many letters/non-letters were randomly selected
    count_non = 0
    count_letter = 0

    for i in data_array:
        if i[-1] == 0:
            count_non += 1
        else:
            count_letter += 1

    print("Non-letters:", count_non)
    print("Letters:", count_letter)

    # Splitting up image and classifier data into their own arrays
    data_classifiers = data_array.T[-1]
    data_array = data_array[:, :-1]

    # define number of hidden layers
    NEURONS = 50 + 1  # Extra 1 weight for bias
    ATTRIBUTE_COUNT = len(data_array[0])  # bias already added

    # weights pre-initialized
    neuron_weights = numpy.random.rand(NEURONS * (ATTRIBUTE_COUNT))
    neuron_weights = neuron_weights * 2 - 1
    neuron_weights = neuron_weights.reshape((NEURONS, ATTRIBUTE_COUNT))
    output_weights = numpy.random.rand(NEURONS)
    output_weights = output_weights * 2 - 1

    pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)
    print("\nLogical Threads being used:", multiprocessing.cpu_count() - 1)

    # MLP Training
    EPOCHS = 100

    previous_error = 0
    same_error_count = 0
    total_error_list = []

    start = time.time()  # Start Timer

    for epoch in range(EPOCHS):
        total_error = 0
        print("Progress:", str(epoch * 100 / EPOCHS) + "%")
        for i in range(len(data_array)):

            # forward calculation
            hidden_layer_z = numpy.ones(NEURONS)

            # zip and send data to function for z values
            data_array_i = numpy.full((NEURONS, len(data_array[i, :])), data_array[i])
            values = list(zip(data_array_i, neuron_weights))
            return_value = pool.starmap(calculate_z, values)

            if return_value:
                hidden_layer_z = numpy.array(return_value)
            return_value.clear()
            values.clear()

            dot_product_output = -numpy.dot(hidden_layer_z, output_weights)
            output_z = 1 / (1 + numpy.exp(dot_product_output))

            # prediction
            prediction = round(output_z, 0)

            total_error = total_error + abs(data_classifiers[i] - prediction)

            # error propagation
            output_error = output_z * (1 - output_z) * (data_classifiers[i] - output_z)
            error = hidden_layer_z * (1 - hidden_layer_z) * (output_error * output_weights)

            # update weights
            values = list(zip(data_array_i, neuron_weights, error))
            return_value = pool.starmap(calculate_neuron_weights, values)

            if return_value:
                neuron_weights = numpy.array(return_value)
            return_value.clear()
            values.clear()

            output_weights = output_weights + alpha * output_error * hidden_layer_z

        total_error_list.append(total_error)

        if previous_error != total_error_list[-1]:
            previous_error = total_error_list[-1]
            same_error_count = 0
        else:
            same_error_count += 1

        if same_error_count > 3:
            print("Training Completed.")
            break

    end = time.time()

    numpy.save("neuron_weights", neuron_weights)
    numpy.save("output_weights", output_weights)

    print("Number of errors during training:", total_error_list[-1])
    print("Percent of errors during training:", total_error_list[-1] / len(data_array) * 100, "%")

    matplotlib.pyplot.plot(total_error_list)
    matplotlib.pyplot.title(label=f"Alpha: {alpha}")
    matplotlib.pyplot.show()

    #with open('neuron_weights.npy', 'rb') as opened_file:
    #    neuron_weights = numpy.load(opened_file)

    #with open('output_weights.npy', 'rb') as opened_file:
    #    output_weights = numpy.load(opened_file)

    #print("neuron_weights:", neuron_weights)
    #print("output_weights:", output_weights)
    print("Training Time:", end - start)

    time_string = "Training Time: " + str(end - start)

    # open text file
    text_file = open("../TrainingTime.txt", "w")
    text_file.write(time_string)
    text_file.close()

Deprecated Files/MLP Training Binary Output.py


from errors import *
import random
import copy

def order_from_spec(spec):
    if isinstance(spec, str):
        return [spec]
    elif isinstance(spec, list):
        shuffle = False
        items = spec
    else:
        assert isinstance(spec, dict)
        shuffle = spec.get('shuffle', False)
        items = spec['items']
    items = copy.copy(items) # shallow ok
    if shuffle:
        random.shuffle(items)
    out = []
    for x in items:
        out += order_from_spec(x)
    return out

def default_order_spec(names):
    pfo = None
    if 'pfo' in names: pfo = 'pfo'
    elif 'paraffin' in names: pfo = 'paraffin'
    if pfo is None: return [names]
    return [pfo, {'shuffle': True, 'items': [x for x in names if x != pfo]}]

def try_typecasting(cfg, *args):
    a = []
    for k, ty in args:
        try:
            a.append(ty(cfg[k]))
        except:
            raise ParseError(f'Failed to typecast param: {k}')
    return tuple(a)

def deep_update(a, b):
    for k, v in b.items():
        if k not in a:
            a[k] = v
        else:
            va = a[k]
            if isinstance(va, dict):
                assert isinstance(v, dict)
                deep_update(va, v)
            else:
                a[k] = v

class VialOdor:
    def __init__(self, odors, carrier_rate, odor_rate):
        self.order = sorted(odors, key=lambda o: o.conc_num())
        self.carrier_rate = carrier_rate
        self.odor_rate = odor_rate

    def insert_steps(self, plan, prestimt, poststimt, stimt):
        for o in self.order:
            plan.push(f'Odor: {o}')
            plan += [
                AdjustOdorFlowStep(o, self.carrier_rate, self.odor_rate),
                WaitStep(prestimt),
                OdorStep(o, stimt),
                WaitStep(poststimt)
            ]
            plan.pop()

def parse_float_or_percent(x, of_what):
    if isinstance(x, str):
        assert x[-1] == '%'
        prop = float(x[:-1])/100
        return prop*of_what
    else:
        return float(x)

class GasOdor:
    def __init__(self, odor, cfg):
        self.odor = odor
        tot = float(cfg['total-flow'])
        oflows = []
        for x in cfg['odor-flows']:
            oflows.append(parse_float_or_percent(x, tot))
        cflows = [tot-x for x in oflows]
        self.rates = sorted(
            list(zip(cflows, oflows)),
            key = lambda x: x[1]
        )

    def insert_steps(self, plan, prestimt, poststimt, stimt):
        for carrier_rate, odor_rate in self.rates:
            pc = round(100*odor_rate/(odor_rate+carrier_rate))
            plan.push(f'Odor: {self.odor} at {pc}%')
            plan += [
                AdjustOdorFlowStep(self.odor, carrier_rate, odor_rate),
                WaitStep(prestimt),
                OdorStep(self.odor, stimt),
                WaitStep(poststimt)
            ]

@plan('Concentration Ramp', 'ramp')
def concentration_ramp_plan(odors, cfg_):
    names = list(set([o.name for o in odors]))
    cfg = {
        'order': default_order_spec(names),
        'gasses': {},
        'nblocks': 3,
        'timing': {
            'stim': 2.0,
            'begin-movie': 30.0,
            'pre-stim': 30.0,
            'post-stim': 30.0,
            'rest': 120.0
        },
        'default-flow': {
            'total-flow': 2000.0,
            'odor-flow': '10%'
        }
    }
    deep_update(cfg, cfg_)

    nb, timing = try_typecasting(cfg,
        ('nblocks', int), ('timing', dict)
    )

    stimt, begint, prestimt, poststimt, restt = try_typecasting(timing,
        ('stim', float), ('begin-movie', float),
        ('pre-stim', float), ('post-stim', float),
        ('rest', float)
    )

    default_flow_cfg = dict(cfg['default-flow'])
    vial_total_rate, = try_typecasting(default_flow_cfg, ('total-flow', float))
    vial_odor_rate = parse_float_or_percent(default_flow_cfg['odor-flow'], vial_total_rate)
    vial_carrier_rate = vial_total_rate - vial_odor_rate

    order_spec = order_from_spec(cfg['order'])
    order = []
    for x in order_spec:
        assert x in names
        relevant = [o for o in odors if o.name == x]
        if x in cfg['gasses']:
            assert len(relevant) == 1
            order.append(GasOdor(relevant[0], cfg['gasses'][x]))
        else:
            assert len(relevant) > 0
            order.append(VialOdor(relevant, vial_carrier_rate, vial_odor_rate))

    sl = StepList()
    for i in range(nb):
        sl.push(f'Block {i+1}')
        sl += [
            MirrorDownStep(),
            ScopeOnStep()
        ]
        if i == 0:
            sl.append(WaitStep(begint))
        for o in order:
            o.insert_steps(sl, prestimt, poststimt, stimt)
        sl += [
            ScopeOffStep(),
            MirrorUpStep()
        ]
        if i+1 < nb:
            sl.append(WaitStep(restt))
        sl.pop()

    return sl


from django.conf.urls import patterns, url

from notes import views

urlpatterns = patterns('notes.views',
        (r'^(?P<file_name>.+\.txt)$', 'post'),
        (r'^new$','newnote'),
        (r"", "main"),
                      )
urlpatterns += patterns('',
        (r'^accounts/login/', 'django.contrib.auth.views.login',
         {'template_name': 'notes/login.html'}),
                       )


import sys
import json
import pickle

# Load the pickle model
with open("C:/Users/Yared/Downloads/SAGE prediction Models/rf_model", "rb") as f:
    model = pickle.load(f)

input_data_array = json.loads(sys.stdin.read())
outputs = []

for input_data in input_data_array:
    feature_names = list(input_data.keys())
    values = [input_data[feature] for feature in feature_names]
    result = model.predict([values])
    outputs.append(result.tolist())

# Print the output predictions to stdout
print(json.dumps(outputs))


from time import time
from typing import Any
from core.db_manager import DBManager
from bson import ObjectId
from dataclasses import dataclass, is_dataclass, field, asdict

def from_dict_utils(cls, ndict):
    d2 = {}
    for key in cls.__dataclass_fields__.keys():
        if key not in ndict:
            continue
        value = cls.__dataclass_fields__[key].type
        if ndict.get(key) is not None and value in [str,float,int]:
            d2[key] = value(ndict.get(key))
        elif value == bool:
            if ndict.get(key) in ["true", "True", True]:
                d2[key] = True
            elif ndict.get(key) in ["false", "False", False]:
                d2[key] = False
        elif ndict.get(key) is not None and is_dataclass(value):
            d2[key] = from_dict_utils(value, ndict.get(key))
        else:
            d2[key] = ndict.get(key)
    if "_id" in ndict and "_id" not in d2:
        d2["_id"] = ndict.get("_id")

    return d2

@dataclass
class Entity():
    created_at: float = field(default_factory=time)
    updated_at: float = field(default_factory=time)
    deleted: bool = False
    _id: ObjectId = field(default_factory=ObjectId)

    @classmethod
    def from_dict(cls, ndict):
        if ndict is None:
            return None
        d2 = from_dict_utils(cls, ndict)
        return cls(**d2)

    @classmethod
    def _db(cls):
        db_manager = DBManager.get_instance()
        return db_manager.get_collection(cls)

    @classmethod
    def find_one(cls, params, keys=[], deleted=False):
        db = cls._db()
        is_object = isinstance(params, dict)
        if not is_object and not ObjectId.is_valid(params):
            params = {"_id": params}
        elif not is_object:
            params = {"_id": ObjectId(params)}
        if not deleted:
            params.update({"deleted":{"$ne":True}})
        if len(keys) == 0:
            obj = db.find_one(params)
        else:
            obj = db.find_one(params, keys)
        return cls.from_dict(obj)

    @classmethod
    def find_many(cls, params, keys=[], deleted=False, limit=0, sort=None):
        db = cls._db()

        if not isinstance(params, dict):
            olist = [ObjectId(_id) if ObjectId.is_valid(_id) else _id for _id in params ]
            params = {"_id":{"$in": olist}}
        if not deleted:
            params.update({"deleted":{"$ne":True}})

        cur = db.find(filter=params, projection=keys, limit=limit, sort=sort)

        return [cls.from_dict(obj) for obj in cur]

    def update(self, keys=[]):
        db = self._db()
        self.updated_at = time()
        ndict = asdict(self)
        if (len(keys) == 0):
            db.update_one({"_id": self._id}, {"$set": ndict},  upsert=True)
        else:
            d2 = {x:ndict.get(x) for x  in keys if x in ndict}
            if (len(d2) >0):
                db.update_one({"_id": self._id}, {"$set": d2},  upsert=True)

    def delete(self, delete_from_db = False):
        db = self._db()
        if (delete_from_db):
            db.delete_one({"_id": self._id})
        else:
            db.update_one({"_id": self._id},{"$set":{"deleted":True}}, upsert = False)

    def update_from_dict(self, params):
        d2 = {x:params.get(x) for x  in self.__dataclass_fields__.keys() if x in params}
        for x,y in d2.items():
            if x in self.__dict__:
                value = self.__dataclass_fields__[x].type

                if  y is not None and value in [str,float,int]:
                    self.__dict__[x] = value(y)
                elif value == bool:
                    if y in ["true", "True", True]:
                        self.__dict__[x] = True
                    elif y in ["false", "False", False]:
                        self.__dict__[x] = False
                elif is_dataclass(y):
                    self.__dict__[x] = from_dict_utils(y, params.get(x))
                else:
                    self.__dict__[x] = y

    def update_document_from_dict(self, params):
        self.update_from_dict(params)
        self.update()

    @classmethod
    def count_documents(cls, params, ):
        return cls._db().count_documents(params)

    def get_dict(self):
        return asdict(self)


import re  # Required for pattern matching

def remove_elements_with_pattern(array, pattern):
    new_array = []
    for element in array:
        if pattern not in element:
            new_array.append(element)
        else:
            print("Removed: " + element)
    return new_array

# Open the input file and read lines into an array
input_filename = "lc.txt"
output_filename = "lc_problems.txt"
pattern_to_remove = "/solution"

with open(input_filename, "r") as file:
    arr = file.readlines()

# Remove lines containing the specified pattern
arr = remove_elements_with_pattern(arr, pattern_to_remove)

# Remove duplicate lines
arr = list(set(arr))

# Write the modified lines to the output file
with open(output_filename, 'a') as f:
    # Iterate over each line in your final list
    for line in arr:
        # Write each line to the file, followed by a newline
        f.write(line)

print("Total lines written to", output_filename, ":", len(arr))


# ensure to activate an environment that has detectron2 installed
import copy
import json
import math
import os
import torch
from collections import defaultdict
from tqdm import tqdm
import cv2
from sklearn.metrics import precision_recall_curve
from detectron2 import model_zoo
from detectron2.config import get_cfg
from detectron2.data import DatasetCatalog, MetadataCatalog
from detectron2.modeling import build_model
from detectron2.structures.boxes import BoxMode
from detectron2.checkpoint.detection_checkpoint import DetectionCheckpointer
from detectron2.engine import DefaultPredictor

from .json_utils import NumpyEncoder
from .stars_config import getEvalCfg

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

class ClassWisePRCurve:
    """Accumulator Class for classwise PR Curve data
    """

    def __init__(self, classes_list):
        self.classes_list = classes_list
        self.pr_data = {}
        for c in self.classes_list:
            self.pr_data[c] = {"y_gt": [], "y_conf": []}
        plt.ion()
        min_x = 0
        max_x = 1
        self.figure, self.ax = plt.subplots()
        (self.lines,) = self.ax.plot([], [], ".", markersize=1)
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(min_x, max_x)
        self.ax.set_xlabel("Recall")
        self.ax.set_ylabel("Precision")
        self.ax.grid()

        # self.annot = None
        # if(self.annot is not None):
        #     self.annot.remove()

        self.annot = self.ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),
                    arrowprops=dict(arrowstyle="->"))

    def addRawData(self, classname, y_gt, y_conf):
        """Accumulator for PR curve
        This data is the class wise results for each class formatted as a binary classifier

        Arguments:
            classname {str} -- Class name
            y_gt {list} -- list of the True prediction
            y_conf {list} -- list of the corresponding confidences for each prediction
        """
        self.pr_data[classname]["y_gt"] += y_gt
        self.pr_data[classname]["y_conf"] += y_conf

    def getPRCurveForClass(self, classname):
        """Get the PR Curve for a particular class

        Arguments:
            classname {str} -- Class name

        Returns:
            (3-tuple) -- array of precisions, recalls, and the threshold steps
        """
        # print(self.pr_data[classname]["y_gt"], self.pr_data[classname]["y_conf"])

        if(len(self.pr_data[classname]["y_gt"])>0):
            precision, recall, thresholds = precision_recall_curve(
                self.pr_data[classname]["y_gt"], self.pr_data[classname]["y_conf"]
            )
        else:
            precision, recall, thresholds = [], [], []
        return precision, recall, thresholds

    def getPRCurves(self):
        """Get PR Curves for all classes

        Returns:
            {dict} -- Dictional containg the precisions, recalls and threshold steps for each class
        """
        res = {}
        for c in self.classes_list:
            p, r, t = self.getPRCurveForClass(c)
            res[c] = {"precisions": p, "recalls": r, "threshold_steps": t}
        return res

    def updateAnnot(self, ind):
        th = round(100 * np.mean(np.take(self.data['threshold_steps'],ind['ind'])),2)
        x,y = self.lines.get_data()
        self.annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
        text = "Threshold: {}".format(th)
        self.annot.set_text(text)
        self.annot.get_bbox_patch().set_alpha(0.4)

    def hover(self, event):
        vis = self.annot.get_visible()
        if event.inaxes == self.ax:
            cont, ind = self.lines.contains(event)
            if cont:
                self.updateAnnot(ind)
                self.annot.set_visible(True)
                self.figure.canvas.draw_idle()
            else:
                if vis:
                    self.annot.set_visible(False)
                    self.figure.canvas.draw_idle()

    def plotCurve(self, data):
        xdata = data["recalls"]
        ydata = data["precisions"]
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        self.ax.relim()
        self.ax.autoscale_view()
        self.figure.canvas.draw()

    def plotPRCurveForClass(self, classname, visualize=True):
        """Plot PR Curve for class

        Arguments:
            classname {str} -- Class name
            visualize {bool} -- True: View plot in pop-up
                                False: Save plot as image
        """
        p, r, t = self.getPRCurveForClass(classname)
        self.data = {"precisions": p, "recalls": r, "threshold_steps": t}

        self.annot.set_visible(False)
        if visualize:
            self.plotCurve(self.data)
            self.figure.canvas.mpl_connect("motion_notify_event", self.hover)
            # time.sleep(0.5)
            self.figure.canvas.flush_events()
        else:
            self.plotCurve(self.data)
            self.figure.canvas.flush_events()
            plt.savefig(f"PR_Curve_{classname}.png")

class ClassWiseStats:
    """Accumulator class for Precision and Recall Stats(at a single value of confidence)
    """

    def __init__(self, classes_list):
        self.classes_list = classes_list
        self.class_wise_scores = {
            classname: {"tp": 0, "fp": 0, "fn": 0} for classname in classes_list
        }

    def addStats(self, classname, tp, fp, fn):
        """Accumulate the counts of stats relevant for P,R Calculation

        Arguments:
            classname {str} -- name of the class
            tp {int} -- True Positive Count
            fp {int} -- False Positive Count
            fn {int} -- False Negative Count
        """
        self.class_wise_scores[classname]["tp"] += tp
        self.class_wise_scores[classname]["fp"] += fp
        self.class_wise_scores[classname]["fn"] += fn

    def getPrecision(self, classname):
        """Calculate Precision for the given class
            Precision = TP/(TP+FP)

        Arguments:
            classname {str} -- class name(must be present in classes list)

        Returns:
            precision -- the precision of the class
        """
        tp = self.class_wise_scores[classname]["tp"]
        fp = self.class_wise_scores[classname]["fp"]
        if (tp + fp) != 0:
            precision = tp / (tp + fp)
        else:
            precision = math.nan
        return precision

    def getRecall(self, classname):
        """Calculate Precision for the given class
            Recall = TP/(TP+FN)

        Arguments:
            classname {str} -- class name(must be present in classes list)

        Returns:
            recall -- the recall of the class
        """
        tp = self.class_wise_scores[classname]["tp"]
        fn = self.class_wise_scores[classname]["fn"]
        if (tp + fn) != 0:
            recall = tp / (tp + fn)
        else:
            recall = math.nan
        return recall

    def getAllStats(self):
        """Return the Precision and Recall for all classes as a dictionary
            Returned dictionary has classnames as keys and another dict as the value
            the second level dictionary has the values in the keys - `Precision` and `Recall`

        Returns:
            class_wise_pr{dict} -- Dictionary with class wise pr
        """
        class_wise_pr = {}
        for c in self.classes_list:
            class_wise_pr[c] = {
                "Precision": self.getPrecision(c),
                "Recall": self.getRecall(c),
            }
        return class_wise_pr

class StarsEvaluator:
    """Custom Evaluator for Object Detection models
    Written for Team S.T.A.R.S - CMU MRSD Capstone.
    `github/t27`
    """

    def __init__(
        self,
        model,
        classes_list,
        train_json=None,
        val_json=None,
        batch_size=8,
        confidence_thres=0.7,
        iou_thres=0.5,
        model_input_format="BGR",
        progress_bar=True,
        iterative_evaluation=False
    ):
        if not iterative_evaluation:
            self.train_dataset = self.get_data_dicts(train_json)
            self.test_dataset = self.get_data_dicts(val_json)
        else:
            self.train_dataset = None
            self.test_dataset = None
        self.model = model
        self.classes_list = classes_list
        self.batch_size = batch_size
        self.class_wise_stats = ClassWiseStats(self.classes_list)
        self.pr_curve_generator = ClassWisePRCurve(self.classes_list)
        self.confidence_thres = confidence_thres
        self.iou_thres = iou_thres
        self.model_input_format = model_input_format
        self.progress_bar = progress_bar

    def getStatsSummary(self):
        return (
            self.class_wise_stats.getAllStats(),
            self.pr_curve_generator.getPRCurves(),
        )

    def plotPRCurveForClass(self, classname):
        self.pr_curve_generator.plotPRCurveForClass(classname)

    def evaluateAndGetTestNumbers(self):
        return self.evaluateDataset(self.test_dataset)

    def getTrainNumbers(self):
        return self.evaluateDataset(self.train_dataset)

    def evaluateDatasetIterative(self, dataset):
        for ob in dataset:
            image_path = ob["file_name"]
            annotations = ob["annotations"]

            cv_image = cv2.imread(image_path)
            # our model is currently trained using the opencv representation(default detectron)
            if self.model_input_format == "RGB":
                cv_image = cv_image[:, :, ::-1]

            image = torch.as_tensor(cv_image.astype("float32").transpose(2, 0, 1))
            gt_boxes = []
            gt_classes = []
            for anno in annotations:
                gt_boxes.append(anno["bbox"])
                gt_classes.append(self.classes_list[anno["category_id"]])

            # This function evaluates an image adds the relevant stats to the Stats and PRCurve objects
            det_boxes, det_scores, det_classes = self.evaluateSingleImage(
                image, gt_boxes, gt_classes
            )
            yield det_boxes, det_scores, det_classes, gt_boxes, gt_classes, cv_image

        # return (
        #     self.class_wise_stats.getAllStats(),
        #     self.pr_curve_generator.getPRCurves(),
        # )

    def evaluateDataset(self, dataset):
        if self.progress_bar:
            dataset_it = tqdm(dataset)
        else:
            dataset_it = dataset
        for ob in dataset_it:
            image_path = ob["file_name"]
            annotations = ob["annotations"]

            image = cv2.imread(image_path)
            # our model is currently trained using the opencv representation(default detectron)
            if self.model_input_format == "RGB":
                image = image[:, :, ::-1]

            image = torch.as_tensor(image.astype("float32").transpose(2, 0, 1))
            gt_boxes = []
            gt_classes = []
            for anno in annotations:
                gt_boxes.append(anno["bbox"])
                gt_classes.append(self.classes_list[anno["category_id"]])

            # This function evaluates an image adds the relevant stats to the Stats and PRCurve objects
            self.evaluateSingleImage(image, gt_boxes, gt_classes)

        return (
            self.class_wise_stats.getAllStats(),
            self.pr_curve_generator.getPRCurves(),
        )

        # TODO: add batch processing of the image

    def evaluateSingleImage(self, image, gt_boxes, gt_classes):
        """Evaluate a single image and get the numbers against GT

        Arguments:
            image {Tensor} -- torch Tensor of the image
            gt_boxes {list} -- List of GT boxes
            gt_classes {list} -- List of classes that correspond to the gt_boxes
        """

        # for each image, make a separate
        # read image
        # compare annotation
        det_boxes, det_scores, det_classes = self.getDetections(image)
        # print(det_classes)
        class_wise_preds = defaultdict(list)
        class_wise_gt = defaultdict(list)
        for idx, classnum in enumerate(det_classes):
            classname = self.classes_list[classnum[0]]
            class_wise_preds[classname].append((det_boxes[idx], det_scores[idx][0]))

        for idx, classval in enumerate(gt_classes):
            class_wise_gt[classval].append(gt_boxes[idx])

        for c in self.classes_list:
            tp, fp, fn, pr_curve_data = self.getConfusionMatrixForClass(
                class_wise_gt[c], class_wise_preds[c]
            )
            self.class_wise_stats.addStats(c, tp, fp, fn)
            self.pr_curve_generator.addRawData(
                c, pr_curve_data["y_gt"], pr_curve_data["y_conf"]
            )
        return det_boxes, det_scores, det_classes

    def getConfusionMatrixForClass(self, gt, preds):

        """Calculate True Positives, False Positives and False Negatives
        This method doesn't consider class, so ensure the class wise filtering
        is done before. Only pass GT and Preds of the same class to this method

        Arguments:
            gt {list} -- Array of GT boxes
            preds {list of 2-tuples} -- Array of predicted boxes and their confidence

        Returns:
            [3-tuple] -- TruePositiveCount,FalsePositiveCount,FalseNegativeCount
        """

        # TODO: ensure the preds are NMS'ed so that we dont have overlapping predictions of the same class
        gt_boxes = copy.deepcopy(gt)

        tp, fp = ([], [])

        y_gt = []
        y_confs = []
        # for representing this as a binary classification problem(for PR Curves),
        # tp - pred = 1, gt=1
        # fp - pred = 1, gt=0
        # fn - pred = 0, gt=1

        for pred_box, conf in preds:
            # find the GT box with the highest IOU, remove that box
            # need a minimum of this iou to be considered useful
            max_iou = self.iou_thres
            max_iou_idx = None
            for idx, gt_box in enumerate(gt_boxes):
                iou = self.getIOU(pred_box, gt_box)
                if iou > max_iou:
                    max_iou = iou
                    max_iou_idx = idx
            if max_iou_idx is not None:
                del gt_boxes[max_iou_idx]
                # since we found a succesful match, this is a true positive
                if conf > self.confidence_thres:
                    tp.append(pred_box)
                # for PR Curve
                y_gt.append(1)
                y_confs.append(conf)
            else:
                if conf > self.confidence_thres:
                    fp.append(pred_box)
                y_gt.append(0)
                y_confs.append(conf)

        for z in gt_boxes:
            y_gt.append(1)
            y_confs.append(0)  # zero confidence

        pr_curve_data = {"y_gt": y_gt, "y_conf": y_confs}

        tp_count = len(tp)
        # number of predictions that didn't match any gt box ar false positives
        fp_count = len(fp)

        # number of gt boxes that didnt match a pred box are false negatives
        fn_count = len(gt_boxes)

        return tp_count, fp_count, fn_count, pr_curve_data

    def getIOU(self, box1, box2):
        """Calculate Intersection over Union

        Arguments:
            box1 {list} -- list of [xmin ymin xmax ymax]
            box2 {list} -- list of [xmin ymin xmax ymax]
        """
        # Intersection
        i_xmin = max(box1[0], box2[0])
        i_ymin = max(box1[1], box2[1])
        i_xmax = min(box1[2], box2[2])
        i_ymax = min(box1[3], box2[3])
        if i_xmax > i_xmin and i_ymax > i_ymin:
            intersection = (i_xmax - i_xmin) * (i_ymax - i_ymin)
        else:
            intersection = 0
            return 0

        def boxarea(box):
            return (box[2] - box[0]) * (box[3] - box[1])

        union = boxarea(box1) + boxarea(box2) - intersection

        return intersection / union

    def getDetections(self, image):
        with torch.no_grad():
            c, h, w = image.shape
            inp = [{"image": image, "height": h, "width": w}]
            out = self.model(inp)[0]
            det_boxes = out["instances"].pred_boxes.tensor.to("cpu").numpy()
            det_scores = out["instances"].scores.to("cpu").unsqueeze(1).numpy()
            det_classes = out["instances"].pred_classes.to("cpu").unsqueeze(1).numpy()
            return det_boxes, det_scores, det_classes

    def get_data_dicts(self, json_file):
        data = json.load(open(json_file))

        for im in data:
            anno = im["annotations"]
            for an in anno:
                an["bbox_mode"] = BoxMode(an["bbox_mode"])
        return data

def prepareEvaluator(
    confidence_thres=0.7, iou_thres=0.5, chkpts_file="outputmodel_final.pth",iterative_evaluation=False
):
    classes_dict = {0: "vehicle", 1: "bike", 2: "pedestrian"}
    # # create cfg
    cfg = getEvalCfg()

    # pred = DefaultPredictor(cfg)

    model = build_model(cfg)  # building custom model, doesnt load chkpts automatically
    model.eval()
    DetectionCheckpointer(model).load(chkpts_file)

    if iterative_evaluation:
        evaluator = StarsEvaluator(
            model,
            list(classes_dict.values()),
            iou_thres=iou_thres,
            confidence_thres=confidence_thres,
            iterative_evaluation=True
        )
    else:
        evaluator = StarsEvaluator(
            model,
            list(classes_dict.values()),
            "stars_carla_train.json",
            "stars_carla_val.json",
            iou_thres=iou_thres,
            confidence_thres=confidence_thres,
        )

    return evaluator

def main():

    evaluator = prepareEvaluator(chkpts_file="final_training/output/model_final.pth")
    class_wise_results, pr_curves = evaluator.evaluateAndGetTestNumbers()
    json.dump(
        class_wise_results,
        open("class_wise_results.json", "w"),
        indent=2,
        cls=NumpyEncoder,
    )
    json.dump(
        pr_curves, open("pr_curves_raw_data.json", "w"), indent=2, cls=NumpyEncoder
    )
    ## Plot PR Curve

if __name__ == "__main__":
    main()

# Spec

# ---- for each image -------
# get gt boxes, and predicted boxes
#       put the gt boxes and predicted boxes in to class wise buckets
# for each class, conside confidence threshold as filter to calculate Positives
# use IOU threshold to identify true and false positives(decrement GT for every matched box), unmatched gt boxes are False negatives


import datetime, sys, dynamic, bruteforce, backtracking, firstBranchBound

def run():
	path = input("Which method do you want to use? \nBrute force (1), Dynamic (2), Best First Branch Bound (3), or Backtracking (4)?\nOr press q to quit  : ")

	if path == '1':
		time1 = datetime.datetime.now()
		print( bruteforce.bruteforce(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Brute force: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()

	elif path == '2':
		time1 = datetime.datetime.now()
		print( dynamic.dynamic(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Dynamic: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()

	elif path == '3':
		time1 = datetime.datetime.now()
		print( firstBranchBound.firstBranchBound(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Best First Branch Bound: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()

	elif path == '4':
		time1 = datetime.datetime.now()
		print( backtracking.backtracking(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Backtracking: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()

	elif path == 'q':
		sys.exit("See ya!")

	else:
		print("Error: no valid option chosen. Please try again.")
		print("\n")
		run()

# ----------------------------------------------------------------------

# Main program, load items

n = int(input("Enter the number of items : "))
W = int(input("Enter total weight : "))

#init 2-dimensional array for items
items = [[0]*4 for i in range(n)]    # create 2-dimensional array

for i in range(n):
	items[i][0] = i+1
	items[i][1] = int(input("Enter profit for %s : " % (i+1) ) )
	items[i][2] = int(input("Enter weight for %s : " % (i+1) ) )
	items[i][3] = int(items[i][1] / items[i][2])

print()
print("Items:  %s" % items)

run()


import numpy as np
n = 4 #number of iterations
true_val = 72
estimate = np.zeros((n+1,1)).reshape(n+1,1)
estimate[0] = 68
#print(estimate)
estimate_error = np.zeros((n+1,1)).reshape(n+1,1)
estimate_error[0] = 2
#print(estimate_error)
measured = np.array([0, 75, 71, 70, 74]).reshape(n+1,1)
measured_error = np.array([0, 4, 4, 4, 4]).reshape(n+1,1)

kalman_gain = np.zeros((n+1,1)).reshape(n+1,1)

for i in range(1,n+1):

    kalman_gain[i] = (estimate_error[i-1])/(estimate_error[i-1] + measured_error[i])

    estimate[i] = estimate[i-1] + ( kalman_gain[i] * (measured[i] - estimate[i-1]) )

    estimate_error[i] = (1 - kalman_gain[i]) * estimate_error[i-1]

print(estimate)
print(kalman_gain)
print(estimate_error)


from gpiozero import LED, Button
from time import time, sleep
import os

class Rullgardin:
    def __init__(self, a1, a2, en, knapp, tid, index):
        self.a1 = LED(a1)
        self.a2 = LED(a2)
        self.en = LED(en)
        self.knapp = Button(knapp)
        self.tid = tid
        self.index = str(index)
        self.state = "Unknown"

    def off(self):
        self.en.off()
        self.a1.off()
        self.a2.off()

    def upp(self):
        if self.state != "Uppe":
            self.state = "Pvg upp"
            self.off()
            self.a2.on()
            self.en.on()
            self.knapp.wait_for_press()
            self.off()
            sleep(0.1)
            self.off()
            self.a1.on()
            self.en.on()
            sleep(0.2)
            self.off()
            if self.state != "Avbruten":
                self.state = "Uppe"

    def ner(self):
        if self.state != "Nere":
            self.state = "Pvg ner"
            self.off()
            self.a1.on()
            self.en.on()
            for i in range(int(self.tid/0.1)):
                sleep(0.1)
                if self.state == "Avbruten":
                    break
            if self.state != "Avbruten":
                self.off()
                self.state = "Nere"

def gardiner():
    file = open("/home/pi/Rullgardin/gardiner.txt", encoding="utf8")
    file_rader = file.readlines()
    rullgardiner = []
    for rad in file_rader:
        rullgardiner.append(rad.rstrip("\n"))
    rullgardiner.pop(0)
    gardiner = []
    for gardin in rullgardiner:
        pinnar = gardin.split()
        index = 1 + rullgardiner.index(gardin)
        a1 = pinnar[0]
        a2 = pinnar[1]
        en = pinnar[2]
        knapp = pinnar[3]
        tid = float(pinnar[4])
        gardiner.append(Rullgardin(a1, a2, en, knapp, tid, index))
    return gardiner


from flask import Flask,request, render_template

app = Flask(__name__)

@app.route('/')

def index():
    user = {'username': 'Miguel'}
    return render_template('index.html', title='Home', user=user,)

if __name__ == "__main__":
    app.run(debug=True)


import os

KEYS = (
    'PAGE_ACCESS_TOKEN',
    'SECURITY_TOKEN',
    'RETHINK_URL',
    'RETHINK_PORT'
)

def load_conf(conf={}, reload_=False, mandatory_keys=KEYS):
    """
    Lazily load configuration key/values from the environment by looking
    for the `JERRY_` prefix.

    All configuration keys in `mandatory_keys` will be checked and an
    AssertionError will be raised if they are not set.
    """
    if reload_:
        conf.clear()

    if conf:
        return conf

    for key in mandatory_keys:
        value = os.environ.get('JERRY_%s' % key)
        assert value, (key, value)
        conf[key] = value

    for key, value in os.environ.items():
        if key.startswith('JERRY_'):
            if key[6:] not in conf:
                conf[key[6:]] = value

    return conf


#!/usr/bin/env python3

import sys
import glob

correct_licence = """\

//              Copyright Catch2 Authors
// Distributed under the Boost Software License, Version 1.0.
//   (See accompanying file LICENSE.txt or copy at
//        https://www.boost.org/LICENSE_1_0.txt)

// SPDX-License-Identifier: BSL-1.0
"""

def check_licence_in_file(filename: str) -> bool:
    with open(filename, 'r') as f:
        file_preamble = ''.join(f.readlines()[:7])

    if correct_licence != file_preamble:
        print('File {} does not have proper licence'.format(filename))
        return False
    return True

def check_licences_in_path(path: str) -> int:
    failed = 0
    files_to_check = glob.glob(path + '/**/*.cpp', recursive=True) \
                   + glob.glob(path + '/**/*.hpp', recursive=True)
    for file in files_to_check:
        if not check_licence_in_file(file):
            failed += 1
    return failed

def check_licences():
    failed = 0
    # Add 'extras' after the amalgamted files are regenerated with the new script (past 3.4.0)
    roots = ['src/catch2', 'tests', 'examples', 'fuzzing']
    for root in roots:
        failed += check_licences_in_path(root)

    if failed:
        print('{} files are missing licence'.format(failed))
        sys.exit(1)

if __name__ == "__main__":
    check_licences()


import gradio as gr
import joblib
import pandas as pd
import random

# Load the pipeline
pipeline = joblib.load('pipeline.joblib')
X_test_smaller = joblib.load('X_test_smaller.joblib')

# Define input components
last_pymnt_amnt = gr.inputs.Number(label='Last Payment Amount')
dti = gr.inputs.Number(label='DTI (Debt-to-Income Ratio)')
mo_sin_old_rev_tl_op = gr.inputs.Number(
    label='Months since Oldest Revolving Account')
int_rate = gr.inputs.Number(label='Interest Rate')
revol_util = gr.inputs.Number(label='Revolving Utilization Rate')
bc_open_to_buy = gr.inputs.Number(label='Credit Line Balance')
revol_bal = gr.inputs.Number(label='Revolving Balance')
avg_cur_bal = gr.inputs.Number(label='Average Current Balance')
total_bal_ex_mort = gr.inputs.Number(label='Total Balance Excluding Mortgage')
annual_inc = gr.inputs.Number(label='Annual Income')
loan_amnt = gr.inputs.Number(label='Loan Amount')

def greet():
    return "Hello!"

generate_button = gr.Button(value="Generate Random Row")

# Combine input components
input_components = [last_pymnt_amnt, dti, mo_sin_old_rev_tl_op, int_rate, revol_util,
                    bc_open_to_buy, revol_bal, avg_cur_bal, total_bal_ex_mort,
                    annual_inc, loan_amnt, generate_button]

# Define prediction function
def predict_loan_approval(last_pymnt_amnt, dti, mo_sin_old_rev_tl_op, int_rate, revol_util,
                          bc_open_to_buy, revol_bal, avg_cur_bal, total_bal_ex_mort,
                          annual_inc, loan_amnt, generate_random_row):
    if generate_random_row:
        random_index = random.randint(0, len(X_test_smaller) - 1)
        # Get the row at the random index
        random_row = X_test_smaller.iloc[random_index]
        # Fill input values with random data
        last_pymnt_amnt = random_row['last_pymnt_amnt']
        dti = random_row['dti']
        mo_sin_old_rev_tl_op = random_row['mo_sin_old_rev_tl_op']
        int_rate = random_row['int_rate']
        revol_util = random_row['revol_util']
        bc_open_to_buy = random_row['bc_open_to_buy']
        revol_bal = random_row['revol_bal']
        avg_cur_bal = random_row['avg_cur_bal']
        total_bal_ex_mort = random_row['total_bal_ex_mort']
        annual_inc = random_row['annual_inc']
        loan_amnt = random_row['loan_amnt']

        input_data = {
        'last_pymnt_amnt': last_pymnt_amnt,
        'dti': dti,
        'mo_sin_old_rev_tl_op': mo_sin_old_rev_tl_op,
        'int_rate': int_rate,
        'revol_util': revol_util,
        'bc_open_to_buy': bc_open_to_buy,
        'revol_bal': revol_bal,
        'avg_cur_bal': avg_cur_bal,
        'total_bal_ex_mort': total_bal_ex_mort,
        'annual_inc': annual_inc,
        'loan_amnt': loan_amnt
        }

        input_df = pd.DataFrame([input_data])
        prediction = pipeline.predict(input_df)
        predict_proba = pipeline.predict_proba(input_df)

        if prediction[0] == 1:
            return f'Fully paid with: {round(predict_proba[0][1] * 100, 2)}% probability \n\nRandomly Generated Row:\n {random_row}'
        else:
            return f'Charged Off with: {round(predict_proba[0][0] * 100, 2)}% probability \nRandomly Generated Row:\n {random_row}'

    else:
        input_data = {
            'last_pymnt_amnt': last_pymnt_amnt,
            'dti': dti,
            'mo_sin_old_rev_tl_op': mo_sin_old_rev_tl_op,
            'int_rate': int_rate,
            'revol_util': revol_util,
            'bc_open_to_buy': bc_open_to_buy,
            'revol_bal': revol_bal,
            'avg_cur_bal': avg_cur_bal,
            'total_bal_ex_mort': total_bal_ex_mort,
            'annual_inc': annual_inc,
            'loan_amnt': loan_amnt
        }

        input_df = pd.DataFrame([input_data])
        prediction = pipeline.predict(input_df)
        predict_proba = pipeline.predict_proba(input_df)

        if prediction[0] == 1:
            return f'Fully paid with {round(predict_proba[0][1] * 100, 2)}% probability'
        else:
            return f'Charged Off with {round(predict_proba[0][0] * 100, 2)}% probability'

# Create the Gradio interface
iface = gr.Interface(
    fn=predict_loan_approval,
    inputs=input_components,
    outputs='text',
    title='Loan Approval Predictor',
    description='If you are using the random row generator, click the button to generate a random row. Then click the Submit button to make a prediction.'
)
iface.launch(server_port=7000, server_name='0.0.0.0')


'''
 $Revision: 1.0 $
 $Author: kunzhong $
 $Date: 2020/03 $
'''

import time
import signal
import socket
import string
import struct
import re
import subprocess
import platform
import sys
import os
import math

#二叉树定义
class BinaryTree(object):
    def __init__(self):
        self.data = None
        self.left_child = None
        self.right_child = None

#删除一个二叉树节点
#@node_p 要删除的节点
#@node_p_parent 要删点的父节点
def delete_binary_tree(node_p_parent, node_p):
    #假如删除的是某个节点的左孩子
    if node_p_parent.left_child == node_p:
        if not node_p.right_child:
            node_p_parent.left_child = node_p.left_child
        elif not node_p.left_child:
            node_p_parent.left_child = node_p.right_child
        else:
            node_s = node_p.left_child
            node_s_parent = node_s
            while node_s.right_child: #找到最右叶子节点，也就是左子树最大节点
                node_s_parent = node_s
                node_s = node_s.right_child

            if node_s_parent != node_s: #左子树不止一个节点
                node_s_parent.right_child = node_s.left_child
                node_s.left_child = node_p.left_child

            node_s.right_child = node_p.right_child
            node_p_parent.left_child = node_s

    elif node_p_parent.right_child == node_p:
        if not node_p.right_child:
            node_p_parent.right_child = node_p.left_child
        elif not node_p.left_child:
            node_p_parent.right_child = node_p.right_child
        else:
            node_s = node_p.left_child
            node_s_parent = node_s
            while node_s.right_child:
                node_s_parent = node_s
                node_s = node_s.right_child

            if node_s_parent != node_s:
                node_s_parent.right_child = node_s.left_child
                node_s.left_child = node_p.left_child

            node_s.right_child = node_p.right_child
            node_p_parent.right_child = node_s

    else:
        print("not mached")

    return

#查找二叉排序树，返回查到的节点
#@array index start from 1
#@low start from 1

node_key_parent = None #parent of key node
def search_binary_tree(bi_tree, key):
    global node_key_parent
    if bi_tree.data == key:
        print("find key %d at %d" % (key, key))
        return bi_tree
    elif bi_tree.data > key and bi_tree.left_child != None:
        node_key_parent = bi_tree
        return search_binary_tree(bi_tree.left_child, key)
    elif bi_tree.data < key and bi_tree.right_child != None:
        node_key_parent = bi_tree
        return search_binary_tree(bi_tree.right_child, key)
    else:
        print("can not find key")
        return

    return

#递归法构建一颗静态二叉排序树
#@array 有序数列
def build_binary_tree(bi_tree, array, low, high):
    i_mid = int((low + high)/2)
    bi_tree.data = array[i_mid]

    if low == i_mid:
        bi_tree.left_child = None
    else:
        bi_tree.left_child = BinaryTree()
        build_binary_tree(bi_tree.left_child, array, low, i_mid - 1)

    if high == i_mid:
        bi_tree.right_child = None
    else:
        bi_tree.right_child = BinaryTree()
        build_binary_tree(bi_tree.right_child, array, i_mid + 1, high)

    return

if __name__ == '__main__':

    #构造一颗二叉排序树
    bi_tree = BinaryTree()
    build_binary_tree(bi_tree, [10, 20, 30, 40, 50, 60, 70, 80], 0, 7)

    find_node = search_binary_tree(bi_tree, 10)
    if node_key_parent and find_node:
        delete_binary_tree(node_key_parent, find_node)
    #quit
    print("Quit successfull");


def main(input_lines):
    diagnostic_report = [
        [int(bit) for bit in diagnostic_line] for diagnostic_line in input_lines
    ]

    gamma_rate, epsilon_rate = analyze_power_consumption(diagnostic_report)
    power_consumption = gamma_rate * epsilon_rate

    oxygen_generator_rating, co2_scrubber_rating = analyze_life_support(
        diagnostic_report
    )
    life_support_rating = oxygen_generator_rating * co2_scrubber_rating

    return power_consumption, life_support_rating

def binary_to_int(bin_number):
    # Horner's method for polynomial evaluation
    int_number = 0
    for bit in bin_number:
        int_number = 2 * int_number + bit
    return int_number

def analyze_power_consumption(diagnostic_report):
    """Find the gamma and epsilon rates from the diagnostic report

    Args:
        diagnostic_report (list of lists of bits, len = n x m)

    Return:
        gamma_rate (int): the i-th bit is the most common element of the report i-th column
        epsilon_rate (int): the i-th bit is the least common element of the report i-th column

    Remark:
        Since each element of the diagnostic_report matrix is a bit (0 or 1),
    If the most common element of a column is 1, then the least common must be 0 (and reciprocally).
    So the binary representations of gamma_rate and epsilon_rate are exactly flipped.
    And they sum to: 111...1 (m bits) = 2^m - 1
    """
    n = len(diagnostic_report)  # pylint: disable=invalid-name
    m = len(diagnostic_report[0])  # pylint: disable=invalid-name

    column_sum = [0] * m
    for diagnostic_line in diagnostic_report:
        for i, bit in enumerate(diagnostic_line):
            column_sum[i] += bit

    most_common_bits = []
    for bit_sum in column_sum:
        most_common_bit = int(bit_sum >= (n + 1) // 2)
        most_common_bits.append(most_common_bit)

    gamma_rate = binary_to_int(most_common_bits)
    epsilon_rate = (2**m - 1) - gamma_rate

    return gamma_rate, epsilon_rate

def find_most_common_bit(bin_numbers, position):
    n_numbers = len(bin_numbers)
    bit_sum = sum(bin_number[position] for bin_number in bin_numbers)
    most_common_bit = int(bit_sum >= (n_numbers + 1) // 2)
    return most_common_bit

def analyze_life_support(diagnostic_report):
    m = len(diagnostic_report[0])  # pylint: disable=invalid-name

    oxygen_generator_rating_candidates = diagnostic_report
    for position in range(m):
        if len(oxygen_generator_rating_candidates) == 1:
            break
        most_common_bit = find_most_common_bit(
            oxygen_generator_rating_candidates, position
        )
        oxygen_generator_rating_candidates = [
            rating_candidate
            for rating_candidate in oxygen_generator_rating_candidates
            if (rating_candidate[position] == most_common_bit)
        ]
    oxygen_generator_rating = binary_to_int(oxygen_generator_rating_candidates[0])

    co2_scrubber_rating_candidates = diagnostic_report
    for position in range(m):
        if len(co2_scrubber_rating_candidates) == 1:
            break
        most_common_bit = find_most_common_bit(co2_scrubber_rating_candidates, position)
        co2_scrubber_rating_candidates = [
            rating_candidate
            for rating_candidate in co2_scrubber_rating_candidates
            if (rating_candidate[position] == (1 - most_common_bit))
        ]
    co2_scrubber_rating = binary_to_int(co2_scrubber_rating_candidates[0])

    return oxygen_generator_rating, co2_scrubber_rating