import re

def longest(alts):
    l = 0
    val = ''
    for a in alts:
        if len(a) > l:
            l = len(a)
            val = a
    return val

s = input().strip()[1:-1]
orig_s = s

for _ in range(1000000):
    m = re.search("\([NEWS|]*\)", s)
    if m is None:
        break
    alts = m[0][1:-1].split('|')
    start, end = m.span()
    s = s[:start] + longest(alts) + s[end:]

for _ in range(1000000):
    m = re.search("NS|SN|EW|WE", s)
    if m is None:
        break
    start, end = m.span()
    s = s[:start] + s[end:]

print(len(s))

grid = []
for _ in range(50):
    grid.append(['#'] * 50)
print(s)

def populategrid(i, j, s):
    print(i,j)
    if grid[i][j] != '#':
        return
    grid[i][j] = '.'
    if s == '':
        return
    if s[0] == 'N':
        grid[i-1][j] = '-'
        populategrid(i-2, j, s[1:])
    if s[0] == 'S':
        grid[i+1][j] = '-'
        populategrid(i+2, j, s[1:])
    if s[0] == 'W':
        grid[i][j-1] = '|'
        populategrid(i, j-2, s[1:])
    if s[0] == 'E':
        grid[i][j+1] = '|'
        populategrid(i, j+2, s[1:])

populategrid(25, 25, s)
grid[25][25] = 'S'
for line in grid:
    print(''.join(line))


def insertionSort(items: list):

    for numSortedItems in range(1, len(items)):

        temp = items[numSortedItems]
        loc = numSortedItems - 1

        while loc >= 0 and items[loc] > temp:
            items[loc + 1] = items[loc]
            loc -= 1

        items[loc + 1] = temp

items = [3, 2, 6, 4, 1]
insertionSort(items)
print(items)


"Death Note"
import glob
import itertools
import os

import nltk
from nltk.tokenize import TweetTokenizer
import webvtt

def get_words():
    sub_files = glob.glob(__path__[0] + "/subs/*.vtt")
    words = []
    for f in sub_files:
        words.extend(get_words_from_subtitles(f))
    return words

def get_words_from_subtitles(file, buffer_size=6):
    "Get the words from the whole serie"
    tknzr = TweetTokenizer()
    file_words = []
    previous = []
    for caption in webvtt.read(file):
        text = caption.text
        if text in previous:
            continue
        previous.append(text)
        if len(previous) > buffer_size + 1:
            del previous[0]
        file_words.extend(tknzr.tokenize(text))
    return file_words


#!/usr/bin/env python
# coding: utf-8

# In[89]:

import os
import operator
def size(file1,file2):
    dict_m = {}
    with open (file1) as f, open (file2) as f2:
        lines = f.readlines()
        size = len(lines)
        lines2 = f.readlines()
        size2 = len(lines2)
        dict_m[file1]=size
        dict_m[file2]=size2
        sorted_values = sorted(dict_m.values())
        sorted_dict = {}
        for i in sorted_values:
            for k in dict_m.keys():
                if dict_m[k] == i:
                    sorted_dict[k] = dict_m[k]
        return(sorted_dict)

# In[107]:

def new_file(main_file):
    with open(main_file, 'w',encoding='utf-8') as file_main:
        dict_main = size('1.txt','2.txt')
        keys = list(dict_main.keys())
        values = list(dict_main.values())
        print(keys)
        file_main.write(f'{keys[0]}\n')
        file_main.write(f'{values[0]}\n')
        with open (f'{keys[0]}') as first, open (f'{keys[1]}') as second:
            f_1 = first.read()
            f_2 = second.read()
            file_main.write(f'{f_1}\n')
            file_main.write(f'{keys[1]}\n')
            file_main.write(f'{values[1]}\n')
            file_main.write(f'{f_2}\n')
size('1.txt','2.txt')
new_file('New_File.txt')

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:


def checkNum(*args):
    result = list(args)
    for i in range(len(args)):
        if type(args[i]) == str:
            if args[i].isdecimal():
                result[i] = int(args[i])
            elif args[i].replace('.', '').isnumeric() and args[i].find('.') != -1:
                result[i] = float(args[i])
            else:
                return []
        elif type(result[i]) == int or type(result[i]) == float:
            result[i] = result[i]
    return result

def plus(num1, num2):
    nums = checkNum(num1, num2)
    if nums:
        return nums[0] + nums[1]
    return "잘못된 입력입니다."

def minus(num1, num2):
    nums = checkNum(num1, num2)
    if nums:
        return nums[0] - nums[1]
    return "잘못된 입력입니다."

def product(num1, num2):
    nums = checkNum(num1, num2)
    if nums:
        return nums[0] * nums[1]
    return "잘못된 입력입니다."

def division(num1, num2):
    nums = checkNum(num1, num2)
    if nums:
        if nums[1] == 0:
            return "0으로는 나눌 수 없습니다."
        return nums[0] / nums[1]
    return "잘못된 입력입니다."

def remainder(num1, num2):
    nums = checkNum(num1, num2)
    if nums:
        if nums[1] == 0:
            return "0으로는 나눌 수 없습니다."
        return nums[0] % nums[1]
    return "잘못된 입력입니다."

def negation(num):
    nums = checkNum(num)
    if nums:
        return -nums[0]
    return "잘못된 입력입니다."

def power(num1, num2):
    nums = checkNum(num1, num2)
    if nums:
        return nums[0] ** nums[1]
    return "잘못된 입력입니다."

print(plus(1, "2"))
print(minus("1", 2))
print(product(2, 3))
print(division(3, 2))
print(remainder(6, 4))
print(negation(9))
print(power(2, 3))


# -*- coding: utf-8 -*-
"""
Created on Mon Jan  6 09:57:48 2020

@author: sattwik
"""

'''
QUESTION:
    Given a table of 7 Players with attributes such as: Position and Rating in terms of Execution, Throwing, Jumping and Defence

    Furthermore, the given contraints are:
    • At least 2 players must be able to play Guard, at least 2 must be able to play Forward
    and at least one must be suitable for Center.
    • For every skill execution, throwing and jumping the chosen players must have an average
    score of at least 2.
    • Connor and Francis don’t like each other and hence must not be selected simultaneously.
    • Ethan only plays well if he can play together with his buddys Andy and Donald. Thus,
    if he is selected, the others must be selected, too.
    • Brayden and Connor are key players. Hence, at least one of them must be part of the
    team.
 OBJECTIVE: To select a team with 5 players that has maximum defensive rating
'''

from gurobipy import *

model = Model("Basketball_team")

players_data = {'Player':['Andy', 'Brayden', 'Connor', 'Donald', 'Ethan', 'Francis', 'Greg'],
        'Position':[['G'], ['C'], ['F', 'G'], ['C', 'F'], ['F', 'G'], ['C', 'F'], ['F', 'G']],
        'Execution':[1, 2, 2, 3, 3, 3, 3 ],
        'Throwing':[3, 1, 3, 3, 3, 1, 2 ],
        'Jumping':[3, 3, 2, 3, 1, 2, 2],
        'Defence':[1, 2, 2, 3, 3, 3, 2]}

index={}
n=0
for i in players_data['Player']:
    index[i]=n
    n=n+1

'''
VARIABLE 1:
    variable x[i] tells whether player[i] is selected or not
'''

x={}
#x = model.addVars(players_data['Player'], obj=players_data['Defence'], vtype='b', name="assign")
for i in range(len(players_data['Player'])):
    x[i]=model.addVar(vtype='b', obj=players_data['Defence'][i])

'''
CONSTRAINT 1: TEAM_CAP
    number of players selected ==5
'''

model.addConstr(quicksum(x[i] for i in range(len(players_data['Player'])))==5)

'''
CONSTRAINT 2:
    At least 2 players must be able to play Guard, at least 2 must be able to play Forward
    and at least one must be suitable for Center.
'''

model.addConstr(quicksum(x[i] for i in range(len(players_data['Player'])) if 'G' in players_data['Position'][i] )>=2)

'''
CONSTRAINT 3:
    For every skill execution, throwing and jumping the chosen players must have an average
    score of at least 2.
'''

model.addConstr(quicksum(players_data['Throwing'][i]*x[i] for i in range(len(players_data['Player'])))>=10)

model.addConstr(quicksum(players_data['Jumping'][i]*x[i] for i in range(len(players_data['Player'])))>=10)

'''
CONSTRAINT 4:
    Connor and Francis don’t like each other and hence must not be selected simultaneously.
'''

model.addConstr(quicksum(x[i] for i in range(len(players_data['Player'])) if players_data['Player']=='Connor' or players_data['Player']=='Francis') <=1)

'''
CONSTRAINT 5:
    Ethan only plays well if he can play together with his buddys Andy and Donald. Thus,
    if he is selected, the others must be selected, too.
'''
#e=index['Ethan']
#a=index['Andy']
#d=index['Donald']

model.addConstr(x[index['Andy']]+x[index['Donald']]>= 1+ x[index['Ethan']])

'''
CONSTRAINT 6:
    Brayden and Connor are key players. Hence, at least one of them must be part of the
    team.
'''

model.addConstr(x[index['Brayden']]+x[index['Connor']]>= 1)

#INVOKING THE SOLVER TO CARRY OUT THE OPTIMIZATION:

model.ModelSense = -1 #for maximizing
model.optimize()

#PRINTING THE RESULTS:

total_throw=0
total_jump=0
total_def=0
if model.status == GRB.OPTIMAL:
    print("\nRESULT:\nPlayers selected in the team are:")
    for i in range(len(players_data['Player'])):
        if x[i].x==1:
            print(f"{players_data['Player'][i]}")
            total_throw = total_throw + players_data['Throwing'][i]
            total_jump = total_jump + players_data['Jumping'][i]
            total_def = total_def + players_data['Defence'][i]
    print(f"\nAverage Throwing points for the selected team = {total_throw/5}")
    print(f"\nAverage Jumping points for the selected team = {total_jump/5}")
    print(f"\nTotal Defence points for the selected team = {total_def}")
else:
    print("\n\nRESULT:\nNo solution could be obtained for given preferences")


from django.shortcuts import render

from pre_login.forms import LoginForm
from pre_login.forms import RegistrationForm
from pre_login.models import Personal_Details
from django.http import HttpResponseRedirect
from django.utils.datastructures import MultiValueDictKeyError

def student(request):
    information = Personal_Details.objects.all()
    # print(information.get(Student="True"))
    info = Personal_Details.objects.get(Email=request.session['Email'])
    details = {"username" : info.username, "Age" : info.Age, "City":
    info.City, "State": info.State, "Country" : info.Country, "Occupation" : info.Occupation}
    return render(request,'quizes/student.html', details)

def project_m(request):
    info = Personal_Details.objects.get(Email=request.session['Email'])
    details = {"username" : info.username, "Age" : info.Age, "City":
    info.City, "State": info.State, "Country" : info.Country, "Occupation" : info.Occupation}
    return render(request,'quizes/project_m.html', details)

def student_details(request):
    information = Personal_Details.objects.all().filter(Student="True")
    print(information)
    diction = {'username' : []}
    for user in information:
        diction.get('username').append(user.username)
        print(diction)

    return render(request, 'quizes/list_stu.html', diction)


from tkinter import *
from tkinter import ttk
import tkinter.messagebox
from docx import Document
from docx.oxml.ns import qn  # 设置字体
from docx.shared import Pt  # 设置字体大小
from docx.enum.text import WD_ALIGN_PARAGRAPH  # 设置对象居中、对齐等
import math
from ttkbootstrap import Style

LOG_LINE_NUM = 0
style = Style(theme='minty')

