#
# @lc app=leetcode.cn id=887 lang=python3
#
# [887] 鸡蛋掉落
#
# https://leetcode-cn.com/problems/super-egg-drop/description/
#
# algorithms
# Hard (29.16%)
# Likes:    687
# Dislikes: 0
# Total Accepted:    51.1K
# Total Submissions: 175.2K
# Testcase Example:  '1\n2'
#
# 给你 k 枚相同的鸡蛋，并可以使用一栋从第 1 层到第 n 层共有 n 层楼的建筑。
#
# 已知存在楼层 f ，满足 0  ，任何从 高于 f 的楼层落下的鸡蛋都会碎，从 f 楼层或比它低的楼层落下的鸡蛋都不会破。
#
# 每次操作，你可以取一枚没有碎的鸡蛋并把它从任一楼层 x 扔下（满足 1
# ）。如果鸡蛋碎了，你就不能再次使用它。如果某枚鸡蛋扔下后没有摔碎，则可以在之后的操作中 重复使用 这枚鸡蛋。
#
# 请你计算并返回要确定 f 确切的值 的 最小操作次数 是多少？
#
#
# 示例 1：
#
#
# 输入：k = 1, n = 2
# 输出：2
# 解释：
# 鸡蛋从 1 楼掉落。如果它碎了，肯定能得出 f = 0 。
# 否则，鸡蛋从 2 楼掉落。如果它碎了，肯定能得出 f = 1 。
# 如果它没碎，那么肯定能得出 f = 2 。
# 因此，在最坏的情况下我们需要移动 2 次以确定 f 是多少。
#
#
# 示例 2：
#
#
# 输入：k = 2, n = 6
# 输出：3
#
#
# 示例 3：
#
#
# 输入：k = 3, n = 14
# 输出：4
#
#
#
#
# 提示：
#
#
# 1
# 1
#
#
#

# @lc code=start

'''

关键字
动态规划 自定义

最坏情况的最少次数

最坏:碎了和没碎的最坏情况
最少:在最坏前提下的最优解

状态:dp(left_k, left_n)
    选择:
        遍历1-i扔鸡蛋,取最小
            碎了:dp(left_k-1, i-1) + 1
            没碎:dp(left_k, left_n - i) + 1
base_case:
    left_k = 1:
        return left_n
    left_n = 0:
        return 0
'''
memo = {}

def superEggDrop(k: int, n: int) -> int:

    def dp(left_k, left_n):
        if left_k == 1:
            return left_n
        if left_n == 0:
            return 0

        if (left_k, left_n) in memo:
            return memo[(left_k, left_n)][0]

        res = float('INF')

        start = 1
        end = left_n
        l = (left_k, left_n)
        while end >= start:
            mid = (end + start)//2
            broken_res = dp(left_k-1, mid-1) + 1
            not_broken_res = dp(left_k, left_n - mid) + 1

            if broken_res > not_broken_res:
                end = mid - 1
                if res <= broken_res:
                    None
                else:
                    l = (left_k-1, mid-1)
                    res = broken_res

            else:
                start = mid + 1
                if res <= not_broken_res:
                    None
                else:
                    l = (left_k, left_n - mid)
                    res = not_broken_res
        memo[(left_k, left_n)] = [res, l]

        return res

    return dp(k, n)

l = (2, 100)
print(superEggDrop(*l))

print(l)
while(l in memo):
    l = memo[l][1]
    print(100-l[1], l[0])

# @lc code=end

887.鸡蛋掉落-最佳策略.py


from __future__ import annotations

import functools
import typing

from ..utils.tags import _not_found_
from ..utils.tree_utils import merge_tree_recursive
from ..utils.typing import array_type, get_args, get_type_hint
from .Entry import Entry
from .HTree import HTree, List, Dict
from .Path import Path, PathLike, as_path

_T = typing.TypeVar("_T")

