from yaml import load
from icalendar import *
import pytz, datetime, re

link = re.compile(r'\[([^\]]*)\]\(([^\)]*)\)')
def deMd(s):
    return link.sub(r'\1 (\2)', s.replace('`', ''))

try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

def fixworking():
    """change to this script's directory as the working directory"""
    import os, os.path
    os.chdir(os.path.realpath(os.path.dirname(__file__)))

eastern = pytz.timezone('America/New_York')

class RealCal:
    def __init__(self, name):
        self.name = name
        self.cal = Calendar()
        self.cal.add('prodid', '-//University of Virginia//'+name+'//EN')
        self.cal.add('calscale', 'GREGORIAN')
        self.cal.add('version', '2.0')
        self.cal.add('name', name)
    def event(self, name, start, duration=None, location=None, end=None, details=None):
        e = Event()
        e.add('dtstamp', datetime.datetime.now(tz=eastern))
        e.add('uid', name+start.isoformat()[:20].rstrip('0:T-'))
        e.add('dtstart', start)
        if end is not None: e.add('dtend', end)
        elif duration is not None: e.add('dtend', start+duration)
        e.add('summary', name)
        if location is not None: e.add('location', location)
        if details is not None: e.add('description', details)
        self.cal.add_component(e)
    def __str__(self):
        return self.cal.to_ical().decode('utf-8').replace('\r\n','\n').strip()
    def bytes(self):
        return self.cal.to_ical()

try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

def calendar(data):
    ans = RealCal('cs1110.s2018')

    m50 = datetime.timedelta(0, 50*60)
    m75 = datetime.timedelta(0, 75*60)
    m180 = datetime.timedelta(0, 180*60)
    m5 = datetime.timedelta(0, 5*60)

    breaks = []
    exams = {}
    for k,v in data['Special Dates'].items():
        if 'recess' in k or 'break' in k or 'Reading' in k:
            if type(v) is dict: breaks.append((v['start'], v['end']))
            else: breaks.append((v, v))
        elif 'xam' in k:
            exams[v] = k

    oneday = datetime.timedelta(1)
    d = data['Special Dates']['Courses begin']
    classnum = 0
    while d < data['Special Dates']['Courses end']:
        if not any(d >= b[0] and d <= b[1] for b in breaks):
            if d.weekday() in (0,2,4):
                sec001 = datetime.datetime(d.year, d.month, d.day, 14, 0, 0, tzinfo=eastern)
                sec002 = datetime.datetime(d.year, d.month, d.day, 12, 0, 0, tzinfo=eastern)
                sec003 = datetime.datetime(d.year, d.month, d.day, 10, 0, 0, tzinfo=eastern)
                sec004 = datetime.datetime(d.year, d.month, d.day, 11, 0, 0, tzinfo=eastern)
                topic = exams.get(d, data['classes'][classnum])
                if topic in data['reading']: topic = deMd(topic) + '\r\nSee '+deMd(' and '.join(data['reading'][topic])) +' for more'
                else: topic = deMd(topic)
                if d not in exams: classnum += 1

                ans.event('1110-001', sec001, m50, location='WIL 402', details=topic)
                ans.event('1110-002', sec002, m50, location='RICE 130', details=topic)
                ans.event('1110-003', sec003, m50, location='RICE 130', details=topic)
                ans.event('1110-004', sec004, m50, location='RICE 130', details=topic)
                if d.weekday() != 4:
                    ans.event('1111', sec001, m75, location='CLRK 108')
            if d.weekday() == 3:
                ans.event('Lab 101', datetime.datetime(d.year, d.month, d.day, 12, 30, 0, tzinfo=eastern), m75, location='OLS 001')
                ans.event('Lab 102', datetime.datetime(d.year, d.month, d.day, 9, 30, 0, tzinfo=eastern), m75, location='OLS 009')
                ans.event('Lab 103', datetime.datetime(d.year, d.month, d.day, 11, 0, 0, tzinfo=eastern), m75, location='OLS 001')
                ans.event('Lab 104', datetime.datetime(d.year, d.month, d.day, 14, 0, 0, tzinfo=eastern), m75, location='OLS 009')
                ans.event('Lab 105', datetime.datetime(d.year, d.month, d.day, 15, 30, 0, tzinfo=eastern), m75, location='OLS 009')
                ans.event('Lab 106', datetime.datetime(d.year, d.month, d.day, 17, 0, 0, tzinfo=eastern), m75, location='OLS 009')
                ans.event('Lab 107', datetime.datetime(d.year, d.month, d.day, 18, 30, 0, tzinfo=eastern), m75, location='OLS 009')
                ans.event('Lab 108', datetime.datetime(d.year, d.month, d.day, 20, 0, 0, tzinfo=eastern), m75, location='OLS 001')
                ans.event('Lab 109', datetime.datetime(d.year, d.month, d.day, 12, 30, 0, tzinfo=eastern), m75, location='MEC 213')
                ans.event('Lab 110', datetime.datetime(d.year, d.month, d.day, 15, 30, 0, tzinfo=eastern), m75, location='MEC 213')
                ans.event('Lab 113', datetime.datetime(d.year, d.month, d.day, 8, 0, 0, tzinfo=eastern), m75, location='OLS 001')
        d += oneday

    e3 = data['Special Dates']['Exam 3']
    ans.event('Final Exam', datetime.datetime(e3.year, e3.month, e3.day, 19, 00, 0, tzinfo=eastern), m180, location='TBA')

    for a,v in data['assignments'].items():
        if a.lower().startswith('lab') or v.get('group','').lower() == 'lab': continue
        if 'due' not in v: continue
        d = v['due']
        if not isinstance(d, datetime.datetime):
            d = datetime.datetime(d.year, d.month, d.day, 23 if v.get('group') == 'project' else 9, 55, 0, tzinfo=eastern)
            ans.event(a+' due', d, m5)

    return ans

if __name__ == '__main__':
    fixworking()
    with open('markdown/cal.yaml') as stream:
        data = load(stream, Loader=Loader)
    cal = calendar(data)
    with open('markdown/cal.ics', 'wb') as f:
        f.write(cal.bytes())


from vk_bot import command_system

def info():
    """функция для формирования списка с командами"""
    message = ''
    for c in command_system.command_list:
        message += c.keys[0] + ' - ' + c.description + '\n'
    return message, ''

info_command = command_system.Command()

info_command.keys = ['помощь']
info_command.description = 'покажу список команд'
info_command.process = info


#!/usr/bin/env python3
import docker
import schedule
import time
import datetime
import logging
import container
import image
import defaults
from logger import set_logger

api_client = docker.APIClient(base_url=defaults.LOCAL_UNIX_SOCKET)

def main():
    if not container.running():
        logging.info('No containers are running')
    else:
        for running_container in container.to_monitor():
            current_image = api_client.inspect_image(running_container['Config']['Image'])
            try:
                latest_image = image.pull_latest(current_image)
            except docker.errors.APIError as e:
                logging.error(e)
                continue
            # If current running container is running latest image
            if not image.is_up_to_date(current_image['Id'], latest_image['Id']):
                logging.info(('{} will be updated').format(container.get_name(running_container)))
                # new container object to create new container from
                new_config = container.NewContainerProperties(running_container, latest_image['RepoTags'][0])
                container.stop(running_container)
                container.remove(running_container)
                new_container = container.create_new_container(new_config.__dict__)
                container.start(new_container)
                image.remove(current_image)
        logging.info('All containers up to date')

if __name__ == "__main__":
    set_logger('debug')
    schedule.every(defaults.INTERVAL).seconds.do(main)
    while True:
        schedule.run_pending()
        time.sleep(defaults.INTERVAL - 5)


import json
from nullroute.core import Core
import time
import urllib.parse
import urllib.request

class OAuth2Client():
    def __init__(self, client_id,
                       client_secret=None,
                       discovery_url=None,
                       authorization_url=None,
                       token_grant_url=None):
        self.client_id = client_id
        self.client_secret = client_secret
        self.discovery_url = discovery_url
        self.authorization_url = authorization_url
        self.token_grant_url = token_grant_url
        self.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"

    def _discover_endpoints(self):
        if not self.discovery_url:
            raise ValueError("either discovery URL or endpoint URLs must be specified")
        Core.debug("fetching discovery document %r", self.discovery_url)
        response = urllib.request.urlopen(self.discovery_url).read()
        response = json.loads(response)
        Core.debug("response data: %r", response)
        if not self.authorization_url:
            self.authorization_url = response["authorization_endpoint"]
        if not self.token_grant_url:
            self.token_grant_url = response["token_endpoint"]

    def make_authorization_url(self, scope):
        if not self.authorization_url:
            self._discover_endpoints()
        params = {"client_id": self.client_id,
                  "response_type": "code",
                  "redirect_uri": self.redirect_uri,
                  "scope": scope}
        # # See OAUTH 5.1 for a definition of which characters need to be escaped
        params = urllib.parse.urlencode(params,
                                        quote_via=urllib.parse.quote,
                                        safe="~-._")
        return "%s?%s" % (self.authorization_url, params)

    def _grant_token(self, params):
        if not self.token_grant_url:
            self._discover_endpoints()
        Core.debug("token grant URL: %r", self.token_grant_url)
        post_data = {"client_id": self.client_id,
                     "client_secret": self.client_secret,
                     **params}
        Core.debug("request data: %r", post_data)
        post_data = urllib.parse.urlencode(post_data).encode()
        Core.debug("encoded data: %r", post_data)
        response = urllib.request.urlopen(self.token_grant_url, post_data).read()
        response = json.loads(response)
        response.setdefault("expires_at", int(time.time() + response["expires_in"]))
        return response

    def grant_token_via_authorization(self, authorization_code):
        return self._grant_token({"grant_type": "authorization_code",
                                  "code": authorization_code,
                                  "redirect_uri": self.redirect_uri})

    def grant_token_via_refresh(self, refresh_token):
        return self._grant_token({"grant_type": "refresh_token",
                                  "refresh_token": refresh_token})


# 1)
for i in range(1, 151):
    c = (5/9)*(i-32)
    print(f'{i}°F = {c:.2f}°C')

#2)
seq = ['ATCDLASKWNWNHTLCAAHCIARRYRGGYCNSKAVCVCRN'], ['TATTAACCGGGTTTAAACTAGCATGCATGATTAACCAGTACATCTTTT'], ['ATCBDLASKWXWNHTLCAAHCIARRYRGGYCNSJAVCVCRN']
DNA = {'A', 'C', 'G', 'T'}
RNA = {'A', 'C', 'G', 'U'}
PROTEINA = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y'}

#3)
seqDNA = 'TATTAACCGGGTTTAAACTAGCATGCATGATTAACCAGTACATCTTTT'
lista = []

for i in seqDNA:
    if i == 'T':
        lista.append('A')
    elif i == 'A':
        lista.append('U')
    elif i == 'C':
        lista.append('G')
    elif i == 'G':
        lista.append('C')

seqRNA = ''.join(lista)
print(seqRNA)

#4)
n = int(input('Insira um número: '))
fatorial = n

print(n)

while n > 1:
    fatorial = (fatorial * (n-1))
    n = n-1

print(fatorial)

#5)
n = 1

while n <= 15:
    for i in range(1, 11):
        result = n*i
        print(f'{n} x {i} = {result}')

    print()
    n += 1

#6)
seq = 'VRSSSRTPSDKPVAHVVANPQAEGQLQWLNRRANALLANGVELRDNQLVVPSEGLYLIYSQVLFKGQGCPSTHVLLTHTISRIAVSYQTKVNLLSAIKSPCQRETPEGAEAKPWYEPIYLGGVFQLEKGDRLSAEINRPDYLLFAESGQVYFGIIAL'
massa = {'A':71.03711, 'C':103.00919, 'D':115.02694, 'E':129.04259, 'F':147.06841, 'G':57.02146, 'H':137.05891, 'I':113.08406, 'K':128.09496,
          'L':113.08406, 'M':131.04049, 'N':114.04293, 'P':97.05276, 'Q':128.05858, 'R':156.10111, 'S':87.03203, 'T':101.04768, 'V':99.06841, 'W':186.07931, 'Y':163.06333}