class MY_GUI():
    def __init__(self,init_window_name):
        self.init_window_name = init_window_name

    #设置窗口
    def set_init_window(self):
        self.init_window_name.title("悬挑板计算小工具_v1.0")           #窗口名
        #self.init_window_name.geometry('320x160+10+10')                         #290 160为窗口大小，+10 +10 定义窗口弹出时的默认展示位置
        self.init_window_name.geometry('1068x681+10+10')
        #self.init_window_name["bg"] = "pink"                                    #窗口背景色，其他背景色见：blog.csdn.net/chl0000/article/details/7657887
        #self.init_window_name.attributes("-alpha",0.9)                          #虚化，值越小虚化程度越高
        #标签
        self.inputlabel = Label(self.init_window_name, text="信息输入：", font=("宋体", 12, "bold"))
        self.inputlabel.grid(row=0, column=0, sticky='e')
        self.namelabel = Label(self.init_window_name, text="构件名称：")
        self.namelabel.grid(row=1, column=1, sticky='e')
        self.hlabel = Label(self.init_window_name, text="板厚h（mm）：")
        self.hlabel.grid(row=2, column=1, sticky='e')
        self.llabel = Label(self.init_window_name, text="挑出长度l（mm）：")
        self.llabel.grid(row=3, column=1, sticky='e')
        self.blabel = Label(self.init_window_name, text="计算宽度b（mm）：")
        self.blabel.grid(row=4, column=1, sticky='e')
        self.dllabel = Label(self.init_window_name, text="恒载dl（kN/m\u00b2）：")
        self.dllabel.grid(row=5, column=1, sticky='e')
        self.lllabel = Label(self.init_window_name, text="活载ll（kN/m\u00b2）：")
        self.lllabel.grid(row=6, column=1, sticky='e')
        self.bllabel = Label(self.init_window_name, text="边缘翻边线荷载bl(kN/m)：")
        self.bllabel.grid(row=7, column=1, sticky='e')
        self.cglabel = Label(self.init_window_name, text="混凝土强度等级c_g：")
        self.cglabel.grid(row=8, column=1, sticky='e')
        self.fclabel = Label(self.init_window_name, text="fc（N/mm\u00b2）：")
        self.fclabel.grid(row=9, column=1, sticky='e')
        self.ftlabel = Label(self.init_window_name, text="ft（N/mm\u00b2）：")
        self.ftlabel.grid(row=10, column=1, sticky='e')
        self.sglabel = Label(self.init_window_name, text="钢筋强度等级s_g：")
        self.sglabel.grid(row=11, column=1, sticky='e')
        self.fylabel = Label(self.init_window_name, text="fy（N/mm\u00b2）：")
        self.fylabel.grid(row=12, column=1, sticky='e')
        self.pminlabel = Label(self.init_window_name, text="最小配筋率：")
        self.pminlabel.grid(row=13, column=1, sticky='e')
        self.aslabel = Label(self.init_window_name, text="纵筋合力点至近边距离（mm）：")
        self.aslabel.grid(row=14, column=1, sticky='e')
        self.y0label = Label(self.init_window_name, text="重要性系数：")
        self.y0label.grid(row=15, column=1, sticky='e')
        self.bblabel = Label(self.init_window_name, text="是否计算内部梁：")
        self.bblabel.grid(row=16, column=1, sticky='e')
        self.Lblabel = Label(self.init_window_name, text="梁宽（mm）：")
        self.Lblabel.grid(row=17, column=1, sticky='e')
        self.Lhlabel = Label(self.init_window_name, text="梁高（mm）：")
        self.Lhlabel.grid(row=18, column=1, sticky='e')
        self.LLlabel = Label(self.init_window_name, text="梁长（mm）：")
        self.LLlabel.grid(row=19, column=1, sticky='e')
        self.nameText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.nameText.grid(row=1, column=2)
        self.nameText.insert(0,'雨棚1')
        self.hText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.hText.grid(row=2, column=2)
        self.hText.insert(0,'120')
        self.lText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.lText.grid(row=3, column=2)
        self.lText.insert(0,'1200')
        self.bText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.bText.grid(row=4, column=2)
        self.bText.insert(0,'1000')
        self.dlText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.dlText.grid(row=5, column=2)
        self.dlText.insert(0,'1.5')
        self.llText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.llText.grid(row=6, column=2)
        self.llText.insert(0,'2')
        self.blText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.blText.grid(row=7, column=2)
        self.blText.insert(0,'1')
        self.cgText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.cgText.grid(row=8, column=2)
        self.cgText.insert(0,'C30')
        self.fcText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.fcText.grid(row=9, column=2)
        self.fcText.insert(0,'14.3')
        self.ftText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.ftText.grid(row=10, column=2)
        self.ftText.insert(0,'1.43')
        self.sgText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.sgText.grid(row=11, column=2)
        self.sgText.insert(0,'HRB400')
        self.fyText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.fyText.grid(row=12, column=2)
        self.fyText.insert(0,'360')
        self.pminText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.pminText.grid(row=13, column=2)
        self.pminText.insert(0,'0.002')
        self.asText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.asText.grid(row=14, column=2)
        self.asText.insert(0,'20')
        self.y0Text = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.y0Text.grid(row=15, column=2)
        self.y0Text.insert(0,'1.0')

        self.bbselection = ttk.Combobox (self.init_window_name,  width=17, textvariable='')
        self.bbselection["value"] = ("是", "否")
        self.bbselection.grid(row=16, column=2)
        self.bbselection.current(0)

        self.LbText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.LbText.grid(row=17, column=2)
        self.LbText.insert(0,'200')
        self.LhText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.LhText.grid(row=18, column=2)
        self.LhText.insert(0,'500')
        self.LLText = Entry(self.init_window_name, width=20,textvariable="")  #原始数据录入框
        self.LLText.grid(row=19, column=2)
        self.LLText.insert(0,'2400')

        self.outputlabel = Label(self.init_window_name, text="结果输出：", font=("宋体", 12, "bold"))
        self.outputlabel.grid(row=0, column=6, sticky='e')
        self.Aslabel = Label(self.init_window_name, text="板受力筋计算面积As(mm\u00b2)：")
        self.Aslabel.grid(row=1, column=7, sticky='e')
        self.AsText = Entry(self.init_window_name, width=20,textvariable="")
        self.AsText.grid(row=1, column=8)
        self.AsText.insert(0,'250')
        self.Aspjlabel = Label(self.init_window_name, text="板受力筋配筋（eg:E8@200)：")
        self.Aspjlabel.grid(row=2, column=7, sticky='e')
        self.AspjText = Entry(self.init_window_name, width=20,textvariable="")
        self.AspjText.grid(row=2, column=8)
        self.Asmjlabel = Label(self.init_window_name, text="实际面积As(mm\u00b2)：")
        self.Asmjlabel.grid(row=3, column=7, sticky='e')
        self.AsmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.AsmjText.grid(row=3, column=8)

        self.LAsvslabel = Label(self.init_window_name, text="梁箍筋计算面积（mm\u00b2/100mm）：")
        self.LAsvslabel.grid(row=5, column=7, sticky='e')
        self.LAsvsText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAsvsText.grid(row=5, column=8)
        self.LAsvsText.insert(0,'250')
        self.LAsvspjlabel = Label(self.init_window_name, text="梁箍筋实际配筋（eg:E8@200）：")
        self.LAsvspjlabel.grid(row=6, column=7, sticky='e')
        self.LAsvspjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAsvspjText.grid(row=6, column=8)
        self.Lasvsmjlabel = Label(self.init_window_name, text="梁箍筋实际面积Asv/s(mm\u00b2/100mm)：")
        self.Lasvsmjlabel.grid(row=7, column=7, sticky='e')
        self.LasvsmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LasvsmjText.grid(row=7, column=8)

        self.AsLlabel = Label(self.init_window_name, text="梁上下纵筋计算面积As=As\'(mm\u00b2)：")
        self.AsLlabel.grid(row=9, column=7, sticky='e')
        self.AsLText = Entry(self.init_window_name, width=20,textvariable="")
        self.AsLText.grid(row=9, column=8)
        self.AsLText.insert(0,'400')
        self.LAspjlabel = Label(self.init_window_name, text="梁上下纵筋配筋（eg:2E16)：")
        self.LAspjlabel.grid(row=10, column=7, sticky='e')
        self.LAspjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAspjText.grid(row=10, column=8)
        self.LAsmjlabel = Label(self.init_window_name, text="梁上下纵筋实际面积As(mm\u00b2)：")
        self.LAsmjlabel.grid(row=11, column=7, sticky='e')
        self.LAsmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAsmjText.grid(row=11, column=8)

        self.Astllabel = Label(self.init_window_name, text="梁抗扭纵筋计算面积Astl(mm\u00b2)：")
        self.Astllabel.grid(row=13, column=7, sticky='e')
        self.AstlText = Entry(self.init_window_name, width=20,textvariable="")
        self.AstlText.grid(row=13, column=8)
        self.AstlText.insert(0,'400')
        self.LAstlpjlabel = Label(self.init_window_name, text="梁抗扭纵筋配筋（eg:2E16)：")
        self.LAstlpjlabel.grid(row=14, column=7, sticky='e')
        self.LAstlpjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAstlpjText.grid(row=14, column=8)
        self.LAstlmjlabel = Label(self.init_window_name, text="梁抗扭纵筋实际面积As(mm\u00b2)：")
        self.LAstlmjlabel.grid(row=15, column=7, sticky='e')
        self.LAstlmjText = Entry(self.init_window_name, width=20,textvariable="")
        self.LAstlmjText.grid(row=15, column=8)

        #按钮
        self.cal = Button(self.init_window_name, text="计算", bg="lightblue", width=10,command=lambda:self.calculation(self.hText.get(),self.lText.get(),self.bText.get(),self.dlText.get(),self.llText.get(),self.blText.get(),self.fcText.get(),self.ftText.get(),self.fyText.get(),self.pminText.get(),self.asText.get(),self.y0Text.get(),self.bbselection.get(),self.LbText.get(),self.LhText.get(),self.LLText.get()))  # 调用内部方法  加()为直接调用
        self.cal.grid(row=21, column=2)
        self.docx = Button(self.init_window_name, text="生成计算书", bg="lightblue", width=10,command=lambda:self.txt(self.nameText.get(),self.hText.get(),self.lText.get(),self.bText.get(),self.dlText.get(),self.llText.get(),self.blText.get(),self.cgText.get(),self.fcText.get(),self.ftText.get(),self.sgText.get(),self.fyText.get(),self.pminText.get(),self.asText.get(),self.y0Text.get(),self.bbselection.get(),self.LbText.get(),self.LhText.get(),self.LLText.get()))  # 调用内部方法  加()为直接调用
        self.docx.grid(row=21, column=8)

    def calculation(self,h,l,b,dl,ll,bl,fc,ft,fy,pmin,a_s,y0,bool_beam,Lb,Lh,LL):
        h = float(h)  # 板厚 mm
        l = float(l)  # 挑出长度  mm
        b = float(b)  # 宽度  mm
        dl = float(dl)  # 恒载 kN/m\u00b2
        ll = float(ll)  # 活载  kN/m\u00b2
        bl = float(bl)  # 边缘翻边线荷载  kN/m\u00b2
        fc = float(fc)  # N/mm\u00b2
        ft = float(ft)  # N/mm\u00b2
        fy = float(fy)  # N/mm\u00b2
        pmin = float(pmin)  # 最小配筋率
        a_s = float(a_s)  # 纵筋合力点至近边距离
        y0 = float(y0)  # 重要性系数
        Lb = float(Lb)  # 梁宽mm  梁即使不算，也保留勿删
        Lh = float(Lh)  # 梁高mm
        LL = float(LL)  # 梁长mm

        # 板荷载计算
        Md = 0.5 * (25 * h / 1000 + dl) * l * l / 1000000
        Vd = (h / 1000 * 25 + dl) * l / 1000
        Ml = 0.5 * (25 * h / 1000 + ll) * l * l / 1000000
        Vl = (h / 1000 * 25 + ll) * l / 1000
        Mb = bl * l / 1000
        Vb = bl
        M = 1.3 * (Md + Mb) + 1.5 * Ml
        V = 1.3 * (Vd + Vb) + 1.5 * Vl
        # 内梁荷载计算
        Lx = V
        LTm = M + Lx * Lb / 2 / 1000
        Tmax = LTm * LL / 2 / 1000
        Mmax = 1 / 8 * Lx * LL * LL / 1000000
        Vmax = 0.5 * Lx * LL / 1000
        # 正截面受弯计算
        h0 = h - a_s
        xb = 0.518
        as1 = y0 * M * 1000000 / (fc * 1000 * h0 * h0)
        x1 = 1 - math.sqrt(1 - 2 * as1)  # 计算相对受压区高度
        if x1 > xb:
            tkinter.messagebox.showinfo('警告','受压区高度' + str(x1) + '>' + str(xb) + ';不满足要求')
        else:
            pass
        As = fc * b * h0 * x1 / fy
        p = As / (b * h)
        Asmin = pmin * b * h
        if As <Asmin:
            As = Asmin
        else:
            pass
        self.AsText.delete(0,END)
        self.AsText.insert(0,int(As))

        # 梁计算参数
        ast = 35
        asb = 35
        Lh0 = Lh - asb
        Wt = Lb * Lb * (3 * Lh0 - Lb) / 6
        bcor = Lb - 50
        hcor = Lh - ast - asb
        Acor = bcor * hcor
        ucor = 2 * (bcor + hcor)

        if bool_beam == '是':  # 梁截面设计
            allow1 = 0.25 * 1 * fc
            allow2 = 0.2 * 1 * fc
            result1 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (0.8 * Lb * Lb * (3 * Lh - Lb) / 6)
            if Lh0 / Lb <= 4:  # 梁截面验算
                if result1 <= allow1:
                    result_jm = '梁截面满足要求'
                else:
                    tkinter.messagebox.showinfo('警告','梁截面不满足要求')
            elif 4 < Lh0 / Lb < 6:
                allow3 = allow1 * (6 - Lh0 / Lb) / 2 + allow2 * (Lh0 / Lb - 4)
                if result1 <= allow3:
                    result_jm = '梁截面满足要求'
                else:
                    tkinter.messagebox.showinfo('警告','梁截面不满足要求')
            else:
                tkinter.messagebox.showinfo('梁高宽比大于6，受扭构件的截面尺寸要求及扭曲截面承载力计算应符合专门规定。')
            result2 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (Lb * Lb * (3 * Lh - Lb) / 6)
            allow4 = 0.7 * ft

            if result2 < allow4: # 剪扭计算判定
                tkinter.messagebox.showinfo('满足要求，可不进行构件受减扭承载力计算，但需满足规范构造要求。')
            else:
                pass
# 正截面受弯计算
            x = 2 * ast
            AsL = (Mmax - 1 * fc * Lb * x * (Lh0 - x / 2)) / (fy * (Lh0 - ast))
            AsLmin = 0.002 * Lb * Lh
            if AsL < AsLmin:
                AsL = AsLmin
            else:
                pass
            self.AsLText.delete(0,END)
            self.AsLText.insert(0,int(AsL))
