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

import logging
from sanic import  Blueprint, response
from sanic.response import json, text, html, redirect
from sanic_openapi import doc
import ujson
from common.utils import jsonify, insert_sql, select_sql, update_sql
import datetime
from bs4 import  BeautifulSoup
import ujson
import pickle
import re
import hashlib
import xml.etree.ElementTree as ET
import datetime
import time
import redis

logger = logging.getLogger('sanic')
youdao_bp = Blueprint('youdao', url_prefix='words')
review_time_list = {
    '0': datetime.timedelta(minutes=5),
    '1': datetime.timedelta(hours=1),
    '2': datetime.timedelta(hours=3),
    '3': datetime.timedelta(hours=6),
    '4': datetime.timedelta(hours=12),
    '5': datetime.timedelta(days=1),
    '6': datetime.timedelta(days=2),
    '7': datetime.timedelta(days=3),
    '8': datetime.timedelta(days=5),
    '9': datetime.timedelta(days=10),
    '10': datetime.timedelta(days=20),
    '11': datetime.timedelta(days=30)
}

async def create_audio(data):
    timestamp = datetime.datetime.timestamp(datetime.datetime.now())
    #主要是懒,@todo写道config.py里面
    path = 'audio/'+str(timestamp*10000).split('.')[0]+'.wav'
    fs = open(path, 'wb')
    fs.write(data)
    fs.close()
    return path

@youdao_bp.route('/audios/<word:string>', methods=['GET'])
async def get_word_audio(request, word):
    records = None
    async with request.app.db.acquire() as cur:
        records = await cur.fetch("select * from word_audio where word = '%s'"%word)
    if records:
        audio_path = records[0]['audio_path']
        async def streaming_fn(response):
            fs = open(audio_path,'rb')
            data = fs.read()
            response.write(data)
        return response.stream(streaming_fn,content_type='audio/mpeg')
    else:
        cli = request.app.client.cli
        #主要是懒,@todo写道config.py里面
        url = "http://dict.youdao.com/dictvoice?audio=" + word
        async with cli.get(url) as res:
            if res.status == 200:
                data = await res.read()
                path = await create_audio(data)
                async with request.app.db as cur:
                     await cur.fetch("INSERT INTO word_audio (create_time,word,audio_path) VALUES (current_timestamp,'%s','%s')" %(word,path))
                async def streaming_fn(response):
                    response.write(data)
                return response.stream(streaming_fn,content_type='audio/mpeg')
    return json({},status = 400)

@youdao_bp.route('/translates/<word:string>', methods=['GET'])
async def get_word_translate(request, word):
    records = None
    async with request.app.db.acquire() as cur:
        records = await cur.fetch("select * from word_translate where word='%s'"%word)
    if records:
        res = ujson.loads(records[0]['translate'])
        return json(res)
    else:
        cli = request.app.client.cli
        #直接写url主要是懒
        #主要是懒,@todo写道config.py里面
        url = "http://dict.youdao.com/search?keyfrom=dict.top&q="+word
        async with cli.get(url) as res:
            if res.status == 200:
                data = await res.text()
                res = await parse_html(request,data,word)
                async with request.app.db as cur:
                    #return json(res)
                    json_data = ujson.dumps(res)
                    json_data = json_data.replace("'","''")
                    await cur.fetch( """INSERT INTO word_translate (create_time,word,translate) VALUES (current_timestamp,'%s','%s')"""%(word,json_data))
                    #await cur.fetch( """INSERT INTO word_translate (create_time,word,translate) VALUES (current_timestamp,'%s',)"""%(word,ujson.dumps(res)))
                    return json(res)
    return json({},status = 400)

@youdao_bp.route('/search/<word:string>', methods=['GET'])
async def get_word(request, word):
    res = await get_word_translate(request, word)
    audio = await get_word_audio(request, word)
    return res

@youdao_bp.route('/users',methods=['POST'])
async def add_user(request,fromu=None):
    data = {}
    try:
        if not fromu:
            data = ujson.loads(request.body)
        else:
            data = {"username":fromu}
    except:
        return json({},status = 400)
    if data.get('username') and len(data.get('username'))>5 :
        async with request.app.db.acquire() as cur:
            records = await cur.fetch("select * from users where username='%s'"%data.get('username'))
            if records:
                request['session']['user_id'] = records[0]['id']
                return json(jsonify(records)[0])
            else:
                sql = """insert into users (create_time,username,name,wechat_user) values
                (current_timestamp,'%s','%s','%s') returning *"""
                user_info = (data.get('username'),data.get('name') if data.get('name') else data.get('username'),data.get('wechat_user') if data.get('wechat_user') else 'NULL')
                records = await cur.fetch(sql%user_info)
                print(records)
                if records:
                    request['session']['user_id'] = records[0]['id']
                res = await add_wordlist(request,data={"name":"新手起步"})
                if res:
                    wordlist_id = ujson.loads(res.body)['id']
                    r = await add_wordlists_word(request,wordlist_id,data={"word":"hello"})
                    return(r.body)
                if records:
                    return json(jsonify(records)[0])
    return json({},status = 400)

@youdao_bp.route('/wordlists/wechat/<wechat_token>', methods=['GET'])
async def get_wechat_word_h5(request,wechat_token):
    res = await add_user(request,wechat_token)
    wordlist_id = -1
    if res:
        await update_wechat_user(request,wechat_user=wechat_token)
        async with request.app.db.acquire() as cur:
            record = await cur.fetch("select * from word_list where user_id=%s"%request['session']['user_id'])
            if record:
                wordlist_id = record[0]['id']
    return redirect('http://bitnotice.susnote.com/html/WordLists.html')

@youdao_bp.route('/users/wechat_user',methods=['POST'])
async def update_wechat_user(request,user_id=None,wechat_user=None):
    data = {}
    try:
        data = ujson.loads(request.body)
    except:
        pass
    if not wechat_user:
        wechat_user = data.get('wechat_user')
    if not user_id:
        user_id = data.get('user_id') if data.get('user_id') else request['session'].get('user_id')

    if wechat_user and user_id:
        async with request.app.db as cur:
            sql = """update users set wechat_user=%s where id=%s returning *"""%(wechat_user,user_id)
            records = cur.fetch(sql)
            return json({})
    return json({},status=400)

@youdao_bp.route('/wordlists/<wordlist_id:int>/words', methods=['GET'])
async def get_wordlists_word(request,wordlist_id):
    user_id = None
    if request['session'].get('user_id'):
        user_id = request['session'].get('user_id')
    if user_id:
        async with request.app.db.acquire() as cur:
            records = await cur.fetch("select * from word_list where id=%s and user_id=%s"%(wordlist_id,user_id))
            if records:
                return json(jsonify(records)[0]["words"])
    return json({},status=400)

@youdao_bp.route('/wordlists/<wordlist_id:int>/words', methods=['POST'])
async def add_wordlists_word(request,wordlist_id,data={}):
    user_id = None
    try:
        if not data:
            data = ujson.loads(request.body)
    except:
        return json({},status=400)
    if request['session'].get('user_id'):
        user_id = request['session'].get('user_id')
    if user_id and data.get('word'):
        async with request.app.db as cur:
            records = await cur.fetch("select * from word_list where id=%s and user_id=%s"%(wordlist_id,user_id))
            if records:
                words = records[0]['words']
                if data.get('word') not in words:
                    words.append(data.get('word'))
                    words = str(list(words)).replace('[','{').replace(']','}').replace("'",'"')
                    records = await cur.fetch("""update word_list set words='%s' where id=%s returning *"""%(words,wordlist_id))
                    r = await cur.fetch("""insert into user_words (create_time,word,words_level,user_id,review_time, word_list_id) values (current_timestamp,'%s',%s,%s,current_timestamp,%s) returning *"""%(data.get('word'),0,user_id,wordlist_id))
                    print(r)
                    if records:
                        return json(jsonify(records)[0])
    return json({})

@youdao_bp.route('/wordlists', methods=['GET'])
async def get_wordlists(request):
    wordlist_id = request.args.get('id', 0)
    user_id = None
    if request['session'].get('user_id'):
        user_id = request['session'].get('user_id')
    if user_id and wordlist_id ==0:
        async with request.app.db.acquire() as cur:
            records = await cur.fetch("select * from word_list where user_id=%s"%(user_id))
            return json(jsonify(records))
    elif user_id:
        async with request.app.db.acquire() as cur:
            records = await cur.fetch("select * from word_list where user_id=%s and id =%s"%(user_id,wordlist_id))
            return json(jsonify(records))

    return json({},status=400)

@youdao_bp.route('/wordlists', methods=['DELETE'])
async def delete_wordlists(request,data={}):
    try:
        if not data:
            data = ujson.loads(request.body)
    except:
        return json({},status=400)
    wordlist_name = data.get("name").replace("'","''") if data.get("name") else "未命名"
    user_id = data.get("user_id") if data.get("user_id") else request['session'].get('user_id')
    if user_id:
        async with request.app.db as cur:
            r = await cur.fetch("select * from word_list where name='%s' and user_id=%s"%(wordlist_name,user_id))
            if r:
                wordlist_id = r[0]['id']
                await cur.fetch("delete from user_words where word_list_id=%s"%wordlist_id)
                res = await cur.fetch("delete from word_list where name='%s' and user_id=%s returning *"%(wordlist_name,user_id))
                return json(jsonify(r))
    return json({},status=400)

@youdao_bp.route('/wordlists', methods=['POST'])
async def add_wordlist(request,data={}):
    try:
        if not data:
            data = ujson.loads(request.body)
    except:
        return json({},status=400)
    wordlist_name = data.get("name").replace("'","''") if data.get("name") else "未命名"
    user_id = data.get("user_id") if data.get("user_id") else request['session'].get('user_id')
    if user_id:
        async with request.app.db as cur:
            r = await cur.fetch("select * from word_list where name='%s' and user_id=%s"%(wordlist_name,user_id))
            if r:
                return json(jsonify(r)[0])
            else:
                records = await cur.fetch("insert into word_list (create_time,words,name,category,user_id) VALUES (current_timestamp,'{}','%s','private',%s) returning *"%(wordlist_name,user_id))
            if records:
                return json(jsonify(records)[0])
    return json({},status=400)

@youdao_bp.route('/wordlists/<wordlist_id:int>', methods=['DELETE'])
async def delete_wordlist(request,wordlist_id):
    user_id = request['session'].get('user_id')
    if user_id:
        async with request.app.db as cur:
            records = await cur.fetch("delete from word_list where user_id=%s and id=%s returning *"%(user_id,wordlist_id))
            if records:
                return json(jsonify(records)[0])
    return json({},status=400)

@youdao_bp.route('/wordlists/<wordlist_id:int>/review/h5', methods=['GET'])
async def get_word_h5(request,wordlist_id):
    env = request.app.env
    template = await env.get_template('WordListReview.html').render_async(wordlist_id=wordlist_id)
    return html(template)

@youdao_bp.route('/wordlists/<wordlist_id:int>/h5', methods=['GET'])
async def get_word_h5(request,wordlist_id):
    env = request.app.env
    template = await env.get_template('WordList.html').render_async(wordlist_id=wordlist_id)
    return html(template)

