# -*- coding: utf-8 -*-
"""
Created on Wed Jul 13 16:01:50 2022

@author: danie
"""

import pandas as pd

gameweek = [gw for gw in range(1, 39)]
csv_url = 'https://raw.githubusercontent.com/vaastav/Fantasy-Premier-League/master/data/2021-22/gws/'
dfs = []

for gw in gameweek:
   dfs1 = []
   gw_url = csv_url+f"gw{gw}.csv"
   for p in gameweek:
       url = gw_url
       print(url)
       df = pd.read_csv(url)
       dfs1.append(df)
   dfs.append(pd.concat(dfs1).drop_duplicates())
#removed axis=1 as it duplicated columns
#added drop_duplicate to remove duplicate rows
result_pm10 = pd.concat(dfs, keys=gameweek)
                #.rename_axis(('location','data'))
                #.dropna(axis=1, how='all')
                #.reset_index()
print (result_pm10)
result_pm10.to_csv(r"D:\Programming\Python\Output\FPL\all_gw_export_data.csv", index = False, header=True)


from typing import Union

# put it here so that it can be used in submit as well.
def keygen(*,
           shuffle_type: str,
           split_seed: Union[int, str],
           sparse: str,
           model_seed: int,
           act_fn: str,
           loss_type: str,
           suffix: str,
           ):
    # suffix itself can contain /
    suffix = suffix.replace('/', '=')
    return f'crcns_pvc8_large/transfer_learning_factorized_vgg/shuffle_type{shuffle_type}/split_seed{split_seed}/act{act_fn}/sparse{sparse}/{suffix}/loss{loss_type}/model_seed{model_seed}'  # noqa: E501

def script_keygen(**kwargs):
    key = keygen(**kwargs)

    # remove crcns_pvc8_large/transfer_learning_factorized_vgg part
    return '+'.join(key.split('/')[2:])


from fastapi import APIRouter, Body, HTTPException, Path, Query, Response

from src.api import schemas
from src.api.models.courses import Conditions, Processor

router = APIRouter()
courses = Processor(json_path="data/courses/11210.json")
DESCRIPTION_OF_LIMITS = "最大回傳資料筆數"

@router.get("/", response_model=list[schemas.courses.CourseData])
async def get_all_courses_list(
    response: Response,
    limits: int = Query(None, ge=1, example=5, description=DESCRIPTION_OF_LIMITS),
):
    """
    取得所有課程。
    """
    result = courses.course_data[:limits]
    response.headers["X-Total-Count"] = str(len(result))
    return result

@router.get("/fields/info", response_model=dict[str, str])
async def get_all_fields_list_info():
    """
    取得所有欄位的資訊。
    """
    return {
        "id": "科號",
        "chinese_title": "課程中文名稱",
        "english_title": "課程英文名稱",
        "credit": "學分數",
        "size_limit": "人限：若為空字串表示無人數限制",
        "freshman_reservation": "新生保留人數：若為0表示無新生保留人數",
        "object": "通識對象：[代碼說明(課務組)](https://curricul.site.nthu.edu.tw/p/404-1208-11133.php)",
        "ge_type": "通識類別",
        "language": '授課語言："中"、"英"',
        "note": "備註",
        "suspend": '停開註記："停開"或空字串',
        "class_room_and_time": "教室與上課時間：一間教室對應一個上課時間，中間以tab分隔；多個上課教室以new line字元分開",
        "teacher": "授課教師：多位教師授課以new line字元分開；教師中英文姓名以tab分開",
        "prerequisite": "擋修說明：會有html entities",
        "limit_note": "課程限制說明",
        "expertise": "第一二專長對應：對應多個專長用tab字元分隔",
        "program": "學分學程對應：用半形/分隔",
        "no_extra_selection": "不可加簽說明",
        "required_optional_note": "必選修說明：多個必選修班級用tab字元分隔",
    }

@router.get("/fields/{field_name}", response_model=list[str])
async def get_selected_fields_list(
    field_name: schemas.courses.CourseFieldName = Path(
        ..., example="id", description="欄位名稱"
    ),
    limits: int = Query(None, ge=1, example=20, description=DESCRIPTION_OF_LIMITS),
):
    """
    取得指定欄位的列表。
    """
    result = courses.list_selected_fields(field_name)[:limits]
    return result

@router.get(
    "/fields/{field_name}/{value}", response_model=list[schemas.courses.CourseData]
)
async def get_selected_field_and_value_data(
    field_name: schemas.courses.CourseFieldName = Path(
        ..., example="chinese_title", description="搜尋的欄位名稱"
    ),
    value: str = Path(..., example="產業創新與生涯探索", description="搜尋的值"),
    limits: int = Query(None, ge=1, example=5, description=DESCRIPTION_OF_LIMITS),
):
    """
    取得指定欄位滿足搜尋值的課程列表。
    """
    condition = Conditions(field_name, value, False)
    result = courses.query(condition)[:limits]
    return result

@router.get("/lists/{list_name}", response_model=list[schemas.courses.CourseData])
async def get_courses_list(
    list_name: schemas.courses.CourseListName,
    response: Response,
    limits: int = Query(None, ge=1, example=5, description=DESCRIPTION_OF_LIMITS),
) -> list[schemas.courses.CourseData]:
    """
    取得指定類型的課程列表。
    """
    if list_name == "16weeks":
        condition = Conditions("note", "16週課程", True)
    elif list_name == "microcredits":
        condition = Conditions("credit", "[0-9].[0-9]", True)
    elif list_name == "xclass":
        condition = Conditions("note", "X-Class", True)
    else:
        raise HTTPException(status_code=400, detail="Invalid list name")
    result = courses.query(condition)[:limits]
    response.headers["X-Total-Count"] = str(len(result))
    return result

@router.get("/searches", response_model=list[schemas.courses.CourseData])
async def search_by_field_and_value(
    field: schemas.courses.CourseFieldName = Query(
        ...,
        example=schemas.courses.CourseFieldName.chinese_title,
        description="搜尋的欄位名稱",
    ),
    value: str = Query(..., example="產業.+生涯", description="搜尋的值（可以使用 Regex，正則表達式）"),
    limits: int = Query(None, ge=1, example=5, description=DESCRIPTION_OF_LIMITS),
):
    """
    取得指定欄位滿足搜尋值的課程列表。
    """
    condition = Conditions(field, value, True)
    result = courses.query(condition)[:limits]
    return result

@router.post("/searches", response_model=list[schemas.courses.CourseData])
async def get_courses_by_condition(
    query_condition: (
        schemas.courses.CourseQueryCondition | schemas.courses.CourseCondition
    ) = Body(
        openapi_examples={
            "normal_1": {
                "summary": "單一搜尋條件",
                "description": "只使用單一搜尋條件，類似於 GET 方法",
                "value": {
                    "row_field": "chinese_title",
                    "matcher": "數統導論",
                    "regex_match": True,
                },
            },
            "normal_2": {
                "summary": "兩個搜尋條件",
                "description": "使用兩個搜尋條件，例如：黃姓老師 或 孫姓老師開設的課程",
                "value": [
                    {
                        "row_field": "teacher",
                        "matcher": "黃",
                        "regex_match": True,
                    },
                    "or",
                    {
                        "row_field": "teacher",
                        "matcher": "孫",
                        "regex_match": True,
                    },
                ],
            },
            "normal_nested": {
                "summary": "多層搜尋條件",
                "description": "使用巢狀搜尋條件，例如：(3學分的課程) 且 ((統計所 或 數學系開設的課程) 且 (開課時間是T3T4 或 開課時間是R3R4))",
                "value": [
                    {"row_field": "credit", "matcher": "3", "regex_match": True},
                    "and",
                    [
                        [
                            {"row_field": "id", "matcher": "STAT", "regex_match": True},
                            "or",
                            {"row_field": "id", "matcher": "MATH", "regex_match": True},
                        ],
                        "and",
                        [
                            {
                                "row_field": "class_room_and_time",
                                "matcher": "T3T4",
                                "regex_match": True,
                            },
                            "or",
                            {
                                "row_field": "class_room_and_time",
                                "matcher": "R3R4",
                                "regex_match": True,
                            },
                        ],
                    ],
                ],
            },
        }
    ),
    limits: int = Query(None, ge=1, example=5, description=DESCRIPTION_OF_LIMITS),
):
    """
    根據條件取得課程。
    """
    if type(query_condition) is schemas.courses.CourseCondition:
        condition = Conditions(
            query_condition.row_field.value,
            query_condition.matcher,
            query_condition.regex_match,
        )
    elif type(query_condition) is schemas.courses.CourseQueryCondition:
        # 設定 mode="json" 是為了讓 dump 出來的內容不包含 python 的實體 (instance)
        condition = Conditions(
            list_build_target=query_condition.model_dump(mode="json")
        )
    result = courses.query(condition)[:limits]
    return result


import pymongo
import random
import json
from pymongo.server_api import ServerApi

# 3 required files: petID.json, pet_info.json,user_info.json
# info => local => cloud
class WatsonPet:
    def __init__(self):
        self.last_active_time = None

        ### fetch ID from file
        with open('routines/general/petID.json') as f:
            info = json.load(f)
            self.id = info['pet']['id']
        self.query = {"_id":self.id}
        ### infos
        self.pet = {}
        self.user = {}

        ### connect to db
        with open('routines/general/credentials.json') as f:
            creds = json.load(f)
        self.conn_str=creds["mongodb_connstr"]
        client = pymongo.MongoClient(self.conn_str, server_api=ServerApi('1'))
        self.database = client["WatsonAIPet"]
        petinfo = self.database['petinfo']
        userinfo = self.database['userinfo']

        ### fetch/ initialise pet info data
        res_pet = None
        for x in petinfo.find({"_id":self.id}):
            res_pet = x

        if res_pet == None:
            self.pet["_id"] = self.id
            touch_mark = [0.5,0.2,0.05]
            random.shuffle(touch_mark)
            self.pet['TOUCH1'] = touch_mark[0]
            self.pet['TOUCH2'] = touch_mark[1]
            self.pet['TOUCH3'] = touch_mark[2]
            self.pet['EYE'] = random.randint(1,3)
            self.pet['MOUTH'] = random.randint(1,5)
            self.pet['VOICE'] = random.randint(0,1)
            print('pet: How shall I call you') #TODO modify to speech processing
            self.pet['OWNER'] = 'lily' #TODO
            self.pet['EMO'] = 8
            petinfo.insert_one(self.pet)
        else:
            self.pet = res_pet

        ### fetch/ initialise pet info data
        res_user = None
        for x in userinfo.find({"_id":self.id}):
            res_user = x

        if res_user == None:
            self.user["_id"] = self.id
            self.user['SPOTIFY'] = 0
            self.user['CALENDAR'] = 0
            self.user['TWITTER'] = 0
            self.user['RATIO'] = round(random.uniform(0.2,0.8),2)
            self.user['MUSIC'] = 0
            self.user['PODCAST'] = 0
            self.user['START_ALARM'] = '7:0'
            self.user['END_ALARM'] = '22:0'
            self.user['REPORT_EVENT'] = 0
            self.user['AUDIO_PLAYING'] = 0
            self.user['BOOK'] = 0
            userinfo.insert_one(self.user)
        else:
            self.user = res_user

    def getInfo(self,table,column): # OK!
        #get a column data value from the a table
        if table == 'pet':
            return self.pet[column]
        elif table == 'user':
            return self.user[column]
        return

    def getAllInfo(self,table): # OK!
        # get all info as a dict from the table
        if table == 'pet':
            return self.pet
        elif table == 'user':
            return self.user
        return

    def updateEmo(self,change): # OK!
        # update the emotion data by adding the changing value and update to db
        self.pet['EMO'] += change
        if self.pet['EMO'] > 10:
            self.pet['EMO'] = 10
        if self.pet['EMO'] < 0:
            self.pet['EMO'] = 0
        petinfo = self.database['petinfo']
        petinfo.update_one(self.query,{"$set":{'EMO':self.pet['EMO']}})

    def updateInfo(self,column,value): # OK!
        # update data of a specified column and update to db
        if column != '_id':
            self.user[column] = value
            userinfo = self.database['userinfo']
            userinfo.update_one(self.query,{"$set":{column:value}})

    def updateRatio(self): # OK!
        # calculate the new ratio via the formula and update to db
        m = self.user['MUSIC']
        p = self.user['PODCAST']
        r = self.user['RATIO']

        if (m+p)!= 0:
            rate  = 0.3
            ratio_mp = m/(m+p)
            value = round((ratio_mp - r)*rate + r,2)
            self.updateInfo('RATIO',value)

    def getWorkingHours(self):
        # extract working hours information from tables
        s = self.user['START_ALARM']
        e = self.user['END_ALARM']
        res = [0,0,0,0]
        res[0],res[1] = int(s.split(':')[0]),int(s.split(':')[1])
        res[2],res[3] = int(e.split(':')[0]),int(e.split(':')[1])
        return res