m = 0

for a in seq:
    m += massa[a]
print(m)

#7)


#Segregation Simulation

from drawingpanel import *
from random import *

#constants
GRID_SIZE = 50
AGENT_ONE = 40
AGENT_TWO = 35
PERCENTAGE = 80
SPEED = 2

def main(): #creates a list of list with agents and simulates until all agents are satisfied
    grid = []
    create_grid(GRID_SIZE, grid)
    p = DrawingPanel(GRID_SIZE * 10,GRID_SIZE * 10, background='white')
    are_satisfy(grid, p)
    while (not are_satisfy(grid,p)): #while not false it will keep iterating
        are_satisfy(grid, p)
        visual (grid, p)
        p.sleep(SPEED)

def create_grid(GRID_SIZE, grid): #creates a list of lists
    for y in range (GRID_SIZE):
        row = [0] * GRID_SIZE
        for x in range (GRID_SIZE):
            number = randint(1,100)
            if (number <= AGENT_ONE):
                row[x] = 1
            elif (number > AGENT_ONE and number <= AGENT_ONE + AGENT_TWO):
                row[x] = 2
        grid.append(row)

def are_satisfy(grid, p): #checks each agent if they are satisfied, if check_neighbor returns true then move the agent and returns a boolean
    temp = True
    for row in range (0, len(grid)):
        for col in range (0, len(grid[row])):
            if check_neighbors(row, col, grid, p):
                temp = False
                move_agent(row, col, grid, p)
    return temp

def check_neighbors(row, col, grid, p): #checks the agents around the point and calls to is_valid helper function
    same_agents = 0
    diff_agents = 0
    #roffset and coffset check all values around the agent
    for roffset in range (-1, 2):
        for coffset in range (-1, 2):
            offset_row = row + roffset
            offset_col = col + coffset
            if (is_valid(offset_row, offset_col)):#if it is a valid point then start counting the agents around it
                if ((row, col) == (offset_row, offset_col) and grid[row][col] != 0):#if row, col are the same as offset_row, offset_col then nothing is added so it doesnt check itself
                    same_agents += 0
                    diff_agents += 0
                elif (grid[row][col] == grid[offset_row][offset_col] and grid[row][col] != 0):
                    same_agents += 1
                elif (grid[row][col] != grid[offset_row][offset_col] and grid[offset_row][offset_col] != 0 and grid[row][col] != 0):
                    diff_agents += 1
    total = same_agents + diff_agents
    return (total != 0 and ((same_agents / total) * 100) < PERCENTAGE) #if agent is unsatisfied, return a true boolean for check_neighbors

def is_valid(offset_row, offset_col): #helper function determines if the points in (offset_row, offset_col) are valid
    return (offset_row >= 0 and offset_row < GRID_SIZE and offset_col >= 0 and offset_col < GRID_SIZE)

def move_agent(row, col, grid, p): #moves agent to a random blank spot, each time this helper function runs, the panel updates
    random_row = randint(0, GRID_SIZE - 1)
    random_col = randint(0, GRID_SIZE - 1)
    while (grid[random_row][random_col] != 0):
        random_row = randint(0, GRID_SIZE - 1)
        random_col = randint(0, GRID_SIZE - 1)
    grid[random_row][random_col] = grid[row][col]
    grid[row][col] = 0

def visual(grid, p): #outputs drawing panel of the initial list
    for i in range (1, GRID_SIZE):
        p.canvas.create_line (i * 10, GRID_SIZE * 10, i * 10, 0)
    for j in range (1, GRID_SIZE):
        p.canvas.create_line (0, j * 10, GRID_SIZE * 10, j * 10)
    for row in range (0, len(grid)):
        for col in range (0, len(grid[row])):
            if (grid[row][col] == 1):
                p.canvas.create_rectangle(row * 10, col * 10, (row + 1) * 10, (col + 1) * 10, fill= "red")
            elif (grid[row][col] == 2):
                p.canvas.create_rectangle(row * 10, col * 10, (row + 1) * 10, (col + 1) * 10, fill= "blue")
            else:
                p.canvas.create_rectangle(row * 10, col * 10, (row + 1) * 10, (col + 1) * 10, fill= "white")
main()


# coding: utf-8
from blueboss import common as bc
import plugin

def _get(decl_or_type):
    is_const = decl_or_type.isConstQualified
    if isinstance(decl_or_type, bc.ElaboratedType):
        decl_or_type = decl_or_type.namedType
        is_const = is_const | decl_or_type.isConstQualified
    decl_or_type = decl_or_type.decl.underlyingType
    is_const = decl_or_type.isConstQualified
    return decl_or_type, is_const

class TypedefPlugin(plugin.Plugin):
    def resolveFilter(self, decl_or_type):
        if isinstance(decl_or_type, bc.ElaboratedType):
            decl_or_type = decl_or_type.namedType
        if isinstance(decl_or_type, bc.TypedefType):
            return True

    def resolveClass(self, decl_or_type):
        return self.creator.resolveClass(_get(decl_or_type)[0])

    def getArgConverter(self, arg_decl, func_decl):
        cxx_type = arg_decl.type
        is_l = False
        is_c = cxx_type.isConstQualified
        if isinstance(cxx_type, bc.LValueReferenceType):
            cxx_type = cxx_type.pointeeType
            is_l = True
            is_c = is_c or cxx_type.isConstQualified
        if isinstance(cxx_type, bc.ElaboratedType):
            cxx_type = cxx_type.namedType
            is_c = is_c or cxx_type.isConstQualified
        # print arg_decl, isinstance(
        # arg_decl.type, bc.TypedefType), type(arg_decl.type)
        if not isinstance(cxx_type, bc.TypedefType):
            return

        if is_l:
            t, c = _get(cxx_type)
            t = t.shallowCopy()
            t.isConstQualified = t.isConstQualified or is_c or c
            cxx_type = bc.LValueReferenceType(t)
        else:
            t, c = _get(cxx_type)
            t = t.shallowCopy()
            t.isConstQualified = t.isConstQualified or is_c or c
            cxx_type = t

        arg_decl = bc.ParmVarDecl(arg_decl.name,
                                  cxx_type,
                                  hasDefaultArg=arg_decl.hasDefaultArg)
        return self.creator.getArgConverter(arg_decl, func_decl)

    def getReturnConverter(self, ret_type, func_decl):
        is_c = False
        if isinstance(ret_type, bc.ElaboratedType):
            ret_type = ret_type.namedType
            is_c = ret_type.isConstQualified
        if not isinstance(ret_type, bc.TypedefType):
            return
        t, c = _get(ret_type)
        t = t.shallowCopy()
        t.isConstQualified = t.isConstQualified or is_c or c
        return self.creator.getReturnConverter(t, func_decl)


import os
import cv2 as cv
import numpy as np

class IdentifyFace:
    def __init__(self, photo):
        self.photo = photo

    def detect_face(self):
        with open(os.path.dirname(os.path.abspath(__file__)) + self.photo, 'rb') as in_memory_photo:
            face_cascade = cv.CascadeClassifier(cv.__path__[0] + "/data/haarcascade_frontalface_default.xml")
            in_memory_photo = in_memory_photo.read()
            nparr = np.frombuffer(in_memory_photo, np.uint8)
            img = cv.imdecode(nparr, 4)
            gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
            faces = face_cascade.detectMultiScale(gray, 1.3, 5)
            if len(faces) > 0:
                return 'Лицо на фото обнаружено'
            else:
                return 'Лицо на фото не обнаружено'

if __name__ == "__main__":
    x = IdentifyFace('\panda.jpg')
    print(x.detect_face())


from data_structure.data_stream import data_stream as data_stream
from method.Preprocessing.binning import binning as binning
from method.change_de.CANDAR2020.baseline_cheb import chebyshev_base as chebyshev_base
from statistics import mean

dic = {}
bin_period = 10
types = ["hinet"]
patterns = ["si"]
LS = [1,5]
IS = [100,1000]
for type in types:
    for pattern in patterns:
        for L in LS:
            for I in IS:
                # data = data_stream(path='C:\\Users\\karnk\\git\\data_stream\\dataset', type=type, pattern=pattern, len=L,
                #                  interval=I)
                data = data_stream(path='D:\\git_project\\data stream\\dataset', type=type, pattern=pattern, len=L,
                                 interval=I)
                data.load_data_fromfile()

                # binning process
                cheb = chebyshev_base(min_size=500,k=3)
                change_points = []
                for i in range(data.get_file_lenght()):
                    file_name = data.get_file_name(i)
                    instances = data.get_dataset_test(i)
                    bin = binning(bin_period=bin_period)

                    for index, instance in enumerate(instances):
                        is_change = False
                        can_add_bin = bin.can_add_bin()
                        if can_add_bin:
                            bin.add_instance(instance)
                        else:
                            mean_bin = mean(bin.get_bin())
                            is_change = cheb.add_element(mean_bin)
                            bin.reset_bin()

                        if is_change:
                            change_points.append(index)

                data.set_change_points(change_points)
                print("### end change detection##")

                # print(change_points)
                result_name = '{}_W{}_L{}'.format(type, L, I)

                key_dict = "{}_L{}_I_{}".format(pattern, L, I)
                dic[key_dict] = data
                # data.save_result_to_csv(dataset_index=0, threshold_after=100, L=L, I=I, Algorithm="Binning Cheb",
                #                         Dataset_type=type, pattern=pattern)

choice = ""
while choice != "exit":
    # try:
        pattern_in = input("Input pattern {} : ".format(patterns))
        L_in = input("Input Len {} : ".format(LS))
        I_in = input("Input Interval {} : ".format(IS))
        input_format = "{}_L{}_I_{}".format(pattern_in,L_in,I_in)
        element = dic.get(input_format)
        index_tran_in = input("Input index tran pattern 0-{}: ".format(element.get_len_tran()-1))
        element.plot_tran(index_tran_in)
    # except:
    #     print("reinput")


from flask import Flask
from flask import render_template
from flask import request
import p1_loadData as data
import p4_commonRating as commonR
import p5_similarityDegree as simiDeg
import p6_mostSimilarityUsers as simiUsers
import p7_recommendMovies as recMovies
import pandas as pd

app = Flask(__name__)

#公共数据，保存原始数据
ratingsData = pd.DataFrame()
movieData = pd.DataFrame()
usersData = pd.DataFrame()

#web根目录
@app.route('/')
def index():
    return render_template("index.html",Data = {"index":-1,"movieData":"","usersData":"","ratingsData":""})

#获取源数据路由
@app.route('/getData',methods = ['POST'])
def getData():

    global ratingsData,movieData,usersData
    if movieData.empty:
        movieData = data.getSourceData("movieData")
    if usersData.empty:
        usersData = data.getSourceData("usersData")
    if ratingsData.empty:
        ratingsData = data.getSourceData("ratingsData")
    sourceData = {"movieData":movieData,"usersData":usersData,"ratingsData":ratingsData}

    return render_template("Q1.resourceData.html",Data = sourceData)

#获取输入面板
@app.route('/getInputPage',methods = ['POST'])
def getInputPage():
    index = int(request.form.get("index", 2))

    if index==1:
        return render_template("Q3.answer.html")
    elif index==2:
        return render_template("Q4.commonR.html")
    elif index==3:
        return render_template("Q5.simiDeg.html")
    elif index==4:
        return render_template("Q6.fiveUsers.html")
    else:
        return render_template("Q7.recMovies.html")

#第四问路由接口
@app.route('/getQ4Ans',methods = ['POST'])
def getQ4Ans():
    global ratingsData
    users = request.form.get("val","0 1")
    users = [int(u) for u in users.split(" ")]
    if ratingsData.empty:
        ratingsData = data.getSourceData("ratingsData")

    commR = commonR.getCommonRating(users[0],users[1],ratingsData)
    return render_template("Q4.answer.html",commR=commR)