class QueryResult(HTree):
    """ Handle the result of query    """

    def __init__(self, query: PathLike, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._path = as_path(query)

    def __getattr__(self, name: str): return self._get(name)

    def _get(self, query: str | int | slice | dict, *args, **kwargs):
        default_value = kwargs.pop("default_value", _not_found_)
        _VT = get_args(self.__orig_class__)[0]
        if isinstance(query, str):

            if default_value is _not_found_ and isinstance(self._default_value, dict):
                default_value = self._default_value.get(query, _not_found_)
            tp = get_type_hint(_VT, query)

            return QueryResult[tp](self._path.append(query), *args, default_value=default_value, **kwargs)
        else:
            return QueryResult[_VT](self._path.append(query), *args, default_value=default_value, **kwargs)

    @property
    def __value__(self) -> typing.Any:
        value = super()._query(self._path)
        if isinstance(value, list):
            value = functools.reduce(self._default_reducer, value)
        return value

    def __call__(self, *args, **kwargs) -> typing.Any:

        value = super()._query(self._path, op=Path.tags.call, *args, **kwargs)

        if isinstance(value, list):
            value = functools.reduce(self._default_reducer, value)

        return value

    def __iter__(self) -> typing.Generator[typing.Tuple[str, _T | HTree] | _T | HTree, None, None]:
        raise NotImplementedError(f"TODO:")

    @staticmethod
    def _default_reducer(first: typing.Any, second: typing.Any) -> typing.Any:

        if first is _not_found_:
            return second
        elif second is _not_found_ or second is None:
            return second
        elif isinstance(first, (str)):
            return first
        elif isinstance(first, array_type) and isinstance(second, array_type):
            return first+second
        elif isinstance(first, (dict, list)) or isinstance(second, (dict, list)):
            return merge_tree_recursive(first, second)
        else:
            return first+second

    def children(self) -> typing.Generator[_T | HTree, None, None]:
        """ 遍历 children """
        cache = self._cache if self._cache is not _not_found_ else self._default_value

        if not isinstance(cache, list) or len(cache) == 0:
            yield from super().children()

        else:
            for idx, value in enumerate(cache):
                if isinstance(value, (dict, Dict)):
                    id = value.get(self._identifier, None)
                else:
                    id = None
                if id is not None:
                    entry = self._entry.child({f"@{self._identifier}": id})
                else:
                    entry = None

                yield self._as_child(value, idx, entry=entry)

class AoS(List[_T]):
    """
        Array of structure
    """

    def __init__(self, *args, identifier: str | None = None, **kwargs):
        super().__init__(*args, **kwargs)
        self._identifier = identifier
        if self._identifier is None:
            self._identifier = self._metadata.get("identifier", None)

    def dump(self, entry: Entry, **kwargs) -> None:
        """ 将数据写入 entry """
        entry.insert([{}]*len(self._cache))
        for idx, value in enumerate(self._cache):
            if isinstance(value, HTree):
                value.dump(entry.child(idx), **kwargs)
            else:
                entry.child(idx).insert(value)

    def _get(self, query: PathLike,  **kwargs) -> HTree | _T | QueryResult[_T]:

        if isinstance(query, int):
            return super()._get(query)

        elif isinstance(query, str):
            query = {f"@{self._identifier}": query}

        elif not isinstance(query, (slice, dict)):
            raise TypeError(f"{type(query)}")

        default_value = kwargs.pop("default_value", self._default_value)

        tp = self._type_hint(0)

        return QueryResult[tp](query, self._cache, entry=self._entry, default_value=default_value, parent=self._parent, **kwargs)


for t in range(1,11):

    N = int(input())

    class Node:
        def __init__(self,op,num,left,right):
            self.op = op
            self.num = num
            self.left = left
            self.right = right

        def __repr__(self):
            return str(self.op) + str(self.num)
    node_li=[]

    for _ in range(N):

        a = input().split()

        ip = a[1:]

        # print(ip)

        if len(ip) == 1:
            node_li.append(Node(None,int(ip[0]),-1,-1))

        else:
            node_li.append(Node(ip[0],None,int(ip[1])-1 ,int(ip[2])-1))

    # print(node_li)

    def dfs(idx):

        if node_li[idx].num != None:
            # print(idx,node_li[idx].num)
            return node_li[idx].num

        else:
            pn = node_li[idx]

            if pn.op == '-':

                return dfs(pn.left) - dfs(pn.right)

            elif pn.op == '/':

                return dfs(pn.left) / dfs(pn.right)

            elif pn.op == '*':

                return dfs(pn.left) * dfs(pn.right)

            elif pn.op == '+':

                return dfs(pn.left) + dfs(pn.right)
    print("#",end='')
    print(t, int(dfs(0)))


from ui_components.components.form_components.form_component import FormComponent
from ui_components.utils.get_driver import get_driver
from ui_components.components.form_components import TextInput, NumberInput

class Form(FormComponent):
    DEFAULT_LOCATOR = "//div[@class='MuiDialogContent-root']//div[contains(@class,'MuiPaper-root')]/div/div/div"

    address = TextInput("详细地址")
    number_field = NumberInput("数字字段")
    field = NumberInput("新增字段")

    def __get__(self, instance, owner):
        super(Form, self).__get__(instance, owner)
        return self

class Page:
    form = Form()

    def __init__(self, driver):
        self.driver = driver

def test():
    driver = get_driver()
    page = Page(driver)
    page.form.address = "测试地址"
    print(page.form.address.value)

def test2():
    driver = get_driver()
    page = Page(driver)
    page.form.field = 11
    print(page.form.field.value)


# -*- coding: utf-8 -*-
###################################################################
# Author: Mu yanru
# Date  : 2013.08
# Email : muyanru345@163.com
###################################################################

try:
    from PySide.QtCore import *
    from PySide.QtGui import *
except ImportError:
    import sip
    sip.setapi("QString",  2)
    sip.setapi("QVariant",  2)
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *

'''
Class Name: MTextEditDialog
Type      : QDialog
 +-+---------------------+
 |-|    Dialog Title     |
 +-----------------------+
 | Content:              |
 | +-------------------+ |
 | |                   | |
 | |                   | |
 | |                   | |
 | |                   | |
 | |                   | |
 | +-------------------+ |
 +-----------------------+
 | +-------+  +--------+ |
 | |  OK   |  | Cancel | |
 | +-------+  +--------+ |
 +-----------------------+
Public Method:
    void setTextContent(QString)
    void setDialogTitle(QString)
    void setLabel(QString)

Public Signal:
    sigDocumentModifed(QString)
'''

class MTextEditDialog(QDialog):
    def __init__(self, parent = None):
        super(MTextEditDialog, self).__init__(parent)
        self.setWindowTitle('MTextEditDialog')
        self.label = QLabel('Label:')
        self.textEdit = QTextEdit()

        okBut = QPushButton('OK')
        okBut.setFixedHeight(30)
        self.connect(okBut, SIGNAL('clicked()'), self.slotOK)

        cancelBut = QPushButton('Cancel')
        cancelBut.setFixedHeight(30)
        self.connect(cancelBut, SIGNAL('clicked()'), self.close)

        butLay = QHBoxLayout()
        butLay.addWidget(okBut)
        butLay.addWidget(cancelBut)

        mainLay = QVBoxLayout()
        mainLay.addWidget(self.label)
        mainLay.addWidget(self.textEdit)
        mainLay.addLayout(butLay)

        self.setLayout(mainLay)

    def setDialogTitle(self, title):
        self.setWindowTitle(title)

    def setLabel(self, label):
        self.label.setText(label)

    def setTextContent(self, text):
        self.textEdit.setDocument(QTextDocument(text))

    def getTextContent(self):
        return self.textEdit.document().toPlainText()

    def slotOK(self):
        self.emit(SIGNAL('sigDocumentModifed(QString)'), self.getTextContent())
        self.close()


from fastapi import Depends
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session

from db.database import get_db
from db.models import LogMessage
from modules import schemas
from routes import app, user

def create_device_log(db: Session, device_id: int, log: schemas.LogMessageBase):
    db_item = LogMessage(**log.dict(), device_id=device_id)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item

def get_device_logs(db: Session, device_id: int):
    return db.query(LogMessage).filter(LogMessage.device_id == device_id).all()

@app.post("/devices/{device_uuid}/logs/", status_code=204, responses={404: {"model": schemas.ErrorMessage}})
async def add_device_logs(device_uuid: str, message: schemas.LogMessageBase, current_user: schemas.User = Depends(user.get_current_active_user), db=Depends(get_db)):
    for device in current_user.devices:
        if device.device_uuid == device_uuid:
            create_device_log(db, device_id=device.id, log=message)
            return

    return JSONResponse(
        status_code=404,
        content=jsonable_encoder(schemas.ErrorMessage(reason="Could not find specified device"))
    )

@app.get("/devices/{device_uuid}/logs/", response_model=list[schemas.LogMessageBase], responses={404: {"model": schemas.ErrorMessage}})
async def fetch_device_logs(device_uuid: str, current_user: schemas.User = Depends(user.get_current_active_user), db=Depends(get_db)):
    for device in current_user.devices:
        if device.device_uuid == device_uuid:
            return get_device_logs(db, device_id=device.id)

    return JSONResponse(
        status_code=404,
        content=jsonable_encoder(schemas.ErrorMessage(reason="Could not find specified device"))
    )


### 1. 두 정수 A와 B가 주어졌을 때, A와 B를 비교하는 프로그램을 작성하시오.
A, B = map(int, input().split())
if A> B:
    print('>')
elif A < B:
    print('<')
else:
    print('==')

### 2. 시험 점수를 입력받아 90 ~ 100점은 A, 80 ~ 89점은 B, 70 ~ 79점은 C, 60 ~ 69점은 D, 나머지 점수는 F를 출력하는 프로그램을 작성하시오.
score = float(input())
if ((score>=90)&(score<=100)):
    print('A')
elif ((score>= 80)&(score<=89)):
    print('B')
elif ((score>=70) & (score<=79)):
    print('C')
elif ((score >=60) & (score<=69)):
    print('D')
else:
    print('F')

### 3.
# 연도가 주어졌을 때, 윤년이면 1, 아니면 0을 출력하는 프로그램을 작성하시오.
# 윤년은 연도가 4의 배수이면서, 100의 배수가 아닐 때 또는 400의 배수일 때이다.
# 예를 들어, 2012년은 4의 배수이면서 100의 배수가 아니라서 윤년이다. 1900년은 100의 배수이고 400의 배수는 아니기 때문에 윤년이 아니다. 하지만, 2000년은 400의 배수이기 때문에 윤년이다
year = int(input())
if str(year/4).split('.')[-1] =='0':
    if str(year/400).split('.')[-1] =='0':
        print(1)

    elif str(year/100).split('.')[-1] != '0':
        print(1)
    else:
        print(0)
else:
    print(0)

### 4.
# 예를 들어, 좌표가 (12, 5)인 점 A는 x좌표와 y좌표가 모두 양수이므로 제1사분면에 속한다. 점 B는 x좌표가 음수이고 y좌표가 양수이므로 제2사분면에 속한다.
# 점의 좌표를 입력받아 그 점이 어느 사분면에 속하는지 알아내는 프로그램을 작성하시오. 단, x좌표와 y좌표는 모두 양수나 음수라고 가정한다
x = int(input())
y = int(input())
if ((x>=0)&(y>=0)):
    print(1)
elif ((x<=0)&(y>=0)):
    print(2)
elif ((x<=0)&(y<=0)):
    print(3)
else:
    print(4)

### 5.
# 첫째 줄에 두 정수 H와 M이 주어진다. (0 ≤ H ≤ 23, 0 ≤ M ≤ 59) 그리고 이것은 현재 상근이가 설정한 놓은 알람 시간 H시 M분을 의미한다.
# 입력 시간은 24시간 표현을 사용한다. 24시간 표현에서 하루의 시작은 0:0(자정)이고, 끝은 23:59(다음날 자정 1분 전)이다. 시간을 나타낼때, 불필요한 0은 사용하지 않는다.
H, M = map(int, input().split())
if M < 45:
    M = 60 - (45-M)
    H -= 1
    if H < 0:
        H = 23
else:
    M = M-45
    if ((M==0)&(H==0)):
        H = 0
print(H,M)

### 6.
# 첫째 줄에는 현재 시각이 나온다. 현재 시각은 시 A (0 ≤ A ≤ 23) 와 분 B (0 ≤ B ≤ 59)가 정수로 빈칸을 사이에 두고 순서대로 주어진다.
# 두 번째 줄에는 요리하는 데 필요한 시간 C (0 ≤ C ≤ 1,000)가 분 단위로 주어진다.
H, M = map(int, input().split())
use_time = int(input())
if use_time > 60:
    print('# # # # # # # # # 1# # # # # # # # # # # # ')
    hour = use_time//60
    H += hour
    if M + (use_time - (60*hour)) >= 60:
        print('# # # # # # # # # 2# # # # # # # # # # # # ')
        M = M + use_time - (60*hour) - 60
        H += 1
        if M == 60:
            M -= 60
            H += 1
        if H > 23:
            H = H - 24

    else:
        print('# # # # # # # # # 3# # # # # # # # # # # # ')
        M += (use_time - (60*hour))
        if M + (use_time - (60*hour)) == 60:
            H += 1
        if H > 23:
            H = H - 24
else:
    print('# # # # # # # # # 4# # # # # # # # # # # # ')
    if M + use_time >= 60:
        print('# # # # # # # # # 5# # # # # # # # # # # # ')
        M = M + use_time - 60
        H += 1
        if H > 23:
            H = H - 24

    else:
        print('# # # # # # # # # 6# # # # # # # # # # # # ')
        M += use_time
        if M + use_time == 60:
            H += 1
        if H > 23:
            H = H - 24
print(H,M)

### 7. 첫째 줄에 3개의 눈이 빈칸을 사이에 두고 각각 주어진다.
# 1에서부터 6까지의 눈을 가진 3개의 주사위를 던져서 다음과 같은 규칙에 따라 상금을 받는 게임이 있다.
# 같은 눈이 3개가 나오면 10,000원+(같은 눈)×1,000원의 상금을 받게 된다.
# 같은 눈이 2개만 나오는 경우에는 1,000원+(같은 눈)×100원의 상금을 받게 된다.
# 모두 다른 눈이 나오는 경우에는 (그 중 가장 큰 눈)×100원의 상금을 받게 된다.
# 예를 들어, 3개의 눈 3, 3, 6이 주어지면 상금은 1,000+3×100으로 계산되어 1,300원을 받게 된다. 또 3개의 눈이 2, 2, 2로 주어지면 10,000+2×1,000 으로 계산되어 12,000원을 받게 된다.
# 3개의 눈이 6, 2, 5로 주어지면 그중 가장 큰 값이 6이므로 6×100으로 계산되어 600원을 상금으로 받게 된다.
# 3개 주사위의 나온 눈이 주어질 때, 상금을 계산하는 프로그램을 작성 하시오.
A, B, C = map(int, input().split())
if ((A==B) & (B==C) & (A==C)):
    result = 10000 + (A*1000)
elif ((A==B)|(A==C)|(B==C)):
    if ((A==B)|(A==C)):
        result = 1000 + (A*100)
    else:
        result = 1000 + (B*100)
else:
    result = max(A,B,C) * 100
print(result)

백준/백준 조건문.py


# !/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@Author:      cz
@Tool:        Sublime Text3
@DateTime:    2018-12-20 12:17:39
'''
#subject:py-vba Excel-files merge dev.
import win32com
from win32com.client import Dispatch, constants
import os
import win32con,win32api
import urllib.request
import tkinter as tk
from tkinter import ttk
import tkinter.messagebox
from time import sleep

#启动配置
def startnow():
	if not os.path.exists(os.getcwd()+'/vb.xlsm'):
		ur='http://datadt.oss-cn-beijing.aliyuncs.com/data/vb.xlsm'#oss资源包
		try:
			urllib.request.urlretrieve(ur,'vb.xlsm')
			sleep(5)
			win32api.SetFileAttributes('vb.xlsm', win32con.FILE_ATTRIBUTE_HIDDEN)
		except:
			tkinter.messagebox.showinfo("提示","请检查网络是否连接")

#调用vba宏模块
def useVBA(file_path,VBA):
    xlApp = win32com.client.DispatchEx("Excel.Application")#打开excel操作环境
    xlApp.Visible = False #True（1）进程可见，False（0）暗自进行
    xlApp.DisplayAlerts = 0#Excel窗口静默加载处理
    xlBook = xlApp.Workbooks.Open(file_path,False)#打开文件，有时候会有警告框说由外部链接什么的（与里面公式有关），要点是则True，否则False
    xlBook.Application.Run(VBA) #宏模块
    xlBook.Close(True)#关闭该文件，并保存，不保存就是False
    xlApp.quit()#关闭excel操作环境

#合并命令
def Mergefiles():
	startnow()
	global info
	info=tkinter.StringVar()
	if cb.get()=='多文件单工作表合并':
		useVBA(os.getcwd()+'/vb.xlsm','way1m')
		info.set('√[多文件单工作表]合并命令执行完成!')
	elif cb.get()=='单文件多工作表合并':
		useVBA(os.getcwd()+'/vb.xlsm','way2m')
		info.set('√[单文件多工作表]合并命令执行完成!')
	elif cb.get()=='多文件多工作表合并':
		useVBA(os.getcwd()+'/vb.xlsm','way3m')
		info.set('√[多文件多工作表]合并命令执行完成!')
	elif cb.get()=='多文件指定多表合并':
		useVBA(os.getcwd()+'/vb.xlsm','way4m')
		info.set('√[多文件指定多表]合并命令执行完成!')
	elif cb.get()=='单工作表转多表拆分':
		useVBA(os.getcwd()+'/vb.xlsm','way5s')
		info.set('√[单工作表转多表]拆分命令执行完成!')
	elif cb.get()=='多表转多个文件拆分':
		useVBA(os.getcwd()+'/vb.xlsm','way6s')
		info.set('√[多表转多个文件]拆分命令执行完成!')
	else:
		useVBA(os.getcwd()+'/vb.xlsm','way7s')
		info.set('√[单表转多个文件]拆分命令执行完成!')
	l3=tk.Label(myapp,textvariable=info,font=('Microsoft YaHei UI',10),width=50,height=2,fg='red')
	l3.place(x=50,y=200)
#帮助
def tips():
	tkinter.messagebox.showinfo('帮助','1.初始化请保持网络畅通,需配置相关文件;\n2.表格文件的合并或拆分暂时支持xls/xlsx/csv格式;\n3.将要合并拆分的文件放在与该程序同一文件夹下;\n4.下拉选择合并拆分的模式后再点击立刻开始按钮;\n5.本程序[大表哥]由datadt开发,仅供个人学习使用！\n--------------搭塔@2018--------------')

#菜单
def menus(myapp):
    menu=tk.Menu(myapp)
    menu.add_cascade(label='帮助',command=tips)
    menu.add_cascade(label='退出',command=myapp.quit)
    myapp.config(menu=menu)

#主程序
myapp=tk.Tk()
myapp.title('表格合并拆分小助手 搭塔@datadt')
myapp.resizable(0,0) #框体大小可调性，分别表示x,y方向的可变性
myapp.geometry('500x300')#主框体大小
menus(myapp)#启用菜单布局
frm=tk.Frame(myapp,width=500,height=222)#构建一个框架,放置主功能模块
frm.pack()
l1=tk.Label(frm,text='Big-Sheets',font=('Arial',20),width=10,height=2,fg='#6495ED').place(x=175,y=10)
l2=tk.Label(frm,text='选择模式 ',font=('Microsoft YaHei UI',10),width=10,height=1,fg='#FF6347').place(x=135,y=100)
cbvalue=tk.StringVar()
cb=ttk.Combobox(frm,textvariable=cbvalue,font=('Microsoft YaHei UI',10),width=15)
cb["values"]=("多文件单工作表合并","单文件多工作表合并","多文件多工作表合并","多文件指定多表合并","单工作表转多表拆分","多表转多个文件拆分","单表转多个文件拆分")
cb.current(0)#默认选择第一种模式
cb.place(x=210,y=100)
b=tk.Button(frm,text='立刻开始',font=('Microsoft YaHei UI',18),width=14,height=1,fg='#00FA9A',bg='#6495ED',command=Mergefiles).place(x=140,y=130)
myapp.mainloop()


export = {
    'DUPERSID': 'id',
    'TOTEXP12': 'spending_dist_total',
    'OPTEXP12': 'spending_dist_outpatient',
    'IPTEXP12': 'spending_dist_inpatient',
    'ERTEXP12': 'spending_dist_emergency',
    'OBTEXP12': 'spending_dist_office',
    'TOTMCD12': 'spending_pay_medicaid',
    'TOTMCR12': 'spending_pay_medicare',
    'TOTPRV12': 'spending_pay_private',
    'TOTSLF12': 'spending_pay_self',
    'FAMINC12': 'demo_fam_income',
    'POVLEV12': 'demo_fam_income_pl',
    'AGE12X': 'demo_age',
    'RACEV1X': 'demo_race_input',
    'RACEAX': 'demo_race_asian',
    'RACEBX': 'demo_race_black',
    'RACEWX': 'demo_race_white',
    'RACETHNX': 'demo_ethnicity_input',
    'EDUCYR': 'demo_education',
    'SEX': 'demo_sex',
    # 'ADGENH42': 'health_selfrate',
    # 'MNHLTH31': 'health_selfmental31',
    # 'MNHLTH42': 'health_selfmental42',
    # 'MNHLTH53': 'health_selfmental53',
    # 'PHQ242': 'health_feelings',
    'BMINDX53': 'health_bmi',
    'ADSMOK42': 'health_smoking',
    # 'IADLHP31': 'limits_IADL31',
    # 'IADLHP42': 'limits_IADL42',
    # 'IADLHP53': 'limits_IADL53',
    # 'IADL3M': 'limits_expectsIADL31',
    # 'IADL3M42': 'limits_expectsIADL42',
    # 'IADL3M53': 'limits_expectsIADL53',
    # 'WLKLIM31': 'limits_WLKLIM31',
    # 'WLKLIM53': 'limits_WLKLIM53',
    # 'WLK3MO31': 'limits_expectsWLKLIM31',
    # 'WLK3MO53': 'limits_expectsWLKLIM53',
    # 'UNABLE31': 'limits_unable31',
    # 'UNABLE53': 'limits_unable3153',
    'MCREV12': 'insurance_medicare',
    'MCDEV12': 'insurance_medicaid',
    'PRVEV12': 'insurance_private',
    'UNINS12': 'insurance_none',
    'HIBPDX': 'chronic_hbp',
    'BPMLDX': 'chronic_hbp2',
    'CHDDX': 'chronic_coronary',
    'MIDX': 'chronic_myocardial',
    'STRKDX': 'chronic_stroke',
    'DIABDX': 'chronic_diabetes',
    'ASTHDX': 'chronic_asthma',
    'ASATAK31': 'chronic_asthma_attack31',
    'ASATAK53': 'chronic_asthma_attack53',
    'ARTHDX': 'chronic_arthritis',
    'CANCERDX': 'chronic_cancer',
    'CABREAST': 'chronic_cancer_breast',
    'CACOLON': 'chronic_cancer_colon',
    'CALUNG': 'chronic_cancer_lung',
    'CAPROSTA': 'chronic_cancer_prostate',
    'CACERVIX': 'chronic_cancer_cervical',
    'IPDIS12': 'service_inpatient',
    # 'OPTOTV12': 'service_outpatient',
    # 'ERTOT12': 'service_emergency',
    # 'HHTOTD12': 'service_home',
    # 'RXTOT12': 'service_meds',
    'OBTOTV12': 'service_office',
    'HAVEUS42': 'gaps_USC_has42',
    # 'LOCATN42': 'gaps_USC_location',
    # 'YNOUSC42': 'gaps_USC_reason_main',
    # 'NOHINS42': 'gaps_USC_reason_uninsured',
    # 'USCNOT42': 'gaps_USC_reason_noavail',
    # 'CARECO42': 'gaps_USC_reason_cost',
    # 'MDUNAB42': 'gaps_care_unable',
    # 'MDUNPR42': 'gaps_care_problem',
    # 'MDUNRS42': 'gaps_care_reason',
    # 'PMUNAB42': 'gaps_meds_unable',
    # 'PMUNPR42': 'gaps_meds_problem',
    # 'PMUNRS42': 'gaps_meds_problem',
    # 'CHECK53': 'gaps_physical',
    # 'CHOLCK53': 'gaps_cholest',
    # 'BPCHECK': 'gaps_bp',
    # 'FLUSHT53': 'gaps_flu',
    # 'PSA53': 'gaps_prostate',
    # 'PAPSMR53': 'gaps_pap',
    # 'MAMMOGR': 'gaps_mamm',
    # 'BSTST53': 'gaps_stool',
    # 'CLNTST53': 'gaps_colon',
     'DSA1C53': 'diabetes_a1c',
     'DSFT1253': 'diabetes_foot',
     'DSE12y': 'diabetes_eye',
     'DSCH1253': 'diabetes_cholest'
}


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

__version__ = "1.0.0"

import io
import logging
import random
import re
from collections import OrderedDict
from pathlib import Path
import shutil
import cairosvg
import fontTools.ttLib
import fontTools.unicodedata as ucd
import vharfbuzz
from PIL import Image
from yaplon import ojson, oyaml

logging.basicConfig(level=logging.WARNING)

is_usvg = False
try:
    from sh import usvg

    is_usvg = True
except ImportError:
    logging.warn("Install Rust, then usvg via: cargo install usvg")

class GetGoFont(object):
    def __init__(self, path, folders, url_bases, redo):
        self.path = path
        self.folders = folders
        self.url_bases = url_bases
        self.redo = redo
        self.page_url = (
            str(self.path.stem).replace("[", "").replace("]", "").replace(",", "-")
        )
        self.vfj_path = Path(self.path.parent, str(self.path.stem) + ".vfj").resolve()
        self.ttf_path = Path(self.path.parent, str(self.path.stem) + ".ttf").resolve()
        self.md_path = Path(self.path.parent, str(self.path.stem) + ".md").resolve()
        self.md_outpath = Path(self.folders["docs"], self.page_url + ".md").resolve()
        self.svg_path = Path(self.folders["images"], self.page_url + ".svg").resolve()
        self.illu_path = Path(self.folders["illu"], self.page_url + ".png").resolve()
        self.png_path = Path(self.folders["images"], self.page_url + ".png").resolve()
        self.woff_path = Path(self.folders["woff"], self.page_url + ".woff2").resolve()
        self.yaml_path = Path(self.path.parent, str(self.path.stem) + ".yaml").resolve()
        self.font = fontTools.ttLib.TTFont(self.path)
        self.name_table = self.font["name"]
        self.family = self.get_family_name()
        self.full_name = self.get_full_name()
        self.copyright = self.get_copyright()
        self.license = self.get_license()
        self.unicodes = []
        self.glyphs_count = len(self.font.getGlyphSet().keys())
        self.scripts = OrderedDict()
        self.script_names = OrderedDict()
        self.metadata = OrderedDict()
        self.index_md = ""
        self.font_md = ""
        self.process()

    def get_download_url(self, path):
        url = str(path).replace(
            str(self.folders["root"]), str(self.url_bases["download"])
        )
        return url

    def get_family_name(self):
        family = self.name_table.getName(16, 3, 1)
        if not family:
            family = self.name_table.getName(1, 3, 1)
        return family.toUnicode() if family else ""

    def get_full_name(self):
        full_name = self.name_table.getName(4, 3, 1)
        return full_name.toUnicode() if full_name else ""

    def get_copyright(self):
        copyright = self.name_table.getName(0, 3, 1)
        return copyright.toUnicode() if copyright else ""

    def get_license(self):
        licenses = {"apache": "Apache", "cc0": "CC-0", "ofl": "OFL"}
        license = (
            str(self.path).replace(str(self.folders["font"]) + "/", "").split("/")[0]
        )
        license = licenses.get(license, license)
        return license

    def build_scripts(self):
        scripts = OrderedDict()
        scripts_coverage = OrderedDict()
        unicodes = []
        for u in self.font.getBestCmap().keys():
            if ucd.category(chr(u))[0] not in ("N", "C") and u not in (0xFFFD, 0x0023):
                unicodes.append(u)
                script = ucd.script(chr(u))
                scripts[script] = scripts.get(script, 0) + 1
                scripts_coverage[script] = scripts_coverage.get(script, []) + [u]
        self.unicodes = sorted(unicodes)
        scripts = OrderedDict(sorted(scripts.items(), key=lambda t: t[1], reverse=True))
        script_sample = ""
        for k, v in scripts_coverage.items():
            if len(v) > 2:
                script_sample += chr(v[0]) + chr(v[1])
        print(self.path)
        print(script_sample)
        for k in ("Zyyy", "Zinh", "Zzzz"):
            if k in scripts.keys():
                del scripts[k]
        if len(self.unicodes) < 10000:
            for k in list(scripts.keys()):
                if scripts[k] / len(self.unicodes) < 0.001:
                    del scripts[k]
        self.scripts = list(scripts.keys()) if len(scripts.keys()) else ["Zsym"]
        self.script_names = [ucd.script_name(script) for script in list(scripts.keys())]

    def save_woff(self):
        if self.redo["woff"] or not self.woff_path.is_file():
            self.font.flavor = "woff2"
            self.font.save(self.woff_path)

    def get_font_css(self):
        url = str(self.woff_path).replace(str(self.folders["docs"]), str("../.."))
        return f"""

@font-face {{
  font-family: '{self.full_name}';
  font-style: normal;
  font-weight: 400;
  font-display: swap;
  src: url({url}) format('woff2');
}}"""

    def build_metadata(self):
        metadata = OrderedDict()
        if not self.redo["yaml"] and self.yaml_path.is_file():
            with open(self.yaml_path, "r", encoding="utf-8") as f:
                metadata = oyaml.read_yaml(f)
        metadata["full_name"] = self.get_full_name()
        metadata["family_name"] = self.get_family_name()
        metadata["copyright"] = self.get_copyright()
        metadata["license"] = metadata.get("license", self.get_license())
        metadata["description"] = metadata.get("description", "Font")
        metadata["scripts"] = self.script_names
        if self.redo["sample_text"]:
            metadata["sample_text"] = self.get_sample_text()
        else:
            metadata["sample_text"] = metadata.get(
                "sample_text", self.get_sample_text()
            )
        metadata["download_large"] = metadata.get("download_large", False)
        with open(self.yaml_path, "w", encoding="utf-8") as f:
            oyaml.yaml_dump(metadata, f)
        self.metadata = metadata

    def get_sample_text(self, words=5, chars=6):
        cats = OrderedDict()
        for u in self.unicodes:
            cat = ucd.category(chr(u))[0]
            if cat in "LNS" and ucd.script(chr(u)) == self.scripts[0]:
                cats[cat] = cats.get(cat, []) + [u]
        try:
            unicodes = sorted(cats.items(), key=lambda t: len(t[1]), reverse=True)[0][1]
        except:
            unicodes = self.unicodes
        lensample = words * chars
        if lensample > len(unicodes):
            lensample = len(unicodes)
        sample = "".join([chr(u) for u in random.sample(unicodes, lensample)])
        words = [sample[0 + i : chars + i] for i in range(0, len(sample), chars)]
        newwords = []
        for wordi, word in enumerate(words):
            if int(wordi / len(words) + 0.7):
                newwords.append(word.lower())
            else:
                newwords.append(word.upper())
        return " ".join(newwords)

    def render_sample_text(self, text=None):
        if (
            self.redo["sample"]
            or not self.png_path.is_file()
            or not self.svg_path.is_file()
        ):
            if not text:
                text = self.metadata["sample_text"]
            v = vharfbuzz.Vharfbuzz(self.path)
            buf = v.shape(text, {"script": self.scripts[0]})
            svg = v.buf_to_svg(buf)
            svg = re.sub(
                r"""<svg xmlns="http://www\.w3\.org/2000/svg" viewBox="0 0 (.*?) (.*?)" transform="matrix\(1 0 0 -1 0 0\)">""",
                r"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 \g<1> \g<2>" transform="translate(0, \g<2>) scale(1, -1)">""",
                svg,
            )
            png = io.BytesIO()
            with open(self.svg_path, "w") as f:
                f.write(svg)
            if is_usvg:
                usvg(self.svg_path, self.svg_path)
            cairosvg.svg2png(bytestring=svg, write_to=png, output_height=56)
            im = Image.open(png)
            im = im.crop((0, 0, 600, 56))
            im.save(self.png_path, "PNG")

    def build_md(self):
        git_download_url = (
            self.url_bases["git_download_large"]
            if self.metadata["download_large"]
            else self.url_bases["git_download"]
        )
        download_url = str(self.vfj_path).replace(
            str(self.folders["font"]), git_download_url
        )
        svg_link = str(self.svg_path).replace(str(self.folders["docs"]) + "/", "")
        md_font_description = f"""license: {self.license} \| {self.metadata["description"]} \| glyphs: {self.glyphs_count} \| scripts: {", ".join(self.script_names)}"""
        #
        with open(self.md_path, "r", encoding="utf-8") as f:
            md_article = f.read()

        self.index_md += f"""

### {self.full_name}

[![{self.metadata["sample_text"]}]({svg_link})]({self.page_url + '/'})

[Download FontLab VFJ]({download_url}){{: .btn target="_blank" }}

{md_font_description} \| [Read more…]({self.page_url + '/'})

---
"""

        illu = ""
        if self.illu_path.is_file():
            illu_link = str(self.illu_path).replace(
                str(self.folders["docs"]) + "/", "../"
            )

            illu = f"""

[![{self.metadata["full_name"]}]({illu_link})]({illu_link}){{: .fancybox data-caption='{self.metadata["full_name"]}' data-fancybox='getgo'}}

"""

        self.font_md += f"""---
layout: default
title: "{self.full_name}"
---

# {self.full_name}

You can type in the box below to preview the font:

{self.metadata["sample_text"]}

[Download FontLab VFJ]({download_url}){{: .btn .btn-purple target="_blank" }}

{md_font_description}

---
{illu}
{md_article}

---

## Character map

{" ".join([chr(u) for u in self.unicodes]).strip()}

"""

    def process(self):
        self.build_scripts()
        self.build_metadata()
        self.save_woff()
        self.render_sample_text()

class GetGoDocs(object):
    def __init__(self):
        self.paths = OrderedDict()
        self.redo = {}
        self.redo["woff"] = False
        self.redo["yaml"] = False
        self.redo["sample_text"] = False
        self.redo["sample"] = True
        self.redo["zip"] = False
        self.folders = {}
        self.folders["root"] = Path(Path(__file__).parent, "..").resolve()
        self.folders["font"] = Path(self.folders["root"], "getgo-fonts").resolve()
        self.folders["md"] = Path(self.folders["root"], "srcdocs").resolve()
        self.folders["docs"] = Path(self.folders["root"], "docs").resolve()
        self.folders["woff"] = Path(self.folders["docs"], "fonts").resolve()
        self.folders["illu"] = Path(self.folders["docs"], "illustrations").resolve()
        self.folders["images"] = Path(self.folders["docs"], "images").resolve()
        self.folders["css"] = Path(self.folders["docs"], "_sass", "custom").resolve()

        self.url_bases = {}

        self.url_bases[
            "web"
        ] = "https://raw.githubusercontent.com/fontlabcom/getgo-fonts/main/docs"
        self.url_bases[
            "download"
        ] = "https://raw.githubusercontent.com/fontlabcom/getgo-fonts/main"
        self.url_bases[
            "github"
        ] = "https://github.com/fontlabcom/getgo-fonts/blob/main/getgo-fonts"
        self.url_bases[
            "git_download"
        ] = "https://cdn.jsdelivr.net/gh/fontlabcom/getgo-fonts/getgo-fonts"
        self.url_bases[
            "git_download_large"
        ] = "https://minhaskamal.github.io/DownGit/#/home?url=https://github.com/fontlabcom/getgo-fonts/blob/main/getgo-fonts"
        self.data = OrderedDict()
        self.font_css = ""
        self.index_md = ""

    def find_fonts(self):
        for self.path in self.folders["font"].glob("**/*.?tf"):
            self.path = self.path.resolve()
            self.paths[self.path] = {}
        sorted_paths = sorted(self.paths.keys(), key=lambda p: p.stem)
        self.paths = OrderedDict((key, self.paths[key]) for key in sorted_paths)

    def process(self):
        with open(Path(self.folders["md"], "prolog.md"), "r", encoding="utf-8") as f:
            self.index_md += (
                f.read()
                + """

## Fonts

"""
            )

        for path in self.paths:
            fo = GetGoFont(path, self.folders, self.url_bases, self.redo)

            self.data[fo.metadata["full_name"]] = OrderedDict()
            drec = self.data[fo.metadata["full_name"]]
            drec.update(fo.metadata)
            drec["categories"] = sorted(
                list(drec.get("categories", [])) + list(drec.get("scripts", []))
            )
            if "scripts" in drec:
                del drec["scripts"]
            drec["url"] = OrderedDict()
            drec["url"]["vfj"] = fo.get_download_url(fo.vfj_path)
            drec["url"]["ttf"] = fo.get_download_url(fo.ttf_path)
            drec["url"]["md"] = fo.get_download_url(fo.md_path)
            drec["url"]["svg"] = fo.get_download_url(fo.svg_path)
            drec["url"]["png"] = fo.get_download_url(fo.png_path)
            self.font_css += fo.get_font_css()
            fo.build_md()
            self.index_md += fo.index_md
            with open(fo.md_outpath, "w", encoding="utf-8") as f:
                f.write(fo.font_md)

        with open(Path(self.folders["css"], "fonts.scss"), "w", encoding="utf-8") as f:
            f.write(self.font_css)
        with open(Path(self.folders["root"], "fonts.json"), "w", encoding="utf-8") as f:
            ojson.json_dump(self.data, f)
        with open(Path(self.folders["docs"], "index.md"), "w", encoding="utf-8") as f:
            f.write(self.index_md)

    def make_zip(self):
        shutil.make_archive(
            Path(self.folders["root"], "getgo-fonts-for-fontlab"),
            "zip",
            self.folders["font"],
        )

    def make(self):
        self.find_fonts()
        self.process()
        if self.redo["zip"]:
            self.make_zip()

def main():
    ggd = GetGoDocs()
    ggd.redo["woff"] = False
    ggd.redo["yaml"] = False
    ggd.redo["sample_text"] = False
    ggd.redo["sample"] = True
    ggd.redo["zip"] = True
    ggd.make()

if __name__ == "__main__":
    main()


def to_val(x):
    global regs
    if str.isalpha(x):
        return regs[x]
    else:
        return int(x)

def do_instruction(inst, reg, val=0):
    global regs
    global ip
    ip_changed = False
    muls = 0
    if val != 0 and str.isalpha(val):
        if inst == "set":
            regs[reg] = regs[val]
        elif inst == "sub":
            regs[reg] -= regs[val]
        elif inst == "mul":
            regs[reg] *= regs[val]
            muls += 1
        elif inst == "jgz":
            if not reg in regs:
                if int(reg) > 0:
                    ip += val
                    ip_changed = True
            elif regs[reg] > 0:
                ip += regs[val]
                ip_changed = True
    else:
        val = int(val)
        if inst == "set":
            regs[reg] = val
        elif inst == "sub":
            regs[reg] -= val
        elif inst == "mul":
            regs[reg] *= val
            muls += 1
        elif inst == "jnz":
            if not reg in regs:
                if int(reg) != 0:
                    ip += val
                    ip_changed = True
            elif regs[reg] != 0:
                ip += val
                ip_changed = True
    if not ip_changed:
        ip += 1
    return muls

def is_prime(n):
    if n == 2 or n == 3: return True
    if n < 2 or n%2 == 0: return False
    if n < 9: return True
    if n%3 == 0: return False
    r = int(n**0.5)
    f = 5
    while f <= r:
        if n%f == 0: return False
        if n%(f+2) == 0: return False
        f +=6
    return True

with open("day23_input") as infile:
    inst = [line.strip().split(' ') for line in infile]
ip = 0
regs = {k[1]: 0 for k in inst if str.isalpha(k[1])}

muls = 0
while ip < len(inst):
    muls += do_instruction(inst[ip][0], inst[ip][1], inst[ip][2])
print(muls)

b = to_val(inst[0][2]) * to_val(inst[4][2]) - to_val(inst[5][2])
c = b - to_val(inst[7][2])
step = -to_val(inst[30][2])
not_primes = 0
for b in range(b, c, step):
    if not is_prime(b):
        not_primes += 1
print(not_primes)


import os

SEQ_LENGTH = 6
VALI_LENGTH = 100
EPOCH = 400
EPOCH_SAVE = 5
BATCH_SIZE = 6
TEST_BATCH_SIZE = 6
DRAW_BATCH_SIZE = 6
NUM_WORKERS = 12
DRAW_NUM_WORKERS = 12
HALF = False
POSE = True

TRAIN_SEQ = ["00", "02", "08", "09"]  #  "03", "04", "05", "06", "07", "10"]
VALI_SEQ = ["01", "04"]
TEST_SEQ = ["01", "03", "05", "06", "10"]
DRAW_SEQ = "00"
PRETRAIN_FLOW_PATH = "weights/flownets_bn_EPE2.459.pth.tar"

VO = "deepvo" + "_weight1"
WEIGHT_FOLDER = f"../{VO}_w"
LOSS_FOLDER = f"../{VO}_l"
RESULT_FOLDER = f"../{VO}_results"
KITTI_PATH = "../dataset3"

for p in [WEIGHT_FOLDER, LOSS_FOLDER, RESULT_FOLDER]:
    if not os.path.exists(p):
        os.makedirs(p)

CUDA_DEVICE_NUM = "cuda:0"
OPTIMIZER = "radam"


#
# @lc app=leetcode.cn id=49 lang=python3
#
# [49] 字母异位词分组
#
# %%
# @lc code=start
class Solution:
    def groupAnagrams(self, strs):
        groups = []
        ch_cnt = []
        res = {}
        for word in strs:
            word_ch = set(word)
            ch_dic = {}
            for x in word_ch:
                ch_dic[x] = word.count(x)
            if (word_ch not in groups) or (ch_dic not in ch_cnt):
                groups.append(word_ch)
                ch_cnt.append(ch_dic)
                idx = ch_cnt.index(ch_dic)
                res[idx] = []
                res[idx].append(word)
            else:
                idx = ch_cnt.index(ch_dic)
                res[idx].append(word)
        return list(res.values())

# @lc code=end
# %%

49.字母异位词分组.py

49.字母异位词分组.py


from typing import List
from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np
import cv2
import numpy as np
from object_detector import Detection
import os
_MARGIN = 10  # pixels
_ROW_SIZE = 10  # pixels
_FONT_SIZE = 1
_FONT_THICKNESS = 1
_TEXT_COLOR = (0, 0, 255)  # red

def myCustomPrediction(image):
  # Load the model
  model = load_model('./models/firedetectornoon.h5')

# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1.
  data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
  # image = Image.open('<IMAGE_PATH>')
#resize the image to a 224x224 with the same strategy as in TM2:
#resizing the image to be at least 224x224 and then cropping from the center
  # size = (224, 224)
  # image = ImageOps.fit(image, size, Image.ANTIALIAS)

#turn the image into a numpy array
  image_array = np.asarray(image)
# Normalize the image
  normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
  data[0] = normalized_image_array

# run the inference
  prediction = model.predict(data)
  print(prediction)
  return [image,prediction]

def myClassDetector(image):
  # Load the model
  model = load_model('./models/classifier.h5')

# Create the array of the right shape to feed into the keras model
# The 'length' or number of images you can put into the array is
# determined by the first position in the shape tuple, in this case 1.
  data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# Replace this with the path to your image
  # image = Image.open('<IMAGE_PATH>')
#resize the image to a 224x224 with the same strategy as in TM2:
#resizing the image to be at least 224x224 and then cropping from the center
  # size = (224, 224)
  # image = ImageOps.fit(image, size, Image.ANTIALIAS)

#turn the image into a numpy array
  image_array = np.asarray(image)
# Normalize the image
  normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
  data[0] = normalized_image_array

# run the inference
  prediction = model.predict(data)
  print(prediction)
  return [image,prediction]

def visualize(
    image: np.ndarray,
    detections: List[Detection],
) -> np.ndarray:
  """Draws bounding boxes on the input image and return it.
  Args:
    image: The input RGB image.
    detections: The list of all "Detection" entities to be visualize.
  Returns:
    Image with bounding boxes.
  """
  for detection in detections:
    # Draw bounding_box
    start_point = detection.bounding_box.left, detection.bounding_box.top
    end_point = detection.bounding_box.right, detection.bounding_box.bottom
    cv2.rectangle(image, start_point, end_point, _TEXT_COLOR, 3)

    # Draw label and score
    category = detection.categories[0]
    class_name = category.label
    probability = round(category.score, 2)
    result_text = class_name + ' (' + str(probability) + ')'
    text_location = (_MARGIN + detection.bounding_box.left,
                     _MARGIN + _ROW_SIZE + detection.bounding_box.top)
    cv2.putText(image, result_text, text_location, cv2.FONT_HERSHEY_PLAIN,
                _FONT_SIZE, _TEXT_COLOR, _FONT_THICKNESS)

  return image

def imageSaver(image,counter):
    directory = r'D:\Nidhin_Projects\raspi\firefighter\cctv\output'
    os.chdir(directory)
    cv2.imwrite("output-"+ str(counter)+".jpg", image)
    counter += 1
    return image


"""
Monte Carlo Tic-Tac-Toe Player
http://www.codeskulptor.org/#user39_9JMeob2f3J_38.py
"""

import random
import poc_ttt_gui
import poc_ttt_provided as provided

# Constants for Monte Carlo simulator
# You may change the values of these constants as desired, but
#  do not change their names.
NTRIALS = 1         # Number of trials to run
SCORE_CURRENT = 1.0 # Score for squares played by the current player
SCORE_OTHER = 1.0   # Score for squares played by the other player

# Add your functions here.

def mc_trial(board, player):
    """
        runs Monte Carlo Trial - choosing moves at
        random until board is in a "finished" state
        """
    current_player = player
    while board.check_win() == None:
        ## get a list of empty positions
        ## randomly pick one of them for player's move
        current_move = random.choice(board.get_empty_squares())
        board.move(current_move[0], current_move[1], current_player)
        # Switch players
        current_player = provided.switch_player(current_player)

def mc_update_scores(scores, board, player):
    """
        Updates "scoreboard" to include results of
        input parameter board by reference
        """
    if board.check_win() == player:
        for row_position in range(board.get_dim()):
            for column_position in range(board.get_dim()):
                if board.square(row_position, column_position) == player:
                    scores[row_position][column_position] += SCORE_CURRENT
                elif board.square(row_position, column_position) == provided.switch_player(player):
                    scores[row_position][column_position] -= SCORE_OTHER
    elif board.check_win() == provided.switch_player(player):
        for row_position in range(board.get_dim()):
            for column_position in range(board.get_dim()):
                if board.square(row_position, column_position) == player:
                    scores[row_position][column_position] -= SCORE_CURRENT
                elif board.square(row_position, column_position) == provided.switch_player(player):
                    scores[row_position][column_position] += SCORE_OTHER
    else:
        ## Board is a draw
        pass

def get_best_move(board, scores):
    """
        Determines which position is best for next move
        and returns tuple denoting that position
        if there are multiple "best" positions, one of
        them is returned randomly.
        Additionally, if the board has no empty squares
        it returns nothing.
        """
    ## get empty positions in board
    empty_scores = {}
    for pos in board.get_empty_squares():
        empty_scores[pos] = scores[pos[0]][pos[1]]
    #    empty_scores = {pos:scores[pos[0]][pos[1]] for pos in board.get_empty_squares()}
    ## if there are no empty squares then return nothing
    if len(empty_scores) < 1:
        return
    # determine which score is best of the empty square scores
    best_score = max([score for score in empty_scores.values()])
    if len([pos for pos,score in empty_scores.items() if score == best_score]) > 1:
        return random.choice([pos for pos,score in empty_scores.items() if score == best_score])
    else:
        return [pos for pos, score in empty_scores.items() if score==best_score][0]

def mc_move(board, player, trials):
    """
        Takes a board, which player is playing and the number of trials to run
        for a MC simulation, returns a position for the machine player to take
        in the form a (row, column) tuple.
        """
    scoreboard = [[0 for _ in range(board.get_dim())] for _ in range(board.get_dim())]
    for _ in range(trials):
        board_copy = board.clone()
        mc_trial(board_copy, player)
        mc_update_scores(scoreboard,board_copy, player)
    return get_best_move(board, scoreboard)

# Test game with the console or the GUI.  Uncomment whichever
# you prefer.  Both should be commented out when you submit
# for testing to save time.

#provided.play_game(mc_move, NTRIALS, False)
#poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False)


import pandas as pd
import sys
from sklearn.feature_extraction.text import CountVectorizer
from sets import Set
from bs4 import BeautifulSoup
import re
from nltk.corpus import stopwords
import sys
import numpy as np

train = pd.read_csv("/Users/ngaonkar/Desktop/Predict542/Gaonkar_assigment4/train_clean_tweets.csv", header=0, \
                 delimiter=",", quoting=3)

print (train.shape)
print(train.columns.values)

def main():
    #train.columns=["Sentiment"]["Tweet"]
    num_tweets = train['Tweet'].size
    clean_train_tweets = []

    for Tweet in range(0, num_tweets):
        # If the index is evenly divisible by 100, print a message
        if (Tweet+1) % 1000 == 0:
            print('Tweet {} of {}'.format(Tweet+1, num_tweets))
            # Call our function for each one, and add the result to the list of clean reviews
        clean_train_tweets.append(review_to_words(train['Tweet'][Tweet]))

    print('Creating the bag of words...')

    # Initialize the "CountVectorizer" object, which is scikit-learn's bag of words tool.
    vectorizer = CountVectorizer(analyzer = 'word',
                            tokenizer = None,
                            preprocessor = None,
                            stop_words = None,
                            max_features = 5000)
    # fit_transform() does two functions: First, it fits the model
    # and learns the vocabaulary; second, it transforms our training data
    # into feature vectors. The input to fit_transform should be a list of strings.
    train_data_features = vectorizer.fit_transform(clean_train_tweets)

    # Numpy arrays are easy to work with, so convert the result to an array
    train_data_features = train_data_features.toarray()
    print('Bag of words completed')
    print(train_data_features.shape)
    vocab = vectorizer.get_feature_names()
    print(vocab)

    # Sum up the counts of each vocabulary word
    dist = np.sum(train_data_features, axis=0)

    # For each, print the vocabulary word and the number of times it
    # appears in the training set
    for tag, count in zip(vocab, dist):
            print(count, tag)

    print('Training the random forest...')
    from sklearn.ensemble import RandomForestClassifier

        # Initialize a Random Forest classifier with 100 trees
    forest = RandomForestClassifier(n_estimators = 100)

    # Fit the forest to the training set, using the bag of words as
    # features and the sentiment labels as the response variable

    forest = forest.fit(train_data_features, train['Sentiment'])
    print('Training Complete!')

    # Read the test data
    test = pd.read_csv('/Users/ngaonkar/Desktop/Predict542/Gaonkar_assigment4/test_clean_data.csv', header=0, delimiter=',', quoting=3)

    # Verifying that there are 1490 rows and 2 columns
    print(test.shape)

    # Create an empty list and append the clean tweet one by one
    num_tweets = len(test['Tweet'])
    clean_test_tweets = []

    print('Cleaning and parsing the test set tweet data...')
    for Tweet in range(0, num_tweets):
        if (Tweet + 1) % 1000 == 0:
            print('Tweet {} of {}'.format(Tweet + 1, num_tweets))
        clean_tweet = review_to_words(test['Tweet'][Tweet])
        clean_test_tweets.append(clean_tweet)

    # Get a bag of words for the test set, and convert to a numpy
    print('Transforming to array...')
    test_data_features = vectorizer.transform(clean_test_tweets)
    test_data_features = test_data_features.toarray()

    # Use the random forest to make sentiment label predictions
    print('Predicting...')
    result = forest.predict(test_data_features)

    # Copy the results to a pandas dataframe with the "id" column and
    # a sentiment column
    output = pd.DataFrame(data={'id': test['id'], 'sentiment': result})

    # Use pandas to write the comma-seperated output file
    print('Writing to CSV')
    output.to_csv('/Users/ngaonkar/Desktop/Predict542/Gaonkar_assigment4/Bag_of_words_model.csv', index=False, quoting=3)

def review_to_words(raw_tweet):
    # Function to convert a raw tweet to a string of words
    # The input is a single string (a raw tweet), and
    # the output is a single string (a preprocessed tweet)
    #
    # 1. Remove HTML
    tweet_text = BeautifulSoup(raw_tweet).get_text()
    #
    # 2. Remove non-letters
    letters_only = re.sub("[^a-zA-Z]", " ", tweet_text)
    #
    # 3. Convert to lower case, split into individual words
    words = letters_only.lower().split()
    #
    # 4 stops = set(stopwords.words("english"))
    stops = ['js','md','mcj','the','of','to','and','in','it','luctthfibk','its',\
    'they','their','we','us','our','you','me','mine','my',\
    'for','by','with','within','about','between','from',\
    'as','for','an','what','who','how','when','where',\
    'whereas','is','are','were','this','that','if','or','oqcjdjfmrz',\
    'not','nor','ltnyq','lrjbrs','lpkupvkl','lozrzsnbf','luzopxg','momknwsshopping','at','why','your','on','yvqwcy','off',\
    'url','png','jpg','jpeg','gif','zkerphs','zechqf','hover','em','px','pdf','orazewuonp',\
    'header','footer','zz','zydd','zwobusl','zrwnnvgrut','zx','padding','before','after','ie','tm','zyqpeknhjq','zyadragab','zvwaudptxl','zurodb','zniavkfsy']
    #
    # 5. Remove stop words
    meaningful_words = [w for w in words if not w in stops]
    #
    # 6. Join the words back into one string separated by space,
    # and return the result.
    return( " ".join( meaningful_words ))

if __name__ == '__main__':
     main()


# load library
from tkinter import filedialog
from tkinter import Canvas
from tkinter import ttk
import tkinter as tk
from cv2 import cv2
import numpy as np
import webbrowser
import shutil
import glob
import os

# frame
root = tk.Tk(className='Wayang Identification by CNN')

window_width = 700
window_height = 620

copyright = u"\u00A9"
huruf=('Times',12,'italic')

# get the screen dimension
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# find the center point / posisi tengah
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)

# set the position of the window to the center of the screen
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')

# label = judul skripsi
labelJudul = tk.Label(root,
        borderwidth = 2,
        width = 600,
        wraplength=600,
        relief="ridge",
        font=("Helvetica", 12),
        text="IDENTIFIKASI KARAKTER WAYANG KULIT DENGAN METODE CANNY EDGE DETECTION DAN ALGORITMA CONVOLUTIONAL NEURAL NETWORK (CNN) PADA WAYANG KULIT GAYA SURAKARTA")

labelJudul.pack(ipadx=5, ipady=5, pady=5)

# display an image label
photo = tk.PhotoImage(file='./assets/img/banner_fix.png')
image_label = ttk.Label(
    root,
    justify="center",
    image=photo,
    padding=5
)
image_label.pack()

# -----------------------fungsi-fungsi | button--------------------------------
# done
def btn_info_app():
    os.system("python about_page.py")

# done
def btn_preprocessing():
    os.system("python detail_preprocess.py")

# done
def btn_canny_scratch():
    os.system("python canny_scratch.py")

# done
def btn_training_cnn():
    webbrowser.open_new(r"https://colab.research.google.com/drive/1tpldXk9W1ZlOui1GfBdqLUuc5Uxz7WsG#scrollTo=2OoY0lelDpkL")

# done
def btn_identify_img():
    os.system("python identifyimg.py")

# done
def btn_quit_app():
    # return root.destroy()
    os.system("python pengujian.py")

# button control
button1 = ttk.Button(root, text='About The App', command=btn_info_app, width=100)
button1.pack(padx=5, pady=5, ipady=3)

button2 = ttk.Button(root, text='Preprocessing Data', command=btn_preprocessing, width=100)
button2.pack(padx=5, pady=5, ipady=3)

button3 = ttk.Button(root, text='Canny Edge Detection', command=btn_canny_scratch, width=100)
button3.pack(padx=5, pady=5, ipady=3)

button4 = ttk.Button(root, text='Training CNN Model', command=btn_training_cnn, width=100)
button4.pack(padx=5, pady=5, ipady=3)

button5 = ttk.Button(root, text='Identify Images Testing', command=btn_identify_img, width=100)
button5.pack(padx=5, pady=5, ipady=3)

button6 = ttk.Button(root, text='Perhitungan Akurasi-Presisi-Recall', command=btn_quit_app, width=100)
button6.pack(padx=5, pady=5, ipady=3)

l1=tk.Label(root,text=copyright + ' Develop by Sanding Riyanto | 1811501541', font=huruf, fg="black").pack()

# main loop all
root.mainloop()


from flask import Flask

from config import ApplicationConfig
from blueprints import root, error_handler, transactions
from middleware import Middleware

def get_application() -> Flask:
    """Creates an application"""

    config = ApplicationConfig()
    app = Flask(__name__)

    app.config.update(**config.dict())
    app.user_config = config

    app.wsgi_app = Middleware(app.wsgi_app)
    return app

app = get_application()

# register blueprints
app.register_blueprint(error_handler, url_prefix="/")
app.register_blueprint(root, url_prefix="/")
app.register_blueprint(transactions, url_prefix="/transactions")

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)


import copy
import os
import warnings

import torch
import torch.nn.functional as F

import torchbearer
from torchbearer.callbacks import Callback

__writers__ = dict()

class VisdomParams:
    """
    Class to hold visdom client arguments. Modify member variables before initialising tensorboard callbacks for custom
    arguments. See: `visdom <https://github.com/facebookresearch/visdom#visdom-arguments-python-only>`_
    """
    SERVER = 'http://localhost'
    ENDPOINT = 'events'
    PORT = 8097
    IPV6 = True
    HTTP_PROXY_HOST = None
    HTTP_PROXY_PORT = None
    ENV = 'main'
    SEND = True
    RAISE_EXCEPTIONS = None
    USE_INCOMING_SOCKET = True
    LOG_TO_FILENAME = None

    def __to_dict__(self):
        base_params = {e.lower(): VisdomParams.__dict__[e] for e in VisdomParams.__dict__ if '__' not in e}
        new_params = {e.lower(): self.__dict__[e] for e in self.__dict__ if '__' not in e}
        base_params.update(new_params)
        return base_params

def get_writer(log_dir, logger, visdom=False, visdom_params=None):
    """
    Get the writer assigned to the given log directory.
    If the writer doesn't exist it will be created, and a reference to the logger added.

    Args:
        log_dir (str): the log directory
        logger: the object requesting the writer. That object should call `close_writer` when its finished
        visdom (bool): if true VisdomWriter is returned instead of tensorboard SummaryWriter
        visdom_params (VisdomParams): Visdom parameter settings object, uses default if None

    Returns:
        the `SummaryWriter` or `VisdomWriter` object
    """
    import tensorboardX
    from tensorboardX import SummaryWriter
    import sys
    import errno
    kwargs = {}
    if sys.version_info[0] >= 3:
        kwargs['exist_ok'] = True

    writer_key = 'writer'
    if visdom:
        writer_key = 'writer_visdom'

    if log_dir not in __writers__ or writer_key not in __writers__[log_dir]:
        if visdom:
            w = tensorboardX.torchvis.VisdomWriter()
            from visdom import Visdom
            try:
                os.makedirs(log_dir, **kwargs)
            except OSError as exc:
                if exc.errno == errno.EEXIST and os.path.isdir(log_dir):
                    pass
                else:
                    raise exc
            if visdom_params is None:
                visdom_params = VisdomParams()
                visdom_params.LOG_TO_FILENAME = os.path.join(log_dir, 'log.log')
            w.vis = Visdom(**visdom_params.__to_dict__())
        else:
            w = SummaryWriter(log_dir=log_dir)
        __writers__[log_dir] = {writer_key: w, 'references': set()}

    __writers__[log_dir]['references'].add(logger)
    return __writers__[log_dir][writer_key]

def close_writer(log_dir, logger):
    """
    Decrement the reference count for a writer belonging to a specific log directory.
    If the reference count gets to zero, the writer will be closed and removed.

    Args:
        log_dir (str): the log directory
        logger: the object releasing the writer
    """
    if log_dir in __writers__:
        __writers__[log_dir]['references'].discard(logger)

        if len(__writers__[log_dir]['references']) is 0:
            if 'writer' in __writers__[log_dir]:
                __writers__[log_dir]['writer'].close()

            if 'writer_visdom' in __writers__[log_dir]:
                __writers__[log_dir]['writer_visdom'].close()

        del __writers__[log_dir]

class AbstractTensorBoard(Callback):
    """TensorBoard callback which writes metrics to the given log directory. Requires the TensorboardX library for python.

    Args:
        log_dir (str): The tensorboard log path for output
        comment (str): Descriptive comment to append to path
        visdom (bool): If true, log to visdom instead of tensorboard
        visdom_params (VisdomParams): Visdom parameter settings object, uses default if None

    State Requirements:
        - :attr:`torchbearer.state.MODEL`: PyTorch model
    """

    def __init__(self, log_dir='./logs',
                 comment='torchbearer', visdom=False, visdom_params=None):
        super(AbstractTensorBoard, self).__init__()

        self.raw_log_dir = log_dir
        self.log_dir = log_dir
        self.comment = comment
        self.writer = None
        self.visdom = visdom
        self.visdom_params = visdom_params

    def get_writer(self, log_dir=None, visdom=False, visdom_params=None):
        """
        Get a SummaryWriter for the given directory (or the default writer if the directory is not given).
        If you are getting a `SummaryWriter` for a custom directory, it is your responsibility to close
        it using `close_writer`.

        Args:
            log_dir (str): the (optional) directory
            visdom (bool): If true, return VisdomWriter, if false return tensorboard SummaryWriter
            visdom_params (VisdomParams): Visdom parameter settings object, uses default if None

        Returns:
            the `SummaryWriter` or `VisdomWriter`
        """
        if log_dir is None:
            self.writer = get_writer(self.log_dir, self, visdom=visdom, visdom_params=visdom_params)
            return self.writer
        else:
            return get_writer(log_dir, self, visdom=visdom, visdom_params=visdom_params)

    def close_writer(self, log_dir=None):
        """
        Decrement the reference count for a writer belonging to the given log directory
        (or the default writer if the directory is not given). If the reference count gets to zero,
        the writer will be closed and removed.

        Args:
            log_dir (str): the (optional) directory
        """
        if log_dir is None:
            close_writer(self.log_dir, self)
        else:
            close_writer(log_dir, self)

    def on_start(self, state):
        self.log_dir = os.path.join(self.log_dir, state[torchbearer.MODEL].__class__.__name__ + '_' + self.comment)
        self.writer = self.get_writer(visdom=self.visdom, visdom_params=self.visdom_params)

    @staticmethod
    def add_metric(add_fn, tag, metric, *args, **kwargs):
        """ Static method that recurses through `metric` until the `add_fn` can be applied. Useful when metric is an
        iterable of tensors so that the tensors can  all be passed to an `add_fn` such as writer.add_scalar.
        For example, if passed `metric` as [[A, B], [C, ], D, {'E': E}] then `add_fn` would be called on A, B, C, D and
        E and the respective tags (with base tag 'met') would be: met_0_0, met_0_1, met_1_0, met_2, met_E. Throws a
        warning if `add_fn` fails to parse a metric.

        Args:
            add_fn: Function to be called to log a metric, e.g. SummaryWriter.add_scalar
            tag: Tag under which to log the metric
            metric: Iterable of metrics.
            *args: Args for `add_fn`
            **kwargs: Keyword args for `add_fn`

        Returns:

        """
        try:
            add_fn(tag, metric, *args, **kwargs)
        except NotImplementedError:
            try:
                for key, met in enumerate(metric):
                    if isinstance(metric, dict):
                        key, met = met, metric[met]

                    AbstractTensorBoard.add_metric(add_fn, tag+'_{}'.format(key), met, *args, **kwargs)
            except TypeError as e:
                warnings.warn('Failed to log metric to tensorboard with error: {}'.format(e))
        except Exception as e:
            warnings.warn('Failed to log metric to tensorboard with error: {}'.format(e))

    def on_end(self, state):
        self.close_writer()

class TensorBoard(AbstractTensorBoard):
    """TensorBoard callback which writes metrics to the given log directory. Requires the TensorboardX library for python.

    Example: ::

        >>> from torchbearer import Trial
        >>> from torchbearer.callbacks import TensorBoard
        >>> import datetime
        >>> current_time = datetime.now().strftime('%b%d_%H-%M-%S')
        # Callback that will log to tensorboard under "(model name)_(current time)"
        >>> tb = TensorBoard(log_dir='./logs', write_graph=False, comment=current_time)
        # Trial that will run the callback and log accuracy and loss metrics
        >>> t = Trial(None, callbacks=[tb], metrics=['acc', 'loss'])

    Args:
        log_dir (str): The tensorboard log path for output
        write_graph (bool): If True, the model graph will be written using the TensorboardX library
        write_batch_metrics (bool): If True, batch metrics will be written
        batch_step_size (int): The step size to use when writing batch metrics, make this larger to reduce latency
        write_epoch_metrics (bool): If True, metrics from the end of the epoch will be written
        comment (str): Descriptive comment to append to path
        visdom (bool): If true, log to visdom instead of tensorboard
        visdom_params (VisdomParams): Visdom parameter settings object, uses default if None

    State Requirements:
        - :attr:`torchbearer.state.MODEL`: PyTorch model
        - :attr:`torchbearer.state.EPOCH`: State should have the current epoch stored
        - :attr:`torchbearer.state.X`: State should have the current data stored if a model graph is to be built
        - :attr:`torchbearer.state.BATCH`: State should have the current batch number stored if logging batch metrics
        - :attr:`torchbearer.state.TRAIN_STEPS`: State should have the number of training steps stored
        - :attr:`torchbearer.state.METRICS`: State should have a dictionary of metrics stored
    """

    def __init__(self, log_dir='./logs',
                 write_graph=True,
                 write_batch_metrics=False,
                 batch_step_size=10,
                 write_epoch_metrics=True,
                 comment='torchbearer',
                 visdom=False,
                 visdom_params=None):
        super(TensorBoard, self).__init__(log_dir, comment, visdom, visdom_params)

        self.write_graph = write_graph
        self.write_batch_metrics = write_batch_metrics
        self.batch_step_size = batch_step_size
        self.write_epoch_metrics = write_epoch_metrics
        self.visdom = visdom

        if self.write_graph and not visdom:
            def handle_graph(state):
                dummy = torch.rand(state[torchbearer.X].size(), requires_grad=False)
                model = copy.deepcopy(state[torchbearer.MODEL]).to('cpu')
                self.writer.add_graph(model, (dummy,))
                self._handle_graph = lambda _: None

            self._handle_graph = handle_graph
        else:
            self._handle_graph = lambda _: None

        self.batch_log_dir = None
        self.batch_writer = None

    def on_start_epoch(self, state):
        if self.write_batch_metrics:
            if self.visdom:
                self.batch_log_dir = os.path.join(self.log_dir, 'epoch/')
            else:
                self.batch_log_dir = os.path.join(self.log_dir, 'epoch-' + str(state[torchbearer.EPOCH]))
            self.batch_writer = self.get_writer(self.batch_log_dir, visdom=self.visdom)

    def on_sample(self, state):
        self._handle_graph(state)

    def on_step_training(self, state):
        if self.write_batch_metrics and state[torchbearer.BATCH] % self.batch_step_size == 0:
            for metric in state[torchbearer.METRICS]:
                if self.visdom:
                    self.add_metric(self.batch_writer.add_scalar, metric, state[torchbearer.METRICS][metric],
                                                 state[torchbearer.EPOCH] * state[torchbearer.TRAIN_STEPS] + state[
                                                     torchbearer.BATCH], main_tag='batch')
                else:
                    self.add_metric(self.batch_writer.add_scalar, 'batch/' + metric, state[torchbearer.METRICS][metric], state[torchbearer.BATCH])

    def on_step_validation(self, state):
        if self.write_batch_metrics and state[torchbearer.BATCH] % self.batch_step_size == 0:
            for metric in state[torchbearer.METRICS]:
                if self.visdom:
                    self.add_metric(self.batch_writer.add_scalar, metric, state[torchbearer.METRICS][metric],
                                                 state[torchbearer.EPOCH] * state[torchbearer.TRAIN_STEPS] + state[
                                                     torchbearer.BATCH], main_tag='batch')
                else:
                    self.add_metric(self.batch_writer.add_scalar, 'batch/' + metric, state[torchbearer.METRICS][metric], state[torchbearer.BATCH])

    def on_end_epoch(self, state):
        if self.write_batch_metrics and not self.visdom:
            self.close_writer(self.batch_log_dir)

        if self.write_epoch_metrics:
            for metric in state[torchbearer.METRICS]:
                if self.visdom:
                    self.add_metric(self.writer.add_scalar, metric, state[torchbearer.METRICS][metric], state[torchbearer.EPOCH],
                                           main_tag='epoch')
                else:
                    self.add_metric(self.writer.add_scalar, 'epoch/' + metric, state[torchbearer.METRICS][metric], state[torchbearer.EPOCH])

    def on_end(self, state):
        super(TensorBoard, self).on_end(state)
        if self.write_batch_metrics and self.visdom:
            self.close_writer(self.batch_log_dir)

class TensorBoardText(AbstractTensorBoard):
    """TensorBoard callback which writes metrics as text to the given log directory. Requires the TensorboardX library
    for python.

    Example: ::

        >>> from torchbearer import Trial
        >>> from torchbearer.callbacks import TensorBoardText
        >>> import datetime
        >>> current_time = datetime.now().strftime('%b%d_%H-%M-%S')
        # Callback that will log to tensorboard under "(model name)_(current time)"
        >>> tb = TensorBoardText(comment=current_time)
        # Trial that will run the callback and log accuracy and loss metrics as text to tensorboard
        >>> t = Trial(None, callbacks=[tb], metrics=['acc', 'loss'])

    Args:
        log_dir (str): The tensorboard log path for output
        write_epoch_metrics (bool): If True, metrics from the end of the epoch will be written
        log_trial_summary (bool): If True logs a string summary of the Trial
        batch_step_size (int): The step size to use when writing batch metrics, make this larger to reduce latency
        comment (str): Descriptive comment to append to path
        visdom (bool): If true, log to visdom instead of tensorboard
        visdom_params (VisdomParams): Visdom parameter settings object, uses default if None

    State Requirements:
        - :attr:`torchbearer.state.SELF`: The :attr:`torchbearer.Trial` running this callback
        - :attr:`torchbearer.state.EPOCH`: State should have the current epoch stored
        - :attr:`torchbearer.state.BATCH`: State should have the current batch number stored if logging batch metrics
        - :attr:`torchbearer.state.METRICS`: State should have a dictionary of metrics stored
    """

    def __init__(self, log_dir='./logs',
                 write_epoch_metrics=True,
                 write_batch_metrics=False,
                 log_trial_summary=True,
                 batch_step_size=100,
                 comment='torchbearer',
                 visdom=False,
                 visdom_params=None):
        super(TensorBoardText, self).__init__(log_dir, comment, visdom, visdom_params)
        self.write_epoch_metrics = write_epoch_metrics
        self.write_batch_metrics = write_batch_metrics
        self.log_trial_summary = log_trial_summary
        self.batch_step_size = batch_step_size
        self.visdom = visdom
        self.batch_log_dir = None
        self.batch_writer = None
        self.logged_summary = False

    @staticmethod
    def table_formatter(string):
        table = '
Metric	Value	'
        string = string.replace('{', '').replace('}', '').replace("'", "")  # TODO: Replace this with single pass regex

        def cell(string):
            return '' + string + '	'

        def row(string):
            return '
' + string + '
'

        metrics = string.split(',')
        for _, metric in enumerate(metrics):
            items = metric.split(':')
            name, value = items[0], items[1]
            table = table + row(cell(name) + cell(value))

        return table + '
'

    def on_start(self, state):
        super(TensorBoardText, self).on_start(state)
        if self.log_trial_summary and not self.logged_summary:
            self.logged_summary = True
            self.writer.add_text('trial', str(state[torchbearer.SELF]).replace('\n', '\n \n'), 1)

    def on_start_epoch(self, state):
        if self.write_batch_metrics:
            if self.visdom:
                self.batch_log_dir = os.path.join(self.log_dir, 'epoch/')
                batch_params = self.visdom_params if self.visdom_params is not None else VisdomParams()
                batch_params.ENV = batch_params.ENV + '-batch'
                self.batch_writer = self.get_writer(self.batch_log_dir, visdom=self.visdom, visdom_params=batch_params)
            else:
                self.batch_log_dir = os.path.join(self.log_dir, 'epoch-' + str(state[torchbearer.EPOCH]))
                self.batch_writer = self.get_writer(self.batch_log_dir)

    def on_step_training(self, state):
        if self.write_batch_metrics and state[torchbearer.BATCH] % self.batch_step_size == 0:
            if self.visdom:
                self.batch_writer.add_text('batch', '
Epoch {} - Batch {}
'.format(state[torchbearer.EPOCH], state[torchbearer.BATCH])+self.table_formatter(str(state[torchbearer.METRICS])), 1)
            else:
                self.batch_writer.add_text('batch', self.table_formatter(str(state[torchbearer.METRICS])), state[torchbearer.BATCH])

    def on_end_epoch(self, state):
        if self.write_epoch_metrics:
            if self.visdom:
                self.writer.add_text('epoch', '
Epoch {}
'.format(state[torchbearer.EPOCH])+self.table_formatter(str(state[torchbearer.METRICS])), 1)
            else:
                self.writer.add_text('epoch', self.table_formatter(str(state[torchbearer.METRICS])), state[torchbearer.EPOCH])

    def on_end(self, state):
        super(TensorBoardText, self).on_end(state)
        if self.write_batch_metrics and self.visdom:
            self.close_writer(self.batch_log_dir)

class TensorBoardImages(AbstractTensorBoard):
    """The TensorBoardImages callback will write a selection of images from the validation pass to tensorboard using the
    TensorboardX library and torchvision.utils.make_grid (requires torchvision). Images are selected from the given key and saved to the given
    path. Full name of image sub directory will be model name + _ + comment.

    Example: ::

        >>> from torchbearer import Trial, state_key
        >>> from torchbearer.callbacks import TensorBoardImages
        >>> import datetime
        >>> current_time = datetime.now().strftime('%b%d_%H-%M-%S')
        >>> IMAGE_KEY = state_key('image_key')

        >>> # Callback that will log to tensorboard under "(model name)_(current time)"
        >>> tb = TensorBoardImages(comment=current_time, name='test_image', key=IMAGE_KEY)
        >>> # Trial that will run log to tensorboard images stored under IMAGE_KEY
        >>> t = Trial(None, callbacks=[tb], metrics=['acc', 'loss'])

    Args:
        log_dir (str): The tensorboard log path for output
        comment (str): Descriptive comment to append to path
        name (str): The name of the image
        key (StateKey): The key in state containing image data (tensor of size [c, w, h] or [b, c, w, h])
        write_each_epoch (bool): If True, write data on every epoch, else write only for the first epoch.
        num_images (int): The number of images to write
        nrow: See `torchvision.utils.make_grid <https://pytorch.org/docs/stable/torchvision/utils.html#torchvision.utils.make_grid>`_
        padding: See `torchvision.utils.make_grid <https://pytorch.org/docs/stable/torchvision/utils.html#torchvision.utils.make_grid>`_
        normalize: See `torchvision.utils.make_grid <https://pytorch.org/docs/stable/torchvision/utils.html#torchvision.utils.make_grid>`_
        norm_range: See `torchvision.utils.make_grid <https://pytorch.org/docs/stable/torchvision/utils.html#torchvision.utils.make_grid>`_
        scale_each: See `torchvision.utils.make_grid <https://pytorch.org/docs/stable/torchvision/utils.html#torchvision.utils.make_grid>`_
        pad_value: See `torchvision.utils.make_grid <https://pytorch.org/docs/stable/torchvision/utils.html#torchvision.utils.make_grid>`_
        visdom (bool): If true, log to visdom instead of tensorboard
        visdom_params (VisdomParams): Visdom parameter settings object, uses default if None

    State Requirements:
        - :attr:`torchbearer.state.EPOCH`: State should have the current epoch stored
        - `key`: State should have images stored under the given state key
    """

    def __init__(self, log_dir='./logs',
                 comment='torchbearer',
                 name='Image',
                 key=torchbearer.Y_PRED,
                 write_each_epoch=True,
                 num_images=16,
                 nrow=8,
                 padding=2,
                 normalize=False,
                 norm_range=None,
                 scale_each=False,
                 pad_value=0,
                 visdom=False,
                 visdom_params=None):
        super(TensorBoardImages, self).__init__(log_dir, comment, visdom=visdom, visdom_params=visdom_params)
        self.name = name
        self.key = key
        self.write_each_epoch = write_each_epoch
        self.num_images = num_images
        self.nrow = nrow
        self.padding = padding
        self.normalize = normalize
        self.norm_range = norm_range
        self.scale_each = scale_each
        self.pad_value = pad_value

        self._data = None
        self.done = False

    def on_step_validation(self, state):
        if not self.done:
            import torchvision.utils as utils
            data = state[self.key].clone()

            if len(data.size()) == 3:
                data = data.unsqueeze(1)

            if self._data is None:
                remaining = self.num_images if self.num_images < data.size(0) else data.size(0)

                self._data = data[:remaining].to('cpu')
            else:
                remaining = self.num_images - self._data.size(0)

                if remaining > data.size(0):
                    remaining = data.size(0)

                self._data = torch.cat((self._data, data[:remaining].to('cpu')), dim=0)

            if self._data.size(0) >= self.num_images:
                image = utils.make_grid(
                    self._data,
                    nrow=self.nrow,
                    padding=self.padding,
                    normalize=self.normalize,
                    range=self.norm_range,
                    scale_each=self.scale_each,
                    pad_value=self.pad_value
                )
                if self.visdom:
                    name = self.name + str(state[torchbearer.EPOCH])
                else:
                    name = self.name
                self.writer.add_image(name, image, state[torchbearer.EPOCH])
                self.done = True
                self._data = None

    def on_end_epoch(self, state):
        if self.write_each_epoch:
            self.done = False

class TensorBoardProjector(AbstractTensorBoard):
    """The TensorBoardProjector callback is used to write images from the validation pass to Tensorboard using the
    TensorboardX library. Images are written to the given directory and, if required, so are associated features.

    Args:
        log_dir (str): The tensorboard log path for output
        comment (str): Descriptive comment to append to path
        num_images (int): The number of images to write
        avg_pool_size (int): Size of the average pool to perform on the image. This is recommended to reduce the overall
            image sizes and improve latency
        avg_data_channels (bool): If True, the image data will be averaged in the channel dimension
        write_data (bool): If True, the raw data will be written as an embedding
        write_features (bool): If True, the image features will be written as an embedding
        features_key (StateKey): The key in state to use for the embedding. Typically model output but can be used to show
            features from any layer of the model.

    State Requirements:
        - :attr:`torchbearer.state.EPOCH`: State should have the current epoch stored
        - :attr:`torchbearer.state.X`: State should have the current data stored
        - :attr:`torchbearer.state.Y_TRUE`: State should have the current targets stored
    """

    def __init__(self, log_dir='./logs',
                 comment='torchbearer',
                 num_images=100,
                 avg_pool_size=1,
                 avg_data_channels=True,
                 write_data=True,
                 write_features=True,
                 features_key=torchbearer.Y_PRED):
        super(TensorBoardProjector, self).__init__(log_dir, comment)
        self.num_images = num_images
        self.avg_pool_size = avg_pool_size
        self.avg_data_channels = avg_data_channels
        self.write_data = write_data
        self.write_features = write_features
        self.features_key = features_key
        self.done = False
        self._images = None
        self._labels = None
        self._features = None
        self._data = None

    def on_step_validation(self, state):
        if not self.done:
            x = state[torchbearer.X].data.clone()

            if len(x.size()) == 3:
                x = x.unsqueeze(1)

            x = F.avg_pool2d(x, self.avg_pool_size).data

            data = None

            if state[torchbearer.EPOCH] == 0 and self.write_data:
                if self.avg_data_channels:
                    data = torch.mean(x, 1)
                else:
                    data = x

                data = data.view(data.size(0), -1)

            feature = None

            if self.write_features:
                feature = state[self.features_key].data.clone()
                feature = feature.view(feature.size(0), -1)

            label = state[torchbearer.Y_TRUE].data.clone()

            if state[torchbearer.BATCH] == 0:
                remaining = self.num_images if self.num_images  label.size(0):
                    remaining = label.size(0)

                self._images = torch.cat((self._images, x[:remaining].to('cpu')), dim=0)
                self._labels = torch.cat((self._labels, label[:remaining].to('cpu')), dim=0)

                if data is not None:
                    self._data = torch.cat((self._data, data[:remaining].to('cpu')), dim=0)

                if feature is not None:
                    self._features = torch.cat((self._features, feature[:remaining].to('cpu')), dim=0)

            if self._labels.size(0) >= self.num_images:
                if state[torchbearer.EPOCH] == 0 and self.write_data:
                    self.writer.add_embedding(self._data, metadata=self._labels, label_img=self._images, tag='data',
                                              global_step=-1)
                if self.write_features:
                    self.writer.add_embedding(self._features, metadata=self._labels, label_img=self._images,
                                              tag='features', global_step=state[torchbearer.EPOCH])
                self.done = True

    def on_end_epoch(self, state):
        if self.write_features:
            self.done = False


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def maxPathSum(self, root) -> int:

        ans = -int(1e9)

        def dfs(u):
            if u == None:
                return 0
            lf = dfs(u.left)
            rg = dfs(u.right)
            nonlocal ans
            ans = max(ans,max(0, lf) + max(0, rg) + u.val)
            return max(0, lf, rg) + u.val

        dfs(root)
        return ans


#############################################################
# Author: Weiming Hu <weiminghu@ucsd.edu>                   #
#                                                           #
#         Center for Western Weather and Water Extremes     #
#         Scripps Institution of Oceanography               #
#         UC San Diego                                      #
#                                                           #
#         https://weiming-hu.github.io/                     #
#         https://cw3e.ucsd.edu/                            #
#                                                           #
# Date of Creation: 2022/02/22                              #
#############################################################
#
# This script implements the early stopping criteria.
#

import numpy as np
import torch.nn as nn

class EarlyStopping:
    """
    This class determines whether the training process should
    be early stopped based on current improvements.
    """

    def __init__(self, patience=None, verbose=True, delta=0.0):
        """
        Args:
            patience (int, optional): The number of epochs to wait before
            termination if no improvements are detected. `None` to turn it off.
            Defaults to None.
            verbose (bool, optional): Whether to be verbose. Defaults to False.
            delta (float, optional): Minimum change in the loss to qualify
            as an improvement. An improvement is detected when
            `current_loss < recorded_best_loss + delta` is satisfied. Defaults to 0.
        """
        self.patience = np.Inf if patience is None else patience
        self.verbose = verbose
        self.delta = delta

        self.counter = 0
        self.best_loss = np.Inf
        self.early_stop = False

    def __call__(self, loss):

        if loss < self.best_loss + self.delta:
            # An improvement is detected
            self.counter = 0
            self.best_loss = loss

        else:
            # No improvement is detected
            self.counter += 1

            if self.counter >= self.patience:
                self.early_stop = True

                if self.verbose:
                    msg = ('Maximum patience reached with no improvements after {} '
                           'epochs at best loss {}. Engage early stopping.'.format(
                               self.patience, self.best_loss))

                    print(msg)

        return self.early_stop


import os
import sys
# magic spell to include files from outer dir
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from lisp import Lisp

getter = """
LDF  15   ; load main. This program creates simple map: [[11,12,13,14], [21,22,23,24]] an then access some element of this array [] - have 0 in the end.
AP   0
RTN
LD 0 0 ;:GETTER PUT
LD 0 1
TSEL 6 13;FOR LOOP INITIAL CONDITION
CDR
LD 0 1
LDC 1
SUB
ST 0 1
LD 0 1
TSEL 6 13
CAR
RTN
LDC  11;:MAIN
LDC  12
LDC  13
LDC  14
LDC  0
CONS
CONS
CONS
CONS
LDC  21
LDC  22
LDC  23
LDC  24
LDC  0
CONS
CONS
CONS
CONS
LDC  0
CONS
CONS
LDC 1
LDF 3;GETTER
AP 2
LDC 2
LDF 3;GETTER
AP 2
RTN
"""

def main():
	lisp = Lisp()
	lisp.load_program(getter)
	if len(sys.argv) > 1:
		lisp.trace()
	else:
		lisp.run()

	# check last element
	result = lisp.vm.data_stack[-1]
	assert result.n == 23

if __name__ == '__main__':
	main()


"""Game of Life algorithm
"""
import logging
from collections import defaultdict
from .gameboard import GameBoard

log = logging.getLogger(__name__)

class GameOfLife:
    def __init__(self, initial_gameboard: GameBoard):
        self.gameboard = initial_gameboard

    def simulate(self):
        """runs the game of life for 1 cycle
        It is a 2 step process
        1) count the number of living neighbours for a cell
        2) using above, apply rules to figure out which cells will live in next generation
        """
        init_state = self.gameboard

        # step 1: count the number of living neighbours for a cell
        count_alive_neighbours = self.count_alive_neighbours(init_state)

        # step 2: now we apply the rules to get the next gameboard
        next_state = self.apply_rules(init_state, count_alive_neighbours)

        self.gameboard = next_state
        return self

    def count_alive_neighbours(self, state: GameBoard) -> dict:
        """Returns a dict which contains the count of number of living neighbours of a cell

        dict[(row, col)] is the count of neighbours for cell(row, col)
        """
        count_neighbours = defaultdict(int)
        for cell in state.cells:
            # explore the 8 directions
            for offset_row in [-1, 0, 1]:
                for offset_col in [-1, 0, 1]:
                    if offset_row == 0 and offset_col == 0:
                        continue
                    row = cell[0] + offset_row
                    col = cell[1] + offset_col
                    if state.is_valid_cell(row, col):
                        count_neighbours[(row, col)] += 1
        return count_neighbours

    def apply_rules(self, state: GameBoard, count_alive_neighbours: dict):
        """Apply the rules of the game and generate the new gameboard"""
        next_state = state.empty_board()
        for (row, col), count in count_alive_neighbours.items():
            if state.is_alive(row, col):
                if count == 2 or count == 3:
                    log.debug("(%s, %s) continues living", row, col)
                    next_state.add(row, col)
                else:
                    log.debug("(%s, %s) dies", row, col)
            else:
                if count == 3:
                    log.debug("(%s, %s) is born", row, col)
                    next_state.add(row, col)
        return next_state

    def simulate_n(self, num_gens: int = 1):
        """Simulate the game for given number of iterations"""
        for i in range(num_gens):
            self.simulate()
            log.info("Generation: %s", 1 + i)
            self.gameboard.display()

        return self

    def display(self):
        self.gameboard.display()

    def print_board(self):
        self.gameboard.print_board()


class ListNode:
    def __init__(self,x):
        self.val = x
        self.next = None

class Linklist:
    def reverseLink(self,head):
        prev = None
        while head:
            curr = head
            head = head.next
            curr.next = prev
            prev = curr
        return prev

    def cycleList(self,head):
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

    def middleNode(self,head):
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next
        return slow

    def findNthFromEnd(self,head, n):
        slow = fast = head
        for _ in range(n):
            fast = fast.next
        while fast.next:
            slow = slow.next
            fast = fast.next
        slow.next = slow.next.next
        return head

    def isPalindrom(self,head):
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next

        prev = None
        while slow:
            curr = slow
            slow = slow.next
            curr.next = prev
            prev = curr

        while prev or head:
            if prev.val != head.val:
                return False
            prev = prev.next
            head = head.next
        return True

    def mergeSortList(self, l1, l2):
        dummy = curr = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                dummy.next = l1
                l1 = l1.next
            else:
                dummy.next = l2
                l2 = l2.next
        dummy.next = l1 or l2
        return curr

    def deletenode(self,node):
        node.val = node.next.val
        node.next = node.next.next

    def deleteval(self,head,val):
        new_head = ListNode(0)
        new_head.next = head
        slow, fast = new_head, head
        while fast:
            if fast.val != val:
                slow.next.val = fast.val
                slow = slow.next
            fast = fast.next
        slow.next = None
        return new_head.next