##############################################
# book_writing_service.py
from enum import Enum
from typing import Union
from datetime import timedelta

from pydantic import BaseModel

class Success(BaseModel):
    book_title: str
    text: str
    time_to_generate: timedelta

class Failed(BaseModel):
    reason: str

class ResultStatus(str, Enum):
    SUCCESS = "SUCCESS"
    FAILED = "FAILED"

class Result(BaseModel):
    status: ResultStatus
    worker_name: str
    data: Union[Success, Failed]

class BookWritingService:
    def write_book(self, book_title: str) -> Result:
        if book_title:
            # ...do complicated stuff here
            return Result(
                status=ResultStatus.SUCCESS,
                worker_name="worker01",
                data=Success(
                    book_title=book_title,
                    text=f"Once there was a {book_title}. THE END",
                    time_to_generate=0,
                ),
            )

        else:
            return Result(
                status=ResultStatus.FAILED,
                worker_name="worker01",
                data=Failed(public_reason="Empty book title"),
            )


from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^islc_2014/', include('islc_2014.foo.urls')),
    # Admin pages
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),

    # website urls
    url(r'^', include('website.urls')),
)


from collections import deque

N,M,T = map(int, input().split())
lst = [list(map(int, input().split())) for _ in range(N)]
dr = [0,1,0,-1]
dc = [1,0,-1,0]
visit = [[[False] * 2 for _ in range(M)] for _ in range(N)]
visit[0][0][0] = True
queue = deque()
queue.append([0,0,0,0])

def bfs():
    while queue:
        q = queue.popleft()
        r, c, t, weapon = q[0], q[1], q[2], q[3]

        if t > T:
            print("Fail")
            return

        if r == N-1 and c == M-1:
            print(str(t))
            return

        for i in range(4):
            nr = r + dr[i]
            nc = c + dc[i]
            nt = t + 1
            if 0 <= nr < N and 0 <= nc < M and not visit[nr][nc][weapon]:
                if weapon == 1:
                    visit[nr][nc][weapon] = True
                    queue.append([nr, nc, nt, 1])
                else:
                    if lst[nr][nc] == 0:
                        visit[nr][nc][weapon] = True
                        queue.append([nr, nc, nt, 0])
                    elif lst[nr][nc] == 2:
                        visit[nr][nc][weapon] = True
                        queue.append([nr, nc, nt, 1])
    print("Fail")
    return
bfs()


from django.contrib import admin

from postac.models import ZestawCechPostaci, Umiejetnosc, Profesja, Postac

class PostacAdmin(admin.ModelAdmin):
    ordering = ('nazwa',)
    list_display = ('nazwa', 'uzytkownik')
    list_display_links = ('nazwa',)
    list_per_page = 50
    list_filter = ('nazwa', 'uzytkownik')
    search_fields = ('question_text',)
    actions = ('cleanup_text', 'example_suffix')
    fieldsets = [
        ('General', {
            'fields': ['nazwa'],
            'description': 'General_info'
        }),
        ('External Information', {
            'fields': ['uzytkownik', 'wiek', 'cechy', 'um', 'profesja', 'ekwipunek', 'historia', 'uzbrojenie'],
            'description': 'Additional Info'
        })
    ]

class ProfesjaAdmin(admin.ModelAdmin):
    ordering = ('nazwa',)
    list_display = ('nazwa',)
    list_display_links = ('nazwa',)
    list_per_page = 50
    list_filter = ('nazwa',)
    search_fields = ('nazwa',)
    actions = ('cleanup_text', 'example_suffix')
    fieldsets = [
        ('General', {
            'fields': ['nazwa'],
            'description': 'General_info'
        }),
        ('External Information', {
            'fields': ['punkty_do_wydania', 'majetnosc_min', 'majetnosc_max',
                       'um_stale', 'wybor1', 'wybor2', 'wybor3', 'wybor4'],
            'description': 'Additional Info'
        })
    ]

admin.site.register(ZestawCechPostaci)
admin.site.register(Umiejetnosc)
admin.site.register(Profesja, ProfesjaAdmin)
admin.site.register(Postac, PostacAdmin)


import sys
from PyQt5 import QtWidgets, QtGui, QtCore
import design
import numpy as np
from math import fabs
import time