#第五问路由接口
@app.route('/getQ5Ans',methods = ['POST'])
def getQ5Ans():
    global ratingsData
    users = request.form.get("val", "0 1")
    users = [int(u) for u in users.split(" ")]
    if ratingsData.empty:
        ratingsData = data.getSourceData("ratingsData")

    simiD = simiDeg.getSimiDeg(users[0],users[1],ratingsData)

    return render_template("Q5.answer.html", simiD=simiD)

#第六问路由接口
@app.route('/getQ6Ans',methods = ['POST'])
def getQ6Ans():
    global ratingsData
    user = request.form.get("val", "0")
    user = int(user)
    if ratingsData.empty:
        ratingsData = data.getSourceData("ratingsData")

    fiveUsers = simiUsers.getMostSimilarUsers(user,5,ratingsData)

    return render_template("Q6.answer.html", fiveUsers=fiveUsers)

#第七问路由接口
@app.route('/getQ7Ans',methods = ['POST'])
def getQ7Ans():
    global ratingsData
    user = request.form.get("val", "0")
    user = int(user)
    if ratingsData.empty:
        ratingsData = data.getSourceData("ratingsData")

    movies = recMovies.getRecommendMovies(user)

    return render_template("Q7.answer.html", movies=movies)

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


# -*- coding: utf-8 -*-
import keras.backend as K
from keras import  activations
from keras.regularizers import l2
from keras.engine import Layer

from keras.initializers import glorot_uniform, orthogonal, zeros
import numpy as np
import theano as T
import theano.tensor as TS
from theano.ifelse import ifelse
from theano.printing import Print
from Encoder_Base import Encoder_Base

class Encoder_Processor(Encoder_Base):
    def __init__(self, **kwargs):
        super(Encoder_Processor, self).__init__(**kwargs)

    def compute_mask(self, input, input_mask=None):
        return None

    def compute_output_shape(self, input_shape):
        return (input_shape[0][0], self.hidden_dim)

    def call(self, input, mask=None):
        x = input[0]

        # Keras doesn't allow 1D model inputs - so that tensor have shape (1,1) instead of scalar or (1,)
        bucket_size = input[1][0][0]

        data_mask = mask[0]
        if data_mask.ndim == x.ndim-1:
            data_mask = K.expand_dims(data_mask)
        assert data_mask.ndim == x.ndim
        data_mask = data_mask.dimshuffle([1,0])
        data_mask = data_mask[:bucket_size]

        x = K.dot(x, self.W_emb) + self.b_emb
        x = x.dimshuffle([1,0,2])
        x = x[:bucket_size]

        initial_depth = K.zeros((1,), dtype="int8")

        #x = Print("x")(x)
        #data_mask = Print("data_mask")(data_mask)

        results, _ = T.scan(self.vertical_step,
                        outputs_info=[x, data_mask, data_mask, initial_depth],
                        non_sequences=[bucket_size],
                        n_steps=self.depth-1)
        outputs = results[0][-1][-1]

        return outputs

    def vertical_step(self, x, x_mask, prev_has_value, prev_depth, bucket_size):

        initial_h = K.zeros((self.batch_size, self.hidden_dim), name="initial_h")
        initial_new_mask = K.ones((self.batch_size), dtype="bool", name="initial_new_mask")
        initial_has_value = K.zeros((self.batch_size), dtype="bool")
        initial_had_both_on_current_lebel = K.zeros((self.batch_size), dtype="bool")
        last_value_mask = TS.concatenate([TS.zeros_like(x_mask, dtype="int8")[:-1], TS.ones_like(x_mask, dtype="int8")[0:1]], axis=0)
        next_x = K.concatenate([x[1:], K.zeros_like(x[0:1])], axis=0)

        results, _ = T.scan(self.horizontal_step,
                            sequences=[x, next_x, x_mask, prev_has_value, last_value_mask],
                            outputs_info=[initial_h, initial_new_mask, initial_has_value, initial_had_both_on_current_lebel])
        new_h = results[0]
        new_mask = results[1]
        has_value = results[2]

        new_mask = TS.concatenate([new_mask[1:], K.ones((1, self.batch_size), dtype="bool")], axis=0)
        depth = TS.cast(prev_depth+1, dtype="int8")

        return [new_h, new_mask, has_value, depth], T.scan_module.until(TS.eq(TS.sum(new_mask*has_value), self.batch_size))

    def horizontal_step(self, x, next_x, prev_mask, prev_has_value, last_value_mask, h_tm1, new_mask_tm1, has_value_tm1, had_both_on_current_level_tm1):

        if 0 < self.dropout_u < 1:
            ones = K.ones((self.inner_dim))
            B_U = K.in_train_phase(K.dropout(ones, self.dropout_u), ones)
        else:
            B_U = K.cast_to_floatx(1.)
        if 0 < self.dropout_w < 1:
            ones = K.ones((self.inner_dim))
            B_W = K.in_train_phase(K.dropout(ones, self.dropout_w), ones)
        else:
            B_W = K.cast_to_floatx(1.)
        if 0 < self.dropout_w < 1:
            ones = K.ones((self.inner_dim))
            B_V = K.in_train_phase(K.dropout(ones, self.dropout_w), ones)
        else:
            B_V = K.cast_to_floatx(1.)
        if 0 < self.dropout_action < 1:
            ones = K.ones((self.action_dim))
            B_action = K.in_train_phase(K.dropout(ones, self.dropout_action), ones)
        else:
            B_action = K.cast_to_floatx(1.)
        if 0 < self.dropout_w < 1:
            ones = K.ones((self.hidden_dim))
            B_W1 = K.in_train_phase(K.dropout(ones, self.dropout_w), ones)
        else:
            B_W1 = K.cast_to_floatx(1.)

        policy = activations.relu(K.dot(x*B_W, self.W_action_1) + K.dot(next_x*B_V, self.V_action_1) + K.dot(h_tm1*B_U, self.U_action_1) + self.b_action_1)
        policy = K.exp(K.minimum(K.dot(policy*B_action, self.W_action_3)+self.b_action_3, 5))

        # 1 = reduce, 0 = continue acc
        new_mask = K.switch(TS.le(policy[:,0], policy[:, 1]), 1, 0)
        new_mask = prev_mask*prev_has_value*new_mask
        new_mask = K.switch(last_value_mask*(1-had_both_on_current_level_tm1), 0, new_mask)
        new_mask = TS.cast(new_mask, "bool")

        #prev_mask = Print("prev_mask")(prev_mask)
        #prev_has_value = Print("prev_has_value")(prev_has_value)
        #new_mask = Print("new_mask")(new_mask)
        #has_value_tm1 = Print("has_value_tm1")(has_value_tm1)

        both = prev_mask*prev_has_value*(1-new_mask)*has_value_tm1
        x_only = prev_mask*prev_has_value*(new_mask + (1-new_mask)*(1-has_value_tm1))
        h_only = (1-prev_mask + prev_mask*(1-prev_has_value))*(1-new_mask)*has_value_tm1

        #both = Print("both")(both)
        #x_only = Print("x_only")(x_only)
        #h_only = Print("h_only")(h_only)

        has_value = both + x_only + h_only
        has_value = TS.cast(has_value, "bool")

        both_for_h = both.dimshuffle([0,'x'])
        both_for_h = TS.extra_ops.repeat(both_for_h, self.hidden_dim, axis=1)
        x_only_for_h = x_only.dimshuffle([0,'x'])
        x_only_for_h = TS.extra_ops.repeat(x_only_for_h, self.hidden_dim, axis=1)
        h_only_for_h = h_only.dimshuffle([0,'x'])
        h_only_for_h = TS.extra_ops.repeat(h_only_for_h, self.hidden_dim, axis=1)

        h_ = self.gru_step(x, h_tm1,B_W,B_U,B_W1,self.W, self.U, self.b, self.inner_dim)
        h = both_for_h*h_ + x_only_for_h*x + h_only_for_h*h_tm1

        both = TS.cast(both, "bool")

        had_both_on_current_level = TS.or_(both, had_both_on_current_level_tm1)

        return h, new_mask, has_value, had_both_on_current_level

    def get_config(self):
        base_config = super(Encoder_Processor, self).get_config()
        return base_config.items()


# -*- coding: utf-8 -*-
import Mygui,os
import calendar
import datetime
from math import floor
from PyQt5.QtWidgets import QMainWindow,QTableWidgetItem,QColorDialog,QHeaderView,QAbstractItemView,QFrame,QApplication,QLineEdit,QMessageBox,QStyleFactory
from PyQt5.QtCore import Qt,QDate,QSize # 导入相应的包
from PyQt5.QtGui import QColor,QFont,QIcon,QPixmap,QKeyEvent
from Mysqlite import ReadSqlite,ReadSqliteDayColor,WriteSqlite,DeleteSqlite,ReadSqliteEventColor
from MyAES import decrypt_oralce,encrypt_oracle
from MyDataClass import WeekDay,ColorDay
from threading import Thread

from matplotlib import rcParams
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import random
import threading
from MyWordCloud import CloudCreat

L = threading.Lock()
L_wc=threading.Lock()