async def parse_html(request,html,word):
    """
    解析web版有道的网页
    :param html:网页内容
    :return:result
    """
    soup = BeautifulSoup(html, "lxml")
    root = soup.find(id='results-contents')

    # query 搜索的关键字
    keyword = root.find(class_='keyword')
    result = {}
    if not keyword:
        result['query'] = word
    else:
        result['query'] = str(keyword.string)

    # 基本解释
    basic = root.find(id='phrsListTab')
    if basic:
        trans = basic.find(class_='trans-container')
        if trans:
            result['basic'] = {}
            result['basic']['explains'] = [str(tran.string) for tran in trans.find_all('li')]
            # 中文
            if len(result['basic']['explains']) == 0:
                exp = trans.find(class_='wordGroup').stripped_strings
                result['basic']['explains'].append(' '.join(exp))

                # 音标
            phons = basic(class_='phonetic', limit=2)
            if len(phons) == 2:
                result['basic']['uk-phonetic'], result['basic']['us-phonetic'] = \
                    [str(p.string)[1:-1] for p in phons]
            elif len(phons) == 1:
                result['basic']['phonetic'] = str(phons[0].string)[1:-1]

    # 翻译
    if 'basic' not in result:
        result['translation'] = await get_translation(request, word)

    # 网络释义(短语)
    web = root.find(id='webPhrase')
    if web:
        result['web'] = [
            {
                'key': str(wordgroup.find(class_='search-js').string).strip(),
                'value': [v.strip() for v in str(wordgroup.find('span').next_sibling).split(';')]
            } for wordgroup in web.find_all(class_='wordGroup', limit=4)
        ]
    return result

async def get_translation(request, word):
        """
        通过web版有道翻译抓取翻译结果
        :param word:str 关键字
        :return:list 翻译结果
        """
        cli = request.app.client.cli
        url = 'http://fanyi.youdao.com/translate?keyfrom=dict.top&i='+word

        async with cli.get(url) as res:
            if res.status == 200:
                data = await res.text()
                pattern = re.compile(r'"translateResult":\[(\[.+\])\]')
                m = pattern.search(data)
                result = ujson.loads(m.group(1))

        return [item['tgt'] for item in result]

@youdao_bp.route('/wechat/login', methods=['GET','POST'])
async def wechat_auth(request):
    if request.method == 'GET':
        token = 'WXokChinaCoinJJ'
        data = request.args
        signature = data.get('signature','')
        timestamp = data.get('timestamp','')
        nonce = data.get('nonce','')
        echostr = data.get('echostr','')
        s = [timestamp,nonce,token]
        s.sort()
        s = ''.join(s)
        s = s.encode('utf-8')
        if (hashlib.sha1(s).hexdigest() == signature):
            return html(echostr)
    else:
        rec = request.body
        xml_rec = ET.fromstring(rec)
        tou = xml_rec.find('ToUserName').text
        fromu = xml_rec.find('FromUserName').text
        content = xml_rec.find('Content').text
        if content in ["背单词","生词本"]:
            content = "开始吧"%fromu
        xml_rep = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"

        response = html(xml_rep % (fromu,tou,str(int(time.time())), content))
        response.content_type = 'application/xml'
        return response

    return 'Hello weixin!'

@youdao_bp.route('/wordlists/<word_list_id:int>/review', methods=['GET'])
async def get_word_level(request,word_list_id):
    user_id = request['session'].get('user_id')
    words = []
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    async with request.app.db.acquire() as cur:
        records = await cur.fetch("""select word from user_words where word_list_id=%s and review_time< '%s'"""%(word_list_id,current_time))
        for record in jsonify(records):
            words.append(record['word'])
        return json(words)
    return json([])

@youdao_bp.route('/wordlists/<word_list_id:int>/review', methods=['PUT'])
async def update_word_level(request,word_list_id,words=None):
    user_id = request['session'].get('user_id')
    result = []
    if not words:
        words = ujson.loads(request.body)
    for word in words:
        word_text = word['word']
        async with request.app.db.acquire() as cur:
            record = await cur.fetch("""select words_level from user_words where word='%s' and user_id=%s and word_list_id=%s"""%(word_text,user_id,word_list_id))
            level = record[0]["words_level"]
        state = word['state']
        if state == 'remember':
            level = level+1 if level<=11 else level
            review_time = datetime.datetime.now() + review_time_list[str(level)]
            async with request.app.db.acquire() as cur:
                r = await cur.fetch("""update user_words set words_level = %s,review_time= '%s' where user_id=%s and word='%s' returning *"""%(level,review_time.strftime('%Y-%m-%d %H:%M:%S'),user_id,word_text))
        elif state == 'confuse':
            review_time = datetime.datetime.now()
            async with request.app.db.acquire() as cur:
                r = await cur.fetch("""update user_words set words_level = %s,review_time= '%s' where user_id=%s and word='%s' returning *"""%(level,review_time.strftime('%Y-%m-%d %H:%M:%S'),user_id,word_text))
        elif state == 'not remember':
            level = 0
            async with request.app.db.acquire() as cur:
                r = await cur.fetch("""update user_words set words_level = %s where user_id=%s and word='%s' returning *"""%(level,user_id,word_text))
        result.append(jsonify(r))
    return json(result)


"""Parse response parameters."""

from enum import Enum, auto
from typing import List, NamedTuple, Optional, Union

class LinkedParams:

    def __init__(self, link_url: str, deep: int = 1):
        self.link = link_url
        self.deep = deep

    def __repr__(self):
        return 'Link: {link}'.format(link=self.link)

DOC_FIELDS = {
    'The rest of the fields are not returned to the case owner',
    'STUDY_APPROVE - Notification to approve a study',
    'JOIN_REQUEST - A user has requested to join the account',
    'DESTINATION_SEARCH - Result of a destination search',
    'USER_INVITE- An invitation to join the account to user has being sent to a user',
    'NODE_CONNECT- A user has requested to connect the public node',
    'STUDY_REQUEST_INBOUND - An incoming study request',
    'STUDY_REQUEST_OUTBOUND - An outgoing study request',
    'TRIAL_QC_TASK - A pending clinical trial QC task',
    '* Epoch time of the event',
    '* LOCKOUT if the login failed due to the lockout or PRIMARY if the login failed due to invalid credentials',
    '* The vanity of the event',
    '* The client IP address',
    '* The rest of the fields hold the email and account information depending on the parameters used for /session/login',
}

LINKED_FIELDS = {
    'The rest of the fields are the same as /user/get':
    LinkedParams('user/get'),
    'The permissions for the user in this account':
    LinkedParams('permission_params'),
    '* The rest of the fields are the optional search parameters in either the /destination/search or the /destination/search/mwl call':
    LinkedParams('union[/destination/search,/destination/search/mwl]', deep=2),
    'The fields from /meeting/get':
    LinkedParams('/meeting/get'),
}

FIX_FIELDS_MAP = {
    # TODO: fixed in new api
    'comments • An array of the study comments, order from most recent too earliest. This is only returned if the user has the study_comment_view permissions. Each object has the fields in':
    'comments • An array of the study comments, order from most recent too earliest. This is only returned if the user has the study_comment_view permissions. Each object has the fields in the /study/comment/get call.',
    # TODO: fixed in new api
    'second_opinion_share Flag if this is a  second opinion workflow (optional)':
    'second_opinion_share • Flag if this is a  second opinion workflow (optional)',
    # TODO: fixed in new api
    'second_opinion_config JSON configuration for the second opinion workflow (optional)':
    'second_opinion_config • JSON configuration for the second opinion workflow (optional)',
    # TODO: fixed in new api
    'second_opinion_case The second opinion case. The fields are per /case/get (optional)':
    'second_opinion_case • The second opinion case. The fields are per /case/get (optional)',
    # TODO: fixed in new api
    'second_opinion_share Flag to enable/disable the second opinion workflow for the share':
    'second_opinion_share • Flag to enable/disable the second opinion workflow for the share',
    # TODO: fixed in new api
    'second_opinion_config JSON configuration for the second opinion workflow':
    'second_opinion_config • JSON configuration for the second opinion workflow',
    # TODO: fixed in new api
    'object The object this is applied against':
    'object • The object this is applied against',
}

BAD_FIELDS = {
    # TODO: fixed in new api
    'the /study/comment/get call.'
}

RETURN_REDIRECT = {
    'A redirect to the passed URL which sets an httponly CSFR token cookie',
    'A redirect to the brand OAuth provider',
    'This call returns a 302 redirect to either the study list or study viewer or uploader page  with the session setup in a cookie or in the URL if the link is valid',
    'This creates a link and uses the /link/redirect call to redirect the user to either the study viewer or a study list if multiple studies are found',
    'This link logs the user into a PHR account with any associated studies shared into it',
}

class Redirect:

    def __init__(self, description: str):
        self.descritpion = description

RETURN_STREAM = {
    'Streams back the PDF report':
    'pdf',
    'Streams back the zip file':
    'zip',
    'A CSS file':
    'css',
    'The data in i18next format':
    'i18next',
    'A binary stream of the zipped data with a content type of application/zip':
    'zip',
}

class Stream:

    def __init__(self, description: str, stream_format: str):
        self.descritpion = description
        self.stream_format = stream_format

class ResponseParameter:

    def __init__(
        self, name: Optional[str], description: Optional[str], deep: int = 0
    ):
        self.name = name
        self.description = description
        self.schema: List[Union['ResponseParameter', LinkedParams]] = []
        self.deep = deep

    def add_to_schema(
        self,
        parameter: Union['ResponseParameter', LinkedParams],
    ):
        self.schema.append(parameter)

    @property
    def is_array(self):
        """Is parameter array."""
        if self.description and 'array' in self.description:
            return True
        return False

    def __repr__(self):
        if self.schema:
            schema_str = '\n'.join([str(rparam) for rparam in self.schema], )
            return '''{name}: {description}\n{schema}'''.format(
                name=self.name,
                description=self.description,
                schema=schema_str,
            )
        return '{space}{name}: {description}'.format(
            space=self.deep * ' ',
            name=self.name,
            description=self.description
        )

class ResponseGroupParametersDoc:

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

def parse_response_parameter(parameter_str):
    # TODO: WTF '↳' is (DICT??)?
    if '*':
        deep = parameter_str.count('*') + 1

    if parameter_str in LINKED_FIELDS:
        return LINKED_FIELDS[parameter_str]
    try:
        name, description = parameter_str.split('•')
    except ValueError:
        raise ValueError(parameter_str)
    name = name.replace('*', '').replace('↳', '').strip()
    return ResponseParameter(name, description, deep)

def parse_response_parameters(parameters_str):

    current_deep = 0
    root = ResponseParameter('root', 'root', current_deep)

    previus = [root]

    for parameter_str in parameters_str.split('\n'):
        parameter_str = parameter_str.strip()
        if parameter_str == '':
            continue

        if parameter_str in BAD_FIELDS:
            continue

        if parameter_str in FIX_FIELDS_MAP:
            parameter_str = FIX_FIELDS_MAP[parameter_str]

        if parameter_str.startswith('--') or parameter_str in DOC_FIELDS:
            doc_parameter = ResponseGroupParametersDoc(parameter_str)
            root.add_to_schema(doc_parameter)
            continue

        if parameter_str in RETURN_REDIRECT:
            assert len(root.schema) == 0
            return Redirect(parameter_str)

        if parameter_str in RETURN_STREAM:
            assert len(root.schema) == 0
            return Stream(parameter_str, RETURN_STREAM[parameter_str])

        new_parameter = parse_response_parameter(parameter_str)
        deep = new_parameter.deep

        deep_diff = deep - current_deep

        # It  is not True for /study/timing/log
        # assert deep_diff in (-1, 0, 1)

        if deep_diff <= 0:
            previus.pop()

        previus[-1].add_to_schema(new_parameter)
        previus.append(new_parameter)
        current_deep = deep
    return root.schema


import logging
import numpy as np
import turtle
import time
import sched