# 剪扭计算
            bt = 1.5 / (1 + 0.5 * Vmax * Wt / (Tmax * 1000 * Lb * Lh0))
            if bt< 0.5:
                bt = 0.5
            elif bt > 1:
                bt = 1
            else:
                pass
            Ast1_st = (Tmax * 1000000 - 0.35 * bt * ft * Wt) / (1.2 * math.sqrt(1.2) * fy * Acor)
            nAsv1_sv = (Vmax - 0.7 * (1.5 - bt) * ft * Lb * Lh0) / (1.25 * fy * Lh0)
            if nAsv1_sv < 0:
                nAsv1_sv = 0
            else:
                pass
            Asv_s = nAsv1_sv / 2 + Ast1_st
            psvmin = 0.28 * ft / fy
            Asvmin_s = psvmin * Lb / 2
            if Asv_s < Asvmin_s:
                Asv_s = Asvmin_s
            else:
                pass

            Astl = 1.2 * fy * ucor / fy * (Ast1_st)
            T_Vb = Tmax * 1000 / Vmax / Lb
            if T_Vb > 2:
                T_Vb = 2
            else:
                pass
            ptlmin = 0.6 * math.sqrt(Tmax * 1000 / (Vmax * Lb)) * ft / fy
            Atlmin = ptlmin * Lb * Lh
            if Astl < Atlmin:
                Astl = Atlmin
            else:
                pass

            self.LAsvsText.delete(0,END)
            self.LAsvsText.insert(0,int(Asv_s * 100))
            self.AstlText.delete(0,END)
            self.AstlText.insert(0,int(Astl))

        else:
            pass

    def txt(self,name,h,l,b,dl,ll,bl,concrete_g,fc,ft,steel_g,fy,pmin,a_s,y0,bool_beam,Lb,Lh,LL):
        # 板参数定义
        h = int(h)  # 板厚 mm
        l = int(l)  # 挑出长度  mm
        b = int(b)  # 宽度  mm
        dl = float(dl)  # 恒载 kN/m\u00b2
        ll = float(ll)  # 活载  kN/m\u00b2
        bl = float(bl)  # 边缘翻边线荷载  kN/m\u00b2
        fc = float(fc)  # N/mm\u00b2
        ft = float(ft)  # N/mm\u00b2
        fy = float(fy)  # N/mm\u00b2
        pmin = float(pmin)  # 最小配筋率
        a_s = int(a_s)  # 纵筋合力点至近边距离
        y0 = float(y0)  # 重要性系数
        Lb = int(Lb)  # 梁宽mm  梁即使不算，也保留勿删
        Lh = int(Lh)  # 梁高mm
        LL = int(LL)  # 梁长mm

        # 板荷载计算
        Md = 0.5 * (25 * h / 1000 + dl) * l * l / 1000000
        Vd = (h / 1000 * 25 + dl) * l / 1000
        Ml = 0.5 * (25 * h / 1000 + ll) * l * l / 1000000
        Vl = (h / 1000 * 25 + ll) * l / 1000
        Mb = bl * l / 1000
        Vb = bl
        M = 1.3 * (Md + Mb) + 1.5 * Ml
        V = 1.3 * (Vd + Vb) + 1.5 * Vl
        # 内梁荷载计算
        Lx = V
        LTm = M + Lx * Lb / 2 / 1000
        Tmax = LTm * LL / 2 / 1000
        Mmax = 1 / 8 * Lx * LL * LL / 1000000
        Vmax = 0.5 * Lx * LL / 1000
        # 正截面受弯计算
        h0 = h - a_s
        xb = 0.518
        as1 = y0 * M * 1000000 / (fc * 1000 * h0 * h0)
        x1 = 1 - math.sqrt(1 - 2 * as1)  # 计算相对受压区高度
        As = fc * b * h0 * x1 / fy
        p = As / (b * h)
        Asmin = pmin * b * h
        # 梁计算参数
        ast = 35
        asb = 35
        Lh0 = Lh - asb
        Wt = Lb * Lb * (3 * Lh0 - Lb) / 6
        bcor = Lb - 50
        hcor = Lh - ast - asb
        Acor = bcor * hcor
        ucor = 2 * (bcor + hcor)

        if bool_beam == '是':  # 梁截面设计
            allow1 = 0.25 * 1 * fc
            allow2 = 0.2 * 1 * fc
            allow3 = allow1 * (6 - Lh0 / Lb) / 2 + allow2 * (Lh0 / Lb - 4)
            result1 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (0.8 * Lb * Lb * (3 * Lh - Lb) / 6)
            result2 = Vmax * 1000 / (Lb * Lh0) + Tmax * 1000000 / (Lb * Lb * (3 * Lh - Lb) / 6)
            allow4 = 0.7 * ft
            bt = 1.5 / (1 + 0.5 * Vmax * Wt / (Tmax * 1000 * Lb * Lh0))

            x = 2 * ast
            AsL = (Mmax - 1 * fc * Lb * x * (Lh0 - x / 2)) / (fy * (Lh0 - ast))
            AsLmin = 0.002 * Lb * Lh
        else:
            pass

        # 文本生成
        document = Document()
        document.styles['Normal'].font.name = 'Times New Roman'  # 默认西体
        document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')  # 默认中体
        document.styles['Normal'].font.size = Pt(10.5)  # 正文全局大小为10.5 小五
        document.styles['Heading 1'].font.size = Pt(14)  # 一级标题字体大小14 四号
        document.styles['Heading 1'].font.bold = True  # 加粗
        document.styles['Heading 2'].font.size = Pt(12)
        document.styles['Heading 2'].font.bold = True

        run = document.add_heading('悬挑板计算书', level=1)  # 标题
        run.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

        document.add_heading('一、构件编号：' + name, level=2)  # 一、计算信息
        document.add_heading('二、计算信息', level=2)  # 计算信息
        document.add_paragraph('1. 几何参数\n        截面类型：矩形\n        截面宽度：b=' + str(b) + 'mm\n        截面高度：h=' + str(h) + 'mm')
        document.add_paragraph('2. 材料信息\n        混凝土等级：' + concrete_g + '  fc=' + str(fc) + 'N/mm\u00b2    ft=' + str(ft) + 'N/mm\u00b2\n        钢筋种类：' + steel_g + '   fy=' + str(fy) + 'N/mm\u00b2\n        最小配筋率：ρmin=' + str(pmin * 100) + '%\n        纵筋合力点至近边距离：as=' + str(a_s) + 'mm')
        document.add_paragraph('3. 设计参数\n        结构重要性系数：γo=' + str(y0))

        document.add_heading('三、荷载计算', level=2)  # 荷载计算
        document.add_paragraph('1. 恒载\n        板面及板底恒载DL=' + str(dl) + 'kN/m\u00b2\n        板端弯矩标准值Md=1/2*(25*h/1000+dl)*l\u00b2/10^6=' + str('%.1f' % Md) + 'kN.m\n        板端剪力标准值Vd=(h/1000*25+dl)*l/1000=' + str('%.1f' % Vd) + 'kN')
        document.add_paragraph('2. 活载\n        板面活载LL=' + str(ll) + 'kN/m\u00b2\n        板端弯矩标准值Ml=1/2*(25*h/1000+ll)*l\u00b2/10^6=' + str('%.1f' % Ml) + 'kN.m\n        板端剪力标准值Vl=(h/1000*25+ll)*l/1000=' + str('%.1f' % Vl) + 'kN')
        document.add_paragraph('3. 翻边\n        均布线荷载BL=' + str(bl) + 'kN/m\u00b2\n        板端弯矩标准值Mb=bl*l/1000=' + str('%.1f' % Mb) + 'kN.m\n        板端剪力标准值Vb=bl=' + str('%.1f' % Vb) + 'kN')
        document.add_paragraph('4. 荷载组合\n        弯矩设计值M=1.3*(Md+Mb)+1.5*Ml=' + str('%.1f' % M) + 'kN.m\n        剪力设计值V=1.3*(Vd+Vb)+1.5*Vl=' + str('%.1f' % V) + 'kN')
        if bool_beam == 'y':
            document.add_paragraph('5. 内梁\n        折算每米均布线荷载Lx=V=' + str(Lx) + 'kN/m\n        折算每米扭矩荷载LT/m=M+Lx*Lb/2/1000=' + str('%.1f' % LTm) + 'kN.m/m\n        梁中最大扭矩Tmax=LT/m*LL/2/1000=' + str('%.1f' % Tmax) + 'kN.m\n        梁中最大弯矩Mmax=1/8*Lx*LL\u00b2/10^6=' + str('%.1f' % Mmax) + 'kN.m\n        梁端最大剪力Vmax=1/2*Lx*LL/1000=' + str('%.1f' % Vmax) + 'kN')
        else:
            pass

        document.add_heading('四、板正截面受弯计算', level=2)  # 板正截面受弯计算
        document.add_paragraph('1. 计算截面有效高度:\n        ho=h-as=' + str(h) + '-' + str(a_s) + '=' + str(h0) + 'mm')
        document.add_paragraph('2. 计算相对受压区高度:\n        ξb=β1/(1+fy/(Es×εcu))=0.8/(1+' + str(fy) + '/(2×10^5×0.0033))=' + str(xb))
        document.add_paragraph('3. 确定计算系数:\n        αs=γo*M/(α1*fc*b*ho*ho)=' + str('%.1f' % y0) + '*' + str('%.1f' % M) + '*10^6/(1.0*' + str(fc) + '*1000*' + str(b) + '*' + str(h0) + '*' + str(h0) + ')=' + str('%.1f' % as1))
        document.add_paragraph('4. 计算相对受压区高度:\n        ξ=1-sqrt(1-2αs)=1-sqrt(1-2*' + str('%.1f' % as1) + ')=' + str('%.3f' % x1) + '≤ξb=0.518    满足要求。')
        document.add_paragraph('5. 计算纵向受拉钢筋面积:\n        As＝α1*fc*b*ho*ξ/fy=1.0*' + str(fc) + '*' + str(b) + '*' + str(h0) + '*' + str('%.3f' % x1) + '/' + str(fy) + '=' + str('%.1f' % As) + 'mm\u00b2')
        document.add_paragraph('6. 验算最小配筋率:\n        ρ=As/(b*h)=' + str('%.1f' % As) + '/(' + str(b) + '*' + str(h) + ')=' + str('%.2f' % (p * 100)) + '%')
        if p < pmin:
            document.add_paragraph('       ρ=' + str('%.2f' % (p * 100)) + '%<ρmin=' + str('%.2f' % (pmin * 100)) + '%，不满足最小配筋率要求，\n        取As=ρmin*b*h=' + str('%.2f' % (pmin * 100)) + '%*' + str(b) + '*' + str(h) + '=' + str('%.2f' % Asmin) + 'mm\u00b2')
            As = Asmin
        else:
            document.add_paragraph('       ρ=' + str('%.2f' % (p * 100)) + '%>ρmin=' + str('%.2f' % (pmin * 100)) + '%，满足最小配筋率要求。')

        Aspj = self.AspjText.get()
        Asmj = self.AsmjText.get()
        document.add_heading('五、板配筋', level=2)  # 板配筋
        document.add_paragraph('       实配为' + Aspj + '，实际配筋面积为' + Asmj + 'mm\u00b2。')

        if bool_beam == '是':
            document.add_heading('六：内梁计算', level=2)  # 内梁弯剪扭计算
# 1. 已知条件
            document.add_paragraph('1. 已知条件及计算要求：\n（1）已知条件：\n        计算截面：矩形梁    Lb=' + str(Lb) + 'mm,Lh=' + str(Lh) + 'mm。\n        砼等级：' + concrete_g + '，fc=' + str(fc) + 'N/mm\u00b2，ft=' + str(ft) + 'N/mm\u00b2\n        纵筋等级：' + steel_g + '，fy=' + str(fy) + 'N/mm\u00b2，fy\'=' + str(fy) + 'N/mm\u00b2\n        箍筋等级：' + steel_g + '，fy=' + str(fy) + 'N/mm\u00b2。')
            document.add_paragraph('      弯矩设计值M=' + str('%.1f' % Mmax) + 'kN.m，剪力设计值V=' + str('%.1f' % Vmax) + 'kN，扭矩设计值T=' + str('%.1f' % Tmax) + 'kN.m。')
            document.add_paragraph('（2）计算要求：\n        1）正截面受弯承载力计算\n        2）斜截面受剪承载力计算\n        3）受扭承载力计算')
# 2. 截面特征量计算
            document.add_paragraph('2. 截面特征量计算：\n        Wt=Lb*Lb*(3*Lh0-Lb)/6=' + str(Lb) + '*' + str(Lb) + '*(3*' + str(Lh0) + '-' + str(Lb) + ')/6=' + str('%.1f' % Wt) + 'mm^3\n        bcor=Lb-50=' + str(Lb) + '-50=' + str(bcor) + 'mm\n        hcor=Lh-as上-as下=' + str(Lh) + '-' + str(ast) + '-' + str(asb) + '=' + str(hcor) + 'mm\n        Acor=bcor*hcor=' + str(bcor) + '*' + str(hcor) + '=' + str(Acor) + 'mm\u00b2\n        ucor=2(bcor+hcor)=2*(' + str(bcor) + '+' + str(hcor) + ')=' + str(ucor) + 'mm')
# 3. 截面尺寸复核
            document.add_paragraph('3. 截面尺寸复核：')
            if Lh0 / Lb <= 4:
                document.add_paragraph('        Lh0/Lb=' + str('%.1f' % (Lh0 / Lb)) + '<4\n        Vmax/(Lb*h0)+Tmax/Wt=' + str('%.2f' % result1) + 'N/mm\u00b2<\n                0.25*βc*fc=' + str(0.25 * 1 * fc) + 'N/mm\u00b2\n        截面尺寸复核要求。')
            else:
                document.add_paragraph('        4<Lh0/Lb=' + str('%.1f' % (Lh0 / Lb)) + '<6\n        Vmax/(Lb*h0)+Tmax/(0.8*Lb*Lb*(3*Lh-Lb)/6)=' + str('%.2f' % result1) + 'N/mm\u00b2\n                <(6-Lh0/Lb)/2*0.25*1*fc)+(Lh0/Lb-4)*(0.2*1*fc)=' + str('%.2f' % allow3) + 'N/mm\u00b2\n        截面尺寸符合要求。')