class MyClass(QMainWindow):

    NameDB='.\\Source\\test.db'
    LoginBK='./Source/Login/'
    BK='./Source/BK/'
    key='helloword'
    ColorCanChange='#5555ff'
    ColorDateDefault='#e5e5e5'
    ColorFontDefault='#bcbcbc'
    IdAll=[]
    # e5e5e5
    Green = ["#81ff81", "#22fe27", "#70ad47"]

    Yellow = ["#ffff00"]

    Blue = ["#00ffff", "#8ea9db"]
    Delight = ["#ccffff"]
    Pink = ["#fff2cc", "#ffcc99", "#ff603b"]

    Tired = ["#ffd966", "#ffc000"]

    Red = ["#ff0000"]
    Fucked = ["#969696", "#595959", "#333333"]

    ColorList1 = Green
    ColorList2 = Yellow
    ColorList3 = Blue+Delight+Pink
    ColorList4 = Tired
    ColorList5 = Red+Fucked

    ColorPaint1 = ColorList1[1]
    ColorPaint2 = ColorList2[0]
    ColorPaint3 = ColorList3[0]
    ColorPaint4 = ColorList4[1]
    ColorPaint5 = ColorList5[0]

    c1 = [0] * 5
    c2 = [0] * 8

    C1=[]
    C2=[]
    C3=[]
    C4=[]
    C5=[]

    colors1 = ["#00da00", "#dada00", "#00b8b8", "#ffaa00", "#da0000"]
    colors2 = ["#22fe27", "#ffff00", "#00ffff", "#ccffff", "#fff2cc", "#ffc000", "#ff0000", "#969696"]

    SliderValue=0
    year = QDate.currentDate().year()
    month = QDate.currentDate().month()
    day = QDate.currentDate().day()
    sbit_first=0
    text=[]
    def __init__(self, parent=None):
        super(MyClass,self).__init__(parent)
        self.ui=Mygui.Ui_MainWindow()
        self.ui.setupUi(self)
        self.show()
        # self.showFullScreen()#全屏显示
        # self.showMaximized()

        self.AllHide()
        # self.login()
        self.ui.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)#列宽自动适应
        # self.ui.tableWidget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)#行高

        listT=os.listdir(self.LoginBK)
        self.LoginBK=self.LoginBK+listT[random.randint(0,len(listT)-1)]
        listT=os.listdir(self.BK)

        self.BK=self.BK+listT[random.randint(0,len(listT)-1)]

        self.KeyInit()
        self.ui.tableWidget.setFrameShape(QFrame.NoFrame)  # 无边框显示
        self.ui.textEdit.setFrameShape(QFrame.NoFrame)  # 无边框显示

        self.ui.widget.setStyleSheet("border-image: url("+self.LoginBK+");")
        self.ui.menuBar.setStyleSheet("background-image: url("+self.LoginBK+");color: white")
        self.ui.statusbar.setStyleSheet("background-image: url("+self.LoginBK+");color: white")

        self.ui.textEdit.setStyleSheet("border-image: url(./Source/paper1.jpg);")
        self.ui.textEdit.setFont(QFont("楷体", 12))
        self.setWindowTitle('Once Upon A Time')
        # self.setWindowTitle('34枚金币时间管理')
        icon = QIcon()
        icon.addPixmap(QPixmap("./Source/Calender.ico"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        # self.ui.horizontalLayout_13.setGeometry(QRect(20, 20, 491, 311))
        # self.ui.widget.setStyleSheet("background-image: url(2.jpg);")#图片平铺
        # self.ui.statusbar.hide()
        #信号槽连接

        self.ui.radioButton_3.setChecked(True)
        self.ui.radioButton_3.toggled.connect(self.Radio3)
        self.ui.radioButton_2.toggled.connect(self.Radio2)
        self.ui.radioButton.toggled.connect(self.Radio1)
        self.ui.pushButton.clicked.connect(self.TableCombine)
        self.ui.pushButton_2.clicked.connect(self.TableClear)
        self.ui.toolButton.clicked.connect(self.ColorSelect)

        self.ui.pushButton_3.clicked.connect(self.Color0)
        self.ui.pushButton_4.clicked.connect(self.Color1)
        self.ui.pushButton_5.clicked.connect(self.Color2)
        self.ui.pushButton_6.clicked.connect(self.Color3)
        self.ui.pushButton_7.clicked.connect(self.Color4)
        self.ui.pushButton_8.clicked.connect(self.Color5)

        self.ui.pushButton_9.clicked.connect(self.DataSave)
        self.ui.pushButton_10.clicked.connect(self.BackToToday)

        self.ui.tableWidget.itemClicked.connect(self.SelectClear1)
        self.ui.tableWidget_2.itemClicked.connect(self.SelectClear2)

        self.ui.dateEdit.dateChanged.connect(self.ResetDate)
        self.ui.comboBox.currentIndexChanged.connect(self.ButtonColorChange1)
        self.ui.comboBox_2.currentIndexChanged.connect(self.ButtonColorChange2)
        self.ui.comboBox_3.currentIndexChanged.connect(self.ButtonColorChange3)
        self.ui.comboBox_4.currentIndexChanged.connect(self.ButtonColorChange4)
        self.ui.comboBox_5.currentIndexChanged.connect(self.ButtonColorChange5)
        self.ui.verticalScrollBar.valueChanged.connect(self.ScrollBarSet)

        self.TableInit(7,34)
        self.TableItemInit(7,34)
        self.ui.pushButton_3.setStyleSheet("background-color: #5555ff")
        self.ui.widget_2.setStyleSheet("background-color: rgba(0,0,0,0.1)")

        Date = self.ui.dateEdit.date()
        self.ColorCount(Date.year(), Date.month(), Date.day(), 0)
        #t.start()

        self.ui.dateEdit.setDate(QDate.currentDate())
        self.dateinit()
        self.ComboBoxInit()
        self.ScrollBarInit()
        self.ui.action.triggered.connect(self.about)

        self.changeStyle("WindowsVista")
        self.ui.widget_5.setStyleSheet("border-image: url(./Source/blackboard.png);")
        # self.ui.widget_3.setStyleSheet("border-image: url(./Source/pie.png);")

    def WCCreat(self):
        L_wc.acquire()
        t_WinSize = self.size()
        H_widget=(t_WinSize.height()-50)*0.95-510
        CloudCreat(self.text, os.getcwd() + "\\Source",235,floor(H_widget))
        self.ui.widget_7.setStyleSheet("border-image: url(./Source/Words/pic.png);")
        L_wc.release()
    def changeStyle(self, styleName):
        QApplication.setStyle(QStyleFactory.create(styleName))
    def Radio3(self):
        Date = self.ui.dateEdit.date()
        self.ColorCount(Date.year(), Date.month(), Date.day(), 0)
        t = Thread(target=self.PaintPie)
        t.start()
    def Radio2(self):
        Date = self.ui.dateEdit.date()
        self.ColorCount(Date.year(), Date.month(), Date.day(), 1)
        t = Thread(target=self.PaintPie)
        t.start()
    def Radio1(self):
        Date = self.ui.dateEdit.date()
        self.ColorCount(Date.year(), Date.month(), Date.day(), 2)
        t = Thread(target=self.PaintPie)
        t.start()
    def PaintPie(self):
        L.acquire()

        fig, ax = plt.subplots()
        c = [1]
        rcParams.update({'font.size': 18, 'font.family': 'serif'})
        ax.pie(self.c2, radius=1.5, colors=self.colors2, shadow=False, startangle=90)
        TempCValue=[]
        TempC=[]
        for i in range(0,len(self.c1)):
            if self.c1[i]!=0:
                TempCValue.append(self.c1[i])
                TempC.append(self.colors1[i])
        if TempCValue:
            ax.pie(TempCValue, radius=1.2,autopct='%1.0f%%', shadow=False, colors=TempC, startangle=90,pctdistance=0.95)
        ax.pie(c, radius=0.9, shadow=False, colors='k', startangle=90)
        Date = self.ui.dateEdit.date()

        self.ColorCount(Date.year(), Date.month(), Date.day(), 3)
        TempCValue=[]
        TempC=[]
        for i in range(0,len(self.c2)):
            if self.c2[i]!=0:
                TempCValue.append(self.c2[i])
                TempC.append(self.colors2[i])
        if TempCValue:
            ax.pie(TempCValue, radius=0.7, autopct='%1.0f%%',shadow=False, colors=TempC, startangle=90)
        plt.savefig(os.getcwd()+'\\Source\\pie.png', format='png', bbox_inches='tight', transparent=True, dpi=100)
        plt.close()
        self.ui.widget_3.setStyleSheet("border-image: url(./Source/pie.png);")
        if self.ui.radioButton_3.isChecked():
            mode=0
        elif self.ui.radioButton_2.isChecked():
            mode=1
        else:
            mode=2
        self.ColorCount(Date.year(), Date.month(), Date.day(), mode)
        fig, ax = plt.subplots()
        plt.grid(True)
        plt.grid(color='w', linestyle='--', linewidth=2, alpha=0.7)
        ax.plot(self.C1,'*-',color="#22fe27",linewidth=3.0)
        ax.plot(self.C2,'*-',color="#ffff00",linewidth=3.0)
        ax.plot(self.C3,'*-',color="#00ffff",linewidth=3.0)
        ax.plot(self.C4,'*-',color="#ffaa00",linewidth=3.0)
        ax.plot(self.C5,'r*-',linewidth=3.0)
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_color('w')
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_color('w')

        plt.savefig(os.getcwd() + '\\Source\\plot1.png', format='png', bbox_inches='tight', transparent=True, dpi=100)
        plt.close()
        self.ui.widget_4.setStyleSheet("border-image: url(./Source/plot1.png);")

        L.release()
    def ColorCount(self,year,month,day,mode):
        ColorAll = ReadSqliteEventColor(self.NameDB, year, month, day, mode)
        self.c1=[0]*5
        self.c2=[0]*8
        self.C1=[]
        self.C2 = []
        self.C3 = []
        self.C4 = []
        self.C5 = []
        for i in range(0, len(ColorAll)):
            id = ColorAll[i].Id
            DayColor = ColorAll[i].DayColor
            Num = ColorAll[i].Num
            EventColor = ColorAll[i].EventColor
            Row = ColorAll[i].Row
            C0 = [0]*5
            for j in range(0, Num):
                if j < Num - 1:
                    num = (int(Row[j + 1]) - int(Row[j]))*0.5
                    ColorNow = EventColor[j].lower()
                    if len(ColorNow) == 9:
                        ColorNow = '#' + ColorNow[3:9]
                    if ColorNow in self.Green:
                        C0[0]+=num
                        self.c1[0] += num
                        self.c2[0] += num
                    elif ColorNow in self.Yellow:
                        C0[1] += num
                        self.c1[1] += num
                        self.c2[1] += num
                    elif ColorNow in self.Blue:
                        C0[2] += num
                        self.c1[2] += num
                        self.c2[2] += num
                    elif ColorNow in self.Delight:
                        C0[2] += num
                        self.c1[2] += num
                        self.c2[3] += num
                    elif ColorNow in self.Pink:
                        C0[2] += num
                        self.c1[2] += num
                        self.c2[4] += num
                    elif ColorNow in self.Tired:
                        C0[3] += num
                        self.c1[3] += num
                        self.c2[5] += num
                    elif ColorNow in self.Red:
                        C0[4] += num
                        self.c1[4] += num
                        self.c2[6] += num
                    elif ColorNow in self.Fucked:
                        C0[4] += num
                        self.c1[4] += num
                        self.c2[7] += num
                else:
                    num = (35 - int(Row[j]))*0.5
                    ColorNow = EventColor[j].lower()
                    if len(ColorNow) == 9:
                        ColorNow = '#' + ColorNow[3:9]
                    if ColorNow in self.Green:
                        C0[0] += num
                        self.c1[0] += num
                        self.c2[0] += num
                    elif ColorNow in self.Yellow:
                        C0[1] += num
                        self.c1[1] += num
                        self.c2[1] += num
                    elif ColorNow in self.Blue:
                        C0[2] += num
                        self.c1[2] += num
                        self.c2[2] += num
                    elif ColorNow in self.Delight:
                        C0[2] += num
                        self.c1[2] += num
                        self.c2[3] += num
                    elif ColorNow in self.Pink:
                        C0[2] += num
                        self.c1[2] += num
                        self.c2[4] += num
                    elif ColorNow in self.Tired:
                        C0[3] += num
                        self.c1[3] += num
                        self.c2[5] += num
                    elif ColorNow in self.Red:
                        C0[4] += num
                        self.c1[4] += num
                        self.c2[6] += num
                    elif ColorNow in self.Fucked:
                        C0[4] += num
                        self.c1[4] += num
                        self.c2[7] += num
            self.C1.append(C0[0])
            self.C2.append(C0[1])
            self.C3.append(C0[2])
            self.C4.append(C0[3])
            self.C5.append(C0[4])
    def about(self):
        Box1=QMessageBox()
        Box1.information(self, "test版本1.1", "快捷键说明：\nCtrl+S ：  保存\nAlt+1~5：涂色1~5")
    def AllHide(self):
        self.ui.verticalScrollBar.hide()
        self.ui.dateEdit.hide()
        self.ui.widget_2.hide()
        self.ui.tableWidget.hide()
        self.ui.tableWidget_2.hide()

        self.ui.textEdit.hide()
        self.ui.pushButton_10.hide()

        self.ui.pushButton_9.hide()
        self.ui.pushButton.hide()
        self.ui.pushButton_4.hide()
        self.ui.pushButton_3.hide()
        self.ui.pushButton_2.hide()
        self.ui.pushButton_5.hide()
        self.ui.pushButton_6.hide()
        self.ui.pushButton_7.hide()
        self.ui.pushButton_8.hide()

        self.ui.comboBox.hide()
        self.ui.comboBox_2.hide()
        self.ui.comboBox_3.hide()
        self.ui.comboBox_4.hide()
        self.ui.comboBox_5.hide()
        self.ui.toolButton.hide()

        self.ui.widget_3.hide()
        self.ui.widget_4.hide()
        self.ui.widget_5.hide()
        self.ui.widget_7.hide()
        self.ui.radioButton.hide()
        self.ui.radioButton_2.hide()
        self.ui.radioButton_3.hide()

        self.ui.lineEdit_2.setEchoMode(QLineEdit.Password)
        self.setMinimumSize(self.width(),self.height())
        self.setMaximumSize(self.width(),self.height())
    def login(self):
        str1=self.ui.lineEdit_2.text()
        if len(str1)==0:
                self.AllShow()
        else:
            self.ui.statusbar.showMessage('Get out of here!(╯‵□′)╯︵┴─┴', 2000)
    def AllShow(self):
        self.ui.widget.setStyleSheet("border-image: url("+self.BK+");")
        self.ui.menuBar.setStyleSheet("background-image: url("+self.BK+");color: white")
        self.ui.statusbar.setStyleSheet("background-image: url("+self.BK+");color: white")

        self.ui.lineEdit_2.hide()
        self.setMaximumSize(111111111,111111111)
        self.showMaximized()

        self.ui.verticalScrollBar.show()
        self.ui.dateEdit.show()
        self.ui.widget_2.show()
        self.ui.tableWidget.show()
        self.ui.tableWidget_2.show()

        self.ui.textEdit.show()
        self.ui.pushButton_10.show()

        self.ui.pushButton_9.show()
        self.ui.pushButton.show()
        self.ui.pushButton_4.show()
        self.ui.pushButton_3.show()
        self.ui.pushButton_2.show()
        self.ui.pushButton_5.show()
        self.ui.pushButton_6.show()
        self.ui.pushButton_7.show()
        self.ui.pushButton_8.show()

        self.ui.comboBox.show()
        self.ui.comboBox_2.show()
        self.ui.comboBox_3.show()
        self.ui.comboBox_4.show()
        self.ui.comboBox_5.show()
        self.ui.toolButton.show()

        self.ui.widget_3.show()
        self.ui.widget_4.show()
        self.ui.widget_5.show()
        self.ui.widget_7.show()
        self.ui.radioButton.show()
        self.ui.radioButton_2.show()
        self.ui.radioButton_3.show()
    def ScrollBarSet(self):
        distance=self.ui.verticalScrollBar.value()
        pos=distance-self.SliderValue
        if pos>0:
            ValueNow=self.SliderValue+1
        elif pos<0:
            ValueNow = self.SliderValue - 1
        else:
            return
        self.ui.verticalScrollBar.setValue(ValueNow)
        self.SliderValue=ValueNow

        year = self.ui.dateEdit.date().year()
        # self.DateSet(year,ValueNow+1,1)
        self.ui.dateEdit.setDate(QDate(year,ValueNow+1, 1))

    def BackToToday(self):
        self.ui.dateEdit.setDate(QDate.currentDate())
        self.dateinit()
    def ScrollBarInit(self):

        month = datetime.datetime.now().month
        self.ui.verticalScrollBar.setMaximum(11)
        self.ui.verticalScrollBar.setValue(month-1)
        self.SliderValue=month-1
    def KeyInit(self):
        a=1
    def keyPressEvent(self, event):
        keyEvent = QKeyEvent(event)
        if keyEvent.key() == Qt.Key_S:
            if QApplication.keyboardModifiers() == Qt.ControlModifier:
                self.DataSave()
        elif keyEvent.key()== Qt.Key_1:
            if QApplication.keyboardModifiers() == Qt.AltModifier:
                self.Color1()
        elif keyEvent.key()== Qt.Key_2:
            if QApplication.keyboardModifiers() == Qt.AltModifier:
                self.Color2()
        elif keyEvent.key()== Qt.Key_3:
            if QApplication.keyboardModifiers() == Qt.AltModifier:
                self.Color3()
        elif keyEvent.key()== Qt.Key_4:
            if QApplication.keyboardModifiers() == Qt.AltModifier:
                self.Color4()
        elif keyEvent.key()== Qt.Key_5:
            if QApplication.keyboardModifiers() == Qt.AltModifier:
                self.Color5()
        elif keyEvent.key()== Qt.Key_Q:
            if QApplication.keyboardModifiers() == Qt.AltModifier:
                self.TableCombine()
        elif keyEvent.key()== Qt.Key_L:
            if QApplication.keyboardModifiers() == Qt.ControlModifier:
                self.login()
    def DayColorAutoSelect(self,ColorAll):
        ColorSum=self.Green+self.Yellow+self.Blue+self.Delight+self.Pink+self.Tired+self.Red+self.Fucked
        C=[0]*len(ColorSum)
        for i in range(0, 1):
            Num = ColorAll.Num
            EventColor = ColorAll.EventColor
            Row = ColorAll.Row
            for j in range(1, Num+1):
                if j < Num:
                    num = int(Row[j + 1]) - int(Row[j])
                    ColorNow = EventColor[j].lower()
                    if len(ColorNow) == 9:
                        ColorNow = '#' + ColorNow[3:9]
                    if ColorNow in ColorSum:
                        C[ColorSum.index(ColorNow)]+=num
                else:
                    num = 35 - int(Row[j])
                    ColorNow = EventColor[j].lower()
                    if len(ColorNow) == 9:
                        ColorNow = '#' + ColorNow[3:9]
                    if ColorNow in ColorSum:
                        C[ColorSum.index(ColorNow)]+=num
        Level=[9,8,7,15,14,13,6,5,2,0,10]
        for pos in Level:
            if C[pos]!=0:
                return ColorSum[pos]
        if sum(C)==0:
            return self.ColorDateDefault
        else:
            return ColorSum[C.index(max(C))]
    def DataSave(self):
        TodayData=self.TableDataGet()
        ColorSingle = ColorDay(TodayData.Id, TodayData.DayColor, TodayData.Num, TodayData.EventColor, TodayData.Row)
        TodayData.DayColor=self.DayColorAutoSelect(ColorSingle)

        if TodayData.Id not in self.IdAll:
            self.ui.statusbar.showMessage('正在写入新数据...')
            WriteSqlite(self.NameDB,TodayData)
            self.ui.statusbar.showMessage('数据已写入!(′～`）',5000)
            self.IdAll.append(TodayData.Id)
        else:
            DeleteSqlite(self.NameDB,TodayData.Id)
            self.ui.statusbar.showMessage('已删除今日数据!')
            WriteSqlite(self.NameDB, TodayData)
            self.ui.statusbar.showMessage('已更新今日数据!－(>口＜-)', 5000)
        # else:
        #     self.ui.statusbar.showMessage('今日数据为空！', 5000)
    def TableDataGet(self):
        DateNow=self.ui.dateEdit.date()
        year=DateNow.year()
        month=DateNow.month()
        day=DateNow.day()
        d1 = datetime.date(2013, 11, 4)
        d2 = datetime.date(year, month,day)
        Id = (d2 - d1).days
        DayYear=year
        DayDate=str(month)+'.'+str(day)
        DayComment=self.ui.textEdit.toPlainText()
        if not DayComment:
            DayComment='12'
        DayComment=encrypt_oracle(self.key,DayComment)
        CalenderData = calendar.monthcalendar(year, month)
        for i in range(0,len(CalenderData)):
            if day in CalenderData[i]:
                table2_i=i
                table2_j=CalenderData[i].index(day)
                table1_j=table2_j
        table2_item=self.ui.tableWidget_2.item(table2_i,table2_j)
        DayColor=table2_item.background().color().name()
        if DayColor=='#000000':
            DayColor=self.ColorDateDefault
        DayValue=[Id]
        EventColor=[Id]
        DayRow=[Id]
        DayNum=0
        for i in range(0,34):
            item=self.ui.tableWidget.item(i,table1_j)
            if item.text():
                DayValue.append(encrypt_oracle(self.key,item.text()))
                EventColor.append(item.background().color().name())
                DayRow.append(i)
                DayNum+=1
        for i in range(0,34-len(DayRow)+1):
            DayValue.append(' ')
            EventColor.append(' ')
            DayRow.append(' ')
        return WeekDay(Id,DayYear, DayDate, DayComment, DayColor, DayNum, DayValue, EventColor, DayRow)
    def TableShowText(self,DYear,DMonth,DDay):
        self.IdAll.clear()
        for i in range(0,7):
            self.TableClear2(i)
        WeekDate=ReadSqlite(self.NameDB,DYear,DMonth,DDay)
        self.ui.textEdit.clear()
        if WeekDate:
            Id=WeekDate[0].Id
            d1 = datetime.date(2013, 11, 4)
            d2 = d1 + datetime.timedelta(days=Id-(Id%7))
            HorizontalHeader = []
            DayNow=(datetime.date(DYear,DMonth,DDay)-d1).days
            for i in range(0, 7):
                t_time = str(d2.month)+'.'+str(d2.day)
                d2=d2+datetime.timedelta(days=1)
                HorizontalHeader.append(t_time)
            self.ui.tableWidget.setHorizontalHeaderLabels(HorizontalHeader)
            PosAll=[]
            for j in range(0, len(WeekDate)):
                Pos=WeekDate[j].Id%7
                PosAll.append(Pos)
                Year=WeekDate[j].Year
                Date=WeekDate[j].Date
                Comment=WeekDate[j].Comment
                DayColor=WeekDate[j].DayColor
                Num=WeekDate[j].Num
                Value=WeekDate[j].Value
                EventColor=WeekDate[j].EventColor
                Row=WeekDate[j].Row
                self.IdAll.append(WeekDate[j].Id)
                for i in range(0,Num):
                    if i<Num-1:
                        self.ui.tableWidget.setSpan(int(Row[i]),Pos,int(Row[i+1])-int(Row[i]),1)  # 要改变单元格的   1行数  2列数     要合并的  3行数  4列
                        newItem = QTableWidgetItem(decrypt_oralce(self.key,Value[i]))
                        newItem.setForeground(QColor(0, 0, 0))  # 设置字体颜色
                        newItem.setFont(QFont("宋体"))
                        newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                        newItem.setBackground(QColor(EventColor[i]))
                        self.ui.tableWidget.setItem(int(Row[i]), Pos, newItem)
                    else:
                        self.ui.tableWidget.setSpan(int(Row[i]),Pos,35-int(Row[i]),1)  # 要改变单元格的   1行数  2列数     要合并的  3行数  4列
                        newItem = QTableWidgetItem(decrypt_oralce(self.key,Value[i]))
                        newItem.setForeground(QColor(0, 0, 0))  # 设置字体颜色
                        newItem.setFont(QFont("宋体"))
                        newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                        newItem.setBackground(QColor(EventColor[i]))
                        self.ui.tableWidget.setItem(int(Row[i]), Pos, newItem)
            if DayNow%7 in PosAll:
                CommentIndex=PosAll.index(DayNow%7)
                Comment = WeekDate[CommentIndex].Comment
                self.ui.textEdit.append(decrypt_oralce(self.key,Comment))
                self.text=decrypt_oralce(self.key,Comment)
                t_wc = Thread(target=self.WCCreat())
                t_wc.start()
        else:
            d1 = datetime.date(2013, 11, 4)
            d2 = datetime.date(DYear, DMonth, DDay)
            Id=(d2-d1).days
            d2 = d1 + datetime.timedelta(days=Id - (Id % 7))
            HorizontalHeader=[]
            for i in range(0, 7):
                t_time = str(d2.month)+'.'+str(d2.day)
                d2=d2+datetime.timedelta(days=1)
                HorizontalHeader.append(t_time)
            self.ui.tableWidget.setHorizontalHeaderLabels(HorizontalHeader)
    def TableFill(self,ColumnNum,RowNum):
        for i in range(0,RowNum):
            for j in range(0,ColumnNum):
                newItem = QTableWidgetItem(str(i*5+j+1)+' '+self.ColorList[i*5+j])
                newItem.setForeground(QColor(0, 0, 0))#设置字体颜色
                newItem.setFont(QFont("宋体"))
                newItem.setTextAlignment(Qt.AlignCenter|Qt.AlignVCenter)
                self.ui.tableWidget.setItem(i, j, newItem)
                newItem.setBackground(QColor(self.ColorList[i*5+j]))
    def ComboBoxInit(self):
        self.ComboBoxInit1()
        self.ComboBoxInit2()
        self.ComboBoxInit3()
        self.ComboBoxInit4()
        self.ComboBoxInit5()
        self.ui.comboBox.setCurrentIndex(1)
        self.ui.comboBox_4.setCurrentIndex(1)
    def ButtonColorChange1(self):
        index=self.ui.comboBox.currentIndex()
        self.ColorPaint1=self.ColorList1[index]
        self.ui.pushButton_4.setStyleSheet("background-color: " + self.ColorList1[index])
    def ButtonColorChange2(self):
        index=self.ui.comboBox_2.currentIndex()
        self.ColorPaint2 = self.ColorList2[index]
        self.ui.pushButton_5.setStyleSheet("background-color: " + self.ColorList2[index])
    def ButtonColorChange3(self):
        index=self.ui.comboBox_3.currentIndex()
        self.ColorPaint3 = self.ColorList3[index]
        self.ui.pushButton_6.setStyleSheet("background-color: " + self.ColorList3[index])
    def ButtonColorChange4(self):
        index=self.ui.comboBox_4.currentIndex()
        self.ColorPaint4 = self.ColorList4[index]
        self.ui.pushButton_7.setStyleSheet("background-color: " + self.ColorList4[index])
    def ButtonColorChange5(self):
        index=self.ui.comboBox_5.currentIndex()
        self.ColorPaint5 = self.ColorList5[index]
        self.ui.pushButton_8.setStyleSheet("background-color: " + self.ColorList5[index])
    def ComboBoxInit1(self):
        for color in self.ColorList1:
            pix_color = QPixmap(60, 20)
            pix_color.fill(QColor(color))
            self.ui.comboBox.addItem(QIcon(pix_color), ' ')
        self.ui.comboBox.setIconSize(QSize(60, 20))
    def ComboBoxInit2(self):
        for color in self.ColorList2:
            pix_color = QPixmap(60, 20)
            pix_color.fill(QColor(color))
            self.ui.comboBox_2.addItem(QIcon(pix_color), ' ')
        self.ui.comboBox_2.setIconSize(QSize(60, 20))
    def ComboBoxInit3(self):
        for color in self.ColorList3:
            pix_color = QPixmap(60, 20)
            pix_color.fill(QColor(color))
            self.ui.comboBox_3.addItem(QIcon(pix_color), ' ')
        self.ui.comboBox_3.setIconSize(QSize(60, 20))
    def ComboBoxInit4(self):
        for color in self.ColorList4:
            pix_color = QPixmap(60, 20)
            pix_color.fill(QColor(color))
            self.ui.comboBox_4.addItem(QIcon(pix_color), ' ')
        self.ui.comboBox_4.setIconSize(QSize(60, 20))
    def ComboBoxInit5(self):
        for color in self.ColorList5:
            pix_color = QPixmap(60, 20)
            pix_color.fill(QColor(color))
            self.ui.comboBox_5.addItem(QIcon(pix_color), ' ')
        self.ui.comboBox_5.setIconSize(QSize(60, 20))
    def resizeEvent(self, event):#重写窗口变换事件
        t_WinSize=self.size()
        self.ui.widget.setMinimumHeight(t_WinSize.height())
        self.ui.widget.setMinimumWidth(t_WinSize.width())
        self.ui.widget.setMaximumHeight(t_WinSize.height())
        self.ui.widget.setMaximumWidth(t_WinSize.width())

        H_table1=(t_WinSize.height()-50)*0.95
        H_table2=(t_WinSize.height()-50)*0.95-206-50
        H_widget=(t_WinSize.height()-50)*0.95-510
        self.ui.tableWidget.setMinimumHeight(H_table1)
        self.ui.tableWidget.setMaximumHeight(H_table1)
        self.ui.textEdit.setMinimumHeight(H_table2)
        self.ui.textEdit.setMaximumHeight(H_table2)

        self.ui.widget_2.setMaximumHeight(H_table1)
        self.ui.widget_2.setMinimumHeight(H_table1)

        self.ui.widget_5.setMaximumHeight(H_widget)
        self.ui.widget_5.setMinimumHeight(H_widget)

        self.ui.widget_7.setMaximumHeight(floor(H_widget-16))
        self.ui.widget_7.setMinimumHeight(floor(H_widget-16))

    def ResetDate(self):
        DateNow=self.ui.dateEdit.date()
        year=DateNow.year()
        month=DateNow.month()
        day=DateNow.day()
        self.DateSet(year,month,day)
        self.TableShowText(year, month, day)
        self.SliderValue=month-1
        self.ui.verticalScrollBar.setValue(month-1)
        if self.ui.radioButton_3.isChecked():
            mode=0
        elif self.ui.radioButton_2.isChecked():
            mode=1
        else:
            mode=2
        self.ColorCount(year, month, day, mode)
        # self.PaintPie()
    def SelectClear1(self):
        self.ui.tableWidget_2.clearSelection()
    def SelectClear2(self):
        self.ui.tableWidget.clearSelection()
        DateOld = self.ui.dateEdit.date()
        YearOld = DateOld.year()
        MonthOld = DateOld.month()
        item = self.ui.tableWidget_2.selectedIndexes()
        for it in item:
            DayNew=self.ui.tableWidget_2.item(it.row(),it.column()).text()
            if it.row()==0 and int(DayNew)>7:
                if MonthOld==1:
                    YearNew=YearOld-1
                    MonthNew=12
                else:
                    YearNew=YearOld
                    MonthNew=MonthOld-1
            elif it.row()>3 and int(DayNew)<=14:
                if MonthOld==12:
                    YearNew=YearOld+1
                    MonthNew=1
                else:
                    YearNew=YearOld
                    MonthNew=MonthOld+1
            else:
                YearNew = YearOld
                MonthNew = MonthOld
        self.DateSet(YearNew, MonthNew, int(DayNew))
        self.ui.dateEdit.setDate(QDate(YearNew, MonthNew, int(DayNew)))
        t = Thread(target=self.PaintPie)
        t.start()

    def DateSet(self,year,month,day):#日历设置
        FillCount = 0
        CalenderData = calendar.monthcalendar(year, month)
        DayColorAll=ReadSqliteDayColor(self.NameDB,year,month,day)
        d2 = datetime.date(year,month, 1)
        d1 = datetime.date(2013, 11, 4)
        DayPos = int((d2 - d1).days)
        DayList=[]
        for i in range(0,len(DayColorAll)):
            DayList.append(DayColorAll[i][0]-DayPos+1)
        for i in range(0,len(CalenderData)):
            for j in range(0,7):
                if CalenderData[i][j]!=0:
                    newItem = QTableWidgetItem(str(CalenderData[i][j]))

                    font = QFont("Times New Roman")
                    font.setPointSize(10)
                    font.setBold(True)
                    if CalenderData[i][j] in DayList:
                        ColorIndex=DayList.index(CalenderData[i][j])
                        newItem.setBackground(QColor(DayColorAll[ColorIndex][1]))
                    if CalenderData[i][j] == day:
                        newItem.setForeground(QColor(255, 0, 0))
                    else:
                        newItem.setForeground(QColor(0, 0, 0))  # 设置字体颜色
                    newItem.setFont(font)
                    newItem.setTextAlignment(Qt.AlignCenter|Qt.AlignVCenter)
                    self.ui.tableWidget_2.setItem(i, j, newItem)
                    FillCount = FillCount + 1
        ###计算前一月数据
        if CalenderData[0][0] == 0:
            if month != 1:
                CalenderData0 = calendar.monthcalendar(year, month - 1)
            else:
                CalenderData0 = calendar.monthcalendar(year - 1, 12)
            for j in range(0, 7):
                data0 = CalenderData0[len(CalenderData0) - 1][j]
                if data0 == 0:
                    break
                newItem = QTableWidgetItem(str(data0))
                font = QFont("Times New Roman")
                font.setPointSize(10)
                newItem.setForeground(QColor(self.ColorFontDefault))
                font.setBold(True)
                newItem.setFont(font)
                newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                self.ui.tableWidget_2.setItem(0, j, newItem)
                FillCount = FillCount + 1
        ###计算后一月数据
        if FillCount<42:
            if month!=12:
                CalenderData1 = calendar.monthcalendar(year, month + 1)
            else:
                CalenderData1 = calendar.monthcalendar(year+1, 1)
            pos = FillCount % 7
            if FillCount<35:
                for j in range(pos, 7):
                    data0 = CalenderData1[0][j]
                    newItem = QTableWidgetItem(str(data0))
                    font = QFont("Times New Roman")
                    font.setPointSize(10)
                    newItem.setForeground(QColor(self.ColorFontDefault))
                    font.setBold(True)
                    newItem.setFont(font)
                    newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                    self.ui.tableWidget_2.setItem(4, j, newItem)
                for j in range(0, 7):
                    data0 = CalenderData1[1][j]
                    newItem = QTableWidgetItem(str(data0))
                    font = QFont("Times New Roman")
                    font.setPointSize(10)
                    newItem.setForeground(QColor(self.ColorFontDefault))
                    font.setBold(True)
                    newItem.setFont(font)
                    newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                    self.ui.tableWidget_2.setItem(5, j, newItem)
            else:
                for j in range(pos, 7):
                    data0 = CalenderData1[0][j]
                    newItem = QTableWidgetItem(str(data0))
                    font = QFont("Times New Roman")
                    font.setPointSize(10)
                    newItem.setForeground(QColor(self.ColorFontDefault))
                    font.setBold(True)
                    newItem.setFont(font)
                    newItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
                    self.ui.tableWidget_2.setItem(5, j, newItem)
    def dateinit(self):
        year = datetime.datetime.now().year
        month = datetime.datetime.now().month
        day = datetime.datetime.now().day

        self.ui.tableWidget_2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget_2.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.ui.tableWidget_2.setEditTriggers(QAbstractItemView.NoEditTriggers)#表格内容禁用修改
        self.ui.tableWidget_2.setSelectionMode(QAbstractItemView.SingleSelection)  #仅能单选
        self.ui.tableWidget_2.verticalHeader().setVisible(False)
        self.ui.tableWidget_2.setFrameShape(QFrame.NoFrame)#无边框显示
        self.ui.tableWidget_2.setShowGrid(False) #设置不显示格子线
        self.DateSet(year,month,day)

    def TableItemInit(self,ColumnNum,RowNum):
        for i in range(0,RowNum):
            for j in range(0,ColumnNum):
                newItem = QTableWidgetItem('23')
                newItem.setForeground(QColor(0, 0, 0))#设置字体颜色
                newItem.setFont(QFont("宋体"))
                newItem.setTextAlignment(Qt.AlignCenter|Qt.AlignVCenter)
                self.ui.tableWidget.setItem(i, j, newItem)

    def TableInit(self,ColumnNum,RowNum):#表格大小设置
        self.ui.tableWidget.setColumnCount(ColumnNum)
        self.ui.tableWidget.setRowCount(RowNum)
        VerticalHeader=[]
        for i in range(0,RowNum):
            self.ui.tableWidget.setRowHeight(i, 20)
        for i in range(7,24):
            t_time=str(i)+':00-'+str(i)+':30'
            VerticalHeader.append(t_time)
            if i!=23:
                t_time = str(i) + ':30-' + str(i+1) + ':00'
                VerticalHeader.append(t_time)
            else:
                t_time = '23:30-00:00'
                VerticalHeader.append(t_time)
        self.ui.tableWidget.setVerticalHeaderLabels(VerticalHeader)
        self.ui.tableWidget.setStyleSheet("selection-background-color:lightblue;")#选中背景设置
        self.ui.tableWidget_2.setStyleSheet("selection-background-color:lightblue;")#选中背景设置
    def TableCombine(self):#合并单元格
        # self.ui.tableWidget.setColumnCount(15)
        item=self.ui.tableWidget.selectedIndexes()
        RowIndex=[]
        ColumnIndex=[]
        SpanIndex=[]
        for it in item:
            RowIndex.append(it.row())
            ColumnIndex.append(it.column())
        if len(RowIndex)<2:
            return
        if ColumnIndex[0] * len(RowIndex) != sum(ColumnIndex): #仅对列进行合并，判断均为一列
            return
        SpanIndex.append(RowIndex[0])
        SpanIndex.append(ColumnIndex[0])
        SpanIndex.append(RowIndex[len(RowIndex)-1]-RowIndex[0]+1)
        SpanIndex.append(1)
        self.ui.tableWidget.setSpan(SpanIndex[0],SpanIndex[1],SpanIndex[2],SpanIndex[3])#要改变单元格的   1行数  2列数     要合并的  3行数  4列
    def TableClear2(self,Column):
        t_ColumnHeadItem=self.ui.tableWidget.horizontalHeaderItem(Column)
        t_ColumnHead=t_ColumnHeadItem.text()#获取当前列表头

        self.ui.tableWidget.removeColumn(Column)#移除当前列
        self.ui.tableWidget.insertColumn(Column)#插入当前列
        item1 = QTableWidgetItem(t_ColumnHead)#重写表头信息
        self.ui.tableWidget.setHorizontalHeaderItem(Column, item1)
        for k in range(0,34):
            newItem = QTableWidgetItem()
            self.ui.tableWidget.setItem(k,Column,newItem)
    def TableClear(self):#还原单元格
        item = self.ui.tableWidget.selectedIndexes()
        RowIndex = []
        ColumnIndex = []
        for it in item:
            RowIndex.append(it.row())
            ColumnIndex.append(it.column())
        if not RowIndex:
            return
        t_ColumnHeadItem=self.ui.tableWidget.horizontalHeaderItem(ColumnIndex[0])
        t_ColumnHead=t_ColumnHeadItem.text()#获取当前列表头

        self.ui.tableWidget.removeColumn(ColumnIndex[0])#移除当前列
        self.ui.tableWidget.insertColumn(ColumnIndex[0])#插入当前列
        item1 = QTableWidgetItem(t_ColumnHead)#重写表头信息
        self.ui.tableWidget.setHorizontalHeaderItem(ColumnIndex[0], item1)
        for k in range(0,34):
            newItem = QTableWidgetItem()
            self.ui.tableWidget.setItem(k,ColumnIndex[0],newItem)
        # horizontalHeader = ["工号", "姓名", "性别", "年龄", "职称"]
        # self.ui.tableWidget.setHorizontalHeaderLabels(horizontalHeader)
    def ColorSelect(self):#颜色选取
        col = QColorDialog.getColor()
        self.ui.pushButton_3.setStyleSheet("background-color: "+col.name())
        self.ColorCanChange=col.name()
    def Color0(self):
        sbit=self.ColorFill1(self.ColorCanChange)
        if sbit:
            return True
        self.ColorFill2(self.ColorCanChange)
    def Color1(self):
        sbit=self.ColorFill1(self.ColorPaint1)
        if sbit:
            return True
        self.ColorFill2(self.ColorPaint1)
    def Color2(self):
        sbit=self.ColorFill1(self.ColorPaint2)
        if sbit:
            return True
        self.ColorFill2(self.ColorPaint2)
    def Color3(self):
        sbit=self.ColorFill1(self.ColorPaint3)
        if sbit:
            return True
        self.ColorFill2(self.ColorPaint3)
    def Color4(self):
        sbit=self.ColorFill1(self.ColorPaint4)
        if sbit:
            return True
        self.ColorFill2(self.ColorPaint4)
    def Color5(self):
        sbit=self.ColorFill1(self.ColorPaint5)
        if sbit:
            return True
        self.ColorFill2(self.ColorPaint5)
    def ColorFill1(self,Colorstr):#颜色填充
        item = self.ui.tableWidget.selectedIndexes()
        RowIndex = []
        ColumnIndex = []
        if not item:
            return False#防止同时给两个表格上色
        for it in item:
            RowIndex.append(it.row())
            ColumnIndex.append(it.column())
        for i in RowIndex:
            for j in ColumnIndex:
                newItem = self.ui.tableWidget.item(i, j)
                newItem.setBackground(QColor(Colorstr))
        return True
    def ColorFill2(self,Colorstr):#颜色填充
        item = self.ui.tableWidget_2.selectedIndexes()
        RowIndex = []
        ColumnIndex = []
        for it in item:
            RowIndex.append(it.row())
            ColumnIndex.append(it.column())
        for i in RowIndex:
            for j in ColumnIndex:
                t_item=self.ui.tableWidget_2.item(i, j)
                t_item.setBackground(QColor(Colorstr))


"""User model."""
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _

class CustomUser(AbstractUser):
    """Custom user."""

    first_name = models.CharField(
        _('first name'),
        max_length=150,
        error_messages={
            'blank': _('ThisFieldCannotBeBlank'),
        },
    )
    last_name = models.CharField(
        _('last name'),
        max_length=150,
        error_messages={
            'blank': _('ThisFieldCannotBeBlank'),
        },
    )

    def get_absolute_url(self):  # noqa: D102
        return reverse_lazy('users')

    def __str__(self) -> str:
        """
        String representation.

        Returns:
            str:
        """
        return self.get_full_name()

    class Meta:  # noqa: WPS306
        """Meta information."""

        verbose_name = _('User')
        verbose_name_plural = _('Users')
        ordering = ['-date_joined']


from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.core.validators import RegexValidator, MinValueValidator
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver

#Import Models:
from posts.models import Account
from delinquency.models import Miscellaneous_Charged, Negative_LateFee, Negative_Monthly
from django.template.defaultfilters import title

# [Delinquency]
class Payment_Type(models.Model):
    code_id = models.PositiveSmallIntegerField(primary_key=True)
    title = models.CharField(max_length=50)

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Paymen Type'

class Payment_Status(models.Model):
    code_id = models.PositiveSmallIntegerField(primary_key=True)
    title = models.CharField(max_length=50)

    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'Paymen Status'

class Payment(models.Model):
    loan_number = models.ForeignKey(Account)
    record_id = models.CharField(max_length=5,
                            validators=[RegexValidator(r'^\d{1,10}$')],
                            blank=True
                            )
    payment_type = models.ForeignKey(Payment_Type)

    confirmation_code  = models.CharField(max_length=50,blank=True,null=True)

    amount  = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.1)],
                            )

    notes = models.TextField(max_length=300,
                            blank=True,
                            null=True,
                            )
    status = models.ForeignKey(Payment_Status,default=0)
    date_approved = models.DateTimeField(
                            auto_now=False,
                            auto_now_add=False,
                            blank=True,
                            null=True,
                            )
    auto_apply = models.BooleanField(default=True)
    applied = models.BooleanField(default=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)

    def __unicode__(self):
        return str(self.loan_number)

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

    class Meta:
        unique_together = ('record_id','loan_number')

    def clean(self):
        if self.record_id is None or self.record_id == '':
            try:
                Pcount = Payment.objects.filter(loan_number=self.loan_number).latest("record_id")
                Pcount = int(Pcount.record_id)
            except:
                Pcount = 0

            if Pcount > 0:
                Pcount += 1
                id_record = "{:0>4d}".format(Pcount)
            if Pcount == 0 or Pcount is None:
                Pcount = 1
                id_record = "{:0>4d}".format(Pcount)

            self.record_id = id_record
        if self.record_id is None or self.record_id == '':
            raise ValidationError(_(
                        '''Please check [Payments] for a bad log'''
                        ))
        #self.save()
        if self.amount is None or self.amount == 0:
            raise ValidationError(_(
                        '''Please complete the form.'''
                    ))

        if self.payment_type is None or self.payment_type == '':
             raise ValidationError(_(
                        '''Please complete the form'''
                    ))

        if str(self.status) == 'Approved' and str(self.confirmation_code) == '' or self.confirmation_code is None:
            raise ValidationError(_(
                        '''Requires a Confirmation Code'''
                    ))

        if str(self.status) == 'Approved' and str(self.confirmation_code) == '' or self.confirmation_code is None:
            raise ValidationError(_(
                        '''Requires a Confirmation Code'''
                    ))

        if str(self.status) == 'Approved' or str(self.status) == 'Decline' and self.date_approved is None:
            self.date_approved = timezone.now()
            self.save()

        else:
            self.date_approved = None
            self.save()

    def get_absolute_url(self):
        #return "/try1/%s/" %(self.id)
        return reverse("payments:detail", kwargs={"loan_number": self.loan_number, "record_id":self.record_id})