from PIL import Image
import subprocess
import os

coefs = (0.2126, 0.7152, 0.0722,)

asc = []
f = open("symbols.txt", "r")
for x in f:
    asc.append(x[:-1])
f.close()

i = input("Enter picture's file name: ")
try:
    img = Image.open(i)
except:
    print("Wrong file name")
    exit()

comp = 7 - int(input("Please state level of vertical compression(0 for none, up to 5): "))
while comp >= img.size[1] or comp > 7:
    print("Level of vertical compression is too high!")
    comp = 7 - int(input("Please state correct level of vertical compression: "))

pix = img.load()
newpix = [['0' for _ in range(img.size[0])] for _ in range(img.size[1])]
num = len(asc) - 1
for i in range(img.size[0]):
    for j in range(img.size[1]):
        col = pix[i,j]
        newpix[j][i] = asc[-1 * round((col[0] * coefs[0] + col[1] * coefs[1] + col[2] * coefs[2]) * num / 255)]

f = open("img.txt", "w")
if comp == 7:
    for i in newpix:
        for j in i:
            f.write(j)
        f.write("\n")
else:
    for i in range(len(newpix)):
        if i % comp == 0:
            continue
        for j in range(len(newpix[i])):
            f.write(newpix[i][j])
        f.write("\n")
f.close()

# for i in range(len(newpix)):
#     if i % 2 == 0:
#         continue
#     for j in range(len(newpix[i])):
#         print(newpix[i][j], end='')
#     print()

subprocess.check_output('start /wait ' + os.path.abspath("img.txt"), shell=True)


import os
from pytube import Playlist

def make_alpha_numeric(string):
    return ''.join(char for char in string if char.isalnum())

link = input("Enter YouTube Playlist URL: âœ¨")

yt_playlist = Playlist(link)

folderName = make_alpha_numeric(yt_playlist.title)
os.mkdir(folderName)

totalVideoCount = len(yt_playlist.videos)
print("Total videos in playlist: ðŸŽ¦", totalVideoCount)