class Display:
    def __init__(self):
        self.window = turtle.Screen()
        self.trt = turtle.Turtle(visible=False)
        self.drawables = []
        self.trt.speed(speed = 0)
        self.updates = []
        self.sch = sched.scheduler(time.time, time.sleep)
        self.flag_update("initialized")
        self.bnds = []

    def add_drawable(self, obj):
        self.drawables.append(obj)
        self.flag_update("add_drawable")

    def add_boundary(self, bnd):
        self.bnds.append(bnd)
        self.add_drawable(bnd)

    def redraw(self):
        stime = time.time()
        logging.warning('Began Clearing Updates \n' + str(self.updates) + '\n At time:' + str(stime))
        self.updates.clear()
        self.window.clear()
        for  obj in self.drawables :
            print('drawing: ' + str(obj))
            obj.draw(self.trt)
            self.window.update()
        logging.warning('Finished Clearing Updates at time: ' + str(time.time()) + '   time elapsed: ' + str(time.time()-stime))

    def flag_update(self, update:str):
        if not self.updates:
            self.updates.append([update, time.time()])
            self.sch.enter(delay= 1/60, priority= 1, action = self.redraw)
            self.sch.run()
        else:
            self.updates.append([update, time.time()])
class Drawable:
    def draw(self, trt:turtle.Turtle):
        trt.dot(1)
        logging.warning('default draw used')


import torch
from torchvision.datasets import ImageFolder
from data.transforms import *
import settings.environment as env
import pandas as pd
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.transforms import Resize
from typing import Tuple, Union, List
from pathlib import Path
import os

def preprocess(img: torch.tensor,
                mean: Tuple(float)=(0.485, 0.456, 0.406),
                std: Tuple(float)=(0.485, 0.456, 0.406)
                ) -> np.ndarray:
    """
    Reverse transform an image that was normalized by the dataloader
    to be plotted
    Args:
        img (torch.tensor): data tensor to be visualized
        mean:(Tuple(float)): mean applied in the dataloader Normalize transform
        std:(Tuple(float)): standard deviation applied in the dataloader Normalize transform
    Returns:
        npimg (np.ndarray): data numpy array ready to be imshowed
    """

    for t, m, s in zip(img, mean, std):
        t.mul_(s).add_(m)
    npimg = img.numpy()
    npimg = np.transpose(npimg, (1, 2, 0))
    return npimg

class CelebaDataset(Dataset):
    """
    Custom Dataset for loading CelebA face images
    """

    def __init__(self, txt_path: Union[str, Path],
                img_dir: Union[str, Path],
                transform: transforms=None
                ) -> None:
        """
        Dataset construction
        Args:
            - text_path (Union[str, Path]): path of the csv file containing the image id along with their label
            Example:
                image_id    y
            0   00001.jpg   1
            1   03234.jpg   0
            2   00024.jpg   1

            - img_dir (Union[str, Path]): path of the folder containing the celebaimages
            Example:
                ./datasets/celeba/img_align_celeba
            - transform (torchvision.transforms): image transform to be applied to the image upon getting an item
        """
        df = pd.read_csv(txt_path)
        self.img_dir = img_dir
        self.txt_path = txt_path
        self.img_names = df["image_id"].values
        self.y = df["y"].values
        self.transform = transform

    def __getitem__(self, index: int) -> Tuple[torch.tensor, torch.tensor]:
        """
        Note that at each __getitem__call, the image is loaded
        from the self.img_dir directory using its path
        """
        img = Image.open(os.path.join(self.img_dir,
                                      self.img_names[index])
                        )
        if self.transform is not None:
            img = self.transform(img)

        label = self.y[index]
        return img, label

    def __len__(self) -> int:
        return self.y.shape[0]

def GenerateLabelsFromDNF(dnf: List[List[Tuple[Union(str, int)]]],
                        csv_path: Union[str, Path]
                        ) -> Tuple[np.ndarray, np.ndarray]:
    """
    Generates image ids along with associated label
    where label=1 is given by a disjunctive normal form (dnf)

    Args:
        - dnf (List[List[Tuple[Union(str, int)]]]):
        each disjunctive normal form is parsed as a list of conjunctions,
        where each conjunction is itself a list of predicates, and each predicate
        is a tuple containing the predicate name (e.g. "Blond_Hair") and whether it
        is negated (-1) or not (+1).

        Example:
            To parse "If it's chubby man with gray hair OR a blond women with eye glasses, then label 1",
            write:
            dnf = [
            [("Gray_Hair", 1), ("Male", 1), ("Chubby", 1)],
            [("Blond_Hair", 1), ("Male", -1), ("Eyeglasses", 1)]
            ]

        - csv_path (Union[str, Path]): path of the whole Celeb csv file (list_attr_celeba.csv) containing, for each of the image_id, the boolean evaluation
        of each of the 40 attributes (1 is True, -1 otherwise)

        Aspect of list_attr_celeba.csv:
                image_id    Attribute 1     Attribute 2     Attribute 3     ...
                000001.jpg      -1              1               1           ...
                000002.jpg       1             -1               1           ...
                000003.jpg       1              1               1           ...

    Returns:
        labels (np.ndarray): boolean evaluation of the DNF over each sample of the CelebA dataset
                            (DNF == True is encoded as 1, 0 otherwise)
        paths (np.ndarray): associated image_ids of each CelebA sample
    """

    df = pd.read_csv(csv_path)
    # Load all available binary descriptors/predicates
    predicates = df.columns[1:].to_numpy()

    # Build a dictionary that maps a predicates to an index
    predicates_dict = {value:key for key, value in enumerate(predicates)}

    # Convert DataFrame to numpy array
    df_np = df.to_numpy()
    batch =  df_np[:, 1:]
    labels = np.zeros(batch.shape[0], dtype=int)
    paths = df_np[:, 0]

    # Evaluate each conjunction in the DNF over the batch
    for conj in dnf:
        # From the data, select only the attributes (i.e. columns) involved in the current conjunction
        conj_idx = [predicates_dict[c[0]] for c in conj]
        batch_tmp = batch[:, conj_idx]

        # Form a mask of the same size as batch_tmp to flip the Truth value
        # of the negated predicate in the current conjunction
        mask = np.tile([c[1] for c in conj], (batch.shape[0], 1))

        #Convert -1 (False) + 1 (True) values to 0 (False) 1 (True) values
        batch_tmp = np.maximum(batch_tmp * mask, 0)

        # Evaluate the conjunction by multiplying along dim 1 (along the columns, e.g. predicates)
        labels += np.prod(batch_tmp, axis=1, dtype=int)

    # Evaluate the DNF over the batch
    labels = np.minimum(labels, 1)

    return labels, paths

def CreateDatasetDataFrame(labels: np.ndarray,
                            paths: np.ndarray,
                            csv_path: Union[Path, str],
                            split: int=0
                            ) -> pd.DataFrame:
    """
    Creates a Pandas Dataframe with image_ids along with
    label DNF evaluation, with balanced positive and negative
    examples, for a given split (train, val or test). The split index
    (i.e. whether a sample belongs to train, val or test) is given
     by a .csv file given with the CelebA dataset

    Args:
        - labels (np.ndarray): numpy array with the label/DNF evaluation
        - paths (np.ndarray): numpy array with the image_id associated to each
                            label/DNF evaluation
        -csv_path (Union[Path, str]): path to the list_eval_partition.csv file partition
                                where each image id is paired with a label 0, 1 or 2 if it
                                belongs to the train, val or test split

    Returns:
        df (pd.DataFrame): Pandas Dataframe containing each image id along with label 0 and 1
                            specified by the DNF given. The first N rows are filled with negative
                            examples (label 0) and the next N ones with positive examples (label 1).
                            The examples are shuffle by the Dataloader object that is subsequently
                            built from this Dataframe (see GenerateDataLoader)

        Example:
                image_id    label
            0   000032.jpg      0
            1   000054.jpg      0
            ...
            N   000124.jpg      1
            N+1 000434.jpg      1
            ...
    """

    df_split = pd.read_csv(csv_path)
    df_split_np = df_split.to_numpy()
    split_idx = df_split_np[:, 1]
    labels, paths = labels[split_idx == split], paths[split_idx == split]
    labels_pos = labels[labels == 1]
    paths_pos = paths[labels == 1]
    labels_neg = labels[labels == 0]
    paths_neg = paths[labels == 0]

    # Ensure the classes are even
    if labels_pos.shape[0] >= labels_neg.shape[0]:
        rand_idx = np.random.permutation(np.arange(labels_pos.shape[0]))
        rand_idx = rand_idx[:labels_neg.shape[0]]
        labels_pos = labels_pos[rand_idx]
        paths_pos = paths_pos[rand_idx]
    else:
        rand_idx = np.random.permutation(np.arange(labels_neg.shape[0]))
        rand_idx = rand_idx[:labels_pos.shape[0]]
        labels_neg = labels_neg[rand_idx]
        paths_neg = paths_neg[rand_idx]

    labels = np.concatenate((labels_pos, labels_neg), 0)
    paths = np.concatenate((paths_pos, paths_neg), 0)

    df = np.concatenate((np.expand_dims(paths, 1), np.expand_dims(labels, 1)), axis = 1)
    df = pd.DataFrame(df, columns = ['image_id', 'y'])
    return df

def GenerateSplitFromDNFs(dnf: List[List[Tuple[Union(str, int)]]],
                        csv_attr_path: Union[Path, str],
                        csv_split_path: Union[Path, str],
                        csv_save_path: Union[Path, str]
                        ) -> None:
    """
    Generate a DataFrame file containing image ids along with labels (specified by a DNF)
    for each split (train, val and test) and save them in the dataset directory

    Args:
        - dnf (List[List[Tuple[Union(str, int)]]]):
        each disjunctive normal form is parsed as a list of conjunctions,
        where each conjunction is itself a list of predicates, and each predicate
        is a tuple containing the predicate name (e.g. "Blond_Hair") and whether it
        is negated (-1) or not (+1).

        Example:
            To parse "If it's chubby man with gray hair OR a blond women with eye glasses, then label 1",
            write:
            dnf = [
            [("Gray_Hair", 1), ("Male", 1), ("Chubby", 1)],
            [("Blond_Hair", 1), ("Male", -1), ("Eyeglasses", 1)]
            ]
        - csv_attr_path (Union[Path, str]): path to the .csv file containing the image_ids with the 40 attributes
        - csv_split_path (Union[Path, str]): path to the list_eval_partition.csv file partition
                                where each image id is paired with a label 0, 1 or 2 if it
                                belongs to the train, val or test split
        - csv_save_path (Union[Path, str]): path where to save the output .csv files
    Returns:
        None (directly saves the .csv files generated)
    """

    labels, paths = GenerateLabelsFromDNF(dnf, csv_attr_path)
    dict_split = {"train": 0, "val": 1, "test": 2}
    df_dict = {key: CreateDatasetDataFrame(labels,
                                            paths, csv_split_path,
                                            split=value)
                for key, value in dict_split.items()
                }
    for key, value in df_dict.items():
        assert len(value.loc[value["y"] == 0]) == len(value.loc[value["y"] == 1])
        value.to_csv(csv_save_path + '/' + key + '.csv')

def GenerateDataLoader(csv_path: Union[str, Path],
                        im_path: Union[str, Path],
                        im_size: int,
                        batch_size: int
                        )-> DataLoader:
    '''
    Creates a dataloader object from the csv_path containing image ids and associated labels
    and path of the directory containing the images
    Args:
        - csv_path (Union[str, Path]): csv file containing the image ids along with labels
        - im_path (Union[str, Path]): path of the directory containing the CelebA images
        - im_size (int): desired width and height of the images
        - batch_size (int): desired batch size
    Returns:
        dataloader (DataLoader)
    '''

    custom_transform = transforms.Compose([
                                        transforms.ToTensor(),
                                        # Resize(size=(im_size, im_size)),
                                        # transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
                                        ])

    dataset = CelebaDataset(txt_path=csv_path,
                                img_dir=im_path,
                                transform=custom_transform)

    dataloader = DataLoader(dataset=dataset,
                            batch_size=batch_size,
                            shuffle=True,
                            num_workers=1)

    return dataloader