class Visual(QtWidgets.QMainWindow, design.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.label.setPalette(QtGui.QPalette(QtCore.Qt.white))
        self.black = QtGui.QColor(QtCore.Qt.black)
        self.white = QtGui.QColor(QtCore.Qt.white)
        self.colour = QtGui.QColor(QtCore.Qt.black)
        self.labelColour.setPalette(QtGui.QPalette(QtCore.Qt.black))
        self.labelColour.setAutoFillBackground(True)

        self.pm = QtGui.QPixmap(541, 436)
        self.pm.fill(self.white)
        self.img = self.pm.toImage()
        self.imgbg = self.pm.toImage()

        self.maxX = 0
        self.minX = 1500
        self.maxY = 0
        self.minY = 1500
        self.objX = np.array([], dtype=int)
        self.objY = np.array([], dtype=int)

        # Связи кнопок и функций.
        self.pushButtonScreenClean.clicked.connect(self.clean_screen)
        self.pushButtonChooseColour.clicked.connect(self.choose_color)
        self.pushButtonFill.clicked.connect(self.fill)
        self.pushButtonTime.clicked.connect(self.count_time)

    def bres_int(self, x_start, y_start, x_end, y_end):
        dx = x_end - x_start
        dy = y_end - y_start
        sx = sign(dx)
        sy = sign(dy)
        dx = fabs(dx)
        dy = fabs(dy)
        if dy >= dx:
            dx, dy = dy, dx
            fl = 1
        else:
            fl = 0
        f = 2 * dy - dx
        x = round(x_start)
        y = round(y_start)
        i = 1
        while i <= dx + 1:
            self.img.setPixel(x, y, self.black.rgb())
            if f >= 0:
                if fl == 1:
                    x += sx
                else:
                    y += sy
                f -= 2 * dx
            if f <= 0:
                if fl == 1:
                    y += sy
                else:
                    x += sx
                f += 2 * dy
            i += 1

    def bres_int_special(self, x_start, y_start, x_end, y_end):
        dx = fabs(x_end - x_start)
        dy = fabs(y_end - y_start)
        stepx = sign(x_end - x_start)
        stepy = sign(y_end - y_start)
        if dy > dx:
            dx, dy = dy, dx
            flag = 1
        else:
            flag = 0
        e = 2 * dy - dx
        lasty = y_start
        x = x_start
        y = y_start
        for i in range(0, round(dx)):
            if lasty != y:
                lasty = y
                self.imgbg.setPixel(x, y, self.black.rgb())
            if e >= 0:
                if flag == 1:
                    x += stepx
                else:
                    y += stepy
                e -= 2 * dx
            if e < 0:
                if flag == 1:
                    y += stepy
                else:
                    x += stepx
            e += 2 * dy

    def add_extra_pixels(self, minX, minY, maxX, maxY):
        for y in range(minY, maxY + 1):
            flag = False
            for x in range(minX, maxX + 1):
                if flag and self.imgbg.pixelColor(x, y) == self.black:
                    flag = False
                    continue
                if self.imgbg.pixelColor(x, y) == self.black:
                    flag = True
                    bx = x
                    by = y
            if flag:
                self.imgbg.setPixel(bx + 1, by, self.black.rgb())

    def choose_color(self):
        self.colour = QtWidgets.QColorDialog.getColor()
        self.labelColour.setPalette(QtGui.QPalette(self.colour))

    def mousePressEvent(self, press):
        self.img = self.pm.toImage()
        if press.button() == QtCore.Qt.LeftButton:
            self.objX = np.append(self.objX, (press.pos() - self.label.pos()).x())
            self.objY = np.append(self.objY, (press.pos() - self.label.pos()).y())
            if self.objX.size >= 2:
                self.bres_int(self.objX[self.objX.size - 2], self.objY[self.objY.size - 2],
                              self.objX[self.objX.size - 1], self.objY[self.objY.size - 1])
                self.bres_int_special(self.objX[self.objX.size - 2], self.objY[self.objY.size - 2],
                                      self.objX[self.objX.size - 1], self.objY[self.objY.size - 1])
        elif press.button() == QtCore.Qt.RightButton:
            if self.objX.size >= 3:
                self.bres_int(self.objX[0], self.objY[0], self.objX[self.objX.size - 1], self.objY[self.objY.size - 1])
                self.bres_int_special(self.objX[0], self.objY[0],
                                      self.objX[self.objX.size - 1], self.objY[self.objY.size - 1])
                self.add_extra_pixels(min(self.objX), min(self.objY), max(self.objX), max(self.objY))
            if self.minX > min(self.objX):
                self.minX = min(self.objX)
            if self.maxX < max(self.objX):
                self.maxX = max(self.objX)
            if self.minY > min(self.objY):
                self.minY = min(self.objY)
            if self.maxY < max(self.objY):
                self.maxY = max(self.objY)
            self.objX = np.array([], dtype=int)
            self.objY = np.array([], dtype=int)
        self.pm = self.pm.fromImage(self.img)
        self.label.setPixmap(self.pm)

    def wait(self, t):
        loop = QtCore.QEventLoop()
        QtCore.QTimer.singleShot(t, loop.quit)
        loop.exec_()

    def update_image(self):
        self.pm = self.pm.fromImage(self.imgbg)
        self.label.setPixmap(self.pm)
        self.label.repaint()

    def fill(self, draw=True, delay=True):
        for y in range(self.minY, self.maxY + 1):
            flag = False
            for x in range(self.minX, self.maxX + 1):
                if self.imgbg.pixelColor(x, y) == self.black:
                    flag = not flag
                if flag:
                    self.imgbg.setPixel(x, y, self.colour.rgb())
                else:
                    self.imgbg.setPixel(x, y, self.white.rgb())
            if delay and int(self.lineEditDelay.text()) > 0:
                self.update_image()
                self.wait(int(self.lineEditDelay.text()))
        self.update_image()

    def count_time(self):
        start = time.time()
        self.fill(True, False)
        self.lineEditTime.setText(str(round(time.time() - start, 4)))
        self.lineEditTime.repaint()

    def clean_screen(self):
        self.pm.fill(self.white)
        self.imgbg = self.pm.toImage()
        self.label.setPixmap(self.pm)
        self.label.repaint()
        self.objX = np.array([], dtype=int)
        self.objY = np.array([], dtype=int)
        self.minX = 1500
        self.minY = 1500
        self.maxX = 0
        self.maxY = 0

def sign(x):
    if x < 0:
        return -1
    elif x > 0:
        return 1
    return 0

def main():
    app = QtWidgets.QApplication(sys.argv)
    window = Visual()
    window.show()
    app.exec_()

if __name__ == '__main__':
    main()


"""
Utility to convert a supported document to a Comic Book archive.

License: GNU AGPL 3.0
Author: (c) Harald Lieder, harald.lieder@outlook.com
Date: 2021-08-30
"""

import os
import sys
import zipfile

import fitz

def main(doc, outfile=None, pages=None, dpi=96):
    if outfile is None:
        if doc.name:
            filename, _ = os.path.splitext(doc.name)
            outfile = filename + ".cbz"
        elif __file__.endswith(".py"):
            outfile = __file__.replace(".py", ".cbz")
        else:
            outfile = "out.cbz"
    zipout = zipfile.ZipFile(
        outfile,
        "w",
        compression=zipfile.ZIP_STORED,
    )
    if pages is None:
        pages = range(doc.page_count)
    zoom = dpi / 72
    mat = fitz.Matrix(zoom, zoom)
    for pno in pages:
        page = doc[pno]
        pix = page.get_pixmap(matrix=mat)
        pix.set_dpi(dpi, dpi)
        pagename = "p%05i.png" % (pno + 1)
        zipout.writestr(pagename, pix.tobytes("png"))
    zipout.close()

if __name__ == "__main__":
    filename = sys.argv[1]
    doc = fitz.open(filename)
    main(doc)


"""
About: Script to plot the power consumption boundaries
and temperature of the tested CPU.
"""

import sys
import os
import numpy as np
import matplotlib.pyplot as plt

freq2idx = {"800-MHz": 0, "3400-MHz": 1, "4000-MHz": 2}

def getData(path, power, temp, pos, mask):
    plot_name = None
    for file in os.listdir(path):
        filename = os.fsdecode(file)
        file = path + filename

        if file.endswith("ts"):
            if plot_name is None:
                plot_name = filename.split("_")[1:3]
                plot_name = (plot_name[0] + "_" + plot_name[1]).split(".")[0]
            m_idx = freq2idx[filename.split("_")[0]]
            data = np.genfromtxt(file, delimiter=",")[2::mask]
            power[m_idx] = data[:, 4].copy()
            temp[m_idx] = data[:, 2].copy()

    return plot_name

def getStats(data):
    m_stats = []

    m_stats.append(np.mean(data, axis=1))
    m_stats.append(np.std(data, axis=1))

    return m_stats

def getLegend(raw_legend, stats):
    m_label = []

    for m_idx in range(0, stats[0].shape[0], 1):
        m_label.append(
            raw_legend[m_idx]
            + "; µ: "
            + str(round(stats[0][m_idx], 3))
            + ", std: "
            + str(round(stats[1][m_idx], 4))
        )

    return m_label

def makePlot(data, title=None, ylabel=None, legend=None, savedir=None):
    stats = getStats(data)
    new_legend = None
    if legend:
        new_legend = getLegend(legend, stats)
    for m_idx in range(0, data.shape[0], 1):
        plt.plot(data[m_idx])

    plt.grid()
    plt.title(title)
    plt.ylabel(ylabel)
    plt.xlabel("Iteration")
    plt.legend((new_legend))
    if savedir:
        savedir += "_" + ylabel.split(" ")[0] + ".png"
        print(savedir)
        plt.savefig(savedir)
        plt.close()
    else:
        plt.show()

if __name__ == "__main__":
    path = "./turbostat_stats/30/"
    savedir = "./turbostat_stats/"
    mask = 3
    pos = 4
    num_it = 10
    frequencies = 3
    power = np.zeros((frequencies, num_it))
    temperature = np.zeros((frequencies, num_it))
    raw_legend = ["800 MHz", "3400 MHz", "4000MHz"]

    plot_name = getData(path, power, temperature, pos, mask)
    savedir += plot_name

    makePlot(
        power,
        title="Power Consumption",
        ylabel="power consumption [W]",
        legend=raw_legend,
        savedir=savedir,
    )
    makePlot(
        temperature,
        title="CPU Package Temperature",
        ylabel="temperature [°C]",
        legend=raw_legend,
        savedir=savedir,
    )


"""HTML Stripper

Strips away all the HTML from a string.

Contains portions of Universal Feed Parser by Mark Pilgrim (http://feedparser.org/)

"""

__license__ = """Copyright (c) 2006, Lawrence Oluyede, All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE."""

__feedparser_license__ = """Copyright (c) 2002-2006, Mark Pilgrim, All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE."""

import sgmllib
import re

class _BaseHTMLProcessor(sgmllib.SGMLParser):
    elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
      'img', 'input', 'isindex', 'link', 'meta', 'param']

    def __init__(self, encoding):
        self.encoding = encoding
        sgmllib.SGMLParser.__init__(self)

    def reset(self):
        self.pieces = []
        sgmllib.SGMLParser.reset(self)

    def _shorttag_replace(self, match):
        tag = match.group(1)
        if tag in self.elements_no_end_tag:
            return '<' + tag + ' />'
        else:
            return '<' + tag + '></' + tag + '>'

    def feed(self, data):
        data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'<!\1', data)
        #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace
        data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data)
        data = data.replace(''', "'")
        data = data.replace('"', '"')
        if self.encoding and type(data) == type(u''):
            data = data.encode(self.encoding)
        sgmllib.SGMLParser.feed(self, data)

    def normalize_attrs(self, attrs):
        # utility method to be called by descendants
        attrs = [(k.lower(), v) for k, v in attrs]
        attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
        return attrs

    def unknown_starttag(self, tag, attrs):
        # called for each start tag
        # attrs is a list of (attr, value) tuples
        # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
        uattrs = []
        # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
        for key, value in attrs:
            if type(value) != type(u''):
                value = unicode(value, self.encoding)
            uattrs.append((unicode(key, self.encoding), value))
        strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]).encode(self.encoding)
        if tag in self.elements_no_end_tag:
            self.pieces.append('<%(tag)s%(strattrs)s />' % locals())
        else:
            self.pieces.append('<%(tag)s%(strattrs)s>' % locals())

    def unknown_endtag(self, tag):
        # called for each end tag, e.g. for </pre>, tag will be 'pre'
        # Reconstruct the original end tag.
        if tag not in self.elements_no_end_tag:
            self.pieces.append("</%(tag)s>" % locals())

    def handle_charref(self, ref):
        # called for each character reference, e.g. for ' ', ref will be '160'
        # Reconstruct the original character reference.
        self.pieces.append('&#%(ref)s;' % locals())

    def handle_entityref(self, ref):
        # called for each entity reference, e.g. for '©', ref will be 'copy'
        # Reconstruct the original entity reference.
        self.pieces.append('&%(ref)s;' % locals())

    def handle_data(self, text):
        # called for each block of plain text, i.e. outside of any tag and
        # not containing any character or entity references
        # Store the original text verbatim.
        self.pieces.append(text)

    def handle_comment(self, text):
        # called for each HTML comment, e.g. <!-- insert Javascript code here -->
        # Reconstruct the original comment.
        self.pieces.append('<!--%(text)s-->' % locals())

    def handle_pi(self, text):
        # called for each processing instruction, e.g. <?instruction>
        # Reconstruct original processing instruction.
        self.pieces.append('<?%(text)s>' % locals())

    def handle_decl(self, text):
        # called for the DOCTYPE, if present, e.g.
        # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        #     "http://www.w3.org/TR/html4/loose.dtd">
        # Reconstruct original DOCTYPE
        self.pieces.append('<!%(text)s>' % locals())

    _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
    def _scan_name(self, i, declstartpos):
        rawdata = self.rawdata
        n = len(rawdata)
        if i == n:
            return None, -1
        m = self._new_declname_match(rawdata, i)
        if m:
            s = m.group()
            name = s.strip()
            if (i + len(s)) == n:
                return None, -1  # end of buffer
            return name.lower(), m.end()
        else:
            self.handle_data(rawdata)
            return None, -1

    def output(self):
        '''Return processed HTML as a single string'''
        return ''.join([str(p) for p in self.pieces])

class _HTMLSanitizer(_BaseHTMLProcessor):
    acceptable_elements = []
##     ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
##      'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',
##      'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset',
##      'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input',
##      'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'optgroup',
##      'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike',
##      'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th',
##      'thead', 'tr', 'tt', 'u', 'ul', 'var']

    acceptable_attributes = []
##     ['abbr', 'accept', 'accept-charset', 'accesskey',
##      'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing',
##      'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols',
##      'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled',
##      'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace',
##      'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method',
##      'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly',
##      'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size',
##      'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type',
##      'usemap', 'valign', 'value', 'vspace', 'width']

    unacceptable_elements_with_end_tag = ['script', 'applet']

    def reset(self):
        _BaseHTMLProcessor.reset(self)
        self.unacceptablestack = 0

    def unknown_starttag(self, tag, attrs):
        if not tag in self.acceptable_elements:
            if tag in self.unacceptable_elements_with_end_tag:
                self.unacceptablestack += 1
            return
        attrs = self.normalize_attrs(attrs)
        attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes]
        _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)

    def unknown_endtag(self, tag):
        if not tag in self.acceptable_elements:
            if tag in self.unacceptable_elements_with_end_tag:
                self.unacceptablestack -= 1
            return
        _BaseHTMLProcessor.unknown_endtag(self, tag)

    def handle_pi(self, text):
        pass

    def handle_decl(self, text):
        pass

    def handle_data(self, text):
        if not self.unacceptablestack:
            _BaseHTMLProcessor.handle_data(self, text)

def stripHTML(htmlSource, encoding):
    p = _HTMLSanitizer(encoding)
    p.feed(htmlSource)
    data = p.output()
    data = data.strip().replace('\r\n', '\n')
    return data


#Exercise 1 – Random Sentence Generator
import random
def get_word_from_file(file):
    with open(file, 'r') as f:
        sentence = f.readlines()
        return sentence

def get_random_sentence(length):
    words_list = get_word_from_file("sowpods.txt")
    words = []
    for x in range(length):
        x = random.choice(words_list)
        words.append(x[:-2])
        return "  ".join(words).lower()

def main():
    """this program will accept integer values between 2 and 20"""
    number_words = int(input("Please enter how long do you want your sentence to be(Please enter between 2 and 20):  "))
    try:
        if 2 <= number_words <= 20:
            return get_random_sentence(number_words)
        else:
            return 'Your number is not between 2 and 20'
    except:
        return'not a number'
print(main.__doc__)
print(main())

#Exercise 2: Working With JSON
#
# import json
# sampleJson = """{
#    "company":{
#       "employee":{
#          "name":"emma",
#          "payable":{
#             "salary":7000,
#             "bonus":800
#          }
#       }
#    }
# }"""
#
# sample_dict = json.loads(sampleJson)
# print(sample_dict["company"]["employee"]["payable"]["salary"])
# sample_dict["company"]["employee"]['birth_date'] = 2000/11/11
# print(sample_dict["company"]["employee"])
#
# sample_file = "samplefile.json"
# with open('sample_json','w') as f:
#     json.dump(sample_dict,f,indent=4)
#
#


import webapp2
from google.appengine.api import users

class MainPage(webapp2.RequestHandler):
	"""docstring for MainPage"""
	def get(self):
		# check for active Google account session
		user = users.get_current_user()

		if user:
			# logged in user
			self.response.headers['Content-Type'] = 'text/plain';
			self.response.write("Hello, %s" % user.nickname())
		else:
			# not logged in
			self.redirect(users.create_login_url(self.request.uri))

app = webapp2.WSGIApplication([
	('/', MainPage),
	], 	debug=True)


import os
import requests
import shutil
import pandas as pd

from zipfile import ZipFile
from os.path import basename

def download_image_web(df, image_url, filename, directory):
	imagem_download = []
	for i in range(len(df)):

		url = str(df[image_url][i])
		file_name = str(df[filename][i])
		file_name =  os.path.join(directory, str(file_name) + ".jpg")
		r = requests.get(url, stream = True)

		if r.status_code == 200:
			imagem_download.append("SIM")
			r.raw.decode_intent = True
			with open(file_name, "wb") as f:
				shutil.copyfileobj(r.raw, f)
		else:
			imagem_download.append("NÃO")

	return imagem_download

def zip_folder(directory):

	dirName = directory

	# create a ZipFile object
	with ZipFile('images.zip', 'w') as zipObj:
	   # Iterate over all the files in directory
	   for folderName, subfolders, filenames in os.walk(dirName):
	       for filename in filenames:
	           #create complete filepath of file in directory
	           filePath = os.path.join(folderName, filename)
	           # Add file to zip
	           zipObj.write(filePath, basename(filePath))

def delete_all_files(directory):

	folder = directory
	for filename in os.listdir(folder):
		file_path = os.path.join(folder, filename)
		try:
			if os.path.isfile(file_path) or os.path.islink(file_path):
				os.unlink(file_path)
			elif os.path.isdir(file_path):
				shutil.rmtree(file_path)
		except Exception as e:
			print('Failed to delete %s. Reason: %s' % (file_path, e))


import numpy as np
import os
import time
from datetime import datetime

func_loc = r'D:\freeze-score'
new_path = r'G:\My Drive\lab\pickle\fz_score'  #folder to store score output (versioning, one dict) and progress txt file

os.chdir(func_loc)

from function import Process
from function import Setup
from function import UserSelect
from function import LightTime
from function import Video
from function import Pickle

new_folder_path, master_path, individual_path = Process.initiate(new_path)
files, sub_dir = Setup.get_files()
## Setup.filter(), remove ones already existing from pickle.

# initial video light and arena check/crop
arena_dict = {}
light_dict = {}
for mouse in files:
    path = Setup.find_path(mouse,sub_dir)

    # light and arena for B
    for by_day in files[mouse]:
        file, txt_file, context = Setup.select_file_ctx(mouse, by_day, path, files, sub_dir)

        if context == 'B':
            print('')
            print(mouse, by_day[0])
            mouse_id, shock_num, tone_duration, initial_delay = UserSelect.get_info_txt(txt_file)

            if 'wt8' in mouse:                   #if rectangle contextBO
                light = np.array([350,0,30,30])
            else:                                #if circle contextB
                arena = UserSelect.circle(file)
                arena_dict[mouse] = arena

                light = UserSelect.light_crop(file, initial_delay)[0]

            light_dict[mouse] = light
            up_error, down_error = UserSelect.optimal_thresh(file, light, initial_delay)

    # thresh hold check for A
    for by_day in files[mouse]:
        file, txt_file, context = Setup.select_file_ctx(mouse, by_day, path, files, sub_dir)

        if context == 'A':
            mouse_id, shock_num, tone_duration, initial_delay = UserSelect.get_info_txt(txt_file)
            light = np.array([360,0,20,20])
            up_error, down_error = UserSelect.optimal_thresh(file, light, initial_delay)

print("\n\n=======================================================")
print("Passed light tests...! Starting video analyzation...\n\n")

# progress indication
total = 0
for _ in files.values():
    total = total + len(_)
vid_rn = 0

a = time.time()
final_start = datetime.now().strftime('%I:%M %p')

final_dict = {}
pres_error = {}

# video processing
for mouse in files:

    path = Setup.find_path(mouse,sub_dir)
    for by_day in files[mouse]:

        vid = f'{mouse} {by_day[0]}'  #name of vid
        Process.mouse(new_folder_path, vid)
        start = time.time()

        file, txt_file, context = Setup.select_file_ctx(mouse, by_day, path, files, sub_dir)

        if context == 'A':
            light = np.array([360,0,20,20])

        elif context == 'B':
            light = light_dict[mouse]

        mouse_id, shock_num, tone_duration, initial_delay = UserSelect.get_info_txt(txt_file)
        up_error, down_error = UserSelect.optimal_thresh(file, light, initial_delay)

        # light initiation, timestamps (when light comes on)
        lightup = LightTime.light_on(file, light, up_error)
        ivalues, timestamps, pres_error = LightTime.check_timestamps(lightup, shock_num, new_folder_path, vid, pres_error)

        # light going off
        ivalues_2 = LightTime.light_off(file,light,ivalues,tone_duration,down_error)

        # finalize on and off with tuples
        on_off_idx = LightTime.integrate_lights(ivalues, ivalues_2)

        if context == 'A':
            pxl_shift = []
            pxl_shift = Video.square(file)

        elif context == 'B':
            if 'wt8' in mouse:                   #if rectangle contextB
                pxl_shift = Video.squareB(file)
            else:                                #if circle contextB
                pxl_shift = Video.circle(file,arena_dict[mouse])

        final = {'pxl_shift': pxl_shift, 'on_off_idx': on_off_idx, 'timestamps': timestamps}
        final_dict[vid] = final

        vid_rn = Process.append(vid_rn, new_folder_path, start, a, total)

# append final message to text file that it is all done
Process.final_append(a, final_start, new_folder_path)
Process.error_append(new_folder_path, pres_error)

# pickle save
Pickle.version(final_dict, master_path)
Pickle.by_mouse(final_dict, individual_path)


import socket
import http.client
import ssl
import time

from ..aws.ec2 import client as ec2_client

def create_socket():
    return socket.socket(socket.AF_INET, socket.SOCK_STREAM)

class ServiceManager(object):
    def __init__(self, instance=None, client=None):
        self.ec2 = client if client else ec2_client()
        self._instance = instance if instance else self.ec2_instance()

    def start_server(self):
        if self.ec2_instance().state.get('Name') == 'stopped':
            self._instance.start()
            self._instance.wait_until_running()

    def stop_server(self):
        self._instance.stop()

    def ec2_instance(self, client=None):
        if hasattr(self, '_instance'):
            return self._instance

        instances = self.ec2.instances.filter(
            Filters=[{'Name': 'tag:Name', 'Values': [self.instance_name()]}])
        for instance in instances:
            return instance

    def get_ip(self):
        return self._instance.public_ip_address

    def instance_name(self):
        return 'build-deploy-server-jenkins'

    def wait_until_ready(self):
        sock = create_socket()
        result = sock.connect_ex((self.get_ip(), 443))
        print('.', end='', flush=True)

        if result == 0:
            conn = http.client.HTTPSConnection(
              self.get_ip(),
              context=ssl._create_unverified_context()
            )

            conn.request('GET', '/')
            res = conn.getresponse()

            if res.status == 503:
                time.sleep(10)
                return self.wait_until_ready()
            return True
        else:
            time.sleep(10)
            return self.wait_until_ready()


"""
66. Plus One

You are given a large integer represented as an integer array digits,
where each digits[i] is the ith digit of the integer.
The digits are ordered from most significant to least significant in left-to-right order.
The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:

Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].

Constraints:

1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.

"""

from typing import List
from unicodedata import digit

def my_timer(func):
    import time
    def wrapper(*args, **kwargs):
        t1 = time.perf_counter()
        result = func(*args, **kwargs)
        t2 = time.perf_counter() - t1
        s = int(t2)
        ms = int(t2*10**3)
        us = int(t2*10**6)
        dt = "{}.{}.{}s".format(s, ms, us)
        print('{0} ran in : {1}'.format(func.__name__, dt))
        return result
    return wrapper

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """

        n = len(digits)

        carry = 0
        for i in range(n):
            d = digits[n-i-1] + carry
            if i == 0: d += 1
            if d == 10:
                carry = 1
                d = 0
            else: carry = 0
            digits[n-i-1] = d

        if carry == 1: digits = [1] + digits

        return digits

@my_timer
def test_case(*args, **kwargs):
    ans = Solution().plusOne(*args, **kwargs)
    print(ans)
    return ans

if __name__ == "__main__":
    arg = [1, 2, 3]
    ans = test_case(arg)
    arg = [9]
    ans = test_case(arg)
    arg = [4, 3, 2, 1]
    ans = test_case(arg)


import os
import sys

sys.path.insert(-1, os.getcwd())
sys.path.insert(-1, os.path.dirname(os.getcwd()))

from spambayes.Options import get_pathname_option
from spambayes import msgs, TestDriver
from tabulate import tabulate
from mislabeledfilemover import MislabeledFileMover
from dictionarywriter import DictionaryWriter
from dictionarysets import write_dictionary_sets

def main():

    ham = [get_pathname_option("TestDriver", "ham_directories") % i for i in range(1, 4)]
    spam = [get_pathname_option("TestDriver", "spam_directories") % i for i in range(1, 4)]

    sizes = [0, 60, 120, 240, 480, 840, 1200, 2400, 3600, 4800, 6000]

    d = TestDriver.Driver()
    d.new_classifier()

    detection_rates = []
    target_rates    = []
    false_positives = []
    false_negatives = []
    unsures         = []

    for size in sizes:

        mislabeler = MislabeledFileMover(size)
        mislabeler.random_move_file()

        d.train(msgs.HamStream(ham[0], [ham[0]]),
            msgs.SpamStream(spam[0], [spam[0]]))
        d.test(msgs.HamStream(ham[1], [ham[1]]),
               msgs.SpamStream(spam[1], [spam[1]]))

        target_rate = d.tester.correct_classification_rate()
        target_rates.append(target_rate)

        d.train(msgs.HamStream(ham[2], [ham[2]]),
                msgs.SpamStream(spam[2], [spam[2]]))
        d.test(msgs.HamStream(ham[1], [ham[1]]),
               msgs.SpamStream(spam[1], [spam[1]]))

        detection_rate = d.tester.correct_classification_rate()
        detection_rates.append(detection_rate)

        fp = d.tester.nham_wrong
        false_positives.append(fp)
        fn = d.tester.nspam_wrong
        false_negatives.append(fn)
        unsure = d.tester.nham_unsure + d.tester.nspam_unsure
        unsures.append(unsure)

        d.untrain(msgs.HamStream(ham[0], [ham[0]]),
                  msgs.SpamStream(spam[0], [spam[0]]))
        d.untrain(msgs.HamStream(ham[2], [ham[2]]),
                  msgs.SpamStream(spam[2], [spam[2]]))

        mislabeler.reset()

    with open("/Users/AlexYang/Desktop/hamasspam.txt", 'w') as outfile:

        outfile.write(tabulate({"# of Mislabeled Words": sizes,
                                "Detection Rates": detection_rates,
                                "Target Rates": target_rates},
                               headers="keys", tablefmt="plain"))

if __name__ == "__main__":
    main()


# Project - Dance floor random partner pair

"""
Logic :
1. Read a name from user
2. It its girl then pick up a boy as partner & vice versa
3. Pairs should be unique (no boy or girl should be repeat)
4. Stop if dance floor is full or either list is empty
"""

import random as r
boys = ['Diptesh','Ajinkya','Yadnesh','Vishal','Ketan','Shubham','Pratik','Abhishek','Himanshu','Bhushan',
        'Uddesh','Ranapratapsingh','Yash','Niranjan','Swanand','Shantanu','Siddhesh','Suraj','Sanket',
        'Kiran','Umesh','Prasad']

girls = ['Mrunal','Priyanka','Sanjeevani','Yashashri','Ashwini','Yashshree','Trupti','Mansi','Geeta','Sakshi',
         'Vaishnavi','Nikita','Sayali','Utkarsha','Shivani','Chaitali','Ruchita','Uma','Nandini','Priyanka',
         'Vaishnavi','Shital']

pairs = int(input("Enter number of maximum pairs : "))
count = 0
while count < pairs:
    name = input("Enter Name : ")
    if name in boys:
        partner = r.choice(girls)
        boys.remove(name)
        girls.remove(partner)
        print(f"Hello {name}, Your Partner is {partner}")
        count += 1
    elif name in girls:
        partner = r.choice(boys)
        girls.remove(name)
        boys.remove(partner)
        print(f"Hello {name}, Your Partner is {partner}")
        count += 1
    else:
        print("Your Are Not Registered Or Already Picked Up...")

    if not boys or not girls:
        print("Sorry, No More Partners Left...")
        break

else:
    print("\nAll Pairs Are Formed...")


'''
Thoughts:

dfs problem
Pay attention to the definition of leaf
A node is only a leaf when:
1. node != None
2. node.left == node.right == None
Such criteria would be the indicator for exiting the recursion
When updating the "cur" array, append str(number) instead of number, which makes it easier when using '->'.join()

'''

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

class Solution:
	def binaryTreePaths(self, root):
		if not root:
			return []
		self.res = []
		self.helper(root, [])
		return self.res

	def helper(self, root, cur):
		if not root.left and not root.right:
			final = cur + [str(root.val)]
			self.res.append('->'.join(final))
		else:
			if root.left:
				self.helper(root.left, cur + [str(root.val)])
			if root.right:
				self.helper(root.right, cur + [str(root.val)])

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

inst = Solution()
print(inst.binaryTreePaths(root))


"""add comment countin article

Revision ID: 7c8925c45417
Revises: aa79ddca3b01
Create Date: 2022-01-12 12:46:36.877017

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '7c8925c45417'
down_revision = 'aa79ddca3b01'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('articles', sa.Column('comment_count', sa.Integer(), nullable=False))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('articles', 'comment_count')
    # ### end Alembic commands ###


# -*- coding: utf-8 -*-
# @Author: zhq
# @Date:   2017-09-24 12:17:16
# @Last Modified by:   zhq
# @Last Modified time: 2018-04-07 16:28:05

from tkinter import *

root = Tk()

textLabel = Label(root,text = "放置一张图片")

textLabel.pack(side = LEFT)

#支持gif格式的图片
photo = PhotoImage(file = "cdd.gif")

imaLabel = Label(root, image = photo)

imaLabel.pack(side = RIGHT)

mainloop()


print ("SI AL REFLEJO DE UN NUMERO CUALQUIERA LE RESTAS DICHO NUMERO")
print ("Y DICHA DIFERENCIA ES DIFERENTE DE O (PORQUE AMBOS SON IGUALES)")
print ("DA SIEMPRE UN NUMERO ENTERO DIVISIBLE POR 3. HAZ LA PRUEBA")

numero= input ("Introduce un numero: ")
isvalid = False
def specul (numero):
    reverse=""
    for digit in numero:
        reverse= digit + reverse
    return reverse

while not isvalid:
    if numero == specul(numero):
        print (int(specul(numero)), " - " ,int(numero), "= ", int(specul(numero)) - int(numero))
        numero= input ("Introduce otro numero, ese no es valido: ")
    else:
        total = int(specul(numero)) - int(numero)
        print (int(specul(numero)), " - " ,int(numero), "= ", total)
        print (total,"/3 = ", total/3)
        isvalid= True


'''

    Globales:
        int: 1000
        float: 3000
        string: 5000
        boolean: 7000 - 9000

    Locales:
        int: 10,000
        float: 13,000
        string: 15,000
        boolean: 17,000 - 19,000

    Constantes:
        int: 20,000
        float: 23,000
        string: 25,000
        boolean: 27,000 -- 29,000

    Temporales:
        int: 30,000
        float: 33,000
        string: 36,000
        boolean: 39,000 - 42,000

'''

class Memoria():

    # __slots__ = ['memoria', 'intGlobal', 'floatGlobal', 'stringGlobal', 'booleanGlobal', 'intLocal', 'floatLocal', 'stringLocal', 'booleanLocal', 'intConstante', 'floatConstante', 'stringConstante', 'booleanConstante', 'intTemporal', 'floatTemporal', 'stringTemporal', 'booleanTemporal']

    def __init__(self):
        #Memoria para manejar las direcciones por tipo
        self.memoria = {
            'global': {
                'int': 1000,
                'float': 3000,
                'string': 5000,
                'boolean': 7000
            },
            'local': {
                'int': 10000,
                'float': 13000,
                'string': 15000,
                'boolean': 17000
            },
            'constante': {
                'int': 20000,
                'float': 23000,
                'string': 25000,
                'boolean': 27000
            },
            'temporal': {
                'int': 30000,
                'float': 33000,
                'string': 36000,
                'boolean': 39000,
                'pointer': 42000
            }
        }
        #* Memoria de ejecucion
        self.memoriaVirtual = {}

        #* Contadores para las direcciones de memoria
        self.intGlobal = 1000
        self.floatGlobal = 3000
        self.stringGlobal = 5000
        self.booleanGlobal = 7000

        self.intLocal = 10000
        self.floatLocal = 13000
        self.stringLocal = 15000
        self.booleanLocal = 17000

        self.intConstante = 20000
        self.floatConstante = 23000
        self.stringConstante = 25000
        self.booleanConstante = 27000

        self.intTemporal = 30000
        self.floatTemporal = 33000
        self.stringTemporal = 36000
        self.booleanTemporal = 39000
        self.pointerTemporal = 42000

    def __str__(self):
        return str(self.memoria)


import numpy as np
import matplotlib.pyplot as plt

def bin2dec(a):
	hasil =0
	for i in range(len(a)):
		hasil = hasil + a[i]*2**i
	return hasil

def lbp(sub_im):
	hasil= np.zeros(8)
	hasil[0] = 1 if sub_im[0,0] > sub_im[1,1] else 0
	hasil[1] = 1 if sub_im[0,1] > sub_im[1,1] else 0
	hasil[2] = 1 if sub_im[0,2] > sub_im[1,1] else 0
	hasil[3] = 1 if sub_im[1,2] > sub_im[1,1] else 0
	hasil[4] = 1 if sub_im[2,2] > sub_im[1,1] else 0
	hasil[5] = 1 if sub_im[2,1] > sub_im[1,1] else 0
	hasil[6] = 1 if sub_im[2,0] > sub_im[1,1] else 0
	hasil[7] = 1 if sub_im[1,0] > sub_im[1,1] else 0
	out_hasil =bin2dec(hasil)
	return (out_hasil)

def rgb2gray(im):
	hasil = 0.33*im[:,:,0]+ 0.59*im[:,:,1]+0.07*im[:,:,2]
	return (hasil)

def gray2lbp(im_gray):
	w,h = im_gray.shape
	hasil = np.zeros((w,h))
	for i in range(1,w-1):
		for j in range(1, h-1):
			hasil[i,j]= lbp(im_gray[i-1: i+2, j-1:j+2])
	return (hasil)

def RUN():
	im = plt.imread('pesawat.jpg')
	im_gray=rgb2gray(im)
	im_Lbp= gray2lbp(im_gray)
	plt.subplot(121);
	plt.imshow(im_gray,cmap='gray')
	plt.subplot(122);
	plt.imshow(im_Lbp,cmap='gray')
	plt.show()

if __name__=="__main__":
	RUN()

Pengolahan Citra Digital/Local Binary Pattern (LBP)/lbp.py


import math
from pathlib import Path

import yaml

from autogluon.common.loaders import load_json

def get_amlb_yaml_ag_baseline() -> dict:
    return dict(
        AutoGluon=dict(
            version="latest",
        )
    )

def get_amlb_yaml_template_bag(name, hyperparameters: dict, max_time_limit=None) -> dict:
    yaml_dict = {
        name: dict(
            extends="AutoGluon",
            version="latest",
            params=dict(
                _save_artifacts=['leaderboard', 'zeroshot', 'model_failures'],
                _leaderboard_test=True,
                calibrate=False,
                fit_weighted_ensemble=False,
                num_bag_folds=8,
                num_bag_sets=1,
                hyperparameters=hyperparameters
            )
        )
    }
    if max_time_limit is not None:
        yaml_dict[name]['params']['ag_args_ensemble'] = {'ag.max_time_limit': max_time_limit}
    return yaml_dict

def construct_hyperparameters_dict(configs) -> dict:
    hyperparameters_dict = {}

    for name in configs:
        config = configs[name]
        hyperparameters = config['hyperparameters']
        model_type = config['model_type']

        if model_type not in hyperparameters_dict:
            hyperparameters_dict[model_type] = []

        hyperparameters_dict[model_type].append(hyperparameters)

    return hyperparameters_dict

def bash_dict_to_str(d: dict) -> str:
    name = d['name']
    if 'frameworks_suffix' in d:
        name = f'{name}:{d["frameworks_suffix"]}'
    benchmark = d['benchmark']
    constraint = d['constraint']
    extra_args = d['extra_args']
    bash_str = f"python ../../code/automlbenchmark/runbenchmark.py {name} {benchmark} {constraint} {extra_args}"
    return bash_str

if __name__ == '__main__':
    json_root = Path(__file__).parent.parent / 'data' / 'configs'

    hyperparameters_dict_list = []
    bash_str_list = []

    benchmark = "ag_244"
    constraint = "60h8c"
    extra_args = "-u custom_configs -f 0 1 2 -m aws -p 3000"  # TODO: custom user dir

    resume_path = "s3://automl-benchmark-ag/aggregated/ec2/2023_07_25/results_valid.csv"
    resume_path = None
    if resume_path is not None:
        extra_args += f" --resume --jobhistory {resume_path}"

    frameworks_suffix = 'zeroshot'

    batch_size = 16
    max_time_limit_per_model = 3600

    config_families = [
        'catboost',
        'lightgbm',
        'xgboost',
        'fastai',
        'nn_torch',
        'rf',
        'xt',
    ]
    for family in config_families:
        print(f'\n\n\n==================== {family} ====================')
        config_file_name = f'configs_{family}.json'
        configs = load_json.load(path=str(json_root / config_file_name))
        config_names = list(configs.keys())
        print(config_names)
        hyperparameters_dict = construct_hyperparameters_dict(configs=configs)

        num_configs = len(configs.keys())
        num_batches = math.ceil(num_configs / batch_size)
        print(num_configs)
        print(num_batches)
        for batch in range(num_batches):
            print(batch)
            config_names_batch = config_names[batch_size*batch:batch_size*(batch+1)]
            print(config_names_batch)
            print(len(config_names_batch))
            configs_batch = {k: configs[k] for k in config_names_batch}
            hyperparameters_dict = construct_hyperparameters_dict(configs=configs_batch)
            name = f'ZS_BAG_{family}_b{batch}'

            # print(hyperparameters_dict)

            yaml_dict = get_amlb_yaml_template_bag(
                name=name,
                hyperparameters=hyperparameters_dict,
                max_time_limit=max_time_limit_per_model,
            )

            # print(yaml_dict)

            yaml_string = yaml.dump(yaml_dict)
            # print(yaml_string)

            hyperparameters_dict_list.append(yaml_string)

            bash_dict = dict(
                name=name,
                frameworks_suffix=frameworks_suffix,
                benchmark=benchmark,
                constraint=constraint,
                extra_args=extra_args,
            )
            bash_str = bash_dict_to_str(d=bash_dict)
            bash_str_list.append(bash_str)

    baselines = [
        "AutoGluon_bq:latest",
        "AutoGluon_hq:latest",
        "AutoGluon_mq:latest",
        "AutoGluon_bq_simple:latest",
        "AutoGluon_ezs:latest",
        "AutoGluon_ezsh:latest",
        "H2OAutoML:2023Q2",
        "autosklearn:2023Q2",
        "autosklearn2:2023Q2",
        "AutoWEKA:2023Q2",
        "flaml:2023Q2",
        "NaiveAutoML:2023Q2",
        "GAMA_benchmark:2023Q2",
        "lightautoml:2023Q2",
        "mljarsupervised_benchmark:2023Q2",
        "TPOT:2023Q2",
        "mlr3automl:2023Q2",
        "constantpredictor:2023Q2",
        "RandomForest:2023Q2",
        "TunedRandomForest:2023Q2",
    ]

    baseline_constraints = ["1h8c", "4h8c"]

    bash_str_list_baselines = []
    for baseline_constraint in baseline_constraints:
        for baseline in baselines:
            bash_dict = dict(
                name=baseline,
                benchmark=benchmark,
                constraint=baseline_constraint,
                extra_args=extra_args,
            )
            bash_str = bash_dict_to_str(d=bash_dict)
            bash_str_list_baselines.append(bash_str)

    bash_str_list = bash_str_list_baselines + bash_str_list

    baseline_autogluon_yaml_dict = get_amlb_yaml_ag_baseline()
    yaml_baseline_string = yaml.dump(baseline_autogluon_yaml_dict)

    combined_str = '\n'.join([yaml_baseline_string] + hyperparameters_dict_list)
    # print(combined_str)

    # data = yaml.load(yaml_string, Loader=yaml.Loader)
    # print(data)

    frameworks_zeroshot_yaml_filename = json_root / f'frameworks_{frameworks_suffix}.yaml'

    with open(frameworks_zeroshot_yaml_filename, "w") as text_file:
        text_file.write(combined_str)

    for s in bash_str_list:
        print(f'"{s}"')

    print('')
    print(f'Saved frameworks yaml file to "{frameworks_zeroshot_yaml_filename}"')

    # TODO: Split into batches of 50 per family?
    # TODO: Write the AMLB run code
    "python ../$REPO/runbenchmark.py $FRAMEWORK $BENCHMARK $CONSTRAINT $CUSTOM_USER_DIR $EXTRA_ARGS"
    "cp -r ../../code/automlbenchmark/custom_configs/ ./"


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('courseevaluations', '0013_evaluationset_created_at'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='evaluationset',
            options={'ordering': ['created_at'], 'permissions': (('can_view_status_reports', 'Can view status reports'), ('can_view_student_links', 'Can view student links'), ('can_send_emails', 'Can send e-mails'))},
        ),
    ]


from matplotlib import pyplot as plt

fr = open(r'D:/PyCharm/代码/数据/Ch02/datingTestSet.txt')
arraylines = fr.readlines()
linesnum = len(arraylines)
lableX1, lableY1, lableX2, lableY2 = [], [], [], []
for line in arraylines:
    line = line.strip()
    ListLine = line.split('\t')
    if ListLine[-1]=='didntLike':
        lableX1.append(ListLine[0])
        lableY1.append(ListLine[1])
    elif ListLine[-1]=='smallDoses':
        lableX2.append(ListLine[0])
        lableY2.append(ListLine[1])
plt.figure(figsize=(8,5),dpi=80)
axes = plt.subplot(111)
lable1 = axes.scatter(lableX1, lableY1, s=20,c='r')
lable2 = axes.scatter(lableX2, lableY2, s=40,c='g')

plt.xlabel('every year fly distance')
plt.ylabel('play video game time')

plt.legend((lable1, lable2), ('didntlike', 'smallDoses'))
plt.show()


import time
import math
import datetime
import concurrent.futures
import threading
from wait_group import WaitGroup

MAX_INT = 10000000
# MAX_INT = 1000000
# MAX_INT = 1000
CONCURRENCY = 10
total_prime_numbers = 0

def check_prime(num, mutex, wg):
    global total_prime_numbers

    if num <= 1:
        return

    max_factors = math.floor(math.sqrt(num))
    for i in range(2, 1 + max_factors):
        if num % i == 0:
            return

    mutex.acquire()
    total_prime_numbers += 1
    mutex.release()
    # end = time.time()
    # wg.done()
    # print(f"Done. Wait count: {wg.wait_count}")

def do_batch(name, n_start, n_end, mutex, wg):
    start = time.time()
    for i in range(n_start, n_end):
        # wg.add(1)
        check_prime(i, mutex, wg)

    wg.done()
    print(f"Done. Wait count: {wg.wait_count}")
    end = time.time()
    print(f"Thread {name} [{n_start, n_end}] completed in { datetime.timedelta(seconds=(end - start)) }")

def main():

    start_time = time.time()
    wg = WaitGroup()

    n_start = 1
    batch_size = int(MAX_INT / CONCURRENCY)
    args_list = []
    threads = []
    mutex = threading.Lock()

    for i in range(CONCURRENCY - 1):
        args_list.append((i, n_start, n_start + batch_size, mutex, wg))
        n_start += batch_size
    args_list.append((CONCURRENCY - 1, n_start, MAX_INT, mutex, wg))

    for args in args_list:
        t = threading.Thread(target=do_batch, args=args)
        wg.add(1)
        print(f"Adding. wait_count: {wg.wait_count}")
        t.start()
        threads.append(t)

    # for thread in threads:
    #     thread.join()

    wg.wait()

    print(f"Finished in {datetime.timedelta(time.perf_counter())} seconds")

    print(f"Total prime numbers between 1 to {MAX_INT}: {total_prime_numbers}")

    end_time = time.time()
    print(f"Time taken: {datetime.timedelta(seconds=(end_time - start_time))}")

if __name__ == "__main__":
    main()


import math

test_cases = int(input())

for _ in range(test_cases):
    inp = int(input())
    prime = True
    if inp == 1:
        print("no")
        continue
    elif inp == 2:
        print("yes")
        continue
    if inp % 2 == 0:
        print('no')
        continue
    for i in range(3, int(math.sqrt(inp))+1, 2):
        if inp % i == 0:
            prime = False
            break
        prime = True
    if prime:
        print('yes')
    else:
        print('no')


from __future__ import print_function
import os
import sys
import numpy as np
caffe_root = "/home/wanghuan/Caffe/Caffe_default"
sys.path.insert(0, os.path.join(caffe_root, 'python'))
import caffe as c
import pickle
'''

'''
def Compare(model, basemodel, prunedmodel, finalmodel):
    FLAG = c.TRAIN if "train" in model else c.TEST
    basenet   = c.Net(model, basemodel, FLAG)
    prunednet = c.Net(model, prunedmodel, FLAG)
    finalnet  = c.Net(model, finalmodel, FLAG)

    saved_cols = {}
    saved_rows = {}
    # Prune columns
    for layer, _ in basenet.params.iteritems():
        baseweight   = basenet.params[layer][0].data
        prunedweight = prunednet.params[layer][0].data
        finalweight  = finalnet.params[layer][0].data
        if len(baseweight.shape) != 4: continue
        print("\ndealing with layer %s:" % layer)

        baseweight.shape   = baseweight.shape[0], -1
        prunedweight.shape = prunedweight.shape[0], -1
        finalweight.shape  = finalweight.shape[0], -1

        prunedweight_col_abs = np.sum(np.abs(prunedweight), axis = 0)
        prunedweight_row_abs = np.sum(np.abs(prunedweight), axis = 1)
        finalweight_col_abs  = np.sum(np.abs(finalweight), axis = 0)
        finalweight_row_abs  = np.sum(np.abs(finalweight), axis = 1)

        assert(list(np.where(finalweight_col_abs != 0)[0]) == list(np.where(prunedweight_col_abs != 0)[0]))
        assert(list(np.where(finalweight_row_abs != 0)[0]) == list(np.where(prunedweight_row_abs != 0)[0]))
        saved_cols[layer] = list(np.where(finalweight_col_abs != 0)[0])
        saved_rows[layer] = list(np.where(finalweight_row_abs != 0)[0])
        print("num_pruned_col = {}, num_pruned_row = {}".format(baseweight.shape[1] - len(saved_cols[layer]),
                                                                baseweight.shape[0] - len(saved_rows[layer])))

        # Print
        baseweight_vec   =   baseweight[saved_rows[layer], :][:, saved_cols[layer]].flatten()
        prunedweight_vec = prunedweight[saved_rows[layer], :][:, saved_cols[layer]].flatten()
        finalweight_vec  =  finalweight[saved_rows[layer], :][:, saved_cols[layer]].flatten()
        diff_final_pruned = np.linalg.norm(finalweight_vec - prunedweight_vec, 2)
        diff_final_base   = np.linalg.norm(finalweight_vec - baseweight_vec, 2)
        print("the magnitude of base   weights = {}".format(np.linalg.norm(baseweight_vec, 2)))
        print("the magnitude of pruned weights = {}".format(np.linalg.norm(prunedweight_vec, 2)))
        print("the magnitude of final  weights = {}".format(np.linalg.norm(finalweight_vec, 2)))
        print("the difference between final weights and pruned weights = {}\nthe difference between final weights and   base weights = {}".format(diff_final_pruned, diff_final_base))

if __name__ == "__main__":
    '''Usage:
        python  this_file.py  train_val/deploy.prototxt  baseline.caffemodel  pruned.caffemodel  final.caffemodel
    '''
    assert(len(sys.argv) == 5)
    Compare(*sys.argv[1:])


from esphome.components import sensor, binary_sensor

DEVICE_CLASS_BASIC = {
    "numeric": sensor.DEVICE_CLASSES,
    "binary": binary_sensor.DEVICE_CLASSES,
}

DEVICE_CLASS_HELPER = {
    "numeric": {
        "dewpoint": "moisture",
        "mass": "weight",
        "pm2_5": "pm25",
        "tvoc": "volatile_organic_compounds"
        # "tvoc": "nitrogen_dioxide" / "nitrogen_monoxide" / "nitrous_oxide" / "volatile_organic_compounds"
        # "pressure": "pressure" / "atmospheric_pressure"
        # "volume": "volume" / "volume_storage" / "water"
    },
    "binary": {},
}

BTHOME_ICONS = {
    0x00: "mdi:counter",
    0x01: "mdi:battery",
    0x02: "mdi:temperature-celsius",
    0x03: "mdi:percent",
    0x04: "mdi:gauge",
    0x05: "mdi:sun-wireless",
    0x06: "mdi:weight-kilogram",
    0x07: "mdi:weight-pound",
    0x08: "mdi:water-thermometer-outline",
    0x09: "mdi:counter",
    0x0A: "mdi:lightning-bolt",
    0x0B: "mdi:power",
    0x0C: "mdi:lightning-bolt",
    0x0D: None,
    0x0E: None,
    0x0F: None,
    0x10: "mdi:power",
    0x11: None,
    0x12: "mdi:molecule-co2",
    0x13: None,
    0x14: "mdi:percent",
    0x15: None,
    0x16: None,
    0x17: None,
    0x18: None,
    0x19: None,
    0x1A: None,
    0x1B: None,
    0x1C: None,
    0x1D: None,
    0x1E: None,
    0x1F: None,
    0x20: None,
    0x21: "mdi:motion-sensor",
    0x22: None,
    0x23: None,
    0x24: None,
    0x25: None,
    0x26: None,
    0x27: None,
    0x28: None,
    0x29: None,
    0x2A: None,
    0x2B: None,
    0x2C: None,
    0x2D: None,
    0x2E: "mdi:percent",
    0x2F: "mdi:percent",
    0x30: None,
    0x31: None,
    0x32: None,
    0x33: None,
    0x34: None,
    0x35: None,
    0x36: None,
    0x37: None,
    0x38: None,
    0x39: None,
    0x3A: None,
    0x3B: None,
    0x3C: None,
    0x3D: "mdi:counter",
    0x3E: "mdi:counter",
    0x3F: None,
    0x40: None,
    0x41: None,
    0x42: None,
    0x43: "mdi:current-ac",
    0x44: None,
    0x45: None,
    0x46: None,
    0x47: None,
    0x48: None,
    0x49: None,
    0x4A: None,
    0x4B: "mdi:gas-cylinder",
    0x4C: "mdi:gas-cylinder",
    0x4D: None,
    0x4E: None,
    0x4F: "mdi:water",
    0x50: None,
    0x51: "mdi:axis-arrow",
    0x52: None,
}

def find_matching_device_class(object_id, measurement_property, main_type):
    matching_classes = ([
        value
        for value in DEVICE_CLASS_BASIC[main_type]
        if value != sensor.DEVICE_CLASS_EMPTY and measurement_property.startswith(value)
    ] if main_type in DEVICE_CLASS_BASIC else []) + ([
        value
        for _, (key, value) in enumerate(DEVICE_CLASS_HELPER[main_type].items())
        if measurement_property.startswith(key)
    ] if main_type in DEVICE_CLASS_HELPER else [])

    device_class_picked = matching_classes[0] if len(
        matching_classes) else None
    # print(f"{measurement_property:>40} = {device_class_picked}")
    return device_class_picked

def find_matching_icon(object_id, measurement_property, main_type):
    return BTHOME_ICONS[object_id]

def msb(val):
    return int(hex(val)[2:4], 16)

def lsb(val):
    return val & 0xff

def hex2(value, length: int | None = None):
    return format(value, f'#0{length+2 if length else length}x')


# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for the Redux Pipe class."""

import os

from sofia_redux.pipeline.pipe import Pipe
from sofia_redux.pipeline.configuration import Configuration

class TestPipe(object):
    def test_run(self, capsys):
        pipe = Pipe()
        data = "any data"
        pipe.run(data)

    def test_config(self, tmpdir):
        input = str(tmpdir.join('test_infiles.txt'))
        param = str(tmpdir.join('test_param.txt'))
        conf_dict = {'input_manifest': input,
                     'parameter_file': param}
        config = Configuration(conf_dict)
        pipe = Pipe(config)

        data = "any data"
        pipe.run(data)

        assert os.path.isfile(input)
        assert os.path.isfile(param)


"""
### Read metadata from rasters ###
"""
# Standard library
import sys; sys.path.append("../../")
from typing import List, Union

# External
from osgeo import gdal

# Internal
from buteo.utils import (
    utils_io,
    utils_base,
)
from buteo.raster.core_raster import _get_basic_metadata_raster

def _raster_to_metadata(
    raster: Union[str, gdal.Dataset],
) -> dict:
    """ Internal. """
    utils_base._type_check(raster, [str, gdal.Dataset], "raster")

    metadata = _get_basic_metadata_raster(raster)

    return metadata

def raster_to_metadata(
    raster: Union[str, gdal.Dataset, List[str], List[gdal.Dataset]],
) -> Union[dict, List[dict]]:
    """
    Reads metadata from a raster dataset or a list of raster datasets, and returns a dictionary or a list of dictionaries
    containing metadata information for each raster.

    Bounding boxes are in the format `[xmin, xmax, ymin, ymax]`. These are the keys in the dictionary:

    - `path` (str): Path to the raster.
    - `basename` (str): Basename of the raster.
    - `name` (str): Name of the raster without extension.
    - `folder` (str): Folder of the raster.
    - `ext` (str): Extension of the raster.
    - `in_memory` (bool): Whether the raster is in memory or not.
    - `driver` (str): Driver of the raster.
    - `projection_osr` (osr.SpatialReference): Projection of the raster as an osr.SpatialReference object.
    - `projection_wkt` (str): Projection of the raster as a WKT string.
    - `geotransform` (tuple): Geotransform of the raster.
    - `size` (tuple): Size of the raster in pixels.
    - `shape` (list): Shape of the raster in pixels. (height, width, bands)
    - `height` (int): Height of the raster in pixels.
    - `width` (int): Width of the raster in pixels.
    - `pixel_size` (tuple): Pixel size of the raster in units of the projection.
    - `pixel_width` (float): Pixel width of the raster in units of the projection.
    - `pixel_height` (float): Pixel height of the raster in units of the projection.
    - `origin` (tuple): Origin of the raster in units of the projection.
    - `origin_x` (float): Origin x of the raster in units of the projection.
    - `origin_y` (float): Origin y of the raster in units of the projection.
    - `bbox` (list): Bounding box of the raster in units of the projection. `[xmin, xmax, ymin, ymax]`
    - `bbox_gdal` (list): Bounding box of the raster in GDAL format. `[xmin, ymin, xmax, ymax]`
    - `bbox_latlng` (list): Bounding box of the raster in latlng format. `[ymin, xmin, ymax, xmax]`
    - `bounds_latlng` (str): Bounding box of the raster in latlng format as a WKT string.
    - `x_min` (float): Minimum x of the raster in units of the projection.
    - `x_max` (float): Maximum x of the raster in units of the projection.
    - `y_min` (float): Minimum y of the raster in units of the projection.
    - `y_max` (float): Maximum y of the raster in units of the projection.
    - `bands` (int): Number of bands in the raster.
    - `dtype_gdal` (int): GDAL data type of the raster.
    - `dtype` (numpy.dtype): Numpy data type of the raster.
    - `dtype_name` (str): Name of the numpy data type of the raster.
    - `area_latlng` (float): Area of the raster in latlng units.
    - `area` (float): Area of the raster in units of the projection.

    Parameters
    ----------
    raster : str or gdal.Dataset or list
        A path to a raster or a gdal.Dataset, or a list of paths to rasters.

    Returns
    -------
    dict or list of dict
        A dictionary or a list of dictionaries containing metadata information for each raster.
    """
    utils_base._type_check(raster, [str, gdal.Dataset, [str, gdal.Dataset]], "raster")

    input_is_list = isinstance(raster, list)
    input_rasters = utils_io._get_input_paths(raster, "raster")

    metadata = []
    for in_raster in input_rasters:
        metadata.append(_raster_to_metadata(in_raster))

    if input_is_list:
        return metadata

    return metadata[0]


from django.urls import path

from .decorators import print_user_permissions
from .views import home, customers, loginPage, register, logoutPage

urlpatterns = [

    path('', home, name='home'),
    path('customers/', customers, name='customers'),
    path('login/', loginPage, name='login'),
    path('logout/', logoutPage, name='logout'),
    path('register/', register, name='register'),
    path('print_permissions/', print_user_permissions, name='print_user_permissions'),
]


# To run all tests:
# python3 -m unittest tests.util.test_time_util
#
# To run a single test:
# python3 -m unittest tests.util.test_time_util.TimeUtilTests.format_stopwatch_seconds

import unittest
from src.util import time_util

class TimeUtilTests(unittest.TestCase):

    def format_stopwatch_seconds(self):
        total_seconds = 5
        expected = "00:00:05"
        actual = time_util.format_stopwatch(total_seconds)
        self.assertEqual(expected, actual)

    def format_stopwatch_minutes(self):
        total_seconds = 5 + 12*60;
        expected = "00:12:05"
        actual = time_util.format_stopwatch(total_seconds)
        self.assertEqual(expected, actual)

    def format_stopwatch_hours(self):
        total_seconds = 5 + 12*60 + 3*60*60;
        expected = "03:12:05"
        actual = time_util.format_stopwatch(total_seconds)
        self.assertEqual(expected, actual)

    def format_stopwatch_days(self):
        total_seconds = 5 + 12*60 + 3*60*60 + 47*24*60*60
        expected = "47.03:12:05"
        actual = time_util.format_stopwatch(total_seconds)
        self.assertEqual(expected, actual)

if __name__ == '__main__':
    unittest.main()


import numpy as np

from ..._common import dist3d, jitted
from .._helpers import register

def decluster(catalog, return_indices=False, window="default"):
    """
    Decluster earthquake catalog using Gardner-Knopoff's method.

    Parameters
    ----------
    catalog : :class:`bruces.Catalog`
        Earthquake catalog.
    return_indices : bool, optional, default False
        If `True`, return indices of background events instead of declustered catalog.
    window : str {'default', 'gruenthal', 'uhrhammer'}, optional, default 'default'
        Distance and time windows:

         - 'default': Gardner and Knopoff (1974)
         - 'gruenthal': personnal communication (see van Stiphout et al., 2012)
         - 'uhrhammer': Uhrhammer (1986)

    Returns
    -------
    :class:`bruces.Catalog` or array_like
        Declustered earthquake catalog or indices of background events.

    """
    if window not in {"default", "gruenthal", "uhrhammer"}:
        raise ValueError()

    t = catalog.years * 365.25  # Days
    x = catalog.eastings
    y = catalog.northings
    z = catalog.depths
    m = catalog.magnitudes

    bg = _decluster(t, x, y, z, m, window)

    return np.flatnonzero(bg) if return_indices else catalog[bg]

@jitted
def _decluster(t, x, y, z, m, window):
    """Window method."""
    N = len(t)

    bg = np.ones(N, dtype=np.bool_)
    for i in range(N):
        mag = m[i]

        if window == "default":
            dr = np.power(10.0, 0.1238 * mag + 0.983)
            dt = (
                np.power(10.0, 0.032 * mag + 2.7389)
                if mag >= 6.5
                else np.power(10.0, 0.5409 * mag - 0.547)
            )

        elif window == "gruenthal":
            dr = np.exp(1.77 + (0.037 + 1.02 * mag) ** 0.5)
            dt = (
                np.exp(-3.95 + (0.62 + 17.32 * mag) ** 0.5)
                if mag < 6.5
                else np.power(10.0, 2.8 + 0.024 * mag)
            )

        elif window == "uhrhammer":
            dr = np.exp(-1.024 + 0.804 * mag)
            dt = np.exp(-2.87 + 1.235 * mag)

        # Loop over catalog
        for j in range(N):
            if bg[j] and m[j] < mag and 0 < t[j] - t[i] < dt:
                r_ij = dist3d(x[i], y[i], z[i], x[j], y[j], z[j])
                if r_ij < dr:
                    bg[j] = False

    return bg

register("gardner-knopoff", decluster)


from dqn_agent import BlokusAgent
from blokus_env import BlokusEnvironment

NUM_EPISODES = 10000

def main():
    """
    Main process of dqn learning
    Returns educated agent.
    """
    red_agent = BlokusAgent()
    blue_agent = BlokusAgent()

    for _ in range(NUM_EPISODES):
        environment = BlokusEnvironment(red_agent, blue_agent)
        while environment.execute_turn():
            environment.render_console()

        red_agent.learn_finalize(environment.session)
    return

if __name__ == "__main__":
    main()


#nickelson, ronald
#2/23/23
#intro to cs

prizes = ('car', 'house', 'plane', 'boat', 'supercar', 'mansion', 'jet', 'yacht', 'apple', 'dirt')
number = int(input('pick a door between 1 and 10: '))
if number >= 1 and number <= 10:
    print(prizes[number - 1])
else:
    print('You lost nerd')


import secrets
import hashlib
import base64
import webbrowser
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs, quote
import requests
import json

from spock.config import CLIENT_ID, REDIRECT_URI, PORT
from spock.templates.template import get_authorized_page, get_error_page
from spock.access_token import AccessToken

CODE_VERIFIER_MIN_LENGTH = 43
CODE_VERIFIER_MAX_LENGTH = 128
CODE_VERIFIER_CHARACTERS = (
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.~"
)
SCOPE = [
    "streaming",
    "user-read-playback-state",
    "user-modify-playback-state",
    "user-read-currently-playing",
    "playlist-read-collaborative",
    "playlist-read-private",
    "user-library-read",
]

def generate_code() -> (str, str):
    """
    Generates a (code_verifier, code_challenge) pair where code_verifier is a cryptographically random
    string and code_challenge is the base64urlencoded string (with right '=' removed) of the sha256 hash of the code_verifier.
    """
    length = (
        secrets.randbelow(
            exclusive_upper_bound=CODE_VERIFIER_MAX_LENGTH
            - CODE_VERIFIER_MIN_LENGTH
            + 1
        )
        + CODE_VERIFIER_MIN_LENGTH
    )

    code_verifier = "".join(
        secrets.choice(CODE_VERIFIER_CHARACTERS) for i in range(length)
    )

    sha = hashlib.sha256(code_verifier.encode()).digest()
    code_challenge = base64.urlsafe_b64encode(sha)

    return (code_verifier, code_challenge.decode().rstrip("="))

STATE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

def generate_state(remote) -> str:
    """
    Generates a cryptographically secure random string for CSRF protection.
    """
    state = "".join(secrets.choice(STATE_CHARACTERS) for i in range(64))
    return ("remote-" if remote else "local-") + state

def generate_spotify_authorize_url(code_challenge, state):
    """
    Returns the Spotify URL to begin the authorization process for a user.
    """
    return (
        f"https://accounts.spotify.com/authorize"
        f"?response_type=code&client_id={CLIENT_ID}"
        f'&redirect_uri={REDIRECT_URI}&scope={quote(" ".join(SCOPE))}'
        f"&state={state}&code_challenge={code_challenge}"
        f"&code_challenge_method=S256"
    )

def merge_kwargs(kwargs1, kwargs2):
    kwargs1.update(kwargs2)
    return kwargs1

class AuthorizationServer:
    """
    Runs a server to capture a Spotify authorization code. Once wait_for_stop()
    has returned the code is accessible from authorization_code.
    """

    def __init__(self, state, code_verifier, remote):
        self.server_started_event = threading.Event()
        self.state = state
        self.code_verifier = code_verifier
        self.remote = remote

        self.authorization_code = None
        self.authorization_attempted_event = threading.Event()

        self.server_thread = threading.Thread(target=self.listen)
        self.server_thread.start()

    def wait_for_start(self):
        """
        A blocking function that will only return once the server has started.
        """
        self.server_started_event.wait()

    def wait_for_stop(self):
        """
        A blocking function that will only return once the server has stopped.
        """
        self.server_thread.join()

    def listen(self):
        with HTTPServer(
            ("", PORT),
            SpotifyRedirectRequestHandler.partial_init(
                state=self.state,
                set_authorization_code=self.set_authorization_code,
                authorization_attempted_event=self.authorization_attempted_event,
            ),
        ) as server:
            self.server_started_event.set()
            while not self.authorization_attempted_event.is_set():
                server.handle_request()

    def set_authorization_code(self, code) -> str:
        """
        Sets the authorization code and returns a key that can be used to authenticate from the CLI
        """
        self.authorization_code = code

        key_dict = {"authorization_code": code, "code_verifier": self.code_verifier}

        key_json = json.dumps(key_dict)

        return (
            base64.urlsafe_b64encode(key_json.encode()).decode("utf-8"),
            self.remote,
        )

class SpotifyRedirectRequestHandler(BaseHTTPRequestHandler):
    STATE_MISMATCH = "state_mismatch"
    MISSING_ARGS = "missing_arguments"
    INVALID_PATH = "invalid_path"

    @staticmethod
    def partial_init(**kwargs):
        return lambda *largs, **lkwargs: SpotifyRedirectRequestHandler(
            *largs, **merge_kwargs(kwargs, lkwargs)
        )

    def __init__(self, *args, **kwargs):
        self.state = kwargs.pop("state")
        self.authorization_attempted_event = kwargs.pop("authorization_attempted_event")
        self.set_authorization_code = kwargs.pop("set_authorization_code")

        super().__init__(*args, **kwargs)

    def _handle_success(self, key, remote):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        self.wfile.write(get_authorized_page(key=key, remote=remote))

    def _handle_error(self, error):
        self.send_response(400)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        self.wfile.write(get_error_page(error_code=error))

    def do_GET(self):
        url = urlparse(self.path)
        query = parse_qs(url.query)

        if url.path == "/authorize":
            self.authorization_attempted_event.set()
            if "code" in query and "state" in query:
                if query["state"][0] == self.state:
                    key, remote = self.set_authorization_code(query["code"][0])
                    self._handle_success(key=key, remote=remote)
                else:
                    self._handle_error(self.STATE_MISMATCH)
            elif "error" in query and "state" in query:
                if query["state"][0] == self.state:
                    self._handle_error(query["error"][0])
                else:
                    self._handle_error(self.MISSING_ARGS)
            else:
                self._handle_error(self.MISSING_ARGS)
        else:
            self._handle_error(self.INVALID_PATH)

    def log_message(self, format, *args):
        """
        Overriden from BaseHTTPRequestHandler to silence logging.
        """
        pass

def get_access_token(authorization_code: str, code_verifier: str):
    """
    Exchanges an authorization code for an access token with the Spotify API
    """
    response = requests.post(
        "https://accounts.spotify.com/api/token",
        data={
            "client_id": CLIENT_ID,
            "grant_type": "authorization_code",
            "code": authorization_code,
            "redirect_uri": REDIRECT_URI,
            "code_verifier": code_verifier,
        },
    )

    return AccessToken(**response.json())

def authenticate() -> AccessToken:
    code_verifier, code_challenge = generate_code()

    state = generate_state(remote=False)

    auth_server = AuthorizationServer(
        state=state, code_verifier=code_verifier, remote=False
    )

    auth_server.wait_for_start()

    url = generate_spotify_authorize_url(code_challenge=code_challenge, state=state)

    print(f"Please visit {url} in a browser where you are logged in to Spotify.")

    webbrowser.open(url=url)

    auth_server.wait_for_stop()

    authorization_code = auth_server.authorization_code

    if not authorization_code:
        print("Authorization failed. Please try again.")
        return

    access_token = get_access_token(
        authorization_code=authorization_code, code_verifier=code_verifier
    )

    return access_token

def authenticate_for_remote():
    code_verifier, code_challenge = generate_code()

    state = generate_state(remote=True)

    auth_server = AuthorizationServer(
        state=state, code_verifier=code_verifier, remote=True
    )

    auth_server.wait_for_start()

    url = generate_spotify_authorize_url(code_challenge=code_challenge, state=state)

    print(f"Please visit {url} in a browser where you are logged in to Spotify.")

    webbrowser.open(url=url)

    auth_server.wait_for_stop()

def authenticate_with_key(key: str) -> AccessToken:
    unhashed = base64.urlsafe_b64decode(key)
    authorization_json = json.loads(unhashed)

    access_token = get_access_token(
        authorization_code=authorization_json["authorization_code"],
        code_verifier=authorization_json["code_verifier"],
    )

    return access_token


print("Welcome to tip calculator")

bill = float(input("What is the total bill..\n"))
tip_percentage = int(input("Enter the percentage of bill you wanted to share..(10/12/15)\n"))
people = int(input("How many ppl to split the bill"))

tip_percentage = tip_percentage/100
total_tips = bill * tip_percentage
final_bill = round((total_tips + bill)/people,2)

print(f"Each one should pay {final_bill}")


from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
#打开文件对话框
from UI.projectFileChooseDialog import Ui_Dialog
#选择钻场 对话框
import os
from UI.projectFileChooseDialog import Ui_Dialog
class projectFileChooseDialog(QDialog,Ui_Dialog):
    def __init__(self,tip = '请选择'):
        super().__init__()
        self.setupUi(self)
        self.retranslateUi(self)
        self.setEvent()
        self.setMore()
        self.label_topTip.setText(tip)

    #其他设置
    def setMore(self):
        #表示是否已经选择
        self.choosed = False
        self.Path = ''
        #只显示文件夹
        self.treeView.myModel.setFilter(QDir.Dirs|QDir.NoDotAndDotDot)
        #测试时，向toolButton添加文子
        self.back_toolButton.setText("退后")
        self.desktop_toolButton.setText("桌面")
        self.disk_toolButton.setText("磁盘")

    #链接信号与动作
    def setEvent(self):
        self.treeView.clicked.connect(self.treeView_clicked_event)
        self.treeView.doubleClicked.connect(self.treeView_doubleClicked_evnet)
        self.pushButton_cancel.clicked.connect(self.close)
        self.pushButton_OK.clicked.connect(self.pushButton_OK_clicked_evevnt)
        self.back_toolButton.clicked.connect(self.back_toolButton_clicked_event)
        self.desktop_toolButton.clicked.connect(self.desktop_toolButton_clicked_event)
        self.disk_toolButton.clicked.connect(self.disk_toolButton_clicked_event)

    # 右上角图标按钮动作
    def back_toolButton_clicked_event(self):
        newPath = self.treeView.myModel.rootPath()
        if newPath != '':
            toPath = os.path.split(newPath)[0]
            self.treeView.setWorkPath(toPath)
            self.lineEdit_currentChoose.setText(toPath)

    #动作：从磁盘选择
    def disk_toolButton_clicked_event(self):
        self.treeView.setWorkPath('')
        self.lineEdit_currentChoose.setText('')

    #动作：从桌面选择
    def desktop_toolButton_clicked_event(self):
        path = os.path.join(os.path.expanduser('~'), 'Desktop')
        if os.path.exists(path):
            self.treeView.setWorkPath(path)
            self.lineEdit_currentChoose.setText(path)

    #确认按钮动作
    def pushButton_OK_clicked_evevnt(self):
        # 检查
        if os.path.exists(self.lineEdit_currentChoose.text()):
            if os.path.exists(os.path.join(self.lineEdit_currentChoose.text(), '.trackNote')):
                self.Path = self.lineEdit_currentChoose.text()
                self.choosed = True
                self.close()
            else:
                reply = QMessageBox.information(self, "提示", "这不是一个测斜钻场文件")
        else:
            reply = QMessageBox.warning(self, '错误', '输入路径错误！')

    #树控件 单击动作
    def treeView_clicked_event(self,index):
        #将值传入line控件
        path = self.treeView.myModel.filePath(index)
        self.lineEdit_currentChoose.setText(path)

    #树控件 双击动作
    def treeView_doubleClicked_evnet(self,index):
        if self.treeView.myModel.isDir(index):
            self.treeView.setWorkPath(self.treeView.myModel.filePath(index))

    #调用静态方法来快速创建选择项目的对话框，将返回选择项目的路径和是否确认选择的bool值
    @staticmethod
    def getOpenProject(parent = None):
        #返回选择项目的路径和是否已经选择
        myself = projectFileChooseDialog('请选择要打开的项目')
        myself.setWindowTitle('选择项目')
        myself.exec_()
        return (myself.Path,myself.choosed)

from UI.newProjectFileDialog import Ui_Dialog
class newProjectFileDialog(QDialog,Ui_Dialog):
    def __init__(self,tip = '请选择'):
        super().__init__()
        self.setupUi(self)
        self.retranslateUi(self)
        self.setEvent()
        self.setMore()
        self.label_topTip.setText(tip)

    #其他设置
    def setMore(self):
        #表示是否已经选择
        self.choosed = False
        self.Path = ''
        #只显示文件夹
        self.treeView.myModel.setFilter(QDir.Dirs|QDir.NoDotAndDotDot)
        #测试时，向toolButton添加文子
        self.back_toolButton.setText("退后")
        self.desktop_toolButton.setText("桌面")
        self.disk_toolButton.setText("磁盘")

    #链接信号与动作
    def setEvent(self):
        self.treeView.clicked.connect(self.treeView_clicked_event)
        self.treeView.doubleClicked.connect(self.treeView_doubleClicked_evnet)
        self.pushButton_cancel.clicked.connect(self.close)
        self.pushButton_OK.clicked.connect(self.pushButton_OK_clicked_evevnt)
        self.back_toolButton.clicked.connect(self.back_toolButton_clicked_event)
        self.desktop_toolButton.clicked.connect(self.desktop_toolButton_clicked_event)
        self.disk_toolButton.clicked.connect(self.disk_toolButton_clicked_event)

    # 右上角图标按钮动作
    def back_toolButton_clicked_event(self):
        newPath = self.treeView.myModel.rootPath()
        if newPath != '':
            toPath = os.path.split(newPath)[0]
            self.treeView.setWorkPath(toPath)
            self.lineEdit_currentChoose.setText(toPath)

    #动作：从磁盘选择
    def disk_toolButton_clicked_event(self):
        self.treeView.setWorkPath('')
        self.lineEdit_currentChoose.setText('')

    #动作：从桌面选择
    def desktop_toolButton_clicked_event(self):
        path = os.path.join(os.path.expanduser('~'), 'Desktop')
        if os.path.exists(path):
            self.treeView.setWorkPath(path)
            self.lineEdit_currentChoose.setText(path)

    #确认按钮动作
    def pushButton_OK_clicked_evevnt(self):
        #检查选择路径是否存在，同时创建钻场文件
        if os.path.exists(self.lineEdit_currentChoose.text()):
            self.Path = os.path.join(self.lineEdit_currentChoose.text(),self.lineEdit_projectName.text())
            os.mkdir(self.Path)
            with open(os.path.join(self.Path,'.trackNote'),'w') as file:
                pass
            self.choosed = True
            self.close()
        else:
            reply = QMessageBox.warning(self,'错误','输入路径错误！')

    #树控件 单击动作
    def treeView_clicked_event(self,index):
        #将值传入line控件
        path = self.treeView.myModel.filePath(index)
        self.lineEdit_currentChoose.setText(path)

    #树控件 双击动作
    def treeView_doubleClicked_evnet(self,index):
        if self.treeView.myModel.isDir(index):
            self.treeView.setWorkPath(self.treeView.myModel.filePath(index))

    #调用静态方法来快速创建选择项目的对话框，将返回选择项目的路径和是否确认选择的bool值
    @staticmethod
    def getOpenProject(parent = None):
        #返回选择项目的路径和是否已经选择
        myself = projectFileChooseDialog('请选择要打开的项目')
        myself.setWindowTitle('选择项目')
        myself.exec_()
        return (myself.Path,myself.choosed)

from dataAnalisy import track
from UI.chooseRootTrack import Ui_Dialog
class chooseRootTrackDialog(QDialog,Ui_Dialog):
    '''
    主孔列表目前暂时使用stringModel，后期有需要可以改成IconModel显示图标和文字
    '''
    def __init__(self):
        super(chooseRootTrackDialog, self).__init__()
        self.setupUi(self)
        self.retranslateUi(self)
        self.setMore()
        self.setEvent()
    def setMore(self):
        self.choosed = False
        self.trackPath = None
        self.projectPath = None
        self.listModel = QStringListModel()
        self.listView_RootTrack.setModel(self.listModel)
        self.listView_RootTrack.setEditTriggers(QAbstractItemView.NoEditTriggers)

    def setEvent(self):
        self.listView_RootTrack.doubleClicked.connect(self.selectRootTrack)
        self.pushButton_OK.clicked.connect(self.pushButton_OK_event)
        self.pushButton_Cancel.clicked.connect(self.close)
        self.toolButton_newRootTrack.clicked.connect(self.toolButton_newRootTrack_event)

    def setProjectPath(self,path : str):
        self.projectPath = path
        self.refreshlist()

    def refreshlist(self):
        l = os.listdir(self.projectPath)
        l.remove('.trackNote')
        self.listModel.setStringList(l)

    def selectRootTrack(self):
        rootTrack = self.listView_RootTrack.currentIndex().data()
        self.trackPath = os.path.join(self.projectPath,str(rootTrack))
        print(os.path.join(self.trackPath,'info.xml'))
        self.treeWidget_TrackBranch._loadTrackInfo(os.path.join(self.trackPath,'info.xml'))

    def pushButton_OK_event(self):
        if self.trackPath is not None:
            self.choosed = True
            self.close()
        else:
            reply = QMessageBox.information(self,"注意","当前未选择任何主孔！")

    def toolButton_newRootTrack_event(self):
        print(self.projectPath)
        newRootTrackDailog.Dialog_show(projectPath=self.projectPath)
        self.refreshlist()

    @staticmethod
    def Dialog_show(parent = None,projectPath = None):
        myself = chooseRootTrackDialog()
        if projectPath is not None:
            myself.setProjectPath(path=projectPath)
        myself.exec_()
        return (myself.trackPath,myself.choosed)

from UI.newRootTrackDailog import Ui_Dialog
class newRootTrackDailog(QDialog,Ui_Dialog):
    def __init__(self,path):
        super(newRootTrackDailog, self).__init__()
        self.setupUi(self)
        self.retranslateUi(self)
        self.projectPath = path
        self.setMore()
        self.setEvent()

    def setMore(self):
        self.checked = False

    def setEvent(self):
        self.pushButton_OK.clicked.connect(self.pushButton_OK_event)
        self.pushButton_Cancel.clicked.connect(self.pushButton_Cancel_event)

    def pushButton_Cancel_event(self):
        self.close()

    def pushButton_OK_event(self):
        targetPath = os.path.join(self.projectPath,self.lineEdit_Name.text())
        print(targetPath)
        if os.path.exists(targetPath):
            reply = QMessageBox.warning(self,'警告','已存在同名主孔！')
        else:
            print(self.doubleSpinBox_dipAngle.text()[:-1],self.doubleSpinBox_intensity.text()[:-2],
                  self.spinBox_designOrientation.text()[:-1],self.spinBox_angle.text()[:-1],
                  self.spinBox_orientation.text()[:-1])
            track().newRootTrack(self.projectPath,self.lineEdit_Name.text(),
                                 declination=self.doubleSpinBox_dipAngle.text()[:-1],
                                 intensity=self.doubleSpinBox_intensity.text()[:-2],
                                 targetOrientation=self.spinBox_designOrientation.text()[:-1],
                                 dipAngle=self.spinBox_angle.text()[:-1],
                                 orientation=self.spinBox_orientation.text()[:-1]
            )
            self.checked =True
            self.close()

    @staticmethod
    def Dialog_show(parent=None,projectPath=None):
        # 返回选择项目的路径和是否已经选择
        myself = newRootTrackDailog(projectPath)
        myself.exec_()

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    dialog = newRootTrackDailog("./test/GammaTrack")
    dialog.show()
    sys.exit(app.exec_())


import copy

def compute_digits(number):
    digits = {}
    for i in map(int, str(number)):
        digits[i] = True

    return digits

def same_digits_multiple(number, digits):
    digits_copy = copy.deepcopy(digits)
    for i in map(int, str(number)):
        if digits_copy.get(i):
            digits_copy[i] = False
        else:
            return False

    return True

def multiple_has_same_digits(number):
    digits = compute_digits(number)
    for i in range(2, 6):
        if not same_digits_multiple(i * number, digits):
            return False

    return True

def permuted_multiples():
    i = 100
    deg = 2
    while True:
        # just check number which multiplied with 6 have the same length
        if len(str(6 * i)) > len(str(i)):
            deg += 1
            i = 10**deg
            continue
        if multiple_has_same_digits(i):
            return i
        else:
            i += 1

print(permuted_multiples())  # 142857