for index, video in enumerate(yt_playlist.videos, start=1):
    print("Downloading:", video.title)
    video_size = video.streams.get_highest_resolution().filesize
    print("Size:", video_size // (1024 ** 2), "ðŸ—œ MB")
    video.streams.get_highest_resolution().download(output_path=folderName)
    print("Downloaded:", video.title, "âœ¨ successfully!")
    print("Remaining Videos:", totalVideoCount - index)

print("All videos downloaded successfully! ðŸŽ‰")


import time
import shutil
import datetime

from worktime_tracker.constants import STATES_TYPE, LOGS_PATH, LAST_CHECK_PATH
from worktime_tracker.utils import reverse_read_lines
from worktime_tracker.date_utils import coerce_to_timestamp

class Log:
    """Represents a log entry at a single point of time, basically containing a timestamp and a state.
    It is supposed to match the format of the logs file.
    """

    def __init__(self, timestamp: float, state: STATES_TYPE) -> None:
        self.timestamp = coerce_to_timestamp(timestamp)
        self.datetime = datetime.datetime.fromtimestamp(self.timestamp)
        self.state = state

    def __repr__(self) -> str:
        date_str = self.datetime.strftime("%Y-%m-%d %H:%M:%S")
        return f"Log<date={date_str}, state={self.state}>"

    def __eq__(self, other) -> bool:
        return self.timestamp == other.timestamp and self.state == other.state

    def __lt__(self, other) -> bool:
        return self.timestamp < other.timestamp

    def __le__(self, other) -> bool:
        return self.timestamp <= other.timestamp

    def __gt__(self, other) -> bool:
        return self.timestamp > other.timestamp

    def __ge__(self, other) -> bool:
        return self.timestamp >= other.timestamp

def write_last_check(timestamp: float) -> None:
    with LAST_CHECK_PATH.open("w") as f:
        f.write(str(timestamp) + "\n")

def read_last_check_timestamp() -> float:
    if not LAST_CHECK_PATH.exists():
        with open(LAST_CHECK_PATH, "w", encoding="utf8") as f:
            f.write("0\n")
    with LAST_CHECK_PATH.open("r") as f:
        return float(f.readline().strip())

def write_log(log: Log) -> None:
    with LOGS_PATH.open("a") as f:
        f.write(f"{log.timestamp}\t{log.state}\n")

def maybe_write_log(log: Log):
    # TODO: lock file
    last_log = read_last_log()
    if last_log.state == log.state:
        return
    write_log(log)

def parse_log_line(log_line: str) -> Log:
    timestamp, state = log_line.strip().split("\t")
    return Log(timestamp=float(timestamp), state=state)

def reverse_read_logs() -> list[Log]:
    if not LOGS_PATH.exists():
        LOGS_PATH.parent.mkdir(exist_ok=True)
        write_log(Log(timestamp=0, state="locked"))
    for line in reverse_read_lines(LOGS_PATH):
        yield parse_log_line(line)

def read_last_log() -> Log:
    try:
        return next(reverse_read_logs())
    except StopIteration:
        return None

def get_rewritten_history_logs(
    logs: list[Log], start_datetime: datetime.datetime, end_datetime: datetime.datetime, new_state: STATES_TYPE
) -> list[Log]:
    # TODO: adapt function to use the Log class and datetimes
    start_timestamp = start_datetime.timestamp()
    end_timestamp = end_datetime.timestamp()
    logs = [(log.timestamp, log.state) for log in logs]
    # TODO: Should we compare to datetime.now() instead? Right now if the last log is old, we can't rewrite after it.
    assert end_timestamp < logs[-1][0], "Rewriting the future not allowed"
    # Remove logs that are in the interval to be rewritten
    logs_before = [(timestamp, state) for (timestamp, state) in logs if timestamp <= start_timestamp]
    logs_after = [(timestamp, state) for (timestamp, state) in logs if timestamp > end_timestamp]
    logs_inside = [(timestamp, state) for (timestamp, state) in logs if start_timestamp < timestamp <= end_timestamp]
    if len(logs_inside) > 0:
        # Push back last log inside to be the first of logs after (the rewritten history needs to end on the same
        # state as it was actually recorded)
        logs_after = [(end_timestamp, logs_inside[-1][1])] + logs_after
    else:
        # If there were no states inside, then just take the last log before to have the same state
        logs_after = [(end_timestamp, logs_before[-1][1])] + logs_after
    # Edge cases to not have two identical subsequent states
    if logs_before[-1][1] == new_state:
        # Change the start date to the previous one if it is the same state
        start_timestamp = logs_before[-1][0]
        logs_before = logs_before[:-1]
    if logs_after[0][1] == new_state:
        # Remove first element if it is the same as the one we are going to introduce
        logs_after = logs_after[1:]
    return logs_before + [(start_timestamp, new_state)] + logs_after

def get_all_logs():
    return [log for log in reverse_read_logs()][::-1]

def rewrite_history(start_datetime: datetime.datetime, end_datetime: datetime.datetime, new_state: STATES_TYPE) -> None:
    from worktime_tracker.history import History  # Circular import

    # Careful, this methods rewrites the entire log file
    backup_dir = LOGS_PATH.parent / "backup"
    backup_dir.mkdir(exist_ok=True)
    shutil.copy(LOGS_PATH, backup_dir / f"{LOGS_PATH.name}.bck{int(time.time())}")
    logs = get_all_logs()
    logs += [Log(time.time(), "locked")]  # So that we take the last interval into account
    # TODO: Rewrite the function to use the Log class
    new_logs = get_rewritten_history_logs(logs, start_datetime, end_datetime, new_state)
    with LOGS_PATH.open("w") as f:
        for timestamp, state in new_logs:
            f.write(f"{timestamp}\t{state}\n")
    History.clear()

def remove_identical_consecutive_states(logs):
    """Cleans identical consecutive logs which should not change the resulting worktime.

    Should be used to clean the log file."""
    previous_state = None
    new_logs = []
    for timestamp, state in logs:
        if state == previous_state:
            continue
        new_logs.append((timestamp, state))
        previous_state = state
    return new_logs


# Task 12
# Созданы переменные a и b. Создайте переменную c куда поместите a умноженное на b.  Результат - переменную с, выведите в консоль с помощью print. Обратите внимание, что задача уже решена. Просто изучите вывод.

a = 3
b = 9

# write your code under this line

c = a * b

print(c)
print(type(c)) # посмотреть тип данных


#numero 95625 Mara Gomes Alves

def eh_labirinto (maze):

    if not isinstance (maze, tuple): #verifica se e tuplo
        return False
    elif len(maze) < 3: #verifica minimo de 3 nas abcissas
        return False

    #subtuplos
    else:
        for t in range(len(maze)):
            if not isinstance (maze[t], tuple): #dentro do tuplo principal so ha tuplos
                return False
            elif len(maze[t]) != len(maze[t-1]): #todos os tuplos tem o mesmo comprimento
                return False
            elif len(maze[t]) < 3: #verifica se cumpre o minimo 3 nas ordenadas
                return False

            #elementos dos subtuplos
            else:
                for e in range(len(maze[t])):
                    if type (maze[t][e]) != int: #corrige o problema de aceitar true e false como elementos
                        return False
                    elif maze[t][e] != 0 and maze[t][e] != 1: #elementos dos tuplos so podem ser 0 ou 1
                        return False
                    elif t == 0 and maze[t][e] != 1: #primeiro tuplo so paredes
                        return False
                    elif t == len(maze)-1 and maze[t][e] != 1: #ultimo tuplo so paredes
                        return False
                    elif (e == 0 and maze[t][e] != 1) or (e == len(maze[t])-1 and maze[t][e] != 1): #primeiro e ultimo elementos dos tuplos sao 1
                        return False
    return True

def eh_posicao (posicao):

    if not isinstance (posicao, tuple): #verifica se e um tuplo
        return False
    elif len(posicao) != 2: #verifica se tem apenas dois elementos
        return False

    else:
        for e in posicao:
            if not isinstance (e, int):
                return False
            if e < 0: #apenas aceita coordenadas positivas
                return False
    return True

def eh_conj_posicoes (unidades):

    if not isinstance (unidades, tuple):
        return False

    posicoes = ()
    for e in unidades:
        if not eh_posicao (e):
            return False
        else:
            if e in posicoes: #se for um elemento repetido, ou seja, se ja estiver na lista de posicoes, e falso
                return False
            else:
                posicoes = posicoes + (e,) #guardar posicoes num novo tuplo para o ciclo verificar se sao repetidas
    return True

def tamanho_labirinto (maze):

    if not eh_labirinto (maze):
        raise ValueError ('tamanho_labirinto: argumento invalido')

    return (len(maze), len(maze[0]))

def eh_mapa_valido (maze, unidades):

    if not eh_labirinto (maze) or not eh_conj_posicoes (unidades):
        raise ValueError ('eh_mapa_valido: algum dos argumentos e invalido')

    for t in range(len(unidades)):
        x = unidades[t][0]
        if x > len (maze): #ver se x das varias posicoes nao ultrapassa o comprimento do labirinto
            return False
        y = unidades[t][1]
        if y > len (maze[0]): #ver se y das varias posicoes nao ultrapassa a altura do labirinto
            return False
        if maze[x][y] == 1: #ver se posicao (x,y) nao calha numa posicao ocupada por parede
            return False

    return True

def eh_posicao_livre (maze, unidades, posicao):

    try: #verifica se as funcoes anteriores deram erro
        eh_mapa_valido (maze, unidades)
        eh_posicao(posicao)
    except ValueError: #se sim, esta funcao tambem da erro
        raise ValueError ('eh_posicao_livre: algum dos argumentos e invalido')

    if not eh_mapa_valido (maze, unidades) or not eh_posicao(posicao): #se as funcoes anteriores deram false esta da erro
        raise ValueError ('eh_posicao_livre: algum dos argumentos e invalido')
    for e in unidades:
        if e == posicao: #se a posicao e igual a alguma posicao ja ocupada pelas unidades entao e falso
            return False
        x = posicao[0]
        if x > len (maze): #ver se x da posicao nao ultrapassa o comprimento do labirinto
            return False
        y = posicao[1]
        if y > len (maze[0]): #ver se y da posicao nao ultrapassa a altura do labirinto
            return False
        if maze[x][y] == 1: #ver se posicao (x,y) nao calha numa posicao ocupada por parede
            return False

    return True

def posicoes_adjacentes (posicao):

    if not eh_posicao(posicao):
        raise ValueError('posicoes_adjacentes: argumento invalido')
    conj_posicoes = ()

    posicao1 = (posicao[0], posicao[1]-1) #calcular a primeira posicao e se for valida adiciona-la ao conjunto das posicoes
    if eh_posicao(posicao1):
        conj_posicoes = conj_posicoes + (posicao1,)

    posicao2 = (posicao[0]-1, posicao[1]) #mesmo processo para as restantes posicoes possiveis
    if eh_posicao(posicao2):
        conj_posicoes = conj_posicoes + (posicao2,)

    posicao3 = (posicao[0]+1, posicao[1])
    if eh_posicao(posicao3):
        conj_posicoes = conj_posicoes + (posicao3,)

    posicao4 = (posicao[0], posicao[1]+1)
    if eh_posicao(posicao4):
        conj_posicoes = conj_posicoes + (posicao4,)

    return conj_posicoes

def mapa_str (maze, unidades):

    #verificar se eh_mapa_valido da erro
    try:
        eh_mapa_valido (maze, unidades)
    except ValueError: #se eh_mapa_valido da erro, mapa_str tambem
        raise ValueError ('mapa_str: algum dos argumentos e invalido')
    if not eh_mapa_valido (maze, unidades): #se eh_mapa_valido da false, mapa_str da erro
        raise ValueError ('mapa_str: algum dos argumentos e invalido')

    res = ('')
    linha = 0
    coluna = 0

    while coluna < len(maze) and linha < len(maze[coluna]):
        if (coluna, linha) in unidades: #se coordenadas forem iguais as de alguma posicao, assinalar com O
            res = res + 'O'
        elif maze[coluna][linha] == 1: #paredes
            res = res + '#'
        elif maze[coluna][linha] == 0: #espacos vazios
            res = res + '.'
        coluna = coluna + 1
        if coluna == len(maze) and linha + 1 < len(maze[coluna-1]): #quando acabar de percorrer uma linha e a proxima ainda existir
            res = res + '\n'
            coluna = 0 #recomecar colunas
            linha = linha + 1 #passar a proxima linha

    return res

def obter_objetivos (maze, unidades, posicao):

    #verificar erros
    try:
        eh_mapa_valido (maze, unidades)
        eh_posicao (posicao)
    except ValueError:
        raise ValueError ('obter_objetivos: algum dos argumentos e invalido')
    if not eh_mapa_valido or not eh_posicao (posicao) or (posicao not in unidades):
        raise ValueError ('obter_objetivos: algum dos argumentos e invalido')

    unidades_exceto_posicao = ()
    objetivos = ()

    #criar nova lista de unidades sem a posicao
    for u in unidades:
        if u != posicao:
            unidades_exceto_posicao = unidades_exceto_posicao + (u,)

    for u in unidades_exceto_posicao:
        #verficar se ha erros erros
        try:
            posicoes_adjacentes (u)
        except ValueError:
            raise ValueError ('obter_objetivos: algum dos argumentos e invalido')

        for a in posicoes_adjacentes(u):
            #verficar se ha erros erros
            try:
                eh_posicao_livre (maze, unidades, a)
            except ValueError:
                raise ValueError ('obter_objetivos: algum dos argumentos e invalido')

            if eh_posicao_livre (maze, unidades, a) and a not in objetivos: #se uma posicao adjacente a uma das unidade estiver livre e ainda nao estiver em objetivos, adiciona-se a objetivos
                objetivos = objetivos + (a,)

    return objetivos

def obter_caminho (maze, unidades, posicao):

    #verificar erros
    try:
        eh_mapa_valido(maze, unidades)
        eh_posicao (posicao)
    except ValueError:
        raise ValueError ('obter_caminho: algum dos argumentos e invalido')
    if not eh_mapa_valido(maze,unidades) or (posicao not in unidades): #verificar validade dos argumentos
        raise ValueError ('obter_caminho: algum dos argumentos e invalido')

    #algoritmo
    lista_exploracao = [(posicao), ()]
    posicoes_visitadas = ()

    if obter_objetivos (maze, unidades, posicao) == (): #se a unidade ja estiver numa das posicoes de objetivo o caminho e ()
        return ()

    while lista_exploracao:
        posicao_atual = lista_exploracao[0]
        caminho_atual = lista_exploracao[1]

        if posicao_atual not in posicoes_visitadas: #marcar posicao como visitada se ainda nao o for
            posicoes_visitadas += (posicao_atual,)
            caminho_atual += (posicao_atual,)

            if posicao_atual in obter_objetivos (maze, unidades, posicao): #se chegou a um dos objetivos acaba
                return caminho_atual
            else:
                for posicao_adjacente in posicoes_adjacentes (posicao_atual):
                    if eh_posicao_livre(maze, unidades, posicao_adjacente): #se posicao adjacente da atual for valida adicionar a lista de exploracao essa posicao e o percurso ate la
                        lista_exploracao += (posicao_adjacente,) + (caminho_atual,)

        del lista_exploracao[1] #apagar o que ja foi percorrido da lista para passar a proxima hipotese
        del lista_exploracao[0]

    return ()

def mover_unidade (maze, unidades, posicao):

    #verificar erros
    try:
        eh_mapa_valido(maze, unidades)
        eh_posicao (posicao)
    except ValueError:
        raise ValueError ('mover_unidade: algum dos argumentos e invalido')
    if not eh_mapa_valido (maze, unidades) or (posicao not in unidades):
        raise ValueError ('mover_unidade: algum dos argumentos e invalido')

    novas_unidades = ()

    if obter_caminho(maze, unidades, posicao) == (): #se nao houver caminho nao fazer alteracao nenhuma a unidades
        return unidades

    for u in unidades:
        if u in posicoes_adjacentes (posicao): #se a unidade ja estiver num dos objetivos nao sofre alteracao nenhuma
            return unidades
        elif u != posicao:
            novas_unidades += (u,) #se a posicao nao corresponder entao adiciona se a novas unidades
        elif u == posicao:
            novas_unidades += (obter_caminho(maze, unidades, posicao)[1],) #se a unidade for a posicao entao substitui se pelo passo seguinte do caminho

    return novas_unidades


l=list(map(int,input().split()))
for i in range(len(l)):
    temp=l[i]
    index=i
    for j in range(i,len(l)):
        if(l[j]<temp):
            temp=l[j]
            index=j
    l[i],l[index]=l[index],l[i]
print(l)


import torch
from config import *

import pandas as pd
import numpy as np

import albumentations as A
import cv2

class SetiDataset(torch.utils.data.Dataset):

    def __init__(self, df, augmentations=None):
        self.df = df
        self.augmentations = augmentations

    def __len__(self):
        return len(self.df)

    def __getitem__(self, idx):

        row = self.df.iloc[idx]
        filepath = "/content/train/{}/{}.npy".format(row.id[0], row.id)
        image = np.load(filepath)
        #image = image[::2]
        image = image.astype(np.float32)
        #image = np.vstack(image).transpose((1, 0))

        if self.augmentations:
            image = self.augmentations(image = image)['image']
        else:
            #image = image[np.newaxis,:,:]
            image = torch.from_numpy(image).float()

        label = torch.unsqueeze(torch.tensor(row.target).float(),-1)

        return {
            'images' : image,
            'labels' : label
        }


import numpy as np
import pydmd
from DMDEnKF.classes.online_dmd import OnlineDMD
from DMDEnKF.classes.DMDEnKF import  TDMD, DMDEnKF
import cmath

'''

Helper functions for the simple sin example, the first case in the synthetic applications section of the DMDEnKF paper

'''

def generate_data(thetas):
    """
    Generate data starting from (1,0) using a rotation matrix of angle theta, with theta specified at each timestep in the list

    Parameters
    ----------
    thetas : list
        List of angles to rotate by at each timestep

    Returns
    -------
    data : numpy.array
        The data generated by the rotation matrices
    """

    #generate data starting from (1,0) and applying 2D rotation matrix of angle theta for each theta in the list of thetas
    state = np.array([[1],[0]])
    states = [state]
    for theta in thetas:
        A = np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])
        state = A@state
        states.append(state)
    return np.array(states)

def iterate_streaming_tdmd(data):
    """
    Apply streaming total DMD over each data point received

    Parameters
    ----------
    data : list
        List of measurements to perform Streaming TDMD over

    Returns
    -------
    eigs : list
        A list of the most dominant eigenvalue (largest absolute value) at each timestep
    """

    #Applys TDMD over the first data points, adding a new data point each step until all data has had TDMD applied to it
    #returns num_data -1 eigs that should be aligned with the tail end of the data
    eigs = []
    for i in range(2,len(data)+1):
        pdmd = pydmd.DMD(2,2)
        pdmd.fit(data[:i])
        eig = pdmd.eigs
        abs_eigs = [abs(e) for e in eig]
        dom_eig_index = abs_eigs.index(np.max(abs_eigs))
        eigs.append(eig[dom_eig_index])
    return eigs

def windowed_tdmd(data,window_size):
    """
    Applies Windowed TDMD with a sliding window over all the data received

    Parameters
    ----------
    data : list
        List of measurements to perform Windowed TDMD over
    window_size : int
        The size of the sliding windowed to use for Windowed TDMD

    Returns
    -------
    eigs : list
        A list of the most dominant eigenvalue (largest absolute value) at each timestep
    """

    #Applies windowed TDMD with specified window size
    #also should be backwards aligned
    eigs = []
    for i in range(window_size,len(data)+1):
        pdmd = pydmd.DMD(2,2)
        pdmd.fit(data[i-window_size:i])
        eig = pdmd.eigs
        abs_eigs = [abs(e) for e in eig]
        dom_eig_index = abs_eigs.index(np.max(abs_eigs))
        eigs.append(eig[dom_eig_index])
    return eigs

def iterate_odmd(data,rho):
    """
    Applies Online DMD with exponentially decaying importance over all the data received

    Parameters
    ----------
    data : list
        List of measurements to perform Online DMD over
    rho : float
        Float between 0-1 that governs the rate of decay in the importance weighting of data from previous timesteps

    Returns
    -------
    eigs : list
        A list of the most dominant eigenvalue (largest absolute value) at each timestep
    """

    #applys Online DMD over the data with exponentially decayed weighting rho
    eigs = []
    data= np.squeeze(data)
    odmd = OnlineDMD(2,rho)
    odmd.initialize(data[:2],data[1:3])
    odmd.initializeghost()
    eig,_ = odmd.computemodes()
    eigs.append(eig[0])
    for i in range(2,len(data)-1):
        odmd.update(data[i:i+1].T,data[i+1:i+2].T)
        eig,_ = odmd.computemodes()
        abs_eigs = [abs(e) for e in eig]
        dom_eig_index = abs_eigs.index(np.max(abs_eigs))
        eigs.append(eig[dom_eig_index])
    return eigs