# 4. 是否按剪扭计算
            document.add_paragraph('4. 是否需按剪扭计算:')
            if result2 < allow4:
                document.add_paragraph('        Vmax/(Lb*Lh0)+Tmax/Wt=' + str('%.1f' % Vmax) + '*1000/(' + str(Lb) + '*' + str(Lh0) + ')+' + str('%.1f' % Tmax) + '*1000000/' + str('%.1f' % Wt) + '=' + str('%.1f' % result2) + '\n                <0.7ft=0.7*' + str(ft) + '=' + str('%.1f' % allow4) + 'N/mm\u00b2\n        满足要求，可不进行构件受减扭承载力计算，但需满足规范构造要求。')
                tkinter.messagebox.showinfo('本计算小程序仅针对需要按剪扭计算进行计算，若不需要，可将第6.7节剪扭计算部分删除')
            else:
                document.add_paragraph('        Vmax/(Lb*Lh0)+Tmax/Wt=' + str('%.1f' % Vmax) + '*1000/(' + str(Lb) + '*' + str(Lh0) + ')+' + str('%.1f' % Tmax) + '*1000000/' + str('%.1f' % Wt) + '=' + str('%.1f' % result2) + '\n                >0.7ft=0.7*' + str(ft) + '=' + str('%.1f' % allow4) + 'N/mm\u00b2\n        需进行构件受减扭承载力计算。')
    # 5. 双筋梁正截面受弯计算
            document.add_paragraph('5. 正截面受弯承载力计算：\n（1）按双筋计算：as下=' + str(asb) + 'mm，as上=' + str(ast) + 'mm\n        假设采用上下对称配筋，则x=(fy*As-fy\'*As\')/(α1*fc*Lb)=0\n        则x≤ξb*Lh0，且需x≥2*a\'，所以取x=2*' + str(ast) + '=' + str(2 * ast) + 'mm\n        As=As\'=(M-α1*fc*Lb*x*(Lh0-x/2))/(fy\'*(Lh0-as\'))=(' + str('%.1f' % M) + '-1.0*' + str(fc) + '*' + str(Lb) + '*' + str(2 * ast) + '*(' + str(Lh0) + '-' + str(2 * ast) + '/2))/(' + str(fy) + '*(' + str(Lh0) + '-' + str(ast) + '))=' + str('%.1f' % AsL) +
                                'mm\u00b2\n（2）构造要求：非抗震ρmin=0.20%，Asmin=0.2%*' + str(Lb) + '*' + str(Lh) + '=' + str(AsLmin) + 'mm\u00b2')
            if AsL <= AsLmin:
                document.add_paragraph('（3）配筋面积：As = ' + str('%.1f' % AsL) + '≤Asmin=' + str(AsLmin) + 'mm\u00b2\n        需As=As\'=' + str(AsLmin) + 'mm\u00b2')
                AsL = AsLmin
            else:
                document.add_paragraph('（3）配筋面积：As = ' + str('%.1f' % AsL) + '>Asmin=' + str(AsLmin) + 'mm\u00b2\n        需As=As\'=' + str('%.1f' % AsL) + 'mm\u00b2')
    # 6. 确定箍筋
            if bt < 0.5:
                document.add_paragraph('6. 确定受剪及受扭箍筋\n（1）受扭所需箍筋量\n        计算剪扭构件受扭承载力降低系数βt\n        βt=1.5/(1+0.5*(V*Wt/(T*Lb*Lh0))=' + str('%.1f' % bt) + '<0.5\n        故取βt=0.5')
                bt = 0.5
            elif bt > 1:
                document.add_paragraph('6. 确定受剪及受扭箍筋\n（1）受扭所需箍筋量\n        计算剪扭构件受扭承载力降低系数βt\n        βt=1.5/(1+0.5*(V*Wt/(T*Lb*Lh0))=' + str('%.1f' % bt) + '>1.0\n        故取βt=1')
                bt = 1
            else:
                document.add_paragraph('6. 确定受剪及受扭箍筋\n（1）受扭所需箍筋量\n        计算剪扭构件受扭承载力降低系数βt\n        βt=1.5/(1+0.5*(V*Wt/(T*Lb*Lh0))=' + str('%.1f' % bt) + '>0.5且<1')
            Ast1_st = (Tmax * 1000000 - 0.35 * bt * ft * Wt) / (1.2 * math.sqrt(1.2) * fy * Acor)
            document.add_paragraph('        令配筋强度比ζ=1.2\n        Ast1/st=(T-0.35*βt*ft*Wt)/(1.2*sqrt(ζ)*fyv*Acor)=' + str('%.1f' % (Ast1_st * 100)) + 'mm\u00b2/100mm')
            nAsv1_sv = (Vmax - 0.7 * (1.5 - bt) * ft * Lb * Lh0) / (1.25 * fy * Lh0)
            Asv_s = nAsv1_sv / 2 + Ast1_st
            psvmin = 0.28 * ft / fy
            Asvmin_s = psvmin * Lb / 2
            if nAsv1_sv > 0:
                document.add_paragraph('（2）受剪所需箍筋数量\n        nAsv1/sv=(V-0.7(1.5-βt)*ft*Lb*Lh0)/(1.25*fyv*Lh0)=' + str('%.1f' % (nAsv1_sv * 100)) + 'mm\u00b2/100mm\n        按照双肢箍考虑，n=2,则单肢箍总的箍筋用量为\n        Asv1\"/s=Asv1/sv+Ast1/st=' + str('%.1f' % (Asv_s * 100)) + 'mm\u00b2/100mm\n        最小配箍率验算：\n        ρsv,min=0.28*ft/fy=' + str('%.2f' % (psvmin * 100)) + '%\n        单肢箍最小配箍面积：\n        Asv,min/s=ρsv,min*b/n=' + str('%.1f' % (Asvmin_s * 100)) + 'mm\u00b2/100mm')
            else:
                Asv_s = Ast1_st
                document.add_paragraph('（2）受剪所需箍筋数量\n        nAsv1/sv=(V-0.7(1.5-βt)*ft*Lb*Lh0)/(1.25*fyv*Lh0)=' + str('%.1f' % (nAsv1_sv * 100)) + 'mm\u00b2/100mm<0取0\n        按照双肢箍考虑，n=2,则单肢箍总的箍筋用量为\n        Asv1\"/s=Asv1/sv+Ast1/st=' + str('%.1f' % (Asv_s * 100)) + 'mm\u00b2/100mm\n        最小配箍率验算：\n        ρsv,min=0.28*ft/fy=' + str('%.2f' % (psvmin * 100)) + '%\n        单肢箍最小配箍面积：\n        Asv,min/s=ρsv,min*b/n=' + str('%.1f' % (Asvmin_s * 100)) + 'mm\u00b2/100mm')
            if Asv_s < Asvmin_s:
                document.add_paragraph('        因为Asv1\"/s<Asv,min/s,\n        故取Asv1\"/s=Asv,min/s=' + str('%.2f' % (psvmin * 100)) + 'mm\u00b2/100mm')
                Asv_s = Asvmin_s
            else:
                document.add_paragraph('        因此Asv1\"/s>Asv,min/s,满足最小配筋率要求。')
            Astl = 1.2 * fy * ucor / fy * (Ast1_st)
            # 7. 计算抗扭纵筋用量
            document.add_paragraph('7. 计算抗扭纵筋用量\n        Astl=ζ*fyv*ucor/fy*(Ast1/st)=' + str(int(Astl)) + 'mm\u00b2\n        抗扭纵筋最小配筋率：')
            T_Vb = Tmax * 1000 / Vmax / Lb
            if T_Vb < 2:
                document.add_paragraph('        T/(V*b)=' + str('%.1f' % T_Vb) + '<2')
            else:
                document.add_paragraph('        T/(V*b)=' + str('%.1f' % T_Vb) + '≥2，取T/(V*b)=2')
            ptlmin = 0.6 * math.sqrt(Tmax * 1000 / (Vmax * Lb)) * ft / fy
            Atlmin = ptlmin * Lb * Lh
            document.add_paragraph('        ρtl,min=0.6*sqrt(T/(V*b))*ft/fy=' + str('%.1f' % (ptlmin * 100)) + '%\n        抗扭纵筋最小配筋面积：Atl,min=ρtl,min*Lb*Lh=' + str(int(Atlmin)) + 'mm\u00b2')
            if Astl > Atlmin:
                document.add_paragraph('        因此Astl>Atl,min，满足最小配筋率要求。')
            else:
                document.add_paragraph('        因为Astl<Atl,min,故取Astl=Atl,min=' + str(int(Atlmin)))
                Astl = Atlmin
    # 8. 梁配筋
            document.add_paragraph('8.梁配筋')
            document.add_paragraph('        箍筋计算面积：Asv/s=' + str(int (Asv_s * 100)) + 'mm\u00b2/100mm')
            LAsvspj = self.LAsvspjText.get()
            Lasvsmj = self.LasvsmjText.get()
            document.add_paragraph('        选用：' + LAsvspj + '\n        实际Asv/s=' + Lasvsmj + 'mm\u00b2')
            document.add_paragraph('        顶部及底部纵筋计算面积：As=As\'=' + str(int( AsL)) + 'mm\u00b2')
            LAspj = self.LAspjText.get()
            Lasmj = self.LAsmjText.get()
            document.add_paragraph('        选用：' + LAspj + '\n        实际As=As\'=' + Lasmj + 'mm\u00b2')
            document.add_paragraph('        抗扭纵筋计算面积：Astl=' + str(int(AsL)) + 'mm\u00b2')
            LAstlpj = self.LAstlpjText.get()
            Lastlmj = self.LAstlmjText.get()
            document.add_paragraph('        选用：' + LAstlpj + '\n        实际Astl=' + Lastlmj + 'mm\u00b2')

        for paragraph in document.paragraphs:
            paragraph_format = paragraph.paragraph_format
            paragraph_format.space_before = Pt(0)
            paragraph_format.space_after = Pt(0)
            paragraph_format.line_spacing = Pt(18)

        document.save(name + '.docx')
        tkinter.messagebox.showinfo('Congratrulations!','计算书已成功导出！')

def gui_start():
    init_window = style.master              #实例化出一个父窗口
    ZMJ_PORTAL = MY_GUI(init_window)
    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()

    init_window.mainloop()          #父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示

gui_start()


class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        ans = 0
        dic = {}
        for n in nums:
            if n in dic: continue
            left = dic.get(n - 1,0)
            right = dic.get(n + 1,0)
            dic[n] = left + right + 1
            dic[n - left] = dic[n]
            dic[n + right] = dic[n]
            #print(dic)
            ans = max(ans,dic[n])
        return ans


# solution by @dualjk and @tirannosario

rules = {"A":[3,6,0], "B":[0,3,6], "C":[6,0,3]}
assignment = {"X":1, "Y":2, "Z":3}

def totalScore():
    game_score = 0
    game_file = open("input.txt", 'r')
    for game in game_file.readlines():
        p1,p2 = game.split(" ")
        game_score += assignment[p2.strip()] + rules[p1][assignment[p2.strip()]-1]
    print("game score: ", game_score)

if __name__ == "__main__":
    totalScore()


"""
This module provides the functions for the one-loop finite
temperature corrections to a potential in QFT.  The two basic
functions are:

    Jb(x) = int[0->inf] dy +y^2 log( 1 - exp(-sqrt(x^2 + y^2)) )

    Jf(x) = int[0->inf] dy -y^2 log( 1 + exp(-sqrt(x^2 + y^2)) )

Call them by:

    Jb(x, approx='high', deriv=0, n = 8)

Here, approx can either be 'exact', 'spline', 'high', or 'low'.
Exact calculates the integral numerically, while high and low
calculate the high and low x expansions of J to order n.
Specify the derivative with the 'deriv' parameter.
"""

import os

import numpy
from scipy import integrate, interpolate
from scipy import special
try:
    from scipy.misc import factorial as fac
except ImportError:
    from scipy.special import factorial as fac

pi = numpy.pi
euler_gamma = 0.577215661901532
log, exp, sqrt = numpy.log, numpy.exp, numpy.sqrt
array = numpy.array

spline_data_path = os.path.dirname(__file__)

# The following are the exact integrals:

def _Jf_exact(x):
    f = lambda y: -y*y*log(1+exp(-sqrt(y*y+x*x)))
    if(x.imag == 0):
        x = abs(x)
        return integrate.quad(f, 0, numpy.inf)[0]
    else:
        f1 = lambda y: -y*y*log(2*abs(numpy.cos(sqrt(abs(x*x)-y*y)/2)))
        return (
            integrate.quad(f1,0,abs(x))[0] +
            integrate.quad(f,abs(x),numpy.inf)[0]
        )

def _Jf_exact2(theta):
    # Note that this is a function of theta so that you can get negative values
    f = lambda y: -y*y*log(1+exp(-sqrt(y*y+theta))).real
    if theta >= 0:
        return integrate.quad(f, 0, numpy.inf)[0]
    else:
        f1 = lambda y: -y*y*log(2*abs(numpy.cos(sqrt(-theta-y*y)/2)))
        return (
            integrate.quad(f, abs(theta)**.5, numpy.inf)[0] +
            integrate.quad(f1, 0, abs(theta)**.5)[0]
        )