if __name__ == "__main__":

    '''
    Initial parsing of a disjunctive normal form:
    Example: If (no eye glasses, male and chubby) or (blond hair and female) => 1
    '''

    dnf = [
            [("Gray_Hair", 1), ("Male", 1), ("Chubby", 1)],
            [("Blond_Hair", 1), ("Male", -1), ("Eyeglasses", 1)]
        ]

    GenerateSplitFromDNFs(dnf,
                        env.DATASETS_FOLDER + '/celeba/list_attr_celeba.csv',
                        env.DATASETS_FOLDER + '/celeba/list_eval_partition.csv',
                        env.DATASETS_FOLDER
                        )

    train_loader = GenerateDataLoader(csv_path = env.DATASETS_FOLDER + '/train.csv',
                                        im_path = env.DATASETS_FOLDER + '/celeba/img_align_celeba/',
                                        im_size = 32,
                                        batch_size = 64)

    _, (x, y) = next(enumerate(train_loader))

    x_pos = x[torch.where(y==1)[0], :][:6, :]
    x_neg = x[torch.where(y==0)[0], :][:6, :]

    fig, (axes1, axes2) = plt.subplots(nrows=2, ncols=6, figsize=[16,6])
    for i in range(len(axes1)):
        axes1[i].imshow(preprocess(x_pos[i]))
        axes1[i].set_title("Positive")
        axes2[i].imshow(preprocess(x_neg[i]))
        axes2[i].set_title("Negative")
    plt.show()

    print("Done!")


from flask import Flask, render_template, request

app = Flask(__name__)

notes = []

@app.route("/", methods=["GET", "POST"])
def index():
	if request.method == "POST":
		note = request.form.get('note')
		notes.append(note)

	return render_template("index.html", notes=notes)

# Here every note will be shown up to every user. That's not we want. Go to the "notes using sessions"
# to see the magic of Sessions.


import sys

input = sys.stdin.readline

m, n, b = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(n)]

# 탐색해야 될 최저 높이, 최대 높이 설정
max_level = max([max(x) for x in grid])
min_level = min([min(x) for x in grid])

# [작업시간, 작업 후 블럭 높이]
ans = [sys.maxsize, 0]

# 모든 높이에 대해 완전탐색
for level in range(min_level, max_level+1):
    plus = 0 # 추가해야 되는 블럭 개수
    minus = 0 # 빼야 되는 블럭 개수
    for j in range(n):
        for k in range(n):
            if grid[j][k] > level:
                minus += grid[j][k] - level
            else:
                plus += level - grid[j][k]
    # 블록 개수가 오버되지 않을 때
    if b + minus >= plus:
        time = minus * 2 + plus
        if ans[0] >= time:
            ans = [time, level]

print(ans[0], ans[1])


# coding=utf-8
import re

from typing import Optional, List

from PyQt5.QtCore import QObject, QRegularExpression, pyqtProperty, pyqtSlot
from PyQt5.QtCore import QVariant
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QColor, QFont
from PyQt5.QtGui import QTextCharFormat
from PyQt5.QtQml import QJSValue
from PyQt5.QtQuick import QQuickItem

from ifj2017.ide.code.expression import SyntaxHighlighter, HighlightRule
from ifj2017.ide.settings import SEARCH_FORMAT

__author__ = "Son Hai Nguyen"
__copyright__ = "Copyright 2017, /dej/uran/dom team"
__credits__ = ["Josef Kolář", "Son Hai Nguyen", "Martin Omacht", "Robert Navrátil"]
__license__ = "GNU GPL Version 3"

class ExpSyntaxHighlighter(QObject):
    """
    Class which wraps SyntaxHighliter and expose only target
    """

    searchMatchedLinesChanged = pyqtSignal(QVariant, arguments=["lines"])

    def __init__(self, parent: Optional[QObject] = None):
        super().__init__(parent)

        self._syntax_highlighter = SyntaxHighlighter(self)
        self._base_font = None
        self._search_matched_lines = []

    def _setupFormat(self, color: QColor, fontSettings: QFont, colorIsForeground: bool = True) -> QTextCharFormat:
        pattern_format = QTextCharFormat()
        if color and colorIsForeground:
            pattern_format.setForeground(color)
        if color and (not colorIsForeground):
            pattern_format.setBackground(color)
        pattern_format.setFontItalic(fontSettings.italic())
        pattern_format.setFontWeight(fontSettings.bold())

        return pattern_format

    @pyqtSlot(list, QJSValue, QFont)
    def addHighlightMultiColorRule(self, patterns: List[str], color: QJSValue,
                                   fontSettings: QFont) -> None:
        """
        Adds highlight rule to syntax highlighter
        :param patterns: Regexp pattners to be matched
        :param color: Foreground color of matched text
        :param fontSettings: Determinates font weight and italic
        """

        pattern_format = list()
        self._base_font = fontSettings

        for single_color in color.toVariant():
            pattern_format.append(self._setupFormat(QColor(single_color), fontSettings))

        for single_pattern in patterns:
            self._syntax_highlighter.addHighlightRule(
                HighlightRule(pattern_format, QRegularExpression(single_pattern))
            )

    @pyqtSlot(list, QColor, QFont)
    def addHighlightSingleColorRule(self, patterns: List[str], color: QColor, fontSettings: QFont) -> None:
        """
        Adds highlight rule to syntax highlighter
        :param patterns: Regexp pattners to be matched
        :param color: Foreground color of matched text
        :param fontSettings: Determinates font weight and italic
        """

        pattern_format = self._setupFormat(color, fontSettings)
        self._base_font = fontSettings

        for single_pattern in patterns:
            self._syntax_highlighter.addHighlightRule(
                HighlightRule(pattern_format, QRegularExpression(single_pattern))
            )

    @pyqtSlot(str)
    def setSearchPattern(self, pattern: str) -> None:
        pattern_format = self._setupFormat(QColor(SEARCH_FORMAT), self._base_font, False)
        if pattern:
            self._syntax_highlighter.setSearchRule(
                HighlightRule(pattern_format, QRegularExpression(re.escape(pattern), QRegularExpression.CaseInsensitiveOption))
            )
        else:
            self._syntax_highlighter.setSearchRule(None)
        self._syntax_highlighter.rehighlight()

        self._search_matched_lines = self._syntax_highlighter.searchMatchedLines()
        self.searchMatchedLinesChanged.emit(QVariant(self._search_matched_lines))

    @pyqtProperty(QVariant, notify=searchMatchedLinesChanged)
    def searchMatchedLines(self):
        return QVariant(self._search_matched_lines)

    @pyqtProperty(QQuickItem)
    def target(self) -> None:
        return self._syntax_highlighter.target

    @target.setter
    def target(self, v: QQuickItem) -> None:
        self._syntax_highlighter.target = v


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import telnetlib
import socket

from pylms.server import Server

import Config
from Exceptions import ServerNotFoundException

server = None

def provide():
    global server

    """

    :rtype: Server
    """
    config = Config.get_config()
    hostname = config.get('lms', 'server')
    server = Server(hostname)  # type: Server

    try:
        # schmutzige lösung um den timeout zu verkürzen auf dem pylms server
        server.telnet = telnetlib.Telnet(hostname, 9000, float(config.get('lms', 'timeout')))
        server.connect(False)

        return server
    except socket.error:
        raise ServerNotFoundException("LMS Server \"" + config.get('lms', 'server') + "\" nicht erreichbar!")


import board
from DB.models import Alarm, Comment, User, Lect, LectEnrollment, Board, UserDelete, Bank, LectBoard, ContestBoard
from django.shortcuts import resolve_url
from django.db.models import Q
from user_controller import get_logined_user

# 대댓글 대상자에게 알람 보내는 함수
# 파라미터: 등록할 댓글 객체
def create_comment_alarm(comment: Comment):
    type = comment.comment_type.comment_type_no
    init_dict = {
        "alarm_cont": f"내 게시글에 {comment.comment_writer.user_name}님이 덧글을 남겼습니다."
    }

    if type == 1:
        board = Board.objects.get(pk=comment.comment_board_ref)
        init_dict.update(
            alarm_user=board.board_writer,
            alarm_link=resolve_url("board_detail", board_no=board.board_no)
        )
    elif type == 2:
        contest_board = ContestBoard.objects.get(pk=comment.comment_board_ref)
        init_dict.update(
            alarm_user=contest_board.contest_writer,
            alarm_link=resolve_url("contest_detail", contest_no=contest_board.contest_no)
        )
    elif type == 3:
        lect_board = LectBoard.objects.get(pk=comment.comment_board_ref)
        init_dict.update(
            alarm_user=lect_board.lect_board_writer,
            alarm_link=resolve_url("lect_board_detail", room_no=lect_board.lect_no.lect_no,
                                   lect_board_no=lect_board.lect_board_no)
        )
    elif type == 4:
        user_delete = UserDelete.objects.get(pk=comment.comment_board_ref)
        init_dict.update(
            alarm_user=user_delete.suggest_user,
            alarm_cont=f"내가 발의한 제명안건에 {comment.comment_writer.user_name}님이 덧글을 남겼습니다.",
            alarm_link=resolve_url("member_delete_detail", user_delete_no=user_delete.user_delete_no)
        )
    if init_dict.get("alarm_user") != comment.comment_writer:
        Alarm.objects.create(**init_dict)

        if comment.comment_cont_ref is not None:
            if comment.comment_cont_ref.comment_writer != comment.comment_writer:
                Alarm.objects.create(
                    alarm_user=comment.comment_cont_ref.comment_writer,
                    alarm_cont=f"내 덧글에 {comment.comment_writer.user_name}님께서 덧글을 남기셨습니다.",
                    alarm_link=init_dict.get("alarm_link")
                )

# user: alarm을 보낼 유저 객체
def create_user_role_update_alarm(user: User):
    alarm = Alarm.objects.create(
        alarm_user=user,
        alarm_cont="회원 등급이 " + user.user_role.role_name + "으로 업데이트 되었습니다.",
        alarm_link=resolve_url("my_info")
    )
    alarm.save()

# user: alarm을 보낼 유저 객체, is_apply: 계정 승인이 막 되었을 때.
def create_user_auth_update_alarm(user: User, is_apply):
    alarm_cont = str()
    if user.user_auth.auth_no == 1:
        alarm_cont = "계정이 활성화되었습니다. 모든 기능을 사용할 수 있습니다."
    elif user.user_auth.auth_no == 2 and is_apply:
        alarm_cont = "가입이 승인되었습니다. 회비를 납부하시면 모든 기능이 활성화됩니다."
    elif user.user_auth.auth_no == 2 and not is_apply:
        alarm_cont = "계정이 비활성화되었습니다. 일부 기능이 제한됩니다."
    alarm = Alarm.objects.create(
        alarm_user=user,
        alarm_cont=alarm_cont,
        alarm_link=resolve_url("my_info")
    )
    alarm.save()

# 강의 등록이 가득 찼을 때 띄우는 알림
def create_lect_full_alarm(lect: Lect):
    if len(LectEnrollment.objects.filter(lect_no=lect)) == lect.lect_limit_num:
        Alarm.objects.create(
            alarm_user=lect.lect_chief,
            alarm_cont="개설하신 " + lect.lect_title + lect.lect_type.type_name + "(이)가 가득 찼습니다.",
            alarm_link=resolve_url("lect_detail", lect_no=lect.lect_no)
        )

# 강의 등록이 성공하였을 때 띄우는 알림(학생관점)
def create_lect_enroll_alarm(lect_enroll: LectEnrollment):
    Alarm.objects.create(
        alarm_user=lect_enroll.student,
        alarm_cont=lect_enroll.lect_no.lect_title + lect_enroll.lect_no.lect_type.type_name + "에 성공적으로 등록되었습니다.",
        alarm_link=resolve_url("lect_detail", lect_no=lect_enroll.lect_no.lect_no)
    )