def apply_dmdenkf(data,num_for_spin_up,system_cov_const,obs_cov_const,eig_cov_const,ensemble_size = 100):
    """
    Initialises the DMDEnKF, and fits it to the provided data

    Parameters
    ----------
    data : numpy.array
        Measurements to fit the DMDEnKF to
    num_for_spin_up : int
        Number of measurements to use training the DMD model in the spin-up phase
    system_cov_const : float
        Float that governs the size of the system state uncertainty covariance matrix (used in filtering step)
    obs_cov_const : float
        Float that governs the size of the measurement uncertainty covariance matrix (used in filtering step)
    eig_cov_const : float
        Float that governs the size of the system eigenvalue uncertainty covariance matrix (used in filtering step)
    ensemble_size : int
        Number of ensemble members to use in the EnKF (default 100)

    Returns
    -------
    dmdenkf : DMDEnKF.DMDEnKF
        A fitted DMDEnKF object, with all relevant info to make reconstructions/predictions stored attributes
    """

    #Sets up the DMDEnKF wiht relevant matrices, fits and returns full filter
    #DMD Joint EnKF
    f = TDMD()
    f.fit(data[:,:num_for_spin_up],r=2)

    #Usual dmdenkf setup of inputs
    x_len = f.data.shape[0]
    e_len = f.E.shape[0]
    observation_operator = np.hstack((np.identity(x_len),np.zeros((x_len,e_len))))
    system_cov = np.diag([system_cov_const]*x_len + [eig_cov_const]*e_len)
    observation_cov = obs_cov_const * np.identity(x_len)
    #P0 = np.diag([system_cov_const]*x_len + [eig_cov_const]*e_len)
    P0 = np.real(np.cov(f.Y-(f.DMD_modes@np.diag(f.E)@np.linalg.pinv(f.DMD_modes)@f.X)))
    P0 = np.block([[P0,np.zeros([x_len,e_len])],[np.zeros([e_len,x_len]),np.diag([eig_cov_const]*e_len)]])
    Y = data[:,num_for_spin_up:]
    #Fit DMDEnKF
    dmdenkf = DMDEnKF(observation_operator=observation_operator, system_cov=system_cov,
                          observation_cov=observation_cov,P0=P0,DMD=f,ensemble_size=ensemble_size,Y=None)
    dmdenkf.fit(Y=Y)
    #return dmdenkf
    return dmdenkf

def hankelify(data, hankel_dim):
    """
    Stacks the provided data to produce a time-delay embedding

    Parameters
    ----------
    data : numpy.array
        Measurements to time-delay embed
    hankel_dim : int
        How many timesteps to use in the delay embedding

    Returns
    -------
    hankel_data : numpy.array
        time-delay embedded data
    """

    #stacks data so that matrix structure is col1: [x1,...,xhankel], col2: [x2,...,xhankel+1], etc
    hankel_list = [data[:,i:-hankel_dim + i + 1] if i+1 != hankel_dim else data[:,i:] for i in range(hankel_dim)]
    hankel_data = np.vstack(list(reversed(hankel_list)))
    return hankel_data

def apply_hankel_dmdenkf(data, num_for_spin_up,hankel_dim,system_cov_const,obs_cov_const,eig_cov_const,ensemble_size = 100):
    """
    Initialises the Hankel-DMDEnKF, and fits it to the provided data

    Parameters
    ----------
    data : numpy.array
        Measurements to fit the Hankel-DMDEnKF to
    num_for_spin_up : int
        Number of measurements to use training the DMD model in the spin-up phase
    hankel_dim : int
        Number of timesteps to stack in the time-delay embedded data
    system_cov_const : float
        Float that governs the size of the system state uncertainty covariance matrix (used in filtering step)
    obs_cov_const : float
        Float that governs the size of the measurement uncertainty covariance matrix (used in filtering step)
    eig_cov_const : float
        Float that governs the size of the system eigenvalue uncertainty covariance matrix (used in filtering step)
    ensemble_size : int
        Number of ensemble members to use in the EnKF (default 100)

    Returns
    -------
    test_dmdenkf : DMDEnKF.DMDEnKF
        A Hankel-DMDEnKF object fitted to the delay-embedded data,
        with all relevant info to make reconstructions/predictions stored attributes
    """

    #Sets up the DMDEnKF wiht relevant matrices, fits and returns full filter
    hankel_data = hankelify(data,hankel_dim)
    #DMD Joint EnKF
    f = TDMD()
    f.fit(hankel_data[:,:num_for_spin_up-(hankel_dim-1)],r=2)

    #Usual hankel dmdenkf setup of inputs
    x_len = hankel_data.shape[0]
    data_x_len = data.shape[0]
    e_len = f.E.shape[0]
    observation_operator = np.hstack((np.identity(data_x_len),np.zeros((data_x_len,x_len - data_x_len + e_len))))
    system_cov = np.diag([system_cov_const]*x_len + [eig_cov_const]*e_len)
    observation_cov = obs_cov_const * np.identity(data_x_len)
    P0 = np.real(np.cov(f.Y-(f.DMD_modes@np.diag(f.E)@f.inv_DMD_modes@f.X)))
    P0 = np.block([[P0,np.zeros([x_len,e_len])],[np.zeros([e_len,x_len]),np.diag([eig_cov_const]*e_len)]])
    #alternative initial covariance that is simply diagonal with state cov const and eig cov const used appropriately
    #P0 = np.diag([system_cov_const]*x_len + [eig_cov_const]*e_len)
    Y = data[:,num_for_spin_up:]
    #fit Hankel DMDEnKF
    test_dmdenkf = DMDEnKF(observation_operator=observation_operator, system_cov=system_cov,
                          observation_cov=observation_cov,P0=P0,DMD=f,ensemble_size=ensemble_size,Y=None)
    test_dmdenkf.fit(Y=Y)
    #return dmdenkf
    return test_dmdenkf

#Generate Error Distributions over multiple runs
def dist_from_true_data(true_eigs,eigs):
    """
    Simple helper function that takes true eigenvalues from the estimated ones (to avoid sign switiching when code repeated)

    Parameters
    ----------
    true_eigs : float
        Real eigenvalues (modulus or argument)
    eigs : float
        Estimated eigenvalues (modulus or argument)
    Returns
    -------
    eig_difference : float
        Esitmated eigs - True eigs
    """

    #Generate Error Distributions over multiple runs
    return eigs - true_eigs

def run_trajectory(data,num_to_keep,num_for_spin_up,true_eigs,window_size,rho,obs_cov_const,system_cov_const,eig_cov_const, ensemble_size,hankel_dim):
    """
    Fits each iterative DMD variant to the provided data, then returns their errors in the eigenvalue argument and modulus

    Parameters
    ----------
    data : numpy.array
        Measurements to fit the DMD variants to
    num_to_keep : int
        Number of dominant (largest modulus) eigenvalues to retain
    num_for_spin_up : int
        Number of measurements to use training the DMD model in the spin-up phase
    true_eigs : list
        Systems real eigenvalues
    window_size : int
        Number of timesteps to use in Windowed TDMD sliding window
    rho : float
        Between 0-1, exponential decay factor for the importance weighting applied to previous timesteps
    obs_cov_const : float
        Float that governs the size of the measurement uncertainty covariance matrix (used in filtering step)
    system_cov_const : float
        Float that governs the size of the system state uncertainty covariance matrix (used in filtering step)
    eig_cov_const : float
        Float that governs the size of the system eigenvalue uncertainty covariance matrix (used in filtering step)
    ensemble_size : int
        Number of ensemble members to use in the EnKF (default 100)
    hankel_dim : int
        Number of timesteps to stack in the time-delay embedded data

    Returns
    -------
    DMD argument distributions : numpy.array
        Array containing the errors in eigenvalue argument for STDMD, WTDMD, ODMD, DMDEnKF and Hankel-DMDEnKF
    DMD modulus distributions : numpy.array
        Array containing the errors in eigenvalue modulus for STDMD, WTDMD, ODMD, DMDEnKF and Hankel-DMDEnKF
    """

    #fit each model, then return the errors in their args and modulus
    #estimate eigenvalues using a variety of iterative methods
    streaming_tdmd_eigs = iterate_streaming_tdmd(data)
    streaming_tdmd_mods = [abs(x)-1 for x in streaming_tdmd_eigs][-num_to_keep:]
    streaming_tdmd_periods = [cmath.polar(x)[1] for x in streaming_tdmd_eigs][-num_to_keep:]
    windowed_tdmd_eigs = windowed_tdmd(data,window_size)
    windowed_tdmd_mods = [abs(x)-1 for x in windowed_tdmd_eigs][-num_to_keep:]
    windowed_tdmd_periods = [cmath.polar(x)[1] for x in windowed_tdmd_eigs][-num_to_keep:]
    odmd_eigs = iterate_odmd(data, rho)
    odmd_mods = [abs(x)-1 for x in odmd_eigs][-num_to_keep:]
    odmd_periods = [cmath.polar(x)[1] for x in odmd_eigs][-num_to_keep:]
    #squeeze data to make into standard format (legacy code from the ghost of bad codemas past)
    data = np.squeeze(data).T
    dmdenkf = apply_dmdenkf(data,num_for_spin_up,system_cov_const,obs_cov_const,eig_cov_const,ensemble_size=ensemble_size)
    #if model does not find a complex conjugate pair, use the dominant eig mod and arg of 0
    if not dmdenkf.conj_pair_list:
        dmdenkf_mods = [np.max(abs(x[-2:]))-1 for x in dmdenkf.X][-num_to_keep:]
        dmdenkf_periods = [0]* num_to_keep
    #otherwise record the mod and arg as standard
    else:
        dmdenkf_periods = [abs(x[-1]) for x in dmdenkf.X][-num_to_keep:]
        dmdenkf_mods = [abs(x[-2])-1 for x in dmdenkf.X][-num_to_keep:]
    hdmdenkf = apply_hankel_dmdenkf(data,num_for_spin_up,hankel_dim,system_cov_const,obs_cov_const,eig_cov_const,ensemble_size=ensemble_size)
    #if model does not find a complex conjugate pair, use the dominant eig mod and arg of 0
    if not hdmdenkf.conj_pair_list:
        hdmdenkf_mods = [np.max(abs(x[-2:]))-1 for x in hdmdenkf.X][-num_to_keep:]
        hdmdenkf_periods = [0]* num_to_keep
    #otherwise record the mod and arg as standard
    else:
        hdmdenkf_periods = [abs(x[-1]) for x in hdmdenkf.X][-num_to_keep:]
        hdmdenkf_mods = [abs(x[-2])-1 for x in hdmdenkf.X][-num_to_keep:]
    true_eigs = true_eigs[-num_to_keep:]
    streaming_tdmd_dist = dist_from_true_data(true_eigs,streaming_tdmd_periods)
    windowed_tdmd_dist = dist_from_true_data(true_eigs,windowed_tdmd_periods)
    odmd_dist = dist_from_true_data(true_eigs,odmd_periods)
    dmdenkf_dist = dist_from_true_data(true_eigs,dmdenkf_periods)
    hdmdenkf_dist = dist_from_true_data(true_eigs,hdmdenkf_periods)
    return np.array([streaming_tdmd_dist, windowed_tdmd_dist, odmd_dist, dmdenkf_dist, hdmdenkf_dist]),np.array([streaming_tdmd_mods,windowed_tdmd_mods,odmd_mods,dmdenkf_mods,hdmdenkf_mods])


# !/usr/bin/env python
# -*- coding: utf-8 -*-
# 'author':'zlw'

"""一个简单的实现访问者模式的程序
此程序模拟不同角色对账本数据的访问。
"""