def _Jb_exact(x):
    f = lambda y: y*y*log(1-exp(-sqrt(y*y+x*x)))
    if(x.imag == 0):
        x = abs(x)
        return integrate.quad(f, 0, numpy.inf)[0]
    else:
        f1 = lambda y: y*y*log(2*abs(numpy.sin(sqrt(abs(x*x)-y*y)/2)))
        return (
            integrate.quad(f1,0,abs(x))[0] +
            integrate.quad(f,abs(x),numpy.inf)[0]
        )

def _Jb_exact2(theta):
    # Note that this is a function of theta so that you can get negative values
    f = lambda y: y*y*log(1-exp(-sqrt(y*y+theta))).real
    if theta >= 0:
        return integrate.quad(f, 0, numpy.inf)[0]
    else:
        f1 = lambda y: y*y*log(2*abs(numpy.sin(sqrt(-theta-y*y)/2)))
        return (
            integrate.quad(f, abs(theta)**.5, numpy.inf)[0] +
            integrate.quad(f1, 0, abs(theta)**.5)[0]
        )

def _dJf_exact(x):
    f = lambda y: y*y*(exp(sqrt(y*y+x*x))+1)**-1*x/sqrt(y*y+x*x)
    return integrate.quad(f, 0, numpy.inf)[0]

def _dJb_exact(x):
    f = lambda y: y*y*(exp(sqrt(y*y+x*x))-1)**-1*x/sqrt(y*y+x*x)
    return integrate.quad(f, 0, numpy.inf)[0]

def arrayFunc(f, x, typ=float):
    # This function allows a 1D array to be passed to something that
    # normally can't handle it
    i = 0
    try:
        n = len(x)
    except:
        return f(x)  # x isn't an array
    s = numpy.empty(n, typ)
    while(i < n):
        try:
            s[i] = f(x[i])
        except:
            s[i] = numpy.NaN
        i += 1
    return s

def Jf_exact(x):
    """Jf calculated directly from the integral."""
    return arrayFunc(_Jf_exact, x, complex)

def Jf_exact2(theta):
    """Jf calculated directly form the integral; input is theta = x^2."""
    return arrayFunc(_Jf_exact2, theta)

def Jb_exact(x):
    """Jb calculated directly from the integral."""
    return arrayFunc(_Jb_exact, x)

def Jb_exact2(theta):
    """Jb calculated directly form the integral; input is theta = x^2."""
    return arrayFunc(_Jb_exact2, theta)

def dJf_exact(x):
    """dJf/dx calculated directly from the integral."""
    return arrayFunc(_dJf_exact, x)

def dJb_exact(x):
    """dJb/dx calculated directly from the integral."""
    return arrayFunc(_dJb_exact, x)

# Spline fitting, Jf
_xfmin = -6.82200203  # -11.2403168
_xfmax = 1.35e3
_Jf_dat_path = spline_data_path+"/finiteT_f.dat.txt"
if os.path.exists(_Jf_dat_path):
    _xf, _yf = numpy.loadtxt(_Jf_dat_path).T
else:
    # x = |xmin|*sinh(y), where y in linear
    # (so that we're not overpopulating the uniteresting region)
    _xf = numpy.linspace(numpy.arcsinh(-1.3*20),
                         numpy.arcsinh(-20*_xfmax/_xfmin), 1000)
    _xf = abs(_xfmin)*numpy.sinh(_xf)/20
    _yf = Jf_exact2(_xf)
    numpy.savetxt(_Jf_dat_path, numpy.array([_xf, _yf]).T)

_tckf = interpolate.splrep(_xf, _yf)
def Jf_spline(X,n=0):
    """Jf interpolated from a saved spline. Input is (m/T)^2."""
    X = numpy.array(X, copy=False)
    x = X.ravel()
    y = interpolate.splev(x,_tckf, der=n).ravel()
    y[x < _xfmin] = interpolate.splev(_xfmin,_tckf, der=n)
    y[x > _xfmax] = 0
    return y.reshape(X.shape)

# Spline fitting, Jb
_xbmin = -3.72402637
# We're setting the lower acceptable bound as the point where it's a minimum
# This guarantees that it's a monatonically increasing function, and the first
# deriv is continuous.
_xbmax = 1.41e3
_Jb_dat_path = spline_data_path+"/finiteT_b.dat.txt"
if os.path.exists(_Jb_dat_path):
    _xb, _yb = numpy.loadtxt(_Jb_dat_path).T
else:
    # x = |xmin|*sinh(y), where y in linear
    # (so that we're not overpopulating the uniteresting region)
    _xb = numpy.linspace(numpy.arcsinh(-1.3*20),
                         numpy.arcsinh(-20*_xbmax/_xbmin), 1000)
    _xb = abs(_xbmin)*numpy.sinh(_xb)/20
    _yb = Jb_exact2(_xb)
    numpy.savetxt(_Jb_dat_path, numpy.array([_xb, _yb]).T)

_tckb = interpolate.splrep(_xb, _yb)
def Jb_spline(X,n=0):
    """Jb interpolated from a saved spline. Input is (m/T)^2."""
    X = numpy.array(X, copy=False)
    x = X.ravel()
    y = interpolate.splev(x,_tckb, der=n).ravel()
    y[x < _xbmin] = interpolate.splev(_xbmin,_tckb, der=n)
    y[x > _xbmax] = 0
    return y.reshape(X.shape)

# Now for the low x expansion (require that n <= 50)
a,b,c,d = -pi**4/45, pi*pi/12, -pi/6, -1/32.
logab = 1.5 - 2*euler_gamma + 2*log(4*pi)
l = numpy.arange(50)+1
g = (-2*pi**3.5 * (-1)**l*(1+special.zetac(2*l+1)) *
     special.gamma(l+.5)/(fac(l+2)*(2*pi)**(2*l+4)))
lowCoef_b = (a,b,c,d,logab,l,g)
del (a,b,c,d,logab,l,g)  # clean up name space

a,b,d = -7*pi**4/360, pi*pi/24, 1/32.
logaf = 1.5 - 2*euler_gamma + 2*log(pi)
l = numpy.arange(50)+1
g = (.25*pi**3.5 * (-1)**l*(1+special.zetac(2*l+1)) *
     special.gamma(l+.5)*(1-.5**(2*l+1))/(fac(l+2)*pi**(2*l+4)))
lowCoef_f = (a,b,d,logaf,l,g)
del (a,b,d,logaf,l,g)  # clean up name space

def Jb_low(x,n=20):
    """Jb calculated using the low-x (high-T) expansion."""
    (a,b,c,d,logab,l,g) = lowCoef_b
    y = a + x*x*(b + x*(c + d*x*(numpy.nan_to_num(log(x*x)) - logab)))
    i = 1
    while i <= n:
        y += g[i-1]*x**(2*i+4)
        i += 1
    return y

def Jf_low(x,n=20):
    """Jf calculated using the low-x (high-T) expansion."""
    (a,b,d,logaf,l,g) = lowCoef_f
    y = a + x*x*(b + d*x*x*(numpy.nan_to_num(log(x*x)) - logaf))
    i = 1
    while i <= n:
        y += g[i-1]*x**(2*i+4)
        i += 1
    return y

# The next few functions are all for the high approximation

def x2K2(k,x):
    y = -x*x*special.kn(2, k*x)/(k*k)
    if(isinstance(x, numpy.ndarray)):
        y[x == 0] = numpy.ones(len(y[x == 0]))*-2.0/k**4
    elif(x == 0):
        return -2.0/k**4
    return y

def dx2K2(k,x):
    y = abs(x)
    return numpy.nan_to_num(x*y*special.kn(1,k*y)/k)

def d2x2K2(k,x):
    x = abs(x)
    y = numpy.nan_to_num(x*(special.kn(1,k*x)/k - x*special.kn(0,k*x)))
    if(isinstance(x, numpy.ndarray)):
        y[x == 0] = numpy.ones(len(y[x == 0]))*1.0/k**2
    elif(x == 0):
        return 1.0/k**2
    return y

def d3x2K2(k,x):
    y = abs(x)
    return numpy.nan_to_num(x*(y*k*special.kn(1,k*y) - 3*special.kn(0,k*y)))

def Jb_high(x, deriv=0, n=8):
    """Jb calculated using the high-x (low-T) expansion."""
    K = (x2K2, dx2K2, d2x2K2, d3x2K2)[deriv]
    y, k = 0.0, 1
    while k <= n:
        y += K(k,x)
        k += 1
    return y

def Jf_high(x, deriv=0, n=8):
    """Jf calculated using the high-x (low-T) expansion."""
    K = (x2K2, dx2K2, d2x2K2, d3x2K2)[deriv]
    y, k, i = 0.0, 1, 1
    while k <= n:
        y += i*K(k,x)
        i *= -1
        k += 1
    return y

# And here are the final functions:
# Note that if approx = 'spline', the function called is
# J(theta) (x^2 -> theta so you can get negative mass squared)
def Jb(x, approx='high', deriv=0, n=8):
    """
    A shorthand for calling one of the Jb functions above.

    Parameters
    ----------
    approx : str, optional
        One of 'exact', 'high', 'low', or 'spline'.
    deriv : int, optional
        The order of the derivative (0 for no derivative).
        Must be <= (1, 3, 0, 3) for approx = (exact, high, low, spline).
    n : int, optional
        Number of terms to use in the low and high-T approximations.
    """
    if(approx == 'exact'):
        if(deriv == 0):
            return Jb_exact(x)
        elif(deriv == 1):
            return dJb_exact(x)
        else:
            raise ValueError("For approx=='exact', deriv must be 0 or 1.")
    elif(approx == 'spline'):
        return Jb_spline(x, deriv)
    elif(approx == 'low'):
        if(n > 100):
            raise ValueError("Must have n <= 100")
        if(deriv == 0):
            return Jb_low(x,n)
        else:
            raise ValueError("For approx=='low', deriv must be 0.")
    elif(approx == 'high'):
        if(deriv > 3):
            raise ValueError("For approx=='high', deriv must be 3 or less.")
        else:
            return Jb_high(x, deriv, n)
    raise ValueError("Unexpected value for 'approx'.")

def Jf(x, approx='high', deriv=0, n=8):
    """
    A shorthand for calling one of the Jf functions above.

    Parameters
    ----------
    approx : str, optional
        One of 'exact', 'high', 'low', or 'spline'.
    deriv : int, optional
        The order of the derivative (0 for no derivative).
        Must be <= (1, 3, 0, 3) for approx = (exact, high, low, spline).
    n : int, optional
        Number of terms to use in the low and high-T approximations.
    """
    if(approx == 'exact'):
        if(deriv == 0):
            return Jf_exact(x)
        elif(deriv == 1):
            return dJf_exact(x)
        else:
            raise ValueError("For approx=='exact', deriv must be 0 or 1.")
    elif(approx == 'spline'):
        return Jf_spline(x, deriv)
    elif(approx == 'low'):
        if(n > 100):
            raise ValueError("Must have n <= 100")
        if(deriv == 0):
            return Jf_low(x,n)
        else:
            raise ValueError("For approx=='low', deriv must be 0.")
    elif(approx == 'high'):
        if(deriv > 3):
            raise ValueError("For approx=='high', deriv must be 3 or less.")
        else:
            return Jf_high(x, deriv, n)
    raise ValueError("Unexpected value for 'approx'.")


#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import datetime
from optparse import OptionParser

from ESP.utils.utils import date_from_str, str_from_date, log, days_in_interval, make_date_folders
from ESP.conf.common import EPOCH
from ESP.vaers.models import EncounterEvent, LabResultEvent, PrescriptionEvent, AllergyEvent, HL7_MESSAGES_DIR

from heuristics import  diagnostic_heuristics, lab_heuristics, prescription_heuristics, allergy_heuristics
from ESP.vaers.rules import define_active_rules

usage_msg = """
Usage: python %prog -b[egin_date] -e[nd_date]
{ [-d --detect],[-r --reports] } | [-f --full]

 One or more of '-l', '-p', '-g', '-f', '-d' or '-a' must be specified.

    DATE variables are specified in this format: 'YYYYMMDD'

"""

def main():

    today = datetime.datetime.today()
    yesterday = today - datetime.timedelta(1)

    parser = OptionParser(usage=usage_msg)
    parser.add_option('-b', '--begin', dest='begin_date', default=str_from_date(yesterday))
    parser.add_option('-e', '--end', dest='end_date', default=str_from_date(today))

    parser.add_option('-l', '--lx', action='store_true', dest='lx', help='Run Lab Results Heuristics')
    parser.add_option('-d', '--diagnostics', action='store_true', dest='diagnostics',
                      help='Run Diagnostics Heuristics')
    parser.add_option('-p', '--rx', action='store_true', dest='rx',help='Run Prescription Heuristics')
    parser.add_option('-g', '--allergy', action='store_true', dest='allergy',help='Run Allergy Heuristics')

    parser.add_option('-a', '--all', action='store_true', dest='all')

    parser.add_option('-c', '--create', action='store_true', dest='create')

    options, args = parser.parse_args()
    # clean rules and load them again
    define_active_rules()

    try:
        begin_date = date_from_str(options.begin_date)
        end_date = date_from_str(options.end_date)
    except:
        log.error('Invalid dates')
        sys.exit(-1)

    if options.all:
        options.diagnostics = True
        options.lx = True
        options.rx = True
        options.allergy = True

    if not (options.diagnostics or options.lx or options.rx or options.allergy):
        parser.print_help()
        sys.exit(-2)

    if not (options.create or options.reports):
        parser.print_help()
        sys.exit(-3)

    heuristics = []
    if options.diagnostics: heuristics += diagnostic_heuristics()
    if options.lx: heuristics += lab_heuristics()
    if options.rx: heuristics += prescription_heuristics()
    if options.allergy: heuristics += allergy_heuristics()

    if options.create:
        log.info('Creating and generating events from %s to %s' % (begin_date, end_date))
        for h in heuristics:
            h.generate(begin_date=begin_date, end_date=end_date)