class Money_Deposit(models.Model):
    loan_number = models.OneToOneField(Account)
    amount_paid_misc = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )

    amount_paid_auto = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )

    total_deposit = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )
    amount_unapplied_misc = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )
    amount_unapplied_auto = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )
    total_unapplied = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )
    amount_applied_misc = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )
    amount_applied_auto = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )
    total_applied = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.0)],
                            default=0.0
                            )

    class Meta:
        verbose_name_plural = 'Bank'

class Monthly_Payment(models.Model):
    loan_number = models.ForeignKey(Account)
    record_id = models.ForeignKey(Negative_Monthly)
    amount  = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.1)],
                            )

    notes = models.TextField(max_length=300,
                            blank=True,
                            null=True,
                            )
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)

    def __unicode__(self):
        return str(self.title)

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

    class Meta:
        verbose_name_plural = 'Monthly Payment'

class Fee_Payment(models.Model):
    loan_number = models.ForeignKey(Account)
    record_id = models.ForeignKey(Negative_LateFee)
    amount  = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.1)],
                            )

    notes = models.TextField(max_length=300,
                            blank=True,
                            null=True,
                            )
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)

    def __unicode__(self):
        return str(self.title)

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

    class Meta:
        verbose_name_plural = 'Late Fee Payment'

class Miscellaneous_Payment(models.Model):
    loan_number = models.ForeignKey(Account)
    title_record = models.ForeignKey(Miscellaneous_Charged)
    amount  = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.1)],
                            )

    notes = models.TextField(max_length=300,
                            blank=True,
                            null=True,
                            )
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)

    def __unicode__(self):
        return str(self.title)

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

    class Meta:
        verbose_name_plural = 'Miscellaneous Payment'