from src.object_structures import AccountBook
from src.elements import (
    Income,
    Pay,
)
from src.visitors import (
    Boss,
    Manager,
    Cashier,
)

if __name__ == '__main__':
    # 实例化元素对象
    income = Income()
    pay = Pay()

    # 实例化对象结构
    account_book = AccountBook()
    # 对象结构增加元素对象(为了可以遍历展示访问结果)
    account_book.add(income)
    account_book.add(pay)

    # 实例化访问者
    boss = Boss()
    manager = Manager()
    cashier = Cashier()

    # 展示访问者对所有元素对象的访问结果
    account_book.accept(boss)
    account_book.accept(manager)
    account_book.accept(cashier)

    # 也可以针对某一个元素对象执行访问
    pay.accept(manager)


#!/usr/bin/env python3

import sys
from PyQt5.QtCore import QCoreApplication, QTimer, QTime

class main(QCoreApplication):
	def __init__(self, *args, **kwargs):
		super().__init__([])

		self.timer = QTimer()
		self.time = QTime(0, 0, 0)

		self.timer.timeout.connect(self.timerEvent)
		self.timer.start(1000)
		print('Ctrl Z to quit')

	def timerEvent(self):
		self.time = self.time.addSecs(1)
		print(self.time.toString("hh:mm:ss"), end = "\r")
		#print ("\r Loading... {}".format(i)+str(i), end="")

if __name__ == '__main__':
	app = QCoreApplication(sys.argv)
	gui = main()
	sys.exit(app.exec_())


from django.utils.html import format_html, mark_safe

from .base import BaseCroppieWidget

class CroppieWidget(BaseCroppieWidget):
    """
        Widget for Django.VERSION < 11 as old versions
        of django does not support templates in widgets.
    """

    def render(self, name, value, attrs=None):
        html = super(CroppieWidget, self).render(name, value, attrs)
        html += format_html(
            '<script type="text/javascript">{}</script>',
            self.make_script_vars(name),
        )
        return html

    def make_script_vars(self, name):
        context = self.process_croppie_context(name)
        vars = 'var croppieFieldName = "{}"\n var croppieOptions = {}' \
            .format(
                context['croppie_field_name'],
                context['croppie_options'],
            )
        return mark_safe(vars)


from django.shortcuts import render, get_object_or_404
from rest_framework import status, filters, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import JsonResponse
from django.http import HttpResponse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .serializers import *
from Employers.models import *
from Employers.api.serializers import *
import json

class AllJobSeekers(APIView):
    serializer_class = JobSeekerSerializer

    def get(self, request):
        if request.method == 'GET':
            jobSeekers = JobSeeker.objects.all()
            serializer = JobSeekerSerializer(jobSeekers, many=True)
            return Response(serializer.data)

class ApplicantCredentialsView(generics.GenericAPIView):
    serializer_class = ApplicantCredentialSerializer

    def get(self, request, id):
        if request.method == 'GET':
            if id:
                applicant_credential = ApplicantCredential.objects.get(id=id)
                serializer = ApplicantCredentialSerializer(applicant_credential)
                if applicant_credential:
                    return Response(serializer.data)
                else:
                    messages.error(request, "This credential does not exist")
                    return Response(status=status.HTTP_404_NOT_FOUND)

    def put(self, request, id):
        applicant_credential = ApplicantCredential.objects.get(id=id)
        if applicant_credential:
            serializer = ApplicantCredentialSerializer(applicant_credential, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
        else:
            messages.error(request, "This credential does not exist")
            return Response(status=status.HTTP_404_NOT_FOUND)

    def delete(self, request, id):
        applicant_credential = get_object_or_404(ApplicantCredential, id=id)
        data = {}
        if applicant_credential:
            applicant_credential.delete()
            data['response'] = "Credential Deleted"
            return Response(data, status=status.HTTP_200_OK)
        else:
            data['response'] = "No credential"
            return Response(data, status=status.HTTP_204_NO_CONTENT)

class JobSeekerView(generics.GenericAPIView):
    serializer_class = JobSeekerSerializer

    def get(self, request, id):
        if request.method == "GET":
            if id:
                jobSeeker = JobSeeker.objects.get(id=id)
                serializer = JobSeekerSerializer(jobSeeker)
                if jobSeeker:
                    return Response(serializer.data)
                else:
                    messages.error(request, "This jobseeker does not exist")
                    return Response(status=status.HTTP_404_NOT_FOUND)

    def put(self, request, id):
        jobseeker = JobSeeker.objects.get(id=id)
        if jobseeker:
            serializer = JobSeekerSerializer(
                jobseeker, data=request.data, partial=True)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            else:
                return Response(serializer.error_messages)
        else:
            messages.error(request, "This jobseeker does not exist")
            return Response(status=status.HTTP_404_NOT_FOUND)

    def delete(self, request, id):
        jobseeker = get_object_or_404(JobSeeker, id=id)
        data = {}
        if jobseeker:
            jobseeker.delete()
            data['response'] = "Jobseeker Deleted"
            return Response(data, status=status.HTTP_200_OK)
        else:
            data['response'] = "Please confirm your email address to complete the registration"
            return Response(data, status=status.HTTP_204_NO_CONTENT)

class AllJobApplications(generics.GenericAPIView):
    serializer_class = JobApplicationSerializer

    def get(self, request):
        if request.method == 'GET':
            job_application = JobApplication.objects.all()
            serializer = JobApplicationSerializer(job_application, many=True)
            return Response(serializer.data)

class getJobSeekerByUserId(APIView):
    serializer_class = JobSeekerSerializer

    def get(self, request, userid):
        if request.method == "GET":
            message = {}
            if userid:
                job_seeker = JobSeeker.objects.get(user=userid)
                serializer = JobSeekerSerializer(job_seeker)
                if job_seeker:
                    message['response'] = "Okay, you have tried"
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    return Response(status=status.HTTP_404_NOT_FOUND)

class jobApp(generics.GenericAPIView):
    serializer_class = CreateJobApplicationSerializer
    # serializer_class = JobApplicationSerializer

    def post(self, request, id):
        if request.method == 'POST':
            job = Job.objects.get(id=id)
            data = request.data
            serializer = self.serializer_class(
                data=data, context={'request': request})
            message = {}
            if serializer.is_valid():
                jobApplication = serializer.save()
                message['response'] = "Job application created"
                return Response(message, status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class JobApplicationView(generics.GenericAPIView):
    serializer_class = JobApplicationSerializer

    def get(self, request, id):
        if request.method == "GET":
            message = {}
            if id:
                job_application = JobApplication.objects.get(id=id)
                serializer = JobApplicationSerializer(job_application)
                if job_application:
                    message['response'] = "Okay, you have tried"
                    return Response(serializer.data)
                else:
                    return Response(status=status.HTTP_404_NOT_FOUND)

    def delete(self, request, id):
        job_application = get_object_or_404(JobApplication, id=id)
        data = {}
        if job_application:
            job_application.delete()
            data['response'] = "Job Application Deleted"
            return Response(data, status=status.HTTP_200_OK)
        else:
            data['response'] = "Unable to delete Job Application"
            return Response(data, status=status.HTTP_204_NO_CONTENT)

class GetJobApplicationByStatus(APIView):
    serializer_class = JobApplicationSerializer

    def get(self, request, applicationStatus):
        if request.method == "GET":
            message = {}
            if status:
                application = JobApplication.objects.filter(
                    status=applicationStatus)
                serializer = JobApplicationSerializer(application, many=True)
                if application:
                    message['response'] = "Application found"
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    message['response'] = "No Application with status Found"
                    return Response(message, status=status.HTTP_404_NOT_FOUND)

class GetApplicationByJobSeekerId(APIView):
    serializer_class = ViewJobApplicationSerializer

    def get(self, request, job_seeker_id):
        if request.method == "GET":
            message = {}
            if job_seeker_id:
                application = JobApplication.objects.filter(
                    job_seeker=job_seeker_id)
                serializer = ViewJobApplicationSerializer(application, many=True)
                if application:
                    message['response'] = "Application found"
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    message['response'] = "No Application with Jobseeker Found"
                    return Response(message, status=status.HTTP_404_NOT_FOUND)

class GetApplicationByJobId(APIView):
    serializer_class = JobApplicationSerializer

    def get(self, request, job_id):
        if request.method == "GET":
            message = {}
            if job_id:
                application = JobApplication.objects.filter(job=job_id)
                serializer = JobApplicationSerializer(application, many=True)
                if application:
                    message['response'] = "Application found"
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    message['response'] = "No Application with ID Found"
                    return Response(message, status=status.HTTP_404_NOT_FOUND)

class saveAJob(generics.GenericAPIView):
    serializer_class = SavedJobSerializer

    def post(self, request):
        if request.method == 'POST':
            serializer = self.serializer_class(
                data=request.data, context={'request': request}
            )
            data = {}
            if serializer.is_valid():
                savedJob = serializer.save()
                data['response'] = "job saved"
                return Response(serializer.data, status.HTTP_200_OK)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class SavedJobsView(APIView):
    serializer_class = ViewSavedJobsSerializer

#     def post (self, request, id):
#         if request.method == 'POST':
#             saved = SavedJob.objects.get(id=id)
#             data = request.data
#             serializer = self.serializer_class(data=data, context={'request': request})
#             message = {}
#             if serializer.is_valid():
#                 saved = serializer.save()
#                 message['response'] = "Job Saved"
#                 return Response(message, status=status.HTTP_201_CREATED)
#             else:
#                 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request, id):
        if request.method == "GET":
            if id:
                saved = SavedJob.objects.get(id=id)
                serializer = ViewSavedJobsSerializer(saved)
                if saved:
                    return Response(serializer.data)
                else:
                    messages.error(request, "This job does not exist")
                    return Response(status=status.HTTP_404_NOT_FOUND)

class GetCredentialByJobSeeker(APIView):
    serializers_class = ApplicantCredentialSerializer

    def get(self, request, job_seeker_id):
        if request.method == "GET":
            message = {}
            if job_seeker_id:
                credential = ApplicantCredential.objects.filter(job_seeker=job_seeker_id)
                serializer = ApplicantCredentialSerializer(credential, many=True)
                if credential:
                    message['response'] = "Credential found"
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    message['response'] = "No Credential with Jobseeker Found"
                    return Response(message, status=status.HTTP_404_NOT_FOUND)
class GetSavedJobsByJobSeeker(APIView):
    serializer_class = ViewSavedJobsSerializer

    def get(self, request, job_seeker_id):
        if request.method == "GET":
            message = {}
            if job_seeker_id:
                saved = SavedJob.objects.filter(job_seeker=job_seeker_id)
                serializer = ViewSavedJobsSerializer(saved, many=True)
                if saved:
                    message['response'] = "Saved Job(s) found"
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    message['response'] = "No Saved Jobs with Jobseeker Found"
                    return Response(message, status=status.HTTP_404_NOT_FOUND)

class DeleteSavedJobByJobSeeker(APIView):
    serializers = SavedJobSerializer

    def delete(self, request, job_seeker_id, id):
        saved = get_object_or_404(SavedJob, job_seeker=job_seeker_id, id=id)
        data = {}
        if saved:
            saved.delete()
            data['response'] = "Saved Job Deleted"
            return Response(data, status=status.HTTP_200_OK)
        else:
            data['response'] = "Saved Job Could Not be Deleted"
            return Response(data, status=status.HTTP_204_NO_CONTENT)

class ArchivedJobsView(APIView):
    serializer_class = ArchivedJobSerializer

    def get(self, request, id):
        if request.method == "GET":
            if id:
                archived = ArchivedJob.objects.get(id=id)
                serializer = ArchivedJobSerializer(archived)
                if archived:
                    return Response(serializer.data)
                else:
                    messages.error(request, "This job does not exist")
                    return Response(status=status.HTTP_404_NOT_FOUND)

class GetArchivedJobsByJobSeeker(APIView):
    serializer_class = ArchivedJobSerializer

    def get(self, request, job_seeker_id):
        if request.method == "GET":
            message = {}
            if job_seeker_id:
                archived = SavedJob.objects.filter(job_seeker=job_seeker_id)
                serializer = ArchivedJobSerializer(archived, many=True)
                if archived:
                    message['response'] = "Archived Job(s) found"
                    return Response(serializer.data, status=status.HTTP_200_OK)
                else:
                    message['response'] = "No Archived Jobs with Jobseeker Found"
                    return Response(message, status=status.HTTP_404_NOT_FOUND)

class DeleteArchivedJobByJobSeeker(APIView):
    serializers = ArchivedJobSerializer

    def delete(self, request, job_seeker_id, id):
        archived = get_object_or_404(
            ArchivedJob, job_seeker=job_seeker_id, id=id)
        data = {}
        if archived:
            archived.delete()
            data['response'] = "Archived Job Deleted"
            return Response(data, status=status.HTTP_200_OK)
        else:
            data['response'] = "Archived Job Could Not be Deleted"
            return Response(data, status=status.HTTP_204_NO_CONTENT)

def get_choices(request):
    university_choices = UniversityName.choices
    degree_choices = DegreeClassification.choices
    year_choices = JobSeeker.YEAR_OF_GRADUATION_CHOICES
    gender_choices = Gender.choices
    role_choices = JobType.choices
    industry_choices = Industry.choices
    subject_choices = SubjectOfStudy.choices
    qualification_choices = JobSeeker.HIGHEST_QUALIFICATION_CHOICES
    context = {
        "university_choices": university_choices,
        "year_choices": year_choices,
        'degree_choices': degree_choices,
        'gender_choices':  gender_choices,
        'role_choices': role_choices,
        'industry_choices': industry_choices,
        'subject_choices': subject_choices,
        'qualification_choices': qualification_choices
    }
    return JsonResponse(context, safe=False)

class SearchJobs(generics.ListCreateAPIView):
    serializer_class = ViewJobSerializer
    search_fields = ['title', 'company__organisation_name']
    filter_backends = (filters.SearchFilter,)
    queryset = Job.objects.all()


def temizleyici(satır):
    satır=satır.replace("\n","")
    satır=satır.replace("	"," ")
    return satır

def ayıklayıcı(futbolcu):
    futbolcu=temizleyici(futbolcu)
    liste = futbolcu.split(" ")
    takımı=""
    for i in liste:
        if(i=="GS"):
            takımı="GS"
        elif (i == "FB"):
            takımı = "FB"
        elif (i == "BJK"):
            takımı = "BJK"
    return futbolcu+","+takımı

with open("futbolcular.txt","r",encoding="utf-8") as file:
    gs = []
    fb = []
    bjk = []
    ayıklanacak_liste=file.readlines()
    for i in ayıklanacak_liste:
        liste2=ayıklayıcı(i).split(",")
        #print(ayıklayıcı(i))
        if (liste2[1] == "GS"):
            gs.append(liste2[0]+"\n")
        elif (liste2[1] == "FB"):
            fb.append(liste2[0]+"\n")
        elif (liste2[1] == "BJK"):
            bjk.append(liste2[0]+"\n")

    with open("gs.txt","w",encoding="utf-8")as file2:
        file2.writelines(gs)
    with open("fb.txt","w",encoding="utf-8")as file2:
        file2.writelines(fb)
    with open("bjk.txt","w",encoding="utf-8")as file2:
        file2.writelines(bjk)


import requests

from django.http import JsonResponse
from allauth.socialaccount.models import SocialToken, SocialApp
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def GoogleGmailDelete(request, email_id):
   if request.method == 'DELETE':
      socialGoogleToken = SocialToken.objects.filter(account__user=request.user, account__provider='google').last()

      if socialGoogleToken:
         access_token = socialGoogleToken.token

         response = requests.delete(f'https://www.googleapis.com/gmail/v1/users/me/messages/{email_id}', params={
            'access_token': access_token,
         })

         print('______________response_______________', response)

         if response.status_code == 204:
            return  JsonResponse({
               'status': 'success',
               'message': f'Email with ID {email_id} deleted successfully'
            }, safe=False)
         else:
            return JsonResponse({
              'status': 'error',
              'message': f'Failed to delete email with ID {email_id}, status code: {response.status_code}'
            }, safe=False)


#!/usr/bin/python3

import re
from collections import deque

valve = {}
tunnels = {}

with open("16.txt") as f:
    for line in f:
        m = re.match('Valve (.*) has flow rate=(\d+); tunnels? leads? to valves? (.*)', line)
        valve[m.group(1)] = int(m.group(2))
        tunnels[m.group(1)] = m.group(3).split(', ')

print(valve)
print(tunnels)

# minute, pos, walk, pos2, walk2, open, flow
status = (0, 'AA', ('AA',), 'AA', ('AA',), tuple(), 0)

queue = deque([status])

s = 0
max_flow = 0
seen = {}
while queue:
    minute, pos, walk, pos2, walk2, opens, flow = queue.popleft()
    s += 1
    if s % 10000 == 0:
        print(minute, pos, walk, pos2, walk2, opens, flow)
    if minute == 26:
        max_flow = max(flow, max_flow)
        continue

    # both open
    if valve[pos] > 0 and pos not in opens and valve[pos2] > 0 and pos2 not in opens:
        new = (pos, (pos,), pos2, (pos2,), tuple(sorted(opens + (pos, pos2))))
        fl = flow + sum({valve[x] for x in opens})
        if new not in seen or seen[new] < fl:
            queue.append((minute+1,) + new + (fl,))
            seen[new] = fl

    # first opens, second walks
    if valve[pos] > 0 and pos not in opens:
        for t2 in tunnels[pos2]:
            if t2 not in walk2: # don't go back
                new = (pos, (pos,), t2, tuple(sorted(walk2 + (t2,))), tuple(sorted(opens + (pos,))))
                fl = flow + sum({valve[x] for x in opens})
                if new not in seen or seen[new] < fl:
                    queue.append((minute+1,) + new + (fl,))
                    seen[new] = fl

    # first walks, second opens
    if valve[pos2] > 0 and pos2 not in opens:
        for t in tunnels[pos]:
            if t not in walk: # don't go back
                new = (t, tuple(sorted(walk + (t,))), pos2, (pos2,), tuple(sorted(opens + (pos2,))))
                fl = flow + sum({valve[x] for x in opens})
                if new not in seen or seen[new] < fl:
                    queue.append((minute+1,) + new + (fl,))
                    seen[new] = fl

    # both walk
    for t in tunnels[pos]:
        if t not in walk: # don't go back
            for t2 in tunnels[pos2]:
                if t not in walk2: # don't go back
                    new = (t, tuple(sorted(walk + (t,))), t2, tuple(sorted(walk2 + (t2,))), opens)
                    fl = flow + sum({valve[x] for x in opens})
                    if new not in seen or seen[new] < fl:
                        queue.append((minute+1,) + new + (fl,))
                        seen[new] = fl

print("max flow is", max_flow)


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

#需求：将非文本文件001.png拷贝一份到002.jpg
"""
思路：
1、只读模式rb打开文件1
2、只写模式wb打开文件2
3、循环遍历文件1，过程中，写入文件2
4、从而实现图片文件拷贝
注意点：
1 非文本文件不涉及encoding，写了会报错

步骤：

"""
#方法1 简洁3行--推荐
path1 = r".\001.png"
path2 = r".\002.jpg" #注意：可以支持拷贝成不同格式的图片，拷贝后的图片，大小可能需要放大才能看清
with open(path1,mode="rb") as f1, open(path2, mode="wb") as f2: #自动刷新和关闭文件
    for i in f1:
        f2.write(i)

#方法2  7行
path1 = r".\001.png"
path3 = r".\003.jpg"
f1 = open(path1,mode="rb")
f2 = open(path3,mode="wb")
for i in f1:
    f2.write(i)
f2.flush()
f1.close()
f2.close()

python16/day1-21/day008 文件操作/课上代码/01非文本文件的拷贝.py

01非文本文件的拷贝.py


import numpy as np
from keras.models import Model
from keras.datasets import mnist
from keras.models import load_model
from sklearn.metrics import label_ranking_average_precision_score
import time
import cv2

t0 = time.time()

#(x_train, y_train), (x_test, y_test) = mnist.load_data()
sw_data = np.load('atlas_sw.npz')
x_train = sw_data['images'].astype('float32') / 255.
x_shape = (x_train.shape[0], x_train.shape[1], x_train.shape[2], 1)
x_train = np.reshape(x_train, x_shape)
y_train = sw_data['labels']
print("X_Train: ", x_train.shape)

print("===--- Paxinos/Watson Atlas")
pw_data = np.load('atlas_pw.npz')
pw_y = pw_data['labels']
pw_im = pw_data['images'].astype('float32') / 255.
pw_shape = pw_im.shape[0], pw_im.shape[1], pw_im.shape[2], 1
pw_im = np.reshape(pw_im, pw_shape)

x_test = np.array([pw_im[7], pw_im[10], pw_im[26], pw_im[39]])
y_test = np.array([pw_y[7], pw_y[10], pw_y[26], pw_y[39]])

x_test = pw_im
y_test = pw_y

print("X_Test: ", x_test.shape)

noise_factor = 0.4
x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape)
x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape)