if __name__ == '__main__':
    main()


from collections import deque

def solution(m, musicinfos):
    qq = deque(m)
    cri = []
    trac = []
    while qq:
        aa = qq.popleft()
        if qq and qq[0] == "#":
            cri.append(aa + qq.popleft())
        else:
            cri.append(aa)

    info = list(map(lambda x: x.replace(':', ',').split(','), musicinfos))
    for setting in info:
        l = (int(setting[2]) - int(setting[0]))*60 + (int(setting[3]) - int(setting[1]))
        q = deque(setting[5])
        eum = []
        while q:
            a = q.popleft()
            if q and q[0] == "#":
                eum.append(a + q.popleft())
            else:
                eum.append(a)

        p, r = divmod(l, len(eum))
        song = deque(eum * p + eum[:r])
        maxcnt = 0
        while song:
            cnt = 0
            point = song.popleft()
            if point == cri[0]:
                cnt += 1
                for i in cri[1:]:
                    if song and song[0] == i:
                        song.popleft()
                        cnt += 1
                    else:
                        break
            maxcnt = max(maxcnt, cnt)
        if len(cri) == maxcnt:
            trac.append([setting[4], l])

    answer = sorted(trac, key = lambda x: -x[1])
    return answer[0][0] if answer else "(None)"


# The algorithm is attributed to Neelam Yadav

def DistinctSums(n):
  my_string = ""
  placeholder = 0
  table = [0] * (n + 1)
  table[0] = 1
  for i in range(1, n):
    for j in range(i, n + 1):
      table[j] += table[j - i]
      if j == n:
        new_sums = table[n] - placeholder
        placeholder = table[n]
    my_string = f"""Max summand {i},  New Sums = {new_sums:,}\n""" + my_string
  print()
  print(my_string)
  print(f"""The number {n} has {table[n]:,} distinct sums\n""")

DistinctSums(100)


import queue
import threading
import time

exitFlag = 0