class Payment_Log(models.Model):
    loan_number = models.ForeignKey(Account)
    confirmation_code = models.CharField(max_length=50)
    due_date = models.DateField(auto_now=False, auto_now_add=False)
    amount  = models.DecimalField(
                            max_digits=12,
                            decimal_places=2,
                            validators=[MinValueValidator(0.1)],
                            )
    target = models.CharField(max_length=50)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    class Meta:
        unique_together = ('loan_number','confirmation_code','due_date','amount', 'target')
        verbose_name_plural = 'Payment Log'


from graphics import *
from graphicsCG import *
import math

def matMult(M, N):
	# print(M)
	# print(N)
	R=[]
	for i in range(len(M)):
		R.append([])
		for j in range(len(N[0])):
			R[i].append(0)
	for i in range(len(M)):
		for j in range(len(N[0])):
			for k in range(len(N)):
				R[i][j] += M[i][k] * N[k][j]
	for i in range(len(M)):
		for j in range(len(N)):
			M[i][j]=R[i][j]
	# print(M)
	return M[0]

def copyMetrics(M):
	a=[]
	for i in range(len(M)):
		a.append([])
		for j in M[i]:
			a[i].append(j)
		a[i].append(1)
	return a

def getKey():
	l=""
	key=win.getKey()
	while(key!='slash'):
		if(key=='period'):
			key='.'
		if(key=='minus'):
			key='-'
		l+=key
		print(l[-1], end="")
		key=win.getKey()
	print()
	return l