x_train_noisy = np.clip(x_train_noisy, 0., 1.)
x_test_noisy = np.clip(x_test_noisy, 0., 1.)
t1 = time.time()
print('Dataset loaded in: ', t1-t0)

print('Loading model :')
t0 = time.time()
autoencoder = load_model('autoencoder.h5')
encoder = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer('encoder').output)
t1 = time.time()
print('Model loaded in: ', t1-t0)

scores = []

def retrieve_closest_elements(test_code, test_label, learned_codes):
    distances = []
    for code in learned_codes:
        distance = np.linalg.norm(code - test_code)
        distances.append(distance)
    nb_elements = learned_codes.shape[0]
    distances = np.array(distances)
    learned_code_index = np.arange(nb_elements)
    labels = np.copy(y_train).astype('float32')
    labels[labels != test_label] = -1
    labels[labels == test_label] = 1
    labels[labels == -1] = 0
    distance_with_labels = np.stack((distances, labels, learned_code_index), axis=-1)
    sorted_distance_with_labels = distance_with_labels[distance_with_labels[:, 0].argsort()]

    sorted_distances = 28 - sorted_distance_with_labels[:, 0]
    sorted_labels = sorted_distance_with_labels[:, 1]
    sorted_indexes = sorted_distance_with_labels[:, 2]
    return sorted_distances, sorted_labels, sorted_indexes

def compute_average_precision_score(test_codes, test_labels, learned_codes, n_samples):
    out_labels = []
    out_distances = []
    retrieved_elements_indexes = []
    for i in range(len(test_codes)):
        sorted_distances, sorted_labels, sorted_indexes = retrieve_closest_elements(test_codes[i], test_labels[i], learned_codes)
        out_distances.append(sorted_distances[:n_samples])
        out_labels.append(sorted_labels[:n_samples])
        retrieved_elements_indexes.append(sorted_indexes[:n_samples])

    out_labels = np.array(out_labels)
    out_labels_file_name = 'computed_data/out_labels_{}'.format(n_samples)
    np.save(out_labels_file_name, out_labels)

    out_distances_file_name = 'computed_data/out_distances_{}'.format(n_samples)
    out_distances = np.array(out_distances)
    np.save(out_distances_file_name, out_distances)
    score = label_ranking_average_precision_score(out_labels, out_distances)
    scores.append(score)
    return score