class myThread(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        print("开启线程：" + self.name)
        process_data(self.name, self.q)
        print("退出线程：" + self.name)

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print("%s processing %s\n" % (threadName, data))
        else:
            queueLock.release()
        # time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3", "Thread-4", "Thread-5", "Thread-6"]
nameList = ["One", "Two", "Three", "Four", "Five", "six", "server", "eng"]
# 定义锁
queueLock = threading.Lock()
# 10个队列
workQueue = queue.Queue(8)
# 线程列表
threads = []
# 线程id
threadID = 1

# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# 等待线程全部启动，便于观察线程竞争
time.sleep(2)

# 获得锁，操作nameList
queueLock.acquire()
for word in nameList:
    # 写入队列
    workQueue.put(word)
# 释放锁
queueLock.release()

# 等待队列清空
# 如果队列为空，返回True,反之False
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
print("退出主线程")


import torch
import torch.nn as nn

class FusionAttentionModule(nn.Module):
    def __init__(self, embedding_size, n_head, dropout):
        super().__init__()
        self.multihead_attention = nn.MultiheadAttention(embedding_size, n_head, batch_first=True, dropout=dropout)
        self.linear = nn.Linear(2*embedding_size, embedding_size)
        self.relu = nn.ReLU()

    def forward(self, text, audio, key_padding_mask):
        x, _ = self.multihead_attention(query=text, key=audio, value=text, key_padding_mask=key_padding_mask)

        x = torch.cat((x, text), dim=2)
        x = self.relu(x)
        x = self.linear(x)
        x = self.relu(x)
        return x

class M2FNet(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.config = config

        self.audio_enabled = config.AUDIO.enabled
        self.text_enabled = config.TEXT.enabled
        self.fam_enabled = config.FAM.enabled

        if not self.audio_enabled and not self.text_enabled:
            raise ValueError("At least one of audio and text must be enabled!")
        if self.fam_enabled and not (self.audio_enabled and self.text_enabled):
            raise ValueError("Fusion Attention Module can only be used with both audio and text enabled!")

        d_model_audio = config.AUDIO.embedding_size
        d_model_text = config.TEXT.embedding_size
        d_model_fam = config.FAM.embedding_size

        self.n_head_audio = config.AUDIO.n_head
        self.n_head_text = config.TEXT.n_head
        self.n_head_fam = config.FAM.n_head

        n_layers_audio = config.AUDIO.n_encoder_layers
        n_layers_text = config.TEXT.n_encoder_layers
        n_layers_fam = config.FAM.n_layers
        n_layers_classifier = config.CLASSIFIER.n_layers

        n_transformers_audio = config.AUDIO.n_transformers
        n_transformers_text = config.TEXT.n_transformers

        hidden_size_classifier = config.CLASSIFIER.hidden_size
        output_size_classifier = config.CLASSIFIER.output_size

        dropout = config.dropout
        self.dropout = nn.Dropout(dropout)

        if self.audio_enabled:
            # Audio encoders
            audio_encoder_layer = nn.TransformerEncoderLayer(d_model=d_model_audio, nhead=self.n_head_audio, dropout=dropout)
            audio_encoder_norm = nn.LayerNorm(d_model_audio)
            self.audio_encoders = nn.ModuleList([
                nn.TransformerEncoder(encoder_layer=audio_encoder_layer, norm=audio_encoder_norm, num_layers=n_layers_audio)
                for _ in range(n_transformers_audio)])

            # Audio projection layer
            self.audio_proj = nn.Linear(d_model_audio, d_model_fam)

        if self.text_enabled:
            # Text encoders
            text_encoder_layer = nn.TransformerEncoderLayer(d_model=d_model_text, nhead=self.n_head_text, dropout=dropout)
            text_encoder_norm = nn.LayerNorm(d_model_text)
            self.text_encoders = nn.ModuleList([
                nn.TransformerEncoder(encoder_layer=text_encoder_layer, norm=text_encoder_norm, num_layers=n_layers_text)
                for _ in range(n_transformers_text)])

            # Text projection layer
            self.text_proj = nn.Linear(d_model_text, d_model_fam)

        if self.fam_enabled:
            # Fusion Attention Module layers
            self.fusion_layers = nn.ModuleList([
                FusionAttentionModule(embedding_size=d_model_fam, n_head=self.n_head_fam, dropout=dropout)
                for _ in range(n_layers_fam)])

        # Output layers
        cls_input_size = 2*d_model_fam if (self.audio_enabled and self.text_enabled) else d_model_fam
        classifier_head = [nn.Linear(cls_input_size, hidden_size_classifier)]
        if n_layers_classifier > 2:
            for _ in range(n_layers_classifier - 2):
                classifier_head.append(nn.ReLU())
                classifier_head.append(nn.Linear(hidden_size_classifier, hidden_size_classifier))

        classifier_head.append(nn.ReLU())
        classifier_head.append(self.dropout)
        classifier_head.append(nn.Linear(hidden_size_classifier, output_size_classifier))

        self.output_layer = nn.Sequential(*classifier_head)

    def forward(self, text, audio, mask):
        if self.audio_enabled:
            # Audio encoders with local skip connections
            audio = audio.permute(1, 0, 2)
            for encoder in self.audio_encoders:
                audio = audio + encoder(audio, src_key_padding_mask=mask)
            audio = audio.permute(1, 0, 2)

            # Audio projection layer
            audio = self.dropout(audio)
            audio = self.audio_proj(audio)
            audio = self.dropout(audio)

        if self.text_enabled:
            # Text encoders with local skip connections
            text = text.permute(1, 0, 2)
            for encoder in self.text_encoders:
                text = text + encoder(text, src_key_padding_mask=mask)
            text = text.permute(1, 0, 2)

            # Text projection layer
            text = self.dropout(text)
            text = self.text_proj(text)
            text = self.dropout(text)

        if self.fam_enabled:
            # Fusion Attention layers
            for fusion_layer in self.fusion_layers:
                text = fusion_layer(text=text, audio=audio, key_padding_mask=mask)
                text = self.dropout(text)

            # Concatenation layer
            x = torch.cat((audio, text), dim=2)
        else:
            # Concatenation layer
            if self.audio_enabled and self.text_enabled:
                x = torch.cat((audio, text), dim=2)
            else:
                x = text if self.text_enabled else audio

        # Fully Connected output layer
        x = self.output_layer(x)

        return x


from flask import Flask, render_template, url_for, session, request, redirect, flash
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
import csv #for db
from io import StringIO
from the_resistance.config import Config
from the_resistance.deploy import is_deploy
from random import randint
import json as j
import re

app = Flask(__name__)
app.config.from_object(Config)
socketio = SocketIO(app)

db = SQLAlchemy(app)

class players(db.Model):
    id = db.Column("id", db.Integer, primary_key=True)
    gameCode = db.Column("gameCode", db.String(10),unique=True)
    playerList = db.Column("playerList", db.String(255),unique=False)
    isPlaying = db.Column("isPlaying", db.String(1),unique=False)
    board = db.Column("board", db.LargeBinary, unique=False)

    def __init__(self, gameCode, playerList, isPlaying):
        self.gameCode = gameCode
        self.playerList = playerList
        self.isPlaying = isPlaying

    def get_id(self):
        return (self._id)

    def get_list(self): # will return a list to pass through websocket
        pJson = j.loads(self.playerList)
        return pJson['playerList']

    def appendList(self, name):
        pJson = j.loads(self.playerList)
        pJson['playerList'].append(name)
        self.playerList = j.dumps(pJson)
        db.session.commit()

    def removePlayer(self, name):
        pJson = j.loads(self.playerList)
        pJson['playerList'].remove(name)
        self.playerList = j.dumps(pJson)
        db.session.commit()

import the_resistance.events

#-------- To make sure name is 'clean' before passing through---------
def checkRe(name):
    reg = re.compile(r'[^a-zA-Z0-9.]')
    return not bool(reg.search(name))
#-----------------------------------------------------------------------

@app.route('/home', methods=['GET', 'POST'])
@app.route('/', methods=['GET', 'POST'])
def home():

    if request.method == "POST":

        code, name = request.form['code'].strip(' '), request.form['uname'].strip(' ')

        found_room = players.query.filter_by(gameCode=code).first()

        if(found_room) and found_room.isPlaying == 'n': #found waiting room succesfully and name is clean

            if len(found_room.get_list()) < 10: #check for lobby capacity, has to be one less as current player has not joined yet
                print("\n\n", len(found_room.get_list()))
                if checkRe(name):
                    if name not in found_room.get_list(): #unique player
                        session['room'] = code
                        session['name'] = name
                        return redirect(url_for('lobby'))
                    else:
                        flash("Whoops! that name is already taken!")
                        return redirect(url_for('home'))
                else:
                    flash("Whoops! your name can only have letters and numbers!")

            else:
                flash("Lobby is full!")
        else:
            flash("This room is not accepting players!")
            return redirect(url_for('home'))

    return render_template('home.html')

@app.route('/lobby')
def lobby():

    if session.get('room') and players.query.filter_by(gameCode=session['room']).first():   #authenticate user trying to acess /lobby

        found_room = players.query.filter_by(gameCode=session['room']).first()
        if found_room.isPlaying == 'y': #in the case a user in a game presses the back button
            return redirect(url_for('play'))

        print('name:    ' + session['name'])
        room = session['room']
        return  render_template('lobby.html', roomID=room, name=session['name'])

    else:
        return redirect(url_for('home'))

@app.route('/play')
def play():

    if session.get('room') and players.query.filter_by(gameCode=session['room']).first():   #authenticate user trying to acess /lobby

        found_room = players.query.filter_by(gameCode=session['room']).first()
        if found_room.isPlaying == 'n':    #in the case a user is not in a game
            return redirect(url_for('lobby'))

        print('name:    ' + session['name'])
        plist = players.query.filter_by(gameCode=session['room']).first().get_list()
        players.query.filter_by(gameCode=session['room']).first().isPlaying = 'y'
        db.session.commit()

        plst = []
        idx = plist.index(session['name'])
        for i in range(len(plist)): #to rearrange elemnts in list to make unique for players
            plst.append(plist[idx])
            idx -= 1

        jData = {'players':plst} #serialize data
        print(jData)
        return render_template('play.html', roomID=session['room'], name=session['name'], jData=jData)

    else:
        return redirect(url_for('home'))

@app.route('/getstarted', methods=['GET', 'POST'])
def getstarted():

    if request.method == 'POST':
        if checkRe(request.form['name'].strip(' ')):
            name = request.form['name']
            session['name'] = name
            usedRooms = []
            for player in players.query.all():
                usedRooms.append(player.gameCode)

            rand = randint(100000,999999)
            while rand in usedRooms:
                rand = randint(100000,999999)

            session['room'] = str(rand)

            pData = j.dumps({'playerList':[session['name']]})
            player = players(gameCode=session['room'], playerList= pData, isPlaying='n')
            db.session.add(player)
            db.session.commit()
            return redirect(url_for('lobby'))

        else:
            flash("Whoops! your name can only have letters and numbers!")

    return render_template("getstarted.html", values=players.query.all())

@app.route('/view', methods=['GET', 'POST']) #for testing purposes
def view():
    if request.method == 'POST':
        code = request.form['code']
        pl = request.form['pl']
        player = players(gameCode=code, playerList=pl)
        db.session.add(player)
        db.session.commit()

    return render_template("view.html", values=players.query.all())

if __name__ == '__main__':
    if not is_deploy:
        db.create_all()
    socketio.run(app, debug=True, host='0.0.0.0')


#! /usr/bin/env python

from __future__ import division
import time

# Import the PCA9685 module.
import pwm as pwm_mod

# Uncomment to enable debug output.
#import logging
#logging.basicConfig(level=logging.DEBUG)

# Initialise the PCA9685 using the default address (0x40).
pwm = pwm_mod.PCA9685()

# Alternatively specify a different address and/or bus:
#pwm = Adafruit_PCA9685.PCA9685(address=0x41, busnum=2)

# Configure min and max servo pulse lengths
servo_min = 150  # Min pulse length out of 4096
servo_max = 600  # Max pulse length out of 4096

# Helper function to make setting a servo pulse width simpler.
def set_servo_pulse(channel, pulse):
    pulse_length = 1000000    # 1,000,000 us per second
    pulse_length //= 60       # 60 Hz
    print('{0}us per period'.format(pulse_length))
    pulse_length //= 4096     # 12 bits of resolution
    print('{0}us per bit'.format(pulse_length))
    pulse *= 1000
    pulse //= pulse_length
    pwm.set_pwm(channel, 0, pulse)

def main():
    # Set frequency to 60hz, good for servos.
    pwm.set_pwm_freq(60)

    print('Moving servo on channel 0, press Ctrl-C to quit...')
    while True:
        # Move servo on channel O between extremes.
        pwm.set_pwm(0, 0, servo_min)
        time.sleep(1)
        pwm.set_pwm(0, 0, servo_max)
        time.sleep(1)

if(__mane__ == "__main__"):
    main()


from django.shortcuts import render
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Pokemon
from pokedex.serializers import PokemonSerializer

import io, csv

def pokemon_upload(request):
    template = "pokemon_upload.html"

    prompt = {
        'order' : 'Order of the CSV should be #,Name,Type 1,Type 2,Total,HP,Attack,Defense,Sp. Atk,Sp. Def,Speed,Generation,Legendary'
    }

    if request.method == "GET":
        return render(request, template, prompt)

    checkbox_mapping = {'on': True, 'off': False}
    csv_file = request.FILES['file']
    filters = checkbox_mapping[request.POST.get('filter', default='off')]

    def check_filters(f, l, g):
        """
        Return True if filters=False
        Return False if filter=True and (legendary=True or ghost type=True)
        Return True if filter=True and  (legendary=False and ghost type=False)
        :param f: Bool filter from checkbox
        :param l: Bool legendary
        :param g: Bool Ghost type
        :return: Bool
        """
        if not f:
            return True
        if l:
            return False
        if g:
            return False
        return True

    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'This is not a csv file')

    data_set = csv_file.read().decode('UTF-8')
    io_string = io.StringIO(data_set)
    next(io_string)
    for column in csv.reader(io_string, delimiter=',', quotechar="|"):
        if check_filters(filters, column[12] == 'True', 'Ghost' in {column[2], column[3]}):
            _, created = Pokemon.objects.update_or_create(
                number=column[0],
                name=column[1],
                type_1=column[2],
                type_2=column[3],
                total=column[4],
                hp=int(column[5]) * (1 + 1*filters*('Steel' in {column[2], column[3]})),
                attack=int(column[6]) // (1 + 0.1*filters*('Fire' in {column[2], column[3]})),
                defense=int(column[7]) + filters*column[1].startswith('G')*5*(len(column[1])-1),
                sp_atk=round(int(column[8]) * (1 - 0.1*filters*({'Bug', 'Flying'} == {column[2], column[3]}))),
                sp_def=column[9],
                speed=column[10],
                generation=column[11],
                legendary=column[12],
            )

    context = {}
    return render(request, template, context)

@api_view(['GET'])
def getAll_Pokemons(request):
    PAGE_SIZE = 2
    try:
        pokemon_all = Pokemon.objects.all()
        paginator = Paginator(pokemon_all, PAGE_SIZE)
        print(request.GET)
        page = request.GET.get('page')
        try:
            pokemons = paginator.page(page)
        except PageNotAnInteger:
            pokemons = paginator.page(1)
        except EmptyPage:
            pokemons = paginator.page(paginator.num_pages)
        serializer_context = {'request': request}
        serializer = PokemonSerializer(pokemons, context=serializer_context, many=True)
        return Response(serializer.data)
    except Pokemon.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

@api_view(['GET'])
def hello_world(request):
    return Response('Hello World! v2')


from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    iphone_12_pro_max = p.devices["iPhone 12 Pro Max"]
    browser = p.webkit.launch(headless=False, args=["--start-maximized"])
    context = browser.new_context(**iphone_12_pro_max, locale='zh-CN', timezone_id='Asia/Shanghai')
    page = context.new_page()
    page.goto('https://www.whatismybrowser.com/')
    page.wait_for_load_state(state='networkidle')
    page.screenshot(path='browser-iphone.png')
    browser.close()


import kfp
from typing import Any, Callable, Dict, NamedTuple, Optional, List
from kfp.v2.dsl import (Artifact, Dataset, Input, InputPath, Model, Output,
                        OutputPath, component, Metrics)

@kfp.v2.dsl.component(base_image='python:3.9')
def get_eval_dataset_path_uri(
    project: str,
    eval_bq_dataset: str,
    model_1_table: str,
    model_2_table: str,
) -> NamedTuple('Outputs',[
    ('model_1_bigquery_table_uri', str),
    ('model_2_bigquery_table_uri', str),
    ('eval_bq_dataset', str),
]):

    import json
    import logging

    model_1_table_path_name = f'{project}:{eval_bq_dataset}:eval-{model_1_table}'
    model_2_table_path_name = f'{project}:{eval_bq_dataset}:eval-{model_2_table}'

    logging.info(model_1_table_path_name)
    logging.info(model_2_table_path_name)

    return (
        f'bq://{model_1_table_path_name}',
        f'bq://{model_2_table_path_name}',
        f'{eval_bq_dataset}',
    )


import numpy as np
import cv2
import joblib
from skimage.feature import hog
from skimage import data, exposure

def features_hog(image):
    features = hog(image, orientations=9, pixels_per_cell=(10, 10), cells_per_block=(2, 2), transform_sqrt=True, block_norm="L1")
    return features

def process_image(image):
    test_data = []
    image = cv2.imread(image)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.resize(image, (300, 300))

    image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

    features = features_hog(image)
    test_data.append(features)

    testX = np.array(test_data)

    loaded_model = joblib.load("trained_models/rfc.pkl")
    result = loaded_model.predict(testX)

    return result


from flask import Flask
from flask import render_template
from flask import request
import forms

app = Flask(__name__)

@app.route('/', methods= ['GET', 'POST'])
def index():
    commet_form = forms.CommentForm(request.form)

    if request.method == 'POST':
       print ('commet_form.username.data')
       print ('commet_form.email.data')
       print ('commet_form.comment.data')

    title = "Curso flask"
    return render_template('index.html', title=title, form = commet_form)

if __name__ == '__main__':
    app.run(debug=True, port=8000)


import argparse
import sys
import re
import fcntl
import subprocess
import time
import itertools
from multiprocessing import Pool
from multiprocessing import Lock

parser = argparse.ArgumentParser(description='Get sam entries for each cell barcode.')
parser.add_argument('--cells',
                    '-c',
                    type=str,
                    default='/home/gdrobertslab/mvc002/analyses/roberts/dev/testSnps/output/two_cancers/two_cancers_clusters_cells_S0149.txt',
                    help='list of cell barcodes with no header')
parser.add_argument('--bam',
                    '-b',
                    type=str,
                    default='/home/gdrobertslab/lab/Counts/S0149/possorted_genome_bam.bam',
                    help='bam file output from cellranger')
parser.add_argument('--out_base',
                    '-o',
                    type = str,
                    default = 'test',
                    help='output bam file name')
parser.add_argument('--sam_batch_n',
                    '-n',
                    type = int,
                    default=10000000,
                    help='number of sam entries to process at a time')
parser.add_argument('--verbose',
                    action='store_true',
                    help='print out extra information')
parser.add_argument('--processes',
                    '-p',
                    type = int,
                    default=1,
                    help='number of processes to use for parallel processing')

args = parser.parse_args()

################################################################################
### Global variables
label_dict = {}
chr_list = []
header = []
read_names = []
all_reads = {}
lock = Lock()

################################################################################
### Code

########
### functions

#########
# Process a batch of bam lines to create a dictionary of sam entries for each barcode
def process_lines(chrom):
    lines_dict = {}
    umi_dict = {}
    cmd_list = ['samtools', 'view', args.bam, chrom]
    # check if any reads in range provided by chrom
    if len(subprocess.check_output(cmd_list).\
                    decode("utf-8").\
                    splitlines()) != 0:
        for line in subprocess.check_output(cmd_list).\
                        decode("utf-8").\
                        splitlines():
            line = line.strip()
            if re.compile(r'CB:Z:([ATGC]+-1)').search(line) and \
               re.compile(r'CB:Z:([ATGC]+-1)').search(line).group(1) in label_dict.keys() and \
               re.compile(r'UB:Z:([ATGC]+)').search(line):
                cell_barcode = re.compile(r'CB:Z:([ATGC]+-1)\t').search(line).group(1)
                umi = re.compile(r'UB:Z:([ATGC]+)').\
                                 search(line).\
                                 group(1)
                chr = line.split('\t')[2]
                pos = line.split('\t')[3]
                molecule = \
                    umi + \
                    chr + \
                    pos + \
                    cell_barcode

                cell_label = label_dict.get(cell_barcode)

                # Add barcode to list inside lines_dict
                if cell_label not in lines_dict:
                    lines_dict[cell_label] = []

                # Don't add line if molecule already in umi_dict
                # This gets rid of PCR duplicates
                if molecule not in umi_dict:
                    lines_dict[cell_label].append(line)
                    umi_dict[molecule] = 1

    def print_dict(label):
        nonlocal lines_dict
        while True:
            try:
                with open(args.out_base + label + ".sam", "a") as filehandle:
                    fcntl.flock(filehandle, fcntl.LOCK_EX | fcntl.LOCK_NB)
                    filehandle.writelines('\n'.join(lines_dict.get(label)) + '\n')
                    fcntl.flock(filehandle, fcntl.LOCK_UN)
                    filehandle.close()
                    break
            except IOError:
                print("Error: " + label + " is locked", file = sys.stderr)
                time.sleep(1)
        return

    # Print out the dictionary for each barcode
    with lock:
        junk = [print_dict(label) for label in list(lines_dict.keys())]

    if args.verbose:
        print(chrom + " is done.", file = sys.stderr)

    return

def write_header(label):
    sam_file = open(args.out_base + label + ".sam", "w")
    sam_file.writelines('\n'.join(bam_header) + '\n')
    sam_file.close()

def add_to_label_dict(x):
    cell, label = x.split('\t')
    label_dict[cell] = label

########
# Read in cell barcodes
# This assumes there is no header in barcode file
barcode_file = open(args.cells, 'r')
cell_barcodes = [add_to_label_dict(x.strip()) for x in barcode_file.readlines()]
all_labels = list(set(label_dict.values()))
# check if cell_barcodes is empty
if not cell_barcodes:
    print("Error: cell_barcodes is empty", file = sys.stderr)
    sys.exit(1)

########
# Read in the bam header
cmd_list = ['samtools', 'view', '-H', args.bam]
bam_header = subprocess.\
            check_output(cmd_list).\
            decode("utf-8").\
            splitlines()

# batch_size = 1000000
# Process header to
for line in bam_header:
    if line.startswith(r'@SQ'):
        chr_len = int(re.sub(r'.+\tLN:', '', line.strip()))
        starts = list(range(1, chr_len, args.sam_batch_n))
        stops = [x - 1 for x in starts]
        stops.append(chr_len)
        stops = stops[1:]
        chr_name = re.compile(r'SN:(.+?)\t').search(line).group(1)
        chr_list.extend([i + ":" + str(j) + "-" + str(k) for i, j, k in \
            zip(itertools.repeat(chr_name), starts, stops)])

# Print out length of chr_list
if args.verbose:
    print(str(len(chr_list)) + " chunks to process", file = sys.stderr)

# Print out the header into each output sam file
with Pool(processes = args.processes) as pool:
    output = pool.map(write_header, all_labels)

# For the test of the file:
# Make list of lists of lines to pass to pool.map

with Pool(processes = args.processes) as pool:
    output = pool.map(process_lines, chr_list)

output = list(output)
print(len(output))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 21 15:24:07 2018

@author: henry
"""

Packets = open("Desktop/Project/Flow_Clustering_2nd_attempt/Packets2")
textcon=open("Desktop/Project/Flow_Clustering_2nd_attempt/textcon.txt","w")

# =============================================================================
# lin=Packets.readline()
# line=lin.split('","')
# =============================================================================

i=0
for lin in Packets:
    i+=1
    line=lin.split('","')

    if ('131.243.141.141' in line[2:4])&('208.189.11.184' in line[2:4])&('1525' in line[6]):
        textcon.write(lin)
    if i%100000==0:
        print(i)

Packets.close()
textcon.close()

# =============================================================================
# =============================================================================
# =============================================================================
filename="Desktop/Project/Data/UNSW/1.pcap"
pingpackets = PcapReader(filename)

counter=0
firstlayerprot=[]
seclayerprot=[]
thirdlayerprot=[]
for line in pingpackets:
    counter+=1
    if not (line.name  in firstlayerprot):
        firstlayerprot.append(line.name)
    if not (line.payload.name  in seclayerprot):
        seclayerprot.append(line.payload.name)
    if not (line.payload.payload.name  in thirdlayerprot):
        thirdlayerprot.append(line.payload.payload.name)


statesNeeded = set(["mt", "wa", "or", "id", "nv", "ut" ,"ca", "az"])

stations = {}
stations["kone"] = set(["id", "nv", "ut"])
stations["ktwo"] = set(["wa", "id", "mt"])
stations["kthree"] = set(["or", "nv", "ca"])
stations["kfour"] = set(["nv", "ut"])
stations["kfive"] = set(["ca", "az"])

finalStations = set()

while statesNeeded :
  bestStation = None
  bestStationCovered = set()
  for station, states in stations.items() :
    covered = statesNeeded & states
    if len(covered) > len(bestStationCovered) :
      bestStation = station
      bestStationCovered = covered

  finalStations.add(bestStation)
  statesNeeded -= bestStationCovered

print(finalStations)


import math

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle

R = np.diag([
	0.05,  			# variance of location on x-axis
    	0.05,  			# variance of location on y-axis
    	np.deg2rad(0.5),  	# variance of yaw angle
]) ** 2  			# predict state covariance

R_sqrt = np.diag([
    	0.05,
    	0.05,
    	np.deg2rad(0.5),
])

Q = np.diag([
	0.1,
	0.1,
	np.deg2rad(1.0),
]) ** 2  			# Observation x,y position covariance

Q_sqrt = np.diag([
	0.1,
	0.1,
	np.deg2rad(1.0),
])

DT = 0.1  # time tick [s]
SIM_TIME = 50.0  # simulation time [s]
v = 0.0  # [m/s]
yawrate = 0.0  # [rad/s]
esc_flag = False
features = np.array([[0,1],[3,0],[2,4],[-3,3]])
feature_x = [0,3,2,-3]
feature_y = [1,0,4,3]

show_animation = True

def detection(x):
	n = 0
	for feature in features:
		print("feature")
		print(feature)
		if (feature[0] - x[0, 0])**2 + (feature[1] - x[1, 0])**2 <= 1.0:
			n = n+1
	return n

def calc_input():
    	#v = 1.0  # [m/s]
    	#yawrate = 0.1  # [rad/s]
    	u = np.array([[v], [yawrate]])
    	return u

def observation_model(x):
    	H = np.array([
        	[1, 0, 0],
        	[0, 1, 0],
        	[0, 0, 1],
    	])
    	z = H @ x
    	return z

def motion_model(x, u):
    	F = np.array([[1.0, 0, 0],
		[0, 1.0, 0],
                [0, 0, 1.0]])
    	B = np.array([[DT * math.cos(x[2, 0]), 0],
        	[DT * math.sin(x[2, 0]), 0],
                [0.0, DT]])
    	x = F @ x + B @ u
    	return x

def observation(xTrue, xd, u):
    	xTrue = motion_model(xTrue, u)
    	# add noise to input
    	xd = motion_model(xd, u) + R_sqrt @ np.random.normal(0,1,(3,1))
    	# add noise to gps x-y-theta
    	n = detection(xTrue)
    	z = observation_model(xTrue) + 1.0 / (n+1) * Q_sqrt @ np.random.normal(0,1,(3,1))
    	return xTrue, z, xd, n

def kf_estimation(xEst, PEst, z, u, n):
	#Q_t = 1.0 / (n+1)**2 * Q
	#R_t = abs(u[0,0]) * R
    	#  Predict
	xPred = motion_model(xEst, u)
	PPred = PEst + R
    	#  Update
	if n == 0:
    		xEst = xPred + R_sqrt @ np.random.normal(0,1,(3,1))
    		PEst = PPred
	else:
		K = PPred @ np.linalg.inv(PPred + Q)
		xEst = xPred + K @ (z - xPred)
		PEst = (np.eye(len(xEst)) - K) @ PPred
	return xEst, PEst

def plot_covariance_ellipse(xEst, PEst):  # pragma: no cover
	Pxy = PEst[0:2, 0:2]
	eigval, eigvec = np.linalg.eig(Pxy)

	if eigval[0] >= eigval[1]:
		bigind = 0
		smallind = 1
	else:
		bigind = 1
		smallind = 0

	t = np.arange(0, 2 * math.pi + 0.1, 0.1)
	a = math.sqrt(eigval[bigind])
	b = math.sqrt(eigval[smallind])
	x = [a * math.cos(it) for it in t]
	y = [b * math.sin(it) for it in t]
	angle = math.atan2(eigvec[bigind, 1], eigvec[bigind, 0])
	rot = np.array([[math.cos(angle), math.sin(angle)],
                    [-math.sin(angle), math.cos(angle)]])
	fx = rot @ (np.array([x, y]))
	px = np.array(fx[0, :] + xEst[0, 0]).flatten()
	py = np.array(fx[1, :] + xEst[1, 0]).flatten()
	plt.plot(px, py, "--r")

	t2 = np.arange(0, 2 * math.pi + 0.1, 0.1)
	x2 = [math.cos(it2) for it2 in t2]
	y2 = [math.sin(it2) for it2 in t2]
	fx2 = np.array([x2, y2])
	px2 = np.array(fx2[0, :] + xEst[0, 0]).flatten()
	py2 = np.array(fx2[1, :] + xEst[1, 0]).flatten()
	plt.plot(px2, py2, "--b")

	t3 = np.arange(0, 2 * math.pi + 0.1, 0.1)
	x3 = [0.1 * math.cos(it3) for it3 in t3]
	y3 = [0.1 * math.sin(it3) for it3 in t3]
	fx3 = np.array([x3, y3])
	px3 = np.array(fx3[0, :] + xEst[0, 0]).flatten()
	py3 = np.array(fx3[1, :] + xEst[1, 0]).flatten()
	plt.fill(px3,py3,'y')

def key_event(event):
	global v,yawrate,esc_flag
	if event.key == 'W':
		v += 0.1
	elif event.key == 'S':
		v -= 0.1
	elif event.key == 'A':
		yawrate += 0.3
	elif event.key == 'D':
		yawrate -= 0.3
	elif event.key == 'escape':
		esc_flag = True
	print(event.key)

def main():
	print(__file__ + " start!!")
	time = 0.0

    	# State Vector [x y theta]'
	xEst = np.zeros((3, 1))
	xTrue = np.zeros((3, 1))
	#PEst = np.eye(3)
	PEst = np.zeros((3, 1))
	xDR = np.zeros((3, 1))  # Dead reckoning

	# history
	hxEst = xEst
	hxTrue = xTrue
	hxDR = xTrue
	hz = np.zeros((3, 1))

	while SIM_TIME >= time:
		time += DT
		u = calc_input()
		xTrue, z, xDR, n = observation(xTrue, xDR, u)

		xEst, PEst = kf_estimation(xEst, PEst, z, u, n)
		print("time: " + str(time))
		print("n: " + str(n))
		print("PEst")
		print(PEst)
		'''print("xEst")
		print(xEst)
		print("xTrue")
		print(xTrue)'''

        	# store data history
		hxEst = np.hstack((hxEst, xEst))
		hxDR = np.hstack((hxDR, xDR))
		hxTrue = np.hstack((hxTrue, xTrue))
		hz = np.hstack((hz, z))

		if show_animation and not esc_flag:
			plt.cla()
            		# for stopping simulation with the esc key.
			plt.gcf().canvas.mpl_connect('key_release_event',key_event)
			plt.plot(feature_x, feature_y,"om")
			plt.plot(hxTrue[0, :].flatten(),hxTrue[1, :].flatten(), "-b")
			plt.plot(hxDR[0, :].flatten(),hxDR[1, :].flatten(), "-k")
			plt.plot(hxEst[0, :].flatten(),hxEst[1, :].flatten(), "-r")
			plot_covariance_ellipse(xEst, PEst)
			plt.axis("equal")
			plt.grid(True)
			plt.pause(1)

	print("END!")

if __name__ == '__main__':
	main()


import torch
from net import Student_sr, Student_fu
from option import args
import os
import numpy as np
import numpy
from torch.autograd import Variable
from torchvision import transforms
from imageio import imread, imsave

def load_model():
    fusion_part = Student_fu(args).cuda()
    sr_part = Student_sr(args).cuda()
    model_dir = './checkpoint/2x/fu_srnet.pth.tar'
    checkpoint = torch.load(model_dir)
    fusion_part.load_state_dict(checkpoint['Sec_Fusionnet_state_dict'])
    sr_part.load_state_dict(checkpoint['srnet_state_dict'])

    para_fu = sum([np.prod(list(p.size())) for p in fusion_part.parameters()])
    para_sr = sum([np.prod(list(p.size())) for p in sr_part.parameters()])
    para = para_fu + para_sr

    type_size = 4
    print('Model {} params: {:4f}M'.format("Student_Network", para * type_size / 1000 / 1000))

    fusion_part.eval()
    fusion_part.cuda()
    sr_part.eval()
    sr_part.cuda()

    return fusion_part, sr_part

def _generate_fusion_image(model, img1, img2):
	en_r = model.encoder_i(img1)
	en_v = model.encoder_v(img2)
	f = model.fusion(en_r, en_v)
	img_fusion_fe = model.decoder(f)
	# img_fusion = model.result(img_fusion_fe[0])
	return img_fusion_fe

def _generate_sr_image(model, lr_fusion_image):
    sr_image_fusion = model(lr_fusion_image[0])
    sr_image = sr_image_fusion[0]
    return sr_image

def save_images(path, data):
    if data.shape[0] == 1:
        data = data.reshape([data.shape[1], data.shape[2]])
    imsave(path, data)

def run_demo(fusion_part, sr_part, lr_infrared_path, lr_visible_path, output_path_root, index, mode):
    lr_ir_img = get_test_images(lr_infrared_path, mode=mode)
    lr_vis_img = get_test_images(lr_visible_path, mode=mode)
    if args.cuda:
        lr_ir_img = lr_ir_img.cuda()
        lr_vis_img = lr_vis_img.cuda()

    lr_ir_img = Variable(lr_ir_img, requires_grad=False)
    lr_vis_img = Variable(lr_vis_img, requires_grad=False)

    img_fusion = _generate_fusion_image(fusion_part, lr_ir_img, lr_vis_img)

    sr_image_fusion = _generate_sr_image(sr_part, img_fusion)
    sr_image_fusion = torch.squeeze(sr_image_fusion)
    sr_image_fusion = sr_image_fusion.cpu().mul_(255).numpy()

    file_name = str(index) + '.png'
    output_path = output_path_root + file_name
    save_images(output_path, sr_image_fusion)
    print(output_path)

def get_test_images(paths,  mode='L'):
	ImageToTensor = transforms.Compose([transforms.ToTensor()])
	if isinstance(paths, str):
		paths = [paths]
	images = []
	for path in paths:
		image = imread(path)
		if mode == 'L':
			image = np.reshape(image, [1, image.shape[0], image.shape[1]])
			amin, amax = image.min(), image.max()  #
			image = (image - amin) / (amax - amin)
		else:
			image = ImageToTensor(image).float().numpy()*255
	images.append(image)
	images = np.stack(images, axis=0)
	images = torch.from_numpy(images).float()
	return images

def main():
    test_path_lr = "./sourceimages/2x/"
    output_path = './outputs/2x/'
    if os.path.exists(output_path) is False:
        os.mkdir(output_path)
    mode = "L"
    with torch.no_grad():
        model = load_model()
        fusion_part = model[0]
        sr_part = model[1]
        for i in range(0,6):
            index = i + 1
            lr_infrared_path = test_path_lr + 'IR' + str(index) + '.png'
            lr_visible_path = test_path_lr + 'VIS' + str(index) + '.png'
            run_demo(fusion_part, sr_part, lr_infrared_path, lr_visible_path, output_path, index, mode)

    print('Done......')

if __name__ == '__main__':
    main()


import pandas as pd
import numpy as np

def p1(df):
    """
        主卖或主买大单量占比 大于0.3
    Parameters
    ------
      df:
    return
    -------
      None
    """
    r = []

    df_s = df[df['主卖大单量占比']>0.3]
    for i, row in df_s.iterrows():
        r.append(row['日期'] + ' 主卖大单量占比： ' + str(row['主卖大单量占比']))

    df_b = df[df['主买大单量占比']>0.3]
    for i, row in df_b.iterrows():
        r.append(row['日期'] + '                          主买大单量占比： ' + str(row['主买大单量占比']))

    return r

def p2(df):
    """
        委托笔比 绝对值大于2
    Parameters
    ------
      df:
    return
    -------
      None
    """
    r = []

    df1 = df[(df['委托笔比']>2) | (df['委托笔比']<-2)]
    for i, row in df1.iterrows():
        r.append(row['日期'] + ' 委托笔比： ' + str(row['委托笔比']))
    return r

def level2_pattern(df):
    '''
    输入：
        df：
    '''

    r =[]

    r += p1(df)
    r += p2(df)

    return r

if __name__ == "__main__":
    codes = ['300408','002273','002570','300433','300461','600776','300461','300602','002792',
             '002859','300136','300502','002341','002454','002475','300134','300693',
             '300394','300036']

    for code in codes:
        df = pd.read_excel('leaf\\'+ code + '_2019-01_leaf.xlsx')
        items = level2_pattern(df)
        for item in items:
            print(code,item)