def choices():
	print("\nenter choice on window(enter '/' at the end).")
	print("select choice for transformation->")
	print("1. Translation")
	print("2. Scaling")
	print("3. Rotation")
	print("4. Shearing")
	print("5. Reflection")
	print("6. Quit")
	pass

if __name__=="__main__":
	#print("enter xmin, ymin, xmax, ymax for window: ", end="")
	xmin , xmax , ymin , ymax = 0, 1000, 0, 900 #map(int, input().split())
	window = size(xmin , xmax , ymin , ymax)

	#print("enter xmin, ymin, xmax, ymax for viewPort: ", end="")
	xvmin , xvmax , yvmin , yvmax = 0, 800, 0, 700 #map(int, input().split())
	viewPort = size(0 , xvmax - xvmin, 0 , yvmax - yvmin)

	win = GraphWin(' Line ' , xvmax - xvmin , yvmax - yvmin, autoflush = False)

	drawLine(win, 0 , window.ymax, 0, window.ymin, 'blue', window,viewPort )
	drawLine(win, window.xmin , 0 , window.xmax, 0, 'red', window,viewPort )

	#print("Enter number of edges of polygon: ", end="")
	n=5#int(input())
	#print("Enter vertices of the edges as (x, y) one by one")
	vertices=[[200, 200], [500, 300], [700, 600], [400, 300], [200, 500]]#[]
	# for i in range(n):
		# vertices.append(list(map(int, input().split())))
	# print("Enter color of the Edges:- ", end="")
	color = 'black'#input()
	drawPolygon(win, n, vertices, color, window, viewPort)
	choices()
	while(1):

		choice=int(getKey())
		print(choice)

		if(choice==1): #translation

			print("enter Tx through window(enter '/' at the end)")
			Tx=float(getKey())
			print("enter Ty through window(enter '/' at the end)")
			Ty=float(getKey())

			T=[[1, 0, 0], [0, 1, 0], [Tx, Ty, 1]]
			k=copyMetrics(vertices)
			print(k)
			for i in k:
				i=matMult([i], T)[:2]
				i[0]=math.ceil(i[0])
				i[1]=math.ceil(i[1])
			print(k)
			print(vertices)
			drawPolygon(win, n, k, 'red', window, viewPort)

		elif(choice==2): #Scaling
			print("enter Sx through window(enter '/' at the end)")
			Sx=float(getKey())
			print("enter Sy through window(enter '/' at the end)")
			Sy=float(getKey())

			S=[[Sx, 0, 0], [0, Sy, 0], [0, 0, 1]]
			print("enter Reference point for rotation (x, y)")
			print("enter x through window(enter '/' at the end)")
			x=float(getKey())
			print("enter y through window(enter '/' at the end)")
			y=float(getKey())
			k=copyMetrics(vertices)
			print(k)
			for i in k:
				l=[i[0]-x, i[1]-y, i[2]]
				l=matMult([l], S)[:2]
				print(l)
				i[0]=x+l[0]
				i[1]=y+l[1]
				i=i[:2]
				i[0]=math.ceil(i[0])
				i[1]=math.ceil(i[1])
			print(k)
			print(vertices)
			drawPolygon(win, n, k, 'red', window, viewPort)

		elif(choice==3):
			print("enter t such that angle of rotation is pi/t: ")
			print("enter t through window(enter '/' at the end)")
			angle=math.pi/float(getKey())
			print("enter directon of rotation through window->")
			print("1. Anti Clockwise")
			print("2. Clockwise")
			k=int(win.getKey())
			if(k==2):
				angle=-angle
			R=[[math.cos(angle), math.sin(angle), 0], [-math.sin(angle), math.cos(angle), 0], [0, 0, 1]]
			print(R)
			print("Reference point for rotation (x, y): ", end=" ")
			x = float(getKey())
			y = float(getKey())
			k=copyMetrics(vertices)
			print(k)
			for i in k:
				l=[i[0]-x, i[1]-y, 1]
				l = matMult([l], R)
				print(l)
				i[0]=x+l[0]
				i[1]=y+l[1]
				i=i[:2]
				i[0]=math.ceil(i[0])
				i[1]=math.ceil(i[1])
			print(k)
			print(vertices)
			drawPolygon(win, n, k, 'red', window, viewPort)

		elif(choice==4):
			print("enter shx through window(enter '/' at the end)")
			shx = float(getKey())
			print("enter shy through window(enter '/' at the end)")
			shy = float(getKey())
			Sh = [[1, shy, 0], [shx, 1, 0], [0, 0, 1]]
			print("Reference point for rotation (x, y): ", end=" ")
			x = float(getKey())
			y = float(getKey())
			k=copyMetrics(vertices)
			print(k)
			for i in k:
				l=[i[0]-x, i[1]-y, i[2]]
				l=matMult([l], Sh)[:2]
				print(l)
				i[0]=x+l[0]
				i[1]=y+l[1]
				i=i[:2]
				i[0]=math.ceil(i[0])
				i[1]=math.ceil(i[1])
			print(k)
			print(vertices)
			drawPolygon(win, n, k, 'red', window, viewPort)

		elif(choice==5):
			print("enter a, b, c where ax+by+c=0 is reference line: ", end="")
			print("enter a through window(enter '/' at the end)")
			a = float(getKey())
			print("enter b through window(enter '/' at the end)")
			b = float(getKey())
			print("enter c through window(enter '/' at the end)")
			c = float(getKey())

			k=copyMetrics(vertices)

			Ref = [[(b*b-a*a)/(a*a+b*b), -2*a*b/(a*a+b*b), 0],
				 [-2*a*b/(a*a+b*b), (a*a-b*b)/(a*a+b*b), 0],
				 [-2*a*c/(a*a+b*b), -2*b*c, 1]]

			for i in k:
				x=i[0]
				y=i[1]
				l=[x, y, 1]
				# i[0]=((b*b-a*a)*x-2*a*b*y-2*a*c)/(a*a+b*b)
				# i[1]=((a*a-b*b)*y-2*a*b*x-2*b*c)/(a*a+b*b)
				l=matMult([l], Ref)[:2]
				print(l)
				i[0]=math.ceil(l[0])
				i[1]=math.ceil(l[1])
				i=i[:2]
			print(k)
			print(vertices)
			drawPolygon(win, n, k, 'red', window, viewPort)

		elif(choice==6):
			break

		else:
			pass
			print("please enter valid choice.")
		choices()

	print("Click on window to exit")

	win.getMouse()
	win.close