INDEX = 0
def retrieve_closest_images(test_element, test_label, n_samples=10):
    global INDEX
    learned_codes = encoder.predict(x_train)
    learned_codes = learned_codes.reshape(learned_codes.shape[0],
                                          learned_codes.shape[1] * learned_codes.shape[2] * learned_codes.shape[3])

    test_code = encoder.predict(np.array([test_element]))
    test_code = test_code.reshape(test_code.shape[1] * test_code.shape[2] * test_code.shape[3])

    distances = []

    for code in learned_codes:
        distance = np.linalg.norm(code - test_code)
        distances.append(distance)
    nb_elements = learned_codes.shape[0]
    distances = np.array(distances)
    learned_code_index = np.arange(nb_elements)
    labels = np.copy(y_train).astype('float32')
    labels[labels != test_label] = -1
    labels[labels == test_label] = 1
    labels[labels == -1] = 0
    distance_with_labels = np.stack((distances, labels, learned_code_index), axis=-1)
    sorted_distance_with_labels = distance_with_labels[distance_with_labels[:, 0].argsort()]

    sorted_distances = 28 - sorted_distance_with_labels[:, 0]
    sorted_labels = sorted_distance_with_labels[:, 1]
    sorted_indexes = sorted_distance_with_labels[:, 2]
    kept_indexes = sorted_indexes[:n_samples]

    score = label_ranking_average_precision_score(np.array([sorted_labels[:n_samples]]), np.array([sorted_distances[:n_samples]]))

    kept_indexes = kept_indexes.astype(np.uint16)
    result_y = y_train[kept_indexes]
    result_distances = sorted_distances[kept_indexes]

    print("Plate {} - ".format(test_label), end='')
    for i in range(n_samples):
        match_y = result_y[i]
        match_d = result_distances[i]
        print("[{},{:.4f}] ".format(match_y, match_d), end='')

    print("")

    #print("Average precision ranking score for tested element is {}".format(score))

    original_image = test_element
    #cv2.imshow('original_image_' + str(INDEX), original_image)
    retrieved_images = x_train[int(kept_indexes[0]), :]
    for i in range(1, n_samples):
        retrieved_images = np.hstack((retrieved_images, x_train[int(kept_indexes[i]), :]))

    #cv2.imshow('Results_' + str(INDEX), retrieved_images)

    cv2.imwrite('test_results/plate_' + str(test_label) + '.jpg', 255 * cv2.resize(original_image, (0,0), fx=3, fy=3))
    cv2.imwrite('test_results/results' + str(test_label) + '.jpg', 255 * cv2.resize(retrieved_images, (0,0), fx=2, fy=2))

    #import pdb
    #pdb.set_trace()

    INDEX += 1
    return result_y

def test_model(n_test_samples, n_train_samples):
    learned_codes = encoder.predict(x_train)
    learned_codes = learned_codes.reshape(learned_codes.shape[0], learned_codes.shape[1] * learned_codes.shape[2] * learned_codes.shape[3])
    test_codes = encoder.predict(x_test)
    test_codes = test_codes.reshape(test_codes.shape[0], test_codes.shape[1] * test_codes.shape[2] * test_codes.shape[3])
    indexes = np.arange(len(y_test))
    np.random.shuffle(indexes)
    indexes = indexes[:n_test_samples]

    print('Start computing score for {} train samples'.format(n_train_samples))
    t1 = time.time()
    score = compute_average_precision_score(test_codes[indexes], y_test[indexes], learned_codes, n_train_samples)
    t2 = time.time()
    print('Score computed in: ', t2-t1)
    print('Model score:', score)

def plot_denoised_images():
    denoised_images = autoencoder.predict(x_test_noisy.reshape(x_test_noisy.shape[0], x_test_noisy.shape[1], x_test_noisy.shape[2], 1))
    test_img = x_test_noisy[0]
    resized_test_img = cv2.resize(test_img, (280, 280))
    cv2.imshow('input', resized_test_img)
    output = denoised_images[0]
    resized_output = cv2.resize(output, (280, 280))
    cv2.imshow('output', resized_output)
    cv2.imwrite('test_results/noisy_image.jpg', 255 * resized_test_img)
    cv2.imwrite('test_results/denoised_image.jpg', 255 * resized_output)

# To test the whole model
n_test_samples = 1000
n_train_samples = [10, 50, 100, 200, 300, 400, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000,
                   20000, 30000, 40000, 50000, 60000]

#for n_train_sample in n_train_samples:
#    test_model(n_test_samples, n_train_sample)

np.save('computed_data/scores', np.array(scores))

import pylab as plt
plt.xkcd()
plt.figure()
plt.title('SW Matching')
plt.xlabel('PW Plate')
plt.ylabel('SW Plate')
# To retrieve closest images
x = []
y = []
for i in range(len(x_test)):
#for i in range(3):
    x.append(y_test[i]) # Plate #
    predictions = retrieve_closest_images(x_test[i], y_test[i])
    y.append(predictions[0]) # Top Prediction

plt.plot(x, y)
plt.savefig('results.png')
plt.show(block=True)

# To plot a denoised image
#plot_denoised_images()


#!/usr/bin/env python
__author__ = 'Timothy Lurvey'

from running_total import RunningTotal

class Donor(RunningTotal):
    """change attribute from 'key' to 'name'"""

    def __init__(self, name: str, total: float = 0., count: int = 0):
        super().__init__(new_key=name, total=total, count=count)

    def __repr__(self):
        return f"Donor('{self.name}', {self.total}, {self.count})"

    @property
    def name(self):
        return self.key

    @name.setter
    def name(self, new_name: str):
        self.key = new_name

class DonorRepository(object):
    """Create and manage a data repository of Donor objects.  Donor objects must have unique names."""
    _REPORT_HEADER = "\nDonor Name                | Total Given | Num Gifts | Average Gift\n" + ("-" * 66) + "\n"

    def __init__(self, data_set: tuple = ()):
        self._data = []
        self._set_data(data_set)

    @property
    def name_list(self) -> tuple:
        """return a list of all donor names"""
        return tuple(sorted([d.name for d in self._data]))

    def _expand_input_values(self, data: (list, tuple, set)) -> tuple:
        """expand all possible values from sequence"""
        n = data[0]
        t = 0.
        c = 0
        try:
            t += float(data[1])
            c += int(data[2])
        except:
            pass
        return n, t, c

    def _set_data(self, data_set) -> None:
        """work through the inputs to create a populated data object"""
        for d_obj in data_set:
            if isinstance(d_obj, Donor):
                add_obj = d_obj
            else:
                n, t, c = self._expand_input_values(d_obj)
                add_obj = Donor(name=n, total=t, count=c)
            self._data.append(add_obj)

    def add_new_donor(self, obj) -> None:
        """add a Donor object or a sequence of data to be converted (name, total, count)
        Donor('x', 1. ,1 )or ('x', 102.5, 2)
        In the data input sequence, total and count are optional"""
        try:
            assert isinstance(obj, Donor) or isinstance(obj, (list, tuple, set))
            self._set_data((obj,))
        except AssertionError:
            raise TypeError("TypeError: object must be a Donor object or a sequence of donor datas")

    def get_donor(self, name) -> Donor:
        if name in self.name_list:
            return [o for o in self._data if name == o.name][0]
        else:
            raise ValueError("ValueError: donor.name='{}' no found in repository".format(name))

    def _compose_email(self, name: str, new_donation: float) -> str:
        """return the string of the formatted email for a given donor, optional additional donation"""
        # get data object from name
        donor_obj = self.get_donor(name=name)
        # determine plurals
        if donor_obj.count == 1:
            s = ""
            is_are = "is"
        else:
            s = "s"
            is_are = "are"
        # create new donation string, if needed
        fnew_donation = ""
        if new_donation:
            fnew_donation += "Thank you for your generous donation of $ {:.2f}.\n".format(new_donation)
        # format email string
        email_str = "\nHello {name},\n\n" \
                    "{new_donation}" \
                    "Your {count} donation{s}, totaling $ {total:.2f}, {is_are} greatly appreciated.\n\n" \
                    "Thank you\n\n".format(name=donor_obj.key,
                                           new_donation=fnew_donation,
                                           count=donor_obj.count,
                                           s=s,
                                           total=donor_obj.total,
                                           is_are=is_are)
        return email_str

    def add_donation(self, name: str = "", amount: float = 0.) -> None:
        self.get_donor(name=name).add_to_total(amount=amount)

    @property
    def formatted_name_list(self) -> str:
        print_list = ""
        for i, name in enumerate(self.name_list):
            print_list += f"{i:>3} : {name}\n"
        return print_list[:-1]

    def get_thank_you_email(self, donor: str = "", new_donation: float = 0.) -> str:
        """This method will get the thank you text for a user in the database who has made a new donation."""
        if new_donation:
            # add the donation to their existing amount
            self.add_donation(name=donor, amount=float(new_donation))
        # return the email string
        return self._compose_email(name=donor, new_donation=float(new_donation))

    def _report_data_line(self, name: str, total: float, count: int) -> str:
        """create a single report line of formatted inputs"""
        ftotal = "$ {:.2f}".format(total)
        if count:
            average = total / count
        else:
            average = 0
        faverage = "$ {:.2f}".format(average)
        return "{name:<26}|{tot:>13}|{num:>11d}|{avg:>13}\n".format(name=name,
                                                                    tot=ftotal,
                                                                    num=count,
                                                                    avg=faverage)

    def report(self) -> str:
        """ Print report in the following format:

        Donor Name                | Total Given | Num Gifts | Average Gift
        ------------------------------------------------------------------
        William Gates, III         $  653784.49           2  $   326892.24"""
        s = self._REPORT_HEADER
        for i, name in enumerate(self.name_list):
            d = self.get_donor(name)
            s += self._report_data_line(name =d.name,
                                        total=d.total,
                                        count=d.count)
        s += ("-" * 66) + "\n"
        return s


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

""" An Simple Example for Tank MC

Adapted from an example from
Scott Rome, http://srome.github.io/Dont-Solve-Simulate-Markov-Chain-Monte-Carlo-Methods-with-PyMC3/

"""

import os
os.environ['MKL_THREADING_LAYER']='GNU'

import numpy as np
import pymc3 as pm
import matplotlib.pyplot as plt

size = 200
a = 1.
b = 2.
x = np.linspace(0,1,size)
y_sigma = 0.1
line = a + b*x

line_noise = line + np.random.normal(
    scale=y_sigma,
    size=size)

model = pm.Model()

#define prior_0_parameters
with model:
    y_hat_sigma = pm.HalfCauchy('sigma',beta=10,testval=1.)
    a_hat = pm.Normal('Intercept',0,sd=20)
    b_hat = pm.Normal('x',0,sd=20)

with model:
    # Define Likelihood
    likelihood = pm.Normal(
        'y',
        mu=a_hat+b_hat*x,
        sd=y_hat_sigma,
        observed=line_noise)

    # inference
    trace = pm.sample(
        progressbar=False,
        tune=1000,
        #njobs=4,
        cores=1)

#plt.figure(figsize=(7, 7))
pm.traceplot(trace)
plt.tight_layout()
plt.show()

plt.figure(figsize=(7, 7))
plt.plot(x, line_noise, 'x', label='data')
pm.plots.plot_posterior_predictive_glm(
    trace,
    samples=100,
    label='posterior predictive regression lines')
plt.plot(x, line, label='true regression line', lw=3., c='y')

plt.title('Posterior predictive regression lines')
plt.legend(loc=0)
plt.xlabel('x')
plt.ylabel('y')
plt.show()


# pylint: disable=C0114, C0115, C0116
# pylint: disable=protected-access
# -*- coding: utf-8 -*-
__copyright__ = """ This code is licensed under the 3-clause BSD license.
Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
See LICENSE.txt for details.
"""

import os
import unittest

import numpy as np

from scine_autocas.interfaces.qcmaquis import Qcmaquis
from scine_autocas.interfaces.qcmaquis.qcmaquis_hdf5_utils import Hdf5Converter
from scine_autocas.interfaces.qcmaquis.qcmaquis_orbital_rdm_builder import OrbitalRDMBuilder