# 공지사항이 올라갈 시 전체 알림
def create_board_notice_alarm(board: Board):
    if board.board_type_no.board_type_no == 1:
        user_list = User.objects.filter(~Q(user_stu=board.board_writer.user_stu))
        for user in user_list:
            Alarm.objects.create(
                alarm_user=user,
                alarm_cont="새로운 공지사항이 등록되었습니다.",
                alarm_link=resolve_url("board_detail", board_no=board.board_no)
            )

# 관리자에 의해 게시글이 삭제되었을 때 알림
def delete_board_by_superuser_alarm(request, board: Board):
    Alarm.objects.create(
        alarm_user=board.board_writer,
        alarm_cont=get_logined_user(
            request).user_name + "님에 의해 \"" + board.board_title[:7] + "...\" 게시글이 삭제되었습니다. 운영 정책에 위반됩니다.",
        alarm_link=resolve_url("board_view", board_type_no=board.board_type_no.board_type_no)
    )

# 관리자에 의해 강의가 삭제되었을 때 알림.
def delete_lect_by_superuser_alarm(request, lect: Lect):
    lect_type = lect.lect_type.type_no
    Alarm.objects.create(
        alarm_user=lect.lect_chief,
        alarm_cont=get_logined_user(request).user_name + "님에 의해 \"" + lect.lect_title[
                                                                      :7] + "...\" 강의가 삭제되었습니다. 운영 정책에 위반됩니다.",
        alarm_link=resolve_url("lect_view", type_no=lect_type)
    )

# 관리자에 의해 강의 게시글이 삭제되었을 때 알림.
def delete_lect_board_by_superuser_alarm(request, lect_board: LectBoard):
    lect_no = lect_board.lect_no.lect_no
    Alarm.objects.create(
        alarm_user=lect_board.lect_board_writer,
        alarm_cont=get_logined_user(request).user_name + "님에 의해\"" + lect_board.lect_board_title[
                                                                     :7] + "...\" 강의가 삭제되었습니다. 운영 정책에 위반됩니다.",
        alarm_link=resolve_url("lect_room_main", room_no=lect_no)
    )

# 제명 안건이 올라왔을 때
def create_user_delete_alarm(user_delete: UserDelete):
    Alarm.objects.create(
        alarm_user=user_delete.deleted_user,
        alarm_cont="귀하에게 제명 안건이 발안되었습니다.",
        alarm_link=resolve_url("member_delete_detail", user_delete_no=user_delete.user_delete_no)
    )

    chief_list = User.objects.filter(Q(user_role__role_no__lte=4) & ~Q(user_stu=user_delete.deleted_user.user_stu) & ~Q(
        user_stu=user_delete.suggest_user.user_stu))
    for chief in chief_list:
        Alarm.objects.create(
            alarm_user=chief,
            alarm_cont=user_delete.deleted_user.user_name + "님에게 제명안건이 발안되었습니다. 투표해주세요.",
            alarm_link=resolve_url("member_delete_detail", user_delete_no=user_delete.user_delete_no)
        )

# 제명 안건이 가결되었을 때
def create_finish_user_delete_alarm(user_delete: UserDelete):
    Alarm.objects.create(
        alarm_user=User.objects.filter(Q(user_role__role_no=1) & Q(user_auth__auth_no=1)).first(),
        alarm_cont=user_delete.deleted_user.user_name + "님 앞으로 발안된 제명안건이 가결되었습니다. 제명 버튼이 활성화됩니다.",
        alarm_link=resolve_url("member_delete_detail", user_delete_no=user_delete.user_delete_no)
    )

# 예산 지원신청을 넣었을 때
def create_bank_alarm(bank: Bank):
    cfo_list = User.objects.filter(Q(user_role__role_no=4) & Q(user_auth__auth_no=1))
    for cfo in cfo_list:
        Alarm.objects.create(
            alarm_user=cfo,
            alarm_cont="새로운 예산 지원신청이 등록되었습니다.",
            alarm_link=resolve_url("bank_support_detail", bank_no=bank.bank_no)
        )

# 새로운 회원이 가입을 할 경우
def create_user_join_alarm(user: User):
    # 운영팀 이상의 회장단을 데려 옴
    chief_crews = User.objects.filter(Q(user_role__role_no__lte=3) & Q(user_auth__auth_no=1))

    for chief_crew in chief_crews:
        Alarm.objects.create(
            alarm_user=chief_crew,
            alarm_cont=user.user_name + "님이 가입 대기중입니다. 확인해주세요.",
            alarm_link=resolve_url("staff_member_list")
        )

# 회원이 회비 납부요청을 할 경우.
def create_user_activate_alarm(user: User):
    cfo_list = User.objects.filter(Q(user_role__role_no=4) & Q(user_auth__auth_no=1))
    for cfo in cfo_list:
        Alarm.objects.create(
            alarm_user=cfo,
            alarm_cont=user.user_name + "님이 회비 납부하였습니다. 확인 후, 권한을 수정해주세요.",
            alarm_link=resolve_url("staff_member_list")
        )

# 강의에서 퇴출당할 경우
def create_user_lect_out_alarm(lect_enrollment: LectEnrollment):
    Alarm.objects.create(
        alarm_user=lect_enrollment.student,
        alarm_cont=f"{lect_enrollment.lect_no.lect_chief.user_name}(강의자)님에 의해 \"{lect_enrollment.lect_no.lect_title}\" 강의에서 퇴출되었습니다.",
        alarm_link=resolve_url("index")
    )


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 19 10:49:44 2021