#! /usr/bin/env python
#
def subset_lex_rank ( n, t ):

#*****************************************************************************80
#
## SUBSET_LEX_RANK computes the lexicographic rank of a subset.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    25 December 2015
#
#  Author:
#
#    John Burkardt
#
#  Reference:
#
#    Donald Kreher, Douglas Simpson,
#    Combinatorial Algorithms,
#    CRC Press, 1998,
#    ISBN: 0-8493-3988-X,
#    LC: QA164.K73.
#
#  Parameters:
#
#    Input, integer N, the number of items in the master set.
#    N must be positive.
#
#    Input, integer T(N), the subset.  If T(I) = 0, item I is
#    not in the subset if T(I) = 1, item I is in the subset.
#
#    Output, integer RANK, the rank of the subset.
#
  from subset_check import subset_check
  from sys import exit
#
#  Check.
#
  check = subset_check ( n, t )

  if ( not check ):
    print ( '' )
    print ( 'SUBSET_LEX_RANK - Fatal error!' )
    print ( '  The subset is not legal.' )
    exit ( 'SUBSET_LEX_RANK - Fatal error!' )

  rank = 0

  for i in range ( 0, n ):

    if ( t[i] == 1 ):
      rank = rank + 2 ** ( n - 1 - i )

  return rank

def subset_lex_rank_test ( ):

#*****************************************************************************80
#
## SUBSET_LEX_RANK_TEST tests SUBSET_LEX_RANK.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    25 December 2015
#
#  Author:
#
#    John Burkardt
#
  import numpy as np
  import platform
  from i4vec_transpose_print import i4vec_transpose_print

  n = 5

  print ( '' )
  print ( 'SUBSET_LEX_RANK_TEST' )
  print ( '  Python version: %s' % ( platform.python_version ( ) ) )
  print ( '  SUBSET_LEX_RANK ranks subsets of a set,' )
  print ( '  using the lexicographic ordering.' )

  t = np.array ( [ 0, 1, 0, 1, 0 ] )
  i4vec_transpose_print ( n, t, '  The element:' )

  rank = subset_lex_rank ( n, t )

  print ( '' )
  print ( '  The rank of the element is computed as %d' % ( rank ) )
#
#  Terminate.
#
  print ( '' )
  print ( 'SUBSET_LEX_RANK_TEST:' )
  print ( '  Normal end of execution.' )
  return

if ( __name__ == '__main__' ):
  from timestamp import timestamp
  timestamp ( )
  subset_lex_rank_test ( )
  timestamp ( )


from south.db import db
from django.db import models

from ella.core.migrations.base.base_0002 import BasePublishableDataMigration
from ella.core.migrations.base.base_0002 import alter_foreignkey_to_int, migrate_foreignkey

class Migration(BasePublishableDataMigration):
    models = dict.copy(BasePublishableDataMigration.models)
    models.update(
        {
            'interviews.interview': {
                'Meta': {'ordering': "('-ask_from',)", '_bases': ['ella.core.models.publishable.Publishable']},
                'ask_from': ('models.DateTimeField', ["_('Ask from')"], {}),
                'ask_to': ('models.DateTimeField', ["_('Ask to')"], {}),
                'content': ('models.TextField', ["_('Text')"], {}),
                'interviewees': ('models.ManyToManyField', ["orm['interviews.Interviewee']"], {'verbose_name': "_('Interviewees')"}),
                'publishable_ptr': ('models.OneToOneField', ["orm['core.Publishable']"], {}),
                'reply_from': ('models.DateTimeField', ["_('Reply from')"], {}),
                'reply_to': ('models.DateTimeField', ["_('Reply to')"], {}),
                'upper_title': ('models.CharField', ["_('Upper title')"], {'max_length': '255', 'blank': 'True'})
            },
            'interviews.interviewee': {
                'Meta': {'ordering': "('name',)"},
                'author': ('models.ForeignKey', ["orm['core.Author']"], {'null': 'True', 'blank': 'True'}),
                'description': ('models.TextField', ["_('Description')"], {'blank': 'True'}),
                'id': ('models.AutoField', [], {'primary_key': 'True'}),
                'name': ('models.CharField', ["_('Name')"], {'max_length': '200', 'blank': 'True'}),
                'slug': ('models.SlugField', ["_('Slug')"], {'max_length': '255'}),
                'user': ('models.ForeignKey', ["orm['auth.User']"], {'null': 'True', 'blank': 'True'})
            },
            'auth.user': {
                '_stub': True,
                'id': ('models.AutoField', [], {'primary_key': 'True'})
            },
            'core.author': {
                'Meta': {'app_label': "'core'"},
                '_stub': True,
                'id': ('models.AutoField', [], {'primary_key': 'True'})
            },
        }
    )

    app_label = 'interviews'
    model = 'interview'
    table = '%s_%s' % (app_label, model)

    publishable_uncommon_cols = {
        'source_id': 'source_id',
        'description': 'perex',
    }

    def alter_self_foreignkeys(self, orm):
        # migrate authors as in base
        super(Migration, self).alter_self_foreignkeys(orm)
        alter_foreignkey_to_int('interviews_question', 'interview')
        alter_foreignkey_to_int('interviews_interview_interviewees', 'interview')

    def move_self_foreignkeys(self, orm):
        # migrate authors as in base
        super(Migration, self).move_self_foreignkeys(orm)
        # migrate new article IDs to question
        migrate_foreignkey(self.app_label, self.model, 'interviews_question', self.model, self.orm)
        # migrate new article IDs to interview_interviewees
        migrate_foreignkey(self.app_label, self.model, 'interviews_interview_interviewees', self.model, self.orm)


# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import discord
import make_chart as make
import os

client = discord.Client()

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.event
async def on_message(message):
    if message.content.startswith('！もやし　１０分'):
        await client.send_message(message.channel, 'チャートを取得しています...')
        # コマンドによってここを変えればほかの通貨もいける。
        make.make_chart('SPROUTS-DOGE', 'data.json')
        path = os.path.dirname(os.path.abspath(__file__)) + '/chart.png'
        await client.send_file(message.channel, path)

client.run('TOKEN')  # わかってると思うけどここにトークンを入れてね


N, K = map(int, input().split())
P = int(1e9+7)

# 再利用する時あらかじめN以下の計算しとく
kaizyo = [0]
kaizyo_inv = [0]
tmp = 1
for i in range(1, N+2):
    tmp = (tmp*i) % P
    kaizyo.append(tmp)
    kaizyo_inv.append(pow(tmp, P - 2, P))

def comb(n, r):
    if n < r or n < 0:
        return 0
    elif n == r or r == 0:
        return 1
    else:
        return kaizyo[n] * kaizyo_inv[r] * kaizyo_inv[n - r]

for i in range(1, K + 1):
    print((comb(K - 1, i - 1) * comb(N - K + 1, i)) % P)


# Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
# Return the array in the form [x1,y1,x2,y2,...,xn,yn].
#
# EXAMPLE:
# Input: nums = [2,5,1,3,4,7], n = 3
# Output: [2,3,5,4,1,7]
# Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].

class Solution:
    def shuffle(self, nums, n):
        res = []
        for i in range(n):
            res.append(nums[i])
            res.append(nums[i+n])
        return res

# Respuesta:
nums = [1,2,3,4,4,3,2,1]
n = 4

solution = Solution()
print(solution.shuffle(nums,n))