class TestQcMquisClasses(unittest.TestCase):
    def setUp(self):
        self.path = os.path.dirname(os.path.abspath(__file__))

    def test_hdf5_converter(self):
        hdf5_converter = Hdf5Converter()
        qcmaquis_result_file = self.path + "/files/n2.results_state.0.h5"
        hdf5_converter.read_hdf5(qcmaquis_result_file)
        self.assertEqual(hdf5_converter.L, 8)
        self.assertAlmostEqual(hdf5_converter.energy, -108.7499817)
        self.assertEqual(hdf5_converter.symmetry, "su2u1pg")
        # fmt: off
        self.assertTrue(
            np.array_equal(hdf5_converter.orbital_order, np.array([1, 2, 3, 4, 5, 6, 7, 8]))
        )

        self.assertRaises(
            AssertionError,
            lambda: hdf5_converter._Hdf5Converter__mat_measurement([(1, 1), (2, 2)], np.array([0, 1, 2]))
        )
        self.assertRaises(
            AssertionError,
            lambda: hdf5_converter._Hdf5Converter__mat_merge_transpose([(1, 1), (2, 2)], np.array([0, 1, 2]),
                                                                       [(1, 1), (2, 2)], np.array([0, 1, 2]))
        )
        # fmt: on
        new_hdf5_converter = Hdf5Converter()
        new_hdf5_converter.result_file = qcmaquis_result_file
        new_hdf5_converter.read_hdf5()
        self.assertEqual(new_hdf5_converter.L, 8)
        self.assertAlmostEqual(new_hdf5_converter.energy, -108.7499817)
        self.assertEqual(new_hdf5_converter.symmetry, "su2u1pg")

    def test_orbital_rdm_builder(self):
        hdf5_converter = Hdf5Converter()
        ordm_builder = OrbitalRDMBuilder()
        self.assertRaises(AttributeError, lambda: ordm_builder.make_one_ordm(hdf5_converter))
        self.assertRaises(AttributeError, lambda: ordm_builder.make_two_ordm(hdf5_converter))
        qcmaquis_result_file = self.path + "/files/n2.results_state.0.h5"
        hdf5_converter.read_hdf5(qcmaquis_result_file)
        one_ordm = ordm_builder.make_one_ordm(hdf5_converter)
        ordm_builder.make_two_ordm(hdf5_converter)
        # fmt: off
        test_one_ordm = np.array(
            [
                [2.53220e-03, 2.53220e-03, 2.52018e-04, 9.94683e-01],
                [2.40389e-03, 2.40389e-03, 1.35218e-03, 9.93840e-01],
                [7.87185e-02, 7.87185e-02, 1.24039e-01, 7.18523e-01],
                [1.24453e-01, 1.24453e-01, 2.49871e-01, 5.01222e-01],
                [1.24453e-01, 1.24453e-01, 2.49871e-01, 5.01221e-01],
                [1.24453e-01, 1.24453e-01, 5.00725e-01, 2.50368e-01],
                [1.24453e-01, 1.24453e-01, 5.00725e-01, 2.50368e-01],
                [8.04333e-02, 8.04333e-02, 7.11261e-01, 1.27871e-01],
            ]
        )
        # fmt: on
        self.assertTrue(np.allclose(one_ordm, test_one_ordm))

    def test_qcmaquis(self):
        qcmaquis_result_file = self.path + "/files/n2.results_state.0.h5"
        qc_maquis = Qcmaquis()
        # this lambda is necessary to check for the AttributeError
        # pylint: disable=unnecessary-lambda
        self.assertRaises(AttributeError, lambda: qc_maquis.make_diagnostics())
        # pylint: enable=unnecessary-lambda
        self.assertRaises(
            AttributeError,
            lambda: qc_maquis.make_s1(
                qc_maquis.orbital_rdm_builder.make_one_ordm(qc_maquis.hdf5_converter)
            ),
        )
        self.assertRaises(
            AttributeError,
            lambda: qc_maquis.make_s2(
                qc_maquis.orbital_rdm_builder.make_two_ordm(qc_maquis.hdf5_converter)
            ),
        )
        qc_maquis.read_hdf5(qcmaquis_result_file)
        qc_maquis.make_diagnostics()
        qc_maquis.make_s1(qc_maquis.orbital_rdm_builder.make_one_ordm(qc_maquis.hdf5_converter))
        qc_maquis.make_s2(qc_maquis.orbital_rdm_builder.make_two_ordm(qc_maquis.hdf5_converter))
        qc_maquis.make_mutual_information()
        qc_maquis.hdf5_converter.L = None
        self.assertRaises(
            AttributeError, lambda: qc_maquis.make_s1(qc_maquis.orbital_rdm_builder.one_ordm)
        )
        self.assertRaises(
            AttributeError, lambda: qc_maquis.make_s2(qc_maquis.orbital_rdm_builder.two_ordm)
        )
        self.assertRaises(
            AttributeError,
            lambda: qc_maquis.make_s1(qc_maquis.orbital_rdm_builder.make_one_ordm(qc_maquis.hdf5_converter))
        )
        qc_maquis.s1_entropy = np.array([])
        # pylint: disable=unnecessary-lambda
        self.assertRaises(AttributeError, lambda: qc_maquis.make_mutual_information())
        self.assertRaises(AttributeError, lambda: qc_maquis.make_diagnostics())
        # pylint: enable=unnecessary-lambda

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


import os, json
import calendar
from datetime import datetime, date, timedelta
from requests_oauthlib import OAuth1Session
#from flask import json, make_response

def tweet_post(text):
    with open('secret.json') as f:
        secret = json.load(f)
        AK = secret['TWIITER_CONSUMER_KEY']
        ASK = secret['TWIITER_CONSUMER_SECRET']
        AT = secret['TWIITER_ACCESS_TOKEN']
        ATS = secret['TWIITER_ACCESS_TOKEN_SECRET']
        EP = secret['TWITTER_ENDPOINT']

    twitter = OAuth1Session(AK, ASK, AT, ATS)
    params = {"status" : text}
    res = twitter.post(EP, params = params)
    if res.status_code == 200: #正常投稿出来た場合
        print("Tweet Success.")
    else: #正常投稿出来なかった場合
        print("Tweet Failed.", res.status_code, res.text)

def calc_fiscal_year(today:datetime)->datetime:
    _uru_year = False
    all_days = 365
    if today.month >= 4: #4月以降なら次年をセット
        end_day = date(year=today.year + 1, month=3, day=31)
        if calendar.isleap(today.year + 1):
            _uru_year = True
    elif today.month < 4:#3月までなら同年をセット
        end_day = date(year=today.year, month=3, day=31)
        if calendar.isleap(today.year):
            _uru_year = True
    else:
        print('error,today.month=', today.month)

    if _uru_year:
        all_days = 366

    #残日数を計算
    _remain_days = end_day - today.date()
    remain_days = _remain_days.days
    rate = (remain_days / all_days) * 100

    return remain_days, rate

today = datetime.now() + timedelta(hours=9) + timedelta(minutes=10)
print(today)
remain_days, rate = calc_fiscal_year(today)
tweet_text = f'{today.year}年{today.month}月{today.day}日になりました。今年度は残り{remain_days}日です。あと{round(rate,1)}％です。'
print(tweet_text)

tweet_post(tweet_text)


import sys, os

# add VHDL-Components to path
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "deps",  "VHDL-Components", "src"))
from axi_csr import Register, write_axi_csr

if __name__ == '__main__':

	registers = [
				Register(0, "status", "read"),
				Register(8, "resets",  "write"),
				Register(9, "control", "write"),
				Register(11, "trigger_word",  "read"), # shift register of last 4 bytes broadcast out on SATA
				Register(12, "trigger_interval", "write", initial_value=0x000186a0), # trigger interval (1ms = 100,000 clock cycles)
				Register(18, "SATA_status", "read"),
				Register(20, "uptime_seconds", "read"),
				Register(21, "uptime_nanoseconds", "read"),
				Register(22, "tdm_version", "read"),
				Register(23, "temperature", "read"), # 11-0
				Register(24, "git_sha1", "read"),
				Register(25, "build_timestamp", "read")
			]

	write_axi_csr(os.path.join(os.path.dirname(__file__), "..", "src", "tdm_csr.vhd"), registers, module_name="TDM_CSR")


import csv
import os

from flask import Flask, request, redirect
from flask.templating import render_template
app = Flask(__name__)

def write_to_csv_file(data: dict):
    path = os.path.join(os.getcwd(), 'data', 'emails.csv')
    with open(path, 'a', newline='') as csv_file:
        email = data['email']
        subject = data['subject']
        message = data['message']

        csv_writer = csv.writer(csv_file,
                                delimiter=',',
                                quotechar='"',
                                quoting=csv.QUOTE_MINIMAL)
        csv_writer.writerow([email, subject, message])

@app.route('/send_form', methods=['POST', 'GET'])
def submit_form():
    if request.method == 'POST':
        data = request.form.to_dict()
        write_to_csv_file(data)

        return redirect('thanks.html')
    else:
        return 'error'

@app.route('/')
def home_route():
    return render_template('index.html')

@app.route('/index.html')
def home():
    return render_template('index.html')

@app.route('/<string:page_name>')
def pages(page_name):
    return render_template(page_name)

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


import os
from collections import defaultdict

class UndeliveredMessages:
    """Class to store undelivered messages. The messages are stored in memory and in a file."""
    def __init__(self, filename: str):
        self.filename = filename

        self.undelivered_msg = defaultdict(list) # Map of recipient username to list of (sender, message) for that recipient
        if os.path.exists(filename):
            # Read the file and store the messages in a dictionary by recipient
            with open(self.filename, 'r') as f:
                lines = f.readlines()
            for line in lines:
                if line.strip():
                    recipient, sender, message = line.strip().split(' ', 2)
                    self.undelivered_msg[recipient].append((sender, message))

    def add_message(self, recipient: str, sender: str, message: str):
        """Add a message to the list of undelivered messages for a recipient."""
        self.undelivered_msg[recipient] += [
            (sender, message)]
        with open(self.filename, 'a') as f:
            f.write(f"{recipient} {sender} {message}\n")
            f.flush()

    def get_messages(self):
        """Return a list of (recipient, [(sender, message)]) for all recipients with undelivered messages."""
        return self.undelivered_msg.items()

    def update_messages(self, recipient, message_infos):
        """Update the messages for a recipient. Replaces the message list for that recipient with the given messages."""
        self.undelivered_msg[recipient] = message_infos
        with open(self.filename, 'r') as f:
            lines = f.readlines()
        with open(self.filename, 'w') as f:
            f.writelines(filter(lambda line: line.strip() and line.strip().split()[0] != recipient, lines))
            f.flush()
            for sender, message in message_infos:
                if (not (sender == "" or message == "")):
                    f.write(f"{recipient} {sender} {message}\n")
                    f.flush()

    def clear(self):
        """
        Clears the undelivered messages for testing purposes
        """
        self.undelivered_msg = defaultdict(list)
        open(self.filename, 'w').close()


import logging
from os import getenv
import sys

def config(
        logging_level : str = "INFO",
        libs_to_silence : list = None,
        env_var_hide_timestamp : list = None
    ):

    # Set higher level for external libs logging
    if libs_to_silence is None:
        libs_to_silence = [
            'botocore',
            'boto3',
            'urllib',
            'urllib3',
            'azure',
            'uamqp',
            'py4j',
        ]
    for lib in libs_to_silence:
            logging.getLogger(lib).setLevel(logging.ERROR)

    LOGGING_LEVEL = getenv('LOGGING_LEVEL', logging_level)

    # Local execution shows time. Remote executions logging has it's own timestamp adding
    if env_var_hide_timestamp is not None and getenv(env_var_hide_timestamp, None) is not None:
        log_format = '%(levelname)s - %(filename)s[%(lineno)s] %(message)s'
    else:
        log_format = '%(asctime)s - %(levelname)s - %(filename)s[%(lineno)s] %(message)s'

    logger = logging.getLogger()
    for h in logger.handlers:
        logger.removeHandler(h)
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(logging.Formatter(log_format))
    logger.addHandler(handler)
    logger.setLevel(LOGGING_LEVEL)

    return logger