@author: asus
"""

import pandas as pd
fire_and_ambulance=pd.read_csv('FireBrigadeAndAmbulanceCallOuts.csv')
num_of_rows=fire_and_ambulance.shape[0]
num_of_cols=fire_and_ambulance.shape[1]
print("\nNumber of rows:" ,num_of_rows)
print("Number of columns:" ,num_of_cols)
non_null_rows_count=fire_and_ambulance.notnull().sum()
print("\nNumber of non-null values (by column):\n" ,non_null_rows_count)
null_rows_count=fire_and_ambulance.isnull().sum()
print("\nNumber of null values (by column):\n" ,null_rows_count)
total_null_count=fire_and_ambulance.isnull().sum().sum()
print("\nNumber of null values for all columns:\n" ,total_null_count)
call_out_by_stationarea = pd.DataFrame(fire_and_ambulance.groupby('Station Area').size())
print("\nTotal number of call outs by Station Area:\n", call_out_by_stationarea)
call_out_by_stationarea_and_date = pd.DataFrame(fire_and_ambulance.groupby(by=['Date','Station Area']).size())
print("\nTotal number of call outs by Date and Station Area:\n", call_out_by_stationarea_and_date)
filter=['Fire CAR','Fire ALARM']
fire_data=fire_and_ambulance.loc[fire_and_ambulance['Description'].isin(filter)]
fire_callout = pd.DataFrame(fire_data.groupby(by=['Station Area','Date']).size())
print("\nTotal number of call outs by Station Area and Date where the description is either Fire Car or Fire Alarm:\n",fire_callout)
replace_comma_and_dash=fire_and_ambulance.replace(',',' ', regex=True)
replace_comma_and_dash=replace_comma_and_dash.replace('-',' ', regex=True)
drop_null_rows=replace_comma_and_dash.dropna(subset=['AH','MAV','CD'])
drop_duplicate_rows=drop_null_rows.drop_duplicates()
min_time_diff= pd.DataFrame(pd.to_datetime(fire_and_ambulance.ORD)-pd.to_datetime(fire_and_ambulance.TOC))
print("\nminimum time difference between TOC and ORD:" ,min_time_diff)
cleaned_data= pd.DataFrame(drop_duplicate_rows)
print("\nCleaned final data:" ,cleaned_data)


import functools
import json
from flask import Flask, Blueprint, session, make_respose
from flask_restful import request, Api, abort, Resource, url_for

app = Flask(__name__)
app.config["SECRET_KEY"] ="THUgLif3"
api_bp =  Blueprint("api", __name__)
api = Api(api_bp)

"""
Below uses default config;
spaces -> 4
"""

@api.representation("application/json")
def out_json(data, code, headers=None):
    resp = api.make_response(json.dumps(data), code)
    resp.headers.extend(headers or {})
    return resp

@api.blueprint.before_app_request
def before():
    user = session.get("user")
    if user is None:
        session["user"] = "Guest"

def data_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        info_ = session.get("data")
        if info_ is None:
            abort(401)
        return view(**kwargs)
    return wrapped_view

@api.blueprint.route("/")
def get_data():
    data = {"name": "Collins"}
    if session.get("user") == "Guest":
        info = {"name":"Collins", "age": 21}
        print(json.dumps(info))
    return {"data":data, "info": info} , 200

@api.blueprint.route("/home/<string:message>",methods=["GET", "POST", "PUT", "HEAD"])
def home(message):
    return {"message":message}, 200

@api.blueprint.route("/red/", methods=["GET"])
def redr():
    return url_for("api.red"), 302

@api.blueprint.route("/redr", methods=["GET"])
def red():
    message = "I am legend"
    return {"message": message}, 200

class AddData(Resource):
    def post(self):
        data = request.json["data"]
        session["data"] = data
        return {"data": data}, 201

api.add_resource(AddData, "/", methods=["POST"])

datamodel = {"name":"Collins"}
class DataModel(Resource):
    method_decorators = [data_required]

    def get(self):
        print(session)
        return datamodel, 200

    def post(self):
        age = request.json["age"]
        datamodel["age"] = age
        print(session)
        return ({"data": datamodel},{"newdata":{"age": age}}), 201

    def put(self):
        name = request.json["name"]
        age = request.json["age"]
        datamodel["name"] = name
        datamodel["age"] = age
        print(session)
        return {"datamodel": datamodel}, 201

    def delete(self):
        print(session)
        session.clear()
        datamodel.clear()
        return "", 204

api.add_resource(DataModel, "/data")
app.register_blueprint(api_bp)

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

"""
blueprints
decorators
use json output
"""


import pandas
import math

def dropUnwantedColumns(df):
    columnsToDrop = [
        'ID',
        'ATENDIMENTO',
        'PACIENTE',
        'DS_SERVICO',
        'UNIDADE',
        'MOTIVO_ALTA',
        #'AGRUPA_ALTA', # Indica se foi óbito
        'STATUS',
        'DATA_ALTA_E_ATEN',
        '....CID',
        '....DS_CID',
        '....GRUPO_CID',
        '....CASOS_PREENCHIDOS',
        '....QT_PRESTADOR',
        '....DS_SGRU_CID',
        '....DS_GRU_CID',
        'PRESTADOR',
        'NR_CEP',
        'CD_UF',
        'CEP_INIT',
        'CD_CID_INT',
        'Procedencia.BUSCA_PROCEDENCIA',
        'table_procedencia.DS_LOC_PROCED',
        'table_procedencia.SN_PROCEDENCIA_EXTERNA',
        'DS_TIPO_INTERNACAO',
        'CD_TIP_ACOM',
        'DS_TIP_ACOM',
    ]
    df.drop(columnsToDrop, inplace=True, axis=1)
    return df

def addSectionAndSubregion(df):
    # Adiciona setor e subregião com base no CEP
    df['SETOR'] = df['CEP_INIT'].apply(lambda x: math.ceil(x/10))
    df['SUBREGIAO'] = df['CEP_INIT'].apply(lambda x: math.ceil(x/100))
    return df

def removeProc(dataframe):
    # Remove linhas com base na Procedência
    procToRemove = ["DOMICILIO", "DEMANDA ESPONTANEA", "POLICIA", "OUTRAS PROCEDENCIAS", "TRABALHO", "VIA URBANA", "...", "...."]
    dataframe = dataframe[dataframe['Procedencia'].isin(procToRemove) == False]
    return dataframe

def removeCities(dataframe):
    # Remove linhas com base na Cidade
    citiesToKeep = ["SAO PAULO"]
    return dataframe[dataframe['CIDADE'].isin(citiesToKeep)]

def fixAgeGroup(df):
    # Corrige valores de Faixa Etária
    df.loc[df['FX_ETARIA'] == '5-Sep', 'FX_ETARIA'] = '05 - 09'
    df.loc[df['FX_ETARIA'] == 'Oct-14', 'FX_ETARIA'] = '10 - 14'
    df.loc[df['FX_ETARIA'] == '0 - 04', 'FX_ETARIA'] = '00 - 04'
    df.loc[df['FX_ETARIA'] == '80 -', 'FX_ETARIA'] = '80 - 99'
    return df

def cleanIt(df):
    df = addSectionAndSubregion(df)
    df = dropUnwantedColumns(df)
    df = removeProc(df)
    df = removeCities(df)
    df = fixAgeGroup(df)

    return df


'''
while True:
    oprt = input("请选择需要执行的选项:")
    print("你选择了选项:",oprt)
    if oprt == "1":
        print("吃饭")
    elif oprt == "2":
        print("睡觉")
    elif oprt == "3":
        print("打豆豆")
    elif oprt == "exit":
        print("正在退出")
    else:
        print("输入错误，请重新输入")
print("End")
'''

'''
l2 = []
j = 0
while j<6:
    l1 = []
    i = 0
    while i<6:
        l1.append(0)
        i = i+1
    l2.append(l1)
    j = j+1

for a in l2:
    for b in l1:
        print(b,end=" ")
    print(" ")
'''

while True:
    oper = input("Please input the size of chessmap:")
    if oper == "q":
        print("exit")
        break
    num = int(oper)
    if num:
        chessmap = []
        j = 0
        while j<num:
            k = []
            i = 0
            while i<num:
                k.append(0)
                i = i+1
            chessmap.append(k)
            j = j+1
        for a in chessmap:
            for c in a:
                print(c,end=" ")
            print(" ")


import copy

from methods import BaseMethod, get_optimizer
from networks import to_device
import losses

class CoVWeightingMethod(BaseMethod):

    def __init__(self, args, loader):
        super(CoVWeightingMethod, self).__init__(args, loader)

        if args.mode == 'train':
            self.criterion = losses.CoVWeightingLoss(args)
            self.criterion.to(self.device)
            self.optimizer = get_optimizer(self.G.parameters(), args)

            # Record the mean weights for an epoch.
            self.mean_weights = [0.0 for _ in range(self.criterion.alphas.shape[0])]

    def set_input(self, data):
        self.data = to_device(data, self.device)
        self.left = self.data['left_image']
        self.right = self.data['right_image']

    def forward(self):
        self.disps = self.G(self.left)

    def backward(self):
        loss_G = self.criterion.forward(self.disps, [self.left, self.right])
        loss_G.backward()
        return loss_G.item()

    def optimize_parameters(self):
        self.optimizer.zero_grad()
        self.forward()
        loss = self.backward()
        self.optimizer.step()

        # Finally, add the scales to the mean scales to get an idea of the mean weights after training.
        for i, weight in enumerate(self.criterion.alphas):
            self.mean_weights[i] += (weight.item() / len(self.loader))
        return loss

    def get_untrained_loss(self):
        loss_G = self.criterion.forward(self.disps, [self.left, self.right])
        return loss_G.item()

    def store_val_loss(self, val_loss, epoch):
        super(CoVWeightingMethod, self).store_val_loss(val_loss, epoch)
        # Besides also store the weights from past training epoch.
        if epoch >= 0:
            self.losses[epoch]['alphas'] = copy.deepcopy(self.mean_weights)
            self.mean_weights = [0.0 for _ in range(self.criterion.alphas.shape[0])]

    @property
    def method(self):
        return 'CoV-Weighting Method'


import socketio
import json
import threading
import time
import alsaaudio

# The ObjectRecognitionWorker class starts the object recognition service on a seperate thread, where it
# uses a socket to connect to the YOLO server. Via the socket, it receives detected objects, and relays them
# as audio. Takes in a priority table, which is used to fetch priorities of different objects, and reset
# the priorities via web requests. Takes in the confidence threshold for object recognition such that
# all detections with a condience less than the minimum threshold are discarded. Also takes in the audio
# controller to play/save audio files. Takes in the yolo server link to connect to the server and receive
# detections
class ObjectRecognitionWorker:

    socket = socketio.Client()

    def __init__(self, server_link, priority_table, conf_thresh, audio_controller):
        self.audioPlaybackTime = 5
        self.detection_count = 0
        self.link = server_link
        self.detections_buffer = []
        self.priority_table = priority_table
        self.conf_thresh = conf_thresh
        self.audio_controller = audio_controller
        threading.Thread(target=self.connect_to_server).start()

    # Updates the detections buffer, filtering out detections that are redundant from the previous scene.
    # After filtering out redundant detections, only updates buffer with ten objects with the highest recognition
    # priority as set by the user, then plays out the newly detected objects in the new scene.
    def update_detections_buffer(self, new_detections):
        # get detections that were not present in existing detections buffer
        updated_detections = [new_obj for new_obj in new_detections if new_obj not in self.detections_buffer]

        # new objects detected, remove redundant objects and add new ones
        # if scene did not change (all objects still in scene), do not play audio (dont do anything)
        # sort updated detections by priority, and include only top n detections
        # update detections_buffer
        if (updated_detections):
          self.detections_buffer = self.priority_table.sort_by_priority(updated_detections)[:10]
          audio_string = ''
          for detection in self.detections_buffer:
              audio_string += str(detection["count"]) + ' ' + str(detection["class"])
          if (audio_string):
            #self.audio_controller.acquire_audio_lock()
            self.audio_controller.play_audio(audio_string)
            #self.audio_controller.release_audio_lock()

    # handles web app requests related to object recognition. Involves requests such as enabling/disabling object
    # recognition audio, updating the recognition priority of different objects, changing the volume of audio relays,
    # and changing the audio playback time.
    def handle_event(self, event):
        self.volumeControl = event.volumeControl
        self.isAudioOn = event.isAudioOn
        self.voiceGender = event.voiceGender # does not look doable in gtts- can instead change accent by using uk-en
        self.priority_table.update_priorities(event.objsPriority)
        self.audioPlaybackTime = event.audioPlaybackTime

        m = alsaaudio.Mixer()
        if(self.isAudioOn):
            m.setvolume(int(self.volumeControl))
        else:
            m.setvolume(0)

        response = "Updated state values for object recognition"
        print(response)
        return response

    # Connects the socket to the YOLO server. Attempts to reconnect every 5 seconds on disconnect.
    # Defines different event handlers depending on the event received by the socket from the YOLO server.
    def connect_to_server(self):

        # service identifies itself as obj recognition service to YOLO server on connect
        @self.socket.event
        def connect():
            print('Object Recognition Service: connected to YOLO server')
            self.socket.emit('see_rasp_pi')

        # tells the user that the service has disconnected on disconnect
        @self.socket.event
        def disconnect():
            print('Object Recognition Service: disconnected from YOLO server')

        # handles the "detections" event emitted by the YOLO server. Receives detections from the server,
        # parses them, and calls self.update_detections_buffer to update the new detections and relay the
        # detections as audio
        @self.socket.event
        def detections(detections):
            self.detection_count += 1

            # output sound for each fifth detection
            if (self.detection_count % self.audioPlaybackTime == 0):
                filtered_detections = []
                for detection in json.loads(detections):
                    print(detection)
                    _confidence = detection['confidence']
                    _class = detection['class']
                    _count = detection['count']

                    # remove detections with conf < conf_thresh
                    for conf in _confidence:
                        if (float(conf) < self.conf_thresh):
                            _count -= 1
                    if _count > 0:
                      filtered_detections.append({"class": _class, "count": _count})

                self.update_detections_buffer(filtered_detections)
        try:
            self.socket.connect(self.link)
            self.socket.wait()
        except Exception as e:
            print("Object Recognition Service: YOLO server not yet started. Attempting to reconnect...")
            time.sleep(5)
            self.connect_to_server()


import json
from typing import Any, Dict, List, Optional, Union

from flet_core.border import Border, BorderSide
from flet_core.constrained_control import ConstrainedControl
from flet_core.control import Control, OptionalNumber
from flet_core.control_event import ControlEvent
from flet_core.event_handler import EventHandler
from flet_core.gesture_detector import TapEvent
from flet_core.gradients import Gradient
from flet_core.ref import Ref
from flet_core.text_style import TextStyle
from flet_core.types import (
    AnimationValue,
    BorderRadiusValue,
    MaterialState,
    OffsetValue,
    ResponsiveNumber,
    RotateValue,
    ScaleValue,
)

class DataColumnSortEvent(ControlEvent):
    def __init__(self, i, a) -> None:
        self.column_index: int = i
        self.ascending: bool = a

class DataColumn(Control):
    def __init__(
        self,
        label: Control,
        ref=None,
        visible: Optional[bool] = None,
        disabled: Optional[bool] = None,
        data: Any = None,
        # specific
        numeric: Optional[bool] = None,
        tooltip: Optional[str] = None,
        on_sort=None,
    ):
        Control.__init__(self, ref=ref, visible=visible, disabled=disabled, data=data)

        self.__on_sort = EventHandler(
            lambda e: DataColumnSortEvent(**json.loads(e.data))
        )
        self._add_event_handler("sort", self.__on_sort.get_handler())

        self.label = label
        self.numeric = numeric
        self.tooltip = tooltip
        self.on_sort = on_sort

    def _get_control_name(self):
        return "c"

    def _get_children(self):
        children = []
        if self.__label:
            self.__label._set_attr_internal("n", "l")
            children.append(self.__label)
        return children

    # label
    @property
    def label(self):
        return self.__label

    @label.setter
    def label(self, value):
        self.__label = value

    # numeric
    @property
    def numeric(self) -> Optional[bool]:
        return self._get_attr("numeric", data_type="bool", def_value=False)

    @numeric.setter
    def numeric(self, value: Optional[bool]):
        self._set_attr("numeric", value)

    # tooltip
    @property
    def tooltip(self):
        return self._get_attr("tooltip")

    @tooltip.setter
    def tooltip(self, value):
        self._set_attr("tooltip", value)

    # on_sort
    @property
    def on_sort(self):
        return self.__on_sort

    @on_sort.setter
    def on_sort(self, handler):
        self.__on_sort.subscribe(handler)
        self._set_attr("onSort", True if handler is not None else None)

class DataCell(Control):
    def __init__(
        self,
        content: Control,
        ref=None,
        visible: Optional[bool] = None,
        disabled: Optional[bool] = None,
        data: Any = None,
        # specific
        on_double_tap=None,
        on_long_press=None,
        on_tap=None,
        on_tap_cancel=None,
        on_tap_down=None,
        placeholder: Optional[bool] = None,
        show_edit_icon: Optional[bool] = None,
    ):
        Control.__init__(self, ref=ref, visible=visible, disabled=disabled, data=data)

        self.__on_tap_down = EventHandler(lambda e: TapEvent(**json.loads(e.data)))
        self._add_event_handler("tap_down", self.__on_tap_down.get_handler())

        self.content = content
        self.on_double_tap = on_double_tap
        self.on_long_press = on_long_press
        self.on_tap = on_tap
        self.on_tap_cancel = on_tap_cancel
        self.on_tap_down = on_tap_down
        self.placeholder = placeholder
        self.show_edit_icon = show_edit_icon

    def _get_control_name(self):
        return "c"

    def _get_children(self):
        return [self.__content]

    # content
    @property
    def content(self):
        return self.__content

    @content.setter
    def content(self, value):
        self.__content = value

    # placeholder
    @property
    def placeholder(self) -> Optional[bool]:
        return self._get_attr("placeholder", data_type="bool", def_value=False)

    @placeholder.setter
    def placeholder(self, value: Optional[bool]):
        self._set_attr("placeholder", value)

    # show_edit_icon
    @property
    def show_edit_icon(self) -> Optional[bool]:
        return self._get_attr("showEditIcon", data_type="bool", def_value=False)

    @show_edit_icon.setter
    def show_edit_icon(self, value: Optional[bool]):
        self._set_attr("showEditIcon", value)

    # on_double_tap
    @property
    def on_double_tap(self):
        return self._get_event_handler("double_tap")

    @on_double_tap.setter
    def on_double_tap(self, handler):
        self._add_event_handler("double_tap", handler)
        self._set_attr("onDoubleTap", True if handler is not None else None)

    # on_long_press
    @property
    def on_long_press(self):
        return self._get_event_handler("long_press")

    @on_long_press.setter
    def on_long_press(self, handler):
        self._add_event_handler("long_press", handler)
        self._set_attr("onLongPress", True if handler is not None else None)

    # on_tap
    @property
    def on_tap(self):
        return self._get_event_handler("tap")

    @on_tap.setter
    def on_tap(self, handler):
        self._add_event_handler("tap", handler)
        self._set_attr("onTap", True if handler is not None else None)

    # on_tap_cancel
    @property
    def on_tap_cancel(self):
        return self._get_event_handler("tap_cancel")

    @on_tap_cancel.setter
    def on_tap_cancel(self, handler):
        self._add_event_handler("tap_cancel", handler)
        self._set_attr("onTapCancel", True if handler is not None else None)

    # on_tap_down
    @property
    def on_tap_down(self):
        return self.__on_tap_down

    @on_tap_down.setter
    def on_tap_down(self, handler):
        self.__on_tap_down.subscribe(handler)
        self._set_attr("onTapDown", True if handler is not None else None)

class DataRow(Control):
    def __init__(
        self,
        cells: Optional[List[Control]] = None,
        ref=None,
        visible: Optional[bool] = None,
        disabled: Optional[bool] = None,
        data: Any = None,
        # specific
        color: Union[None, str, Dict[MaterialState, str]] = None,
        selected: Optional[bool] = None,
        on_long_press=None,
        on_select_changed=None,
    ):
        Control.__init__(self, ref=ref, visible=visible, disabled=disabled, data=data)

        self.cells = cells
        self.color = color
        self.selected = selected
        self.on_long_press = on_long_press
        self.on_select_changed = on_select_changed

    def _get_control_name(self):
        return "r"

    def _before_build_command(self):
        super()._before_build_command()
        self._set_attr_json("color", self.__color)

    def _get_children(self):
        return self.__cells

    # cells
    @property
    def cells(self):
        return self.__cells

    @cells.setter
    def cells(self, value):
        self.__cells = value if value is not None else []

    # color
    @property
    def color(self) -> Union[None, str, Dict[MaterialState, str]]:
        return self.__color

    @color.setter
    def color(self, value: Union[None, str, Dict[MaterialState, str]]):
        self.__color = value

    # selected
    @property
    def selected(self) -> Optional[bool]:
        return self._get_attr("selected", data_type="bool", def_value=False)

    @selected.setter
    def selected(self, value: Optional[bool]):
        self._set_attr("selected", value)

    # on_long_press
    @property
    def on_long_press(self):
        return self._get_event_handler("long_press")

    @on_long_press.setter
    def on_long_press(self, handler):
        self._add_event_handler("long_press", handler)
        self._set_attr("onLongPress", True if handler is not None else None)

    # on_select_changed
    @property
    def on_select_changed(self):
        return self._get_event_handler("select_changed")

    @on_select_changed.setter
    def on_select_changed(self, handler):
        self._add_event_handler("select_changed", handler)
        self._set_attr("onSelectChanged", True if handler is not None else None)

class DataTable(ConstrainedControl):
    def __init__(
        self,
        columns: Optional[List[DataColumn]] = None,
        rows: Optional[List[DataRow]] = None,
        ref: Optional[Ref] = None,
        key: Optional[str] = None,
        width: OptionalNumber = None,
        height: OptionalNumber = None,
        left: OptionalNumber = None,
        top: OptionalNumber = None,
        right: OptionalNumber = None,
        bottom: OptionalNumber = None,
        expand: Union[None, bool, int] = None,
        col: Optional[ResponsiveNumber] = None,
        opacity: OptionalNumber = None,
        rotate: RotateValue = None,
        scale: ScaleValue = None,
        offset: OffsetValue = None,
        aspect_ratio: OptionalNumber = None,
        animate_opacity: AnimationValue = None,
        animate_size: AnimationValue = None,
        animate_position: AnimationValue = None,
        animate_rotation: AnimationValue = None,
        animate_scale: AnimationValue = None,
        animate_offset: AnimationValue = None,
        on_animation_end=None,
        tooltip: Optional[str] = None,
        visible: Optional[bool] = None,
        disabled: Optional[bool] = None,
        data: Any = None,
        #
        # DataTable-specific
        #
        border: Optional[Border] = None,
        border_radius: BorderRadiusValue = None,
        horizontal_lines: Optional[BorderSide] = None,
        vertical_lines: Optional[BorderSide] = None,
        checkbox_horizontal_margin: OptionalNumber = None,
        column_spacing: OptionalNumber = None,
        data_row_color: Union[None, str, Dict[MaterialState, str]] = None,
        data_row_min_height: OptionalNumber = None,
        data_row_max_height: OptionalNumber = None,
        data_text_style: Optional[TextStyle] = None,
        bgcolor: Optional[str] = None,
        gradient: Optional[Gradient] = None,
        divider_thickness: OptionalNumber = None,
        heading_row_color: Union[None, str, Dict[MaterialState, str]] = None,
        heading_row_height: OptionalNumber = None,
        heading_text_style: Optional[TextStyle] = None,
        horizontal_margin: OptionalNumber = None,
        show_bottom_border: Optional[bool] = None,
        show_checkbox_column: Optional[bool] = None,
        sort_ascending: Optional[bool] = None,
        sort_column_index: Optional[int] = None,
        on_select_all=None,
    ):
        ConstrainedControl.__init__(
            self,
            ref=ref,
            key=key,
            width=width,
            height=height,
            left=left,
            top=top,
            right=right,
            bottom=bottom,
            expand=expand,
            col=col,
            opacity=opacity,
            rotate=rotate,
            scale=scale,
            offset=offset,
            aspect_ratio=aspect_ratio,
            animate_opacity=animate_opacity,
            animate_size=animate_size,
            animate_position=animate_position,
            animate_rotation=animate_rotation,
            animate_scale=animate_scale,
            animate_offset=animate_offset,
            on_animation_end=on_animation_end,
            tooltip=tooltip,
            visible=visible,
            disabled=disabled,
            data=data,
        )

        self.columns = columns
        self.rows = rows
        self.border = border
        self.border_radius = border_radius
        self.horizontal_lines = horizontal_lines
        self.vertical_lines = vertical_lines
        self.bgcolor = bgcolor
        self.gradient = gradient
        self.divider_thickness = divider_thickness
        self.checkbox_horizontal_margin = checkbox_horizontal_margin
        self.column_spacing = column_spacing
        self.data_row_color = data_row_color
        self.data_row_min_height = data_row_min_height
        self.data_row_max_height = data_row_max_height
        self.data_text_style = data_text_style
        self.heading_row_color = heading_row_color
        self.heading_row_height = heading_row_height
        self.heading_text_style = heading_text_style
        self.horizontal_margin = horizontal_margin
        self.show_bottom_border = show_bottom_border
        self.show_checkbox_column = show_checkbox_column
        self.sort_ascending = sort_ascending
        self.sort_column_index = sort_column_index
        self.on_select_all = on_select_all

    def _get_control_name(self):
        return "datatable"

    def _before_build_command(self):
        super()._before_build_command()
        self._set_attr_json("border", self.__border)
        self._set_attr_json("gradient", self.__gradient)
        self._set_attr_json("borderRadius", self.__border_radius)
        self._set_attr_json("horizontalLines", self.__horizontal_lines)
        self._set_attr_json("verticalLines", self.__vertical_lines)
        self._set_attr_json("dataRowColor", self.__data_row_color)
        self._set_attr_json("headingRowColor", self.__heading_row_color)
        self._set_attr_json("dataTextStyle", self.__data_text_style)
        self._set_attr_json("headingTextStyle", self.__heading_text_style)

    def _get_children(self):
        children = []
        children.extend(self.__columns)
        children.extend(self.__rows)
        return children

    # columns
    @property
    def columns(self):
        return self.__columns

    @columns.setter
    def columns(self, value: Optional[List[DataColumn]]):
        self.__columns = value if value is not None else []

    # rows
    @property
    def rows(self):
        return self.__rows

    @rows.setter
    def rows(self, value: Optional[List[DataRow]]):
        self.__rows = value if value is not None else []

    # border
    @property
    def border(self) -> Optional[Border]:
        return self.__border

    @border.setter
    def border(self, value: Optional[Border]):
        self.__border = value

    # border_radius
    @property
    def border_radius(self) -> BorderRadiusValue:
        return self.__border_radius

    @border_radius.setter
    def border_radius(self, value: BorderRadiusValue):
        self.__border_radius = value

    # horizontal_lines
    @property
    def horizontal_lines(self) -> Optional[BorderSide]:
        return self.__horizontal_lines

    @horizontal_lines.setter
    def horizontal_lines(self, value: Optional[BorderSide]):
        self.__horizontal_lines = value

    # vertical_lines
    @property
    def vertical_lines(self) -> Optional[BorderSide]:
        return self.__vertical_lines

    @vertical_lines.setter
    def vertical_lines(self, value: Optional[BorderSide]):
        self.__vertical_lines = value

    # checkbox_horizontal_margin
    @property
    def checkbox_horizontal_margin(self) -> OptionalNumber:
        return self._get_attr("checkboxHorizontalMargin")

    @checkbox_horizontal_margin.setter
    def checkbox_horizontal_margin(self, value: OptionalNumber):
        self._set_attr("checkboxHorizontalMargin", value)

    # column_spacing
    @property
    def column_spacing(self) -> OptionalNumber:
        return self._get_attr("columnSpacing")

    @column_spacing.setter
    def column_spacing(self, value: OptionalNumber):
        self._set_attr("columnSpacing", value)

    # divider_thickness
    @property
    def divider_thickness(self) -> OptionalNumber:
        return self._get_attr("dividerThickness", data_type="float", def_value=1.0)

    @divider_thickness.setter
    def divider_thickness(self, value: OptionalNumber):
        self._set_attr("dividerThickness", value)

    # horizontal_margin
    @property
    def horizontal_margin(self) -> OptionalNumber:
        return self._get_attr("horizontalMargin")

    @horizontal_margin.setter
    def horizontal_margin(self, value: OptionalNumber):
        self._set_attr("horizontalMargin", value)

    # data_row_color
    @property
    def data_row_color(self) -> Union[None, str, Dict[MaterialState, str]]:
        return self.__data_row_color

    @data_row_color.setter
    def data_row_color(self, value: Union[None, str, Dict[MaterialState, str]]):
        self.__data_row_color = value

    # data_row_min_height
    @property
    def data_row_min_height(self) -> OptionalNumber:
        return self._get_attr("dataRowMinHeight")

    @data_row_min_height.setter
    def data_row_min_height(self, value: OptionalNumber):
        self._set_attr("dataRowMinHeight", value)

    # data_row_max_height
    @property
    def data_row_max_height(self) -> OptionalNumber:
        return self._get_attr("dataRowMaxHeight")

    @data_row_max_height.setter
    def data_row_max_height(self, value: OptionalNumber):
        self._set_attr("dataRowMaxHeight", value)

    # data_text_style
    @property
    def data_text_style(self):
        return self.__data_text_style

    @data_text_style.setter
    def data_text_style(self, value: Optional[TextStyle]):
        self.__data_text_style = value

    # bgcolor
    @property
    def bgcolor(self):
        return self._get_attr("bgColor")

    @bgcolor.setter
    def bgcolor(self, value):
        self._set_attr("bgColor", value)

    # gradient
    @property
    def gradient(self) -> Optional[Gradient]:
        return self.__gradient

    @gradient.setter
    def gradient(self, value: Optional[Gradient]):
        self.__gradient = value

    # heading_row_color
    @property
    def heading_row_color(self) -> Union[None, str, Dict[MaterialState, str]]:
        return self.__heading_row_color

    @heading_row_color.setter
    def heading_row_color(self, value: Union[None, str, Dict[MaterialState, str]]):
        self.__heading_row_color = value

    # heading_row_height
    @property
    def heading_row_height(self) -> OptionalNumber:
        return self._get_attr("headingRowHeight")

    @heading_row_height.setter
    def heading_row_height(self, value: OptionalNumber):
        self._set_attr("headingRowHeight", value)

    # heading_text_style
    @property
    def heading_text_style(self):
        return self.__heading_text_style

    @heading_text_style.setter
    def heading_text_style(self, value: Optional[TextStyle]):
        self.__heading_text_style = value

    # show_bottom_border
    @property
    def show_bottom_border(self) -> Optional[bool]:
        return self._get_attr("showBottomBorder", data_type="bool", def_value=False)

    @show_bottom_border.setter
    def show_bottom_border(self, value: Optional[bool]):
        self._set_attr("showBottomBorder", value)

    # show_checkbox_column
    @property
    def show_checkbox_column(self) -> Optional[bool]:
        return self._get_attr("showCheckboxColumn", data_type="bool", def_value=False)

    @show_checkbox_column.setter
    def show_checkbox_column(self, value: Optional[bool]):
        self._set_attr("showCheckboxColumn", value)

    # sort_ascending
    @property
    def sort_ascending(self) -> Optional[bool]:
        return self._get_attr("sortAscending", data_type="bool", def_value=False)

    @sort_ascending.setter
    def sort_ascending(self, value: Optional[bool]):
        self._set_attr("sortAscending", value)

    # sort_column_index
    @property
    def sort_column_index(self) -> Optional[int]:
        return self._get_attr("sortColumnIndex")

    @sort_column_index.setter
    def sort_column_index(self, value: Optional[int]):
        self._set_attr("sortColumnIndex", value)

    # on_select_all
    @property
    def on_select_all(self):
        return self._get_event_handler("select_all")

    @on_select_all.setter
    def on_select_all(self, handler):
        self._add_event_handler("select_all", handler)
        self._set_attr("onSelectAll", True if handler is not None else None)

class Item(Control):
    def __init__(self, obj):
        Control.__init__(self)
        assert obj, "obj cannot be empty"
        self.obj = obj

    def _set_attr(self, name, value, dirty=True):
        if value is None:
            return

        orig_val = self._get_attr(name)
        if orig_val is not None:
            if isinstance(orig_val, bool):
                value = str(value).lower() == "true"
            elif isinstance(orig_val, float):
                value = float(str(value))

        self._set_attr_internal(name, value, dirty=False)
        if isinstance(self.obj, dict):
            self.obj[name] = value
        else:
            setattr(self.obj, name, value)

    def _fetch_attrs(self):
        # reflection
        obj = self.obj if isinstance(self.obj, dict) else vars(self.obj)

        for name, val in obj.items():
            data_type = (
                type(val).__name__ if isinstance(val, (bool, float)) else "string"
            )
            orig_val = self._get_attr(name, data_type=data_type)

            if val != orig_val:
                self._set_attr_internal(name, val, dirty=True)

    def _get_control_name(self):
        return "item"


from django.urls import path
from ..main.views import AddBookingView, LoginView, RegistrationView, MyLogoutoView, AboutUsView

urlpatterns = [
    path('AddBooking/', AddBookingView.as_view(), name='AddBooking'),
    path('login/', LoginView.as_view(), name='Login'),
    path('registration/', RegistrationView.as_view(), name='Registration'),
    path('logout/', MyLogoutoView.as_view(), name='Logout'),
    path('aboutus/', AboutUsView.as_view(), name='AboutUs')
]


## Data processing
import pandas as pd
import numpy as np
import collections_model_get_data_v1 as gd
from collections_model_utility_functions_v1 import get_connector, get_raw_data, truncate_table, write_to_snowflake, read_file
import collections_model_utility_functions_v1 as uf
# Model and performance evaluation
from sklearn.metrics import roc_curve, auc, precision_score, recall_score
## unpickling the model
import pickle

conn = get_connector()
cur = conn.cursor()

def identify_column_type(series):
    if pd.api.types.is_numeric_dtype(series):
        return 'numeric'
    elif pd.api.types.is_categorical_dtype(series):
        return 'categorical'
    else:
        return 'other'

def remove_inconsistent_values(df,feature_list):
    for column in feature_list:
        column_type = identify_column_type(df[column])
        if column_type == 'numeric':
            df[column] = pd.to_numeric(df[column], errors='coerce')
            # df = df.dropna(subset=[column])
        elif column_type == 'categorical':
            # df[column] = df[column].astype('category')
            df[column] = pd.to_numeric(df[column], errors='coerce')
        else:
            # Handle other column types if needed
            df[column] = pd.to_numeric(df[column], errors='coerce')
            # pass
    return df

def model_run():
    start_date = '2023-06-02'
    end_date = '2023-06-03'
    # get data
    data= get_raw_data(start_date,end_date,cur,gd.query)

    # pick only selected features utilized in model
    feature_list=pd.read_csv(
    read_file(uf.s3_bucket, uf.model_path + "XGBoost_feature_list_100_prev.csv")
    )['variables']
    # select only cols used in model
    data_filter = data[list(feature_list)]
    # remove_inconsistent_values(data)
    data_filter = remove_inconsistent_values(data_filter,feature_list)

    data_filter = gd.missing_ind_convert_num(data_filter)
    # unpickle cm_ac_vanilla_v1 model
    model=pickle.loads(
                uf.s3.Bucket(uf.s3_bucket).Object(f"{uf.model_path}Vanilla_model_v1.pkl").get()["Body"].read()
            )

    # run predictions and store the result
    data['Pred_PD']=model.predict_proba(data_filter)[:,1]

    # finding threshold value for 35% prediction coverage
    threshold_value = uf.find_threshold(data,uf.cut_off)

    # converting threshold cut to binary
    data['Pred_PD_binary_tc_thresh'] = np.where(data['Pred_PD']>threshold_value,1,0)

    # store only relevant info:
    data_write = data[list(feature_list)+['LOAN_ID','USER_ID','FULL_DATE','Pred_PD','Pred_PD_binary_tc_thresh','AUTO_CURE_FLAG']]

    precision = precision_score(data_write['AUTO_CURE_FLAG'], data_write["Pred_PD_binary_tc_thresh"])
    # Calculate recall
    recall = recall_score(data_write['AUTO_CURE_FLAG'], data_write["Pred_PD_binary_tc_thresh"])
    print("Precision Val data  {:.4f}%".format(precision*100))
    print("Recall Val data {:.4f}%".format(recall*100))

    fpr, tpr, thresholds = roc_curve(data_write['AUTO_CURE_FLAG'], data_write["Pred_PD"])
    roc_auc = auc(fpr, tpr)
    GINI_Val = (2 * roc_auc) - 1
    print(f'Gini on Val data with XGBoost: {GINI_Val}')

    # write back to snowflake:
    truncate_table("dod_results", "cm_ac_vanilla_v1".lower(),cur)

    # write temp DoD table:
    write_to_snowflake(data_write, "dod_results", "cm_ac_vanilla_v1".lower())

    # merge back to master result table
    # merge()
    cur.close()
    conn.close()

model_run()


import numpy as np
import tensorflow as tf
from tensorflow.keras import layers,models

np.random.seed(10)

data=np.random.normal(size=(2,3,4))
# print(data)

inputLayer=layers.Input(shape=(3,4))
lstm1=layers.LSTM(6,return_sequences=False,return_state=True)(inputLayer)

model=models.Model(inputs=inputLayer,outputs=(lstm1))
outputs,lastHiddenState,lastCellState=model.predict(data)
print('\nHidden States')
print(outputs) #当return_sequences为true时，返回所有时序的Hidden State,反之，返回最后一个时序的Hidden State
print('\nLast Hidden State')
print(lastHiddenState) #当return_state为true时，返回最后一个时序的Hidden State 和 Cell State

print('\nLast Cell State')
print(lastCellState)


import django_filters
from .models import Property

class PropertyFilter(django_filters.FilterSet):
    class Meta:
        model = Property
        fields = {
            'property_type': ['exact'],
            'state': ['exact'],
            'bedrooms': ['exact'],
            'bathroom_type': ['exact'],
            'price': ['gte', 'lte'],
        }


#
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] x 的平方根
#

# @lc code=start
class Solution:
    def mySqrt(self, x: int) -> int:
        i = 10 * (len(str(x))-2) if x>=100 else 0
        while i*i<=x:
            i+=1
        return int(i-1)
# @lc code=end


x = 0
y = 0
totalImpares = 0
totalPares = 0
quantidadeX = 0
quantidadeY = 0

for x in range(1,50,2):
    print('VOCÊ ESTÁ DIGITANDO AS NOTAS DOS ALUNOS IMPARES')
    notasImpares = float(input(f'POR FAVOR, INSIRA A NOTA DO ALUNO DE NÚMERO {x}.'))
    totalImpares = totalImpares + notasImpares
    quantidadeX = x + quantidadeX
for y in range(2,51,2):
    print('VOCÊ ESTÁ DIGITANDO AS NOTAS DOS ALUNOS PARES')
    notasPares = float(input(f'POR FAVOR, INSIRA A NOTA DO ALUNO DE NÚMERO {y}.'))
    totalPares = totalPares + notasPares
    quantidadeY = y + quantidadeY

mediaImpares = totalImpares/quantidadeX
mediaPares = totalPares/quantidadeY

if mediaImpares > mediaPares:
    print('Alunos Impares venceram')
elif mediaPares > mediaImpares:
    print('Alunos Pares venceram')

Faculdade/F2 A1/Cap 3 Atividade/RM553279_EX03.py


#Watts farmer Bot

import signal
import sys
import json
sys.path.append('../')

from structure import Den
from nxbot import RaidBot

def signal_handler(signal, frame): #CTRL+C handler
    print()
    print("Stop request")
    b.close()

config = json.load(open("../config.json"))
b = RaidBot(config["IP"])

signal.signal(signal.SIGINT, signal_handler)

currWatts = b.TrainerSave.Watts()
b.setWatts(currWatts)
print(f"Current Watts: {currWatts}\n")

print("Farming watts...")
while True:
    b.click('R') #R on Luxray "+1" button
    b.pause(0.7)

    for ii in range(RaidBot.DENCOUNT):
        if ii > 189:
                den = Den(b.readDen(ii+32))
        elif ii > 99:
                den = Den(b.readDen(ii+11))
        else:
                den = Den(b.readDen(ii))
        if den.isActive() and den.isWishingPiece():
             if den.hasWatts():
                b.getWatts(True,0.5)
                break
             else:
                print("No watts in Den")
                break

#    stop = input("Continue farming? (y/n): ")
#    if stop == 'n' or stop == 'N':
#        break

print("Watts farming ended")
print()
b.close()