import os
import sys
import argparse
import json
from collections import defaultdict
# pylint: disable=unused-import # tool cant handle urlib import
import urllib.request
from urllib.request import Request, urlopen

import copy
import time
from datetime import datetime
import subprocess
import schedule
from github import Github
from aiohttp.web_routedef import options

###########################################################################################
# Global needed configurations, see example setenv.sh file for settings these
############################################################################################

# Github related settings
TOKENFILE = ""  # "KEEP TOKENFILE PRIVATE, NOT TO BE STORED PUBLIC GIT, used to access Github repo for PR observations
TESTREPO = None  # Repo under PR observations
TESTPR = ""  # f"https://api.github.com/repos/{TESTREPO}/pulls"
ORGANIZATION = None  # required Github organization membership before building PR proceeds
# local file to store handled (built) PRs by their Github ID
BUILDPRSFILE = None
# local file to store builds done for open, allready built, but PR having changes being made
BUILDCHANGEDPRSFILE = None

# CLI command (Ghaf inhouse public tool) to manage Hydra operations
HYDRACTL = None
EXT_PORT = None  # Hybdra port dedicated for this POC build server
SERVER = None  # Hydra build server to be commanded
RUNDELAY = None  # minutes to wait before next execution of this script

__version__ = "0.73300"

# HYDRACTL_USERNAME and HYDRACTL_PASSWORD env variables (Hydra admin account). DO NOT STORE TO PUBLIC GIHUB
# Use for example local .sh file which exports them in shell when sourced

# Global commandline options

DRYRUNMODE = None
VERBOSEMODE = None
SERVICEMODE = None
CHERRYPICKEDPR = None

#########################################################################################################
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
def GetChangePRData(pr, counter, myChangedfile, changetime):
    """
    Check if detected change in PR is a new one or has been allready built
    In case a new one, update database file (also if new change for open PR is detected)
    """

    # myChangedfile = ""
    print("")
    pr = str(counter)
    myChangedfile.seek(0)  # we need to read from start
    print(
        f"----- Changed PR numbers and change times from the DB file:{BUILDCHANGEDPRSFILE} ----------")
    foundnewtime = 0
    PRCount = 0
    FilePRNumbers = []
    ContentOfFilePRNumber = []

    myChangedfile.seek(0)
    for one_line in myChangedfile:
        PRCount = PRCount+1

        if (VERBOSEMODE is not None):
            print(one_line)
        # get runtime copy for possible changes
        ContentOfFilePRNumber.append(one_line)
    PRCount = PRCount-1  # fictional first value
    if (VERBOSEMODE is not None):
        print(
            f"------- Existing PRs with done change builds:{PRCount} ----------------")

    myChangedfile.seek(0)
    for one_line in myChangedfile:
        values = one_line.strip().split(",")
        readPR = values[0]
        readChangetime = values[1:]
        if (readPR == pr):
            FilePRNumbers.append(pr)

            if (changetime in readChangetime):
                print("Changetime found from PR built changes list")
            else:
                print("Found new changed time for this PR")
                foundnewtime = 1

# pylint: disable=no-else-return # returning intentionally
    if (pr in FilePRNumbers and foundnewtime == 0):
        print("No new PRs nor existing PRs with new changes found. No actions needed")
        return "NO"
    elif (pr in FilePRNumbers and foundnewtime > 0):
        print("Existing PRs with new changes found")
        print("Going to update changed PRs file!")
        addline = pr+","+changetime

        for index, item in enumerate(ContentOfFilePRNumber):
            if item.startswith(pr):
                matching_index = index
                print(f"Internal matching_index:{matching_index}")
                break
        if (matching_index is not None):
            ContentOfFilePRNumber[matching_index] = addline
        else:
            print("Internal: Can't change PR change time list")
            return "ERROR"

        myChangedfile = open(BUILDCHANGEDPRSFILE, "w", encoding='utf-8')

        for line in ContentOfFilePRNumber:  # write whole "changed PRs build" file again.
            print(f"Writing line:{line}")
            niceline = line+"\n"

            if (DRYRUNMODE is not None):
                print("!!!Dryrun mode, not going to do actions!!!")
            else:
                myChangedfile.write(niceline)

            myChangedfile = open(BUILDCHANGEDPRSFILE, "a", encoding='utf-8')
        return "YES"

    elif (pr not in FilePRNumbers):
        print(
            f"New PR:{pr}with changes found. Cleaned changetime:{changetime}")
        print("Going to update changed PRs file!")
        addline = pr+","+changetime
        ContentOfFilePRNumber.append(addline)

        myChangedfile = open(BUILDCHANGEDPRSFILE, "w", encoding='utf-8')
        for line in ContentOfFilePRNumber:  # write whole "changed PRs build" file again.
            niceline = line+"\n"
            if (DRYRUNMODE is not None):
                print("!!!Dryrun mode, not going to do actions!!!")
            else:
                myChangedfile.write(niceline)

            myChangedfile = open(BUILDCHANGEDPRSFILE, "a", encoding='utf-8')
        return "YES"

    return "DONE"

#########################################################################################
def CheckChangedPR(pr, repo, counter):
    """
    Check if PR (still open) has been changed since creation time
    """
    print(f"Checking PR:{pr}")
    pr = repo.get_pull(counter)
    CREATED = pr.created_at
    commits = pr.get_commits()
    # Sort the commits by the commit timestamp in descending order
    sorted_commits = sorted(
        commits, key=lambda c: c.commit.committer.date, reverse=True)
    if (VERBOSEMODE is not None):
        print(f"Found commits:{sorted_commits}")
    # Get the timestamp of the most recent commit
    CHANGED = sorted_commits[0].commit.committer.date

    print(f"CREATED:{CREATED}")
    print(f"CHANGED:{CHANGED}")

    time_diff_mins = (CHANGED - CREATED).total_seconds() / 60
    print(f"Time difference in minutes:{time_diff_mins}")

# pylint: disable=no-else-return # returning intentionally
    if (time_diff_mins > 10):
        print("Possible change in open PR detected, may require rebuilding")

        return "YES", CHANGED
    else:
        print("No changes for open PR detected")
        return "NO", ""

#########################################################################################
# pylint: disable=too-many-arguments
def PRBuilding(data, ErroCounter, g, org, counter, myfile, tbd_list, timetoken):
    """
    If PR creator is in defined Github membership, initate Hydra build definition actions
    """

    # parse PR info (from Github JSON)
    SOURCE = "NONE"
    TARGET = "NONE"
    SOURCE_REPO = "NONE"
    ErroCounter = 0
    print("")
    try:
        print(f"==> SOURCE PR BRANCH:{data['head']['ref']}")
        SOURCE = data["head"]["ref"]
    except KeyError:
        print("ERROR: no head ref found")
        ErroCounter = ErroCounter+1

    try:
        print(f"==> TARGET BRANCH (like main/master):{data['base']['ref']}")
        TARGET = data["base"]["ref"]
        if (TARGET == "main"):
            print("==> OK target(main) repo")
        else:
            print("ERROR: source repo is not main")
            ErroCounter = ErroCounter+1
    except KeyError:
        print("no base ref found")
    try:
        print(f"==> SOURCE REPO:{data['head']['repo']['html_url']}")
        SOURCE_REPO = data["head"]["repo"]["html_url"]
    except KeyError:
        print("ERROR:no source repo info found")
        ErroCounter = ErroCounter+1

    USER = data["user"]["login"]
    user = g.get_user(USER)

    if (org.has_in_members(user)):
        print(
            f"---> The user '{USER}' is a member of the organization '{ORGANIZATION}'.")
        if (counter in tbd_list):
            print(f"------> Handling PR number:{counter}")
            if (ErroCounter == 0):

                PRActions(SOURCE, counter, TARGET, myfile,
                          USER, SOURCE_REPO, timetoken)

            else:
                print("Errors in PR data from Github, not doing build activities")
    else:
        print(
            f"The user: {USER} is not a member of the organization {ORGANIZATION}")
        print("No build activities done")
    print("--------------------------------------------------------------------------------------------------")

##########################################################################################
# pylint: disable=too-many-locals
def PRActions(SOURCE, PR, TARGET, myfile, USER, SOURCE_REPO, timetoken):
    """
    Construct Hydra build command from PullRequests data (Using Ghaf inhouse CLI command)
    Record handled PR info to local db file
    """

    OK_CMDEXE_COUNTER = 0
    print("")
    print(
        f"Construct Hydra(for project tiiuae/ghaf) build job set for branch:{SOURCE}")

    if (VERBOSEMODE is not None):
        print(f"--> Target main branch:{TARGET}")
        print(f"--> Source branch:{SOURCE}")
        print(f"--> Source repo:{SOURCE_REPO}")
        print(f"--> PR number:{PR}")
        print(f"--> HYDRACTL command location used:{HYDRACTL}")
        print(f"--> Hydra port:{EXT_PORT}")
        print(f"--> Hydra server:{SERVER}")
        print(f"--> User:{USER}")
        print(f"--> Timetoken:{timetoken}")
        print("")
    DESCRIPTION = "\"PR:"+str(PR)+" User:"+USER + \
        " Repo:"+SOURCE_REPO+" Branch:"+SOURCE+"\""  # kept format intentionally

    if (len(timetoken) == 0):
        PROJECT = f"{USER}X{SOURCE}"
    else:
        PROJECT = f"{USER}X{SOURCE}X{timetoken}"

    # two phased convertings got this item usage working
    PROJECT = PROJECT.encode('ascii', errors='ignore')
    # Then convert it from bytes back to a string using:
    PROJECT = PROJECT.decode()

    FLAKE = "git+"+SOURCE_REPO+"/?ref="+SOURCE  # kept format intentionally
    if (len(timetoken) == 0):
        JOBSET = f"{SOURCE}X{PR}"
    else:
        JOBSET = f"{SOURCE}X{PR}X{timetoken}"

    if (VERBOSEMODE is not None):
        print(f"--> Hydra PROJECT:{PROJECT}")
        print(f"--> Hydra DESCRIPTION:{DESCRIPTION}")
        print(f"--> Hydra FLAKE:{FLAKE}")
        print(f"--> Hydra JOBSET:{JOBSET}")
    APCOMMAND = f"python3 {HYDRACTL} {SERVER}  AP --project {PROJECT} --display {DESCRIPTION}"
    AJCOMMAND = f"python3 {HYDRACTL} {SERVER} AJ --description {DESCRIPTION} --check 300 --type flake --flake {FLAKE} -s enabled --jobset {JOBSET} --project {PROJECT}"
    if (VERBOSEMODE is not None):
        print("")
        print(f"Created Hydra CLI APCOMMAND:{APCOMMAND}")
        print("")
        print(f"Created Hydra CLI AJCOMMAND:{AJCOMMAND}")
    DONE = PR  # write PR number to db file if both CMD exections are ok
    DONE = str(DONE)+"\r\n"  # intentionally kept format

    # NOTE: As executing commands from Python file failed (Hydra jobset creation) and using same commands were ok from shell
    # saving commands to file and executing the content from the read file
    # this is temp solution for this POC only

    cmdfile1 = open("cmdfile1", "w", encoding='utf-8')
    # cmdfile1.seek(0) # only if mode a used
    cmdfile2 = open("cmdfile2", "w", encoding='utf-8')
    # cmdfile2.seek(0)
    FIRSTLINE = "#!/bin/bash"+"\r\n"  # intentionally kept format

    cmdfile1.write(FIRSTLINE)
    cmdfile1.write(APCOMMAND)

    cmdfile2.write(FIRSTLINE)
    cmdfile2.write(AJCOMMAND)

    cmdfile1.close()
    cmdfile2.close()

    cmd1 = open("cmdfile1", "r", encoding='utf-8')
    APline1 = cmd1.read()
    rc, _out, err = ExeCMD(APline1)

    if (rc != 0):
        print(f"Command execution error:{rc}")
        print(f"Error message:{err}")
    else:
        print("OK command execution")
        OK_CMDEXE_COUNTER += 1

    time.sleep(2)
    cmd2 = open("cmdfile2", "r", encoding='utf-8')
    AJline2 = cmd2.read()
    rc, _out, err = ExeCMD(AJline2)
    if (rc != 0):
        print(f"Command execution error:{rc}")
        print(f"Error message:{err}")
    else:
        print("OK command execution")
        OK_CMDEXE_COUNTER += 1

    if (OK_CMDEXE_COUNTER == 2):
        if (len(timetoken) == 0):
            print(
                f"2 correct CMD executions,NEW build, going to record PR:{PR} as done deed")
            if (DRYRUNMODE is not None):
                print("!!!Dryrun mode, not going to do actions!!!")
            else:
                myfile.write(DONE)
        else:
            print(
                f"2 correct CMD executions, CHANGED PR build, going to record PR:{PR} with CHANGE time:{timetoken} to own db file")
    else:
        print("-------------------------------------------------------------------------------")
        print(
            f"ERROR ===> CMD executions errors found, NOT marking PR:{PR} as done")
        print("-------------------------------------------------------------------------------")

    # clean temp commandfiles
    os.remove("./cmdfile1")
    os.remove("./cmdfile2")
    time.sleep(2)

    print("*******************************************************************************************************")

##############################################################
def ExeCMD(commandLine):
    """
    Execute given command string and return system feedback
    """

    print("------------------------------------------------------------------------------------------")
    print(f"Executing command:{commandLine}")
    print("------------------------------------------------------------------------------------------")

# pylint: disable=no-else-return # returning intentionally
    if (DRYRUNMODE is not None):
        print("!!! Dryrun mode, not doing actions !!!")
        return (42, "dryrun mode", "dryrun mode")

    else:
        sp = subprocess.Popen(commandLine,
                              shell=True,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
        rc = sp.wait()
        out, err = sp.communicate()

        return rc, out, err

##########################################################################################
def Finder():
    """
    Check if any new (not built) pull requests exists in defined repo (fro main branch
    """

    print("------------------------------------------------------------------------------------------")

    #########################################################################
    # Authorization to Github
    # Tokenfile used to provide token for observed Github Repo access
    # DO NOT STORE TOKENFILE TO GITHUB, KEEP IT PRIVATE
    #

    file_exists = os.path.exists(TOKENFILE)
    if (file_exists):
        file = open(TOKENFILE, "r", encoding='utf-8')
        config_array = file.read().split()
        githubtoken = str(config_array[0])
    else:
        print(f"No Github tokenfile found, check:{TOKENFILE}")
        githubtoken = None

    g = Github(githubtoken)
    repo = g.get_repo(TESTREPO)
    org = g.get_organization(ORGANIZATION)
    pulls = repo.get_pulls(state='open', sort='created', base='main')

    ##########################################################################
    # Get all open PRs into a dictionary for data processing
    i = 0
    open_prs = defaultdict(lambda: "OFF")
    print(f"------ All open PullRequest for repo: {TESTREPO} -------")
    for pull in pulls:
        print(pull)
        open_prs.update({pull.number: "ON"})
        i = i+1

    if (i == 0):
        print("No open PRs found, exiting")
        sys.exit(4)
    ####################################################################################
    # Read allready built PRs from disk, initialize possible empty bookkeeping files
    #
    done_prs = defaultdict(lambda: "NONE")
    myfile = open(BUILDPRSFILE, "a+", encoding='utf-8')
    myChangedfile = open(BUILDCHANGEDPRSFILE, "a+", encoding='utf-8')

    # add fictional done PR number to an empty file in order to keep logic running
    if (os.stat(BUILDPRSFILE).st_size == 0):
        print("No done PRs found, adding fictional PR number to an empty file")
        FICTIONALPR = 123456789
        FICTIONALPR = str(FICTIONALPR)+"\r\n"
        myfile.seek(0)
        myfile.write(FICTIONALPR)

    # add fictional changed PR number (and timetoken) to an empty file in order to keep logic running
    if (os.stat(BUILDCHANGEDPRSFILE).st_size == 0):
        print("No done PRs file found, adding fictional PR number and change time to an empty file")
        FICTIONALPR = 123456789
        FICTIONALCHANGETIME = "2020-02-02-23-00-00"
        # kept format intentionally
        FICTIONALCHANGEPR = str(FICTIONALPR)+","+FICTIONALCHANGETIME+"\r\n"
        myChangedfile.seek(0)
        myChangedfile.write(FICTIONALCHANGEPR)
    ##########################################################################################################

    # a+ adds fd to end of file, for appends, we need to read from start
    myfile.seek(0)
    print(f"------Built PR numbers from the DB file: {BUILDPRSFILE}------")
    for one_pr_number in myfile:
        if (VERBOSEMODE is not None):
            print(str(one_pr_number), end='')
        done_prs[int(one_pr_number)] = "DONE"

    print("------ Checking which open PRs are new and require building ------")
    # shallow copies are iterared over as defaultdict changes dict size when default value must be returned
    copy_done_prs = copy.copy(done_prs)
    copy_open_prs = copy.copy(open_prs)
    tbd_list = []
    counter = 1
    ###############################################################################
    # Process all repo's open pull requests
    processed_pr = []
    ErroCounter = 0
    for newPr in copy_open_prs:

        url = str(TESTPR)+"/"+str(newPr)  # kept format intentionally
        with urlopen(url) as response:
            body = response.read()
        data = json.loads(body)
        print("###########################################################################################################################")
        print("==> PR:"+url)

        if (CHERRYPICKEDPR is not None):
            if (CHERRYPICKEDPR == newPr):
                print(f"===> To be cherry picked PR found:{newPr}")
            else:
                print(
                    f"Skipping this one, trying to cherry pick PR:{CHERRYPICKEDPR}")
                continue

        print(f"==> CHECKING ---> SOURCE PR BRANCH: {data['head']['ref']}")

        counter = newPr  # not anymore running counter, but the actual open PR numbers
        for _doneline in copy_done_prs:

            # check duplicate PRs in db file
            # pylint: disable=no-else-break # breaking intentionally
            if (counter in processed_pr):
                print(f"Processed PRs:{processed_pr}")
                print(
                    f"---> Duplicate PR found in db file: {counter} skipping to next one!")
                print(
                    "--------------------------------------------------------------------------------------------------")
                break

            elif (open_prs[counter] == "ON" and done_prs[counter] == "DONE"):
                print(f"==> OLD PR in PR list, has been built:{counter}")

                print("Checking if this (still open) PR has been changed")
                pr = repo.get_pull(counter)
                answer, changetime = CheckChangedPR(pr, repo, counter)
                if (answer == "YES"):
                    print(f"PR changed, timetoken in use:{changetime}")

                    processed_pr.append(counter)
                    if (counter not in tbd_list):
                        tbd_list.append(counter)
                    else:
                        print("not adding")

                    # hydra doesnt like spaces in arguments, nor :
                    changeTimeCleaned = str(changetime).replace(" ", "-")
                    changeTimeCleaned = changeTimeCleaned.replace(":", "-")
                    if (VERBOSEMODE is not None):
                        print("Cleaned (book keeping) timetoken:" +
                              changeTimeCleaned)

                    answer = GetChangePRData(
                        pr, counter, myChangedfile, changeTimeCleaned)
                    if (answer == "YES"):
                        # SOURCE=data["head"]["ref"]
                        print(
                            f"==> CHECKING ---> SOURCE PR BRANCH:{data['head']['ref']}")

                        PRBuilding(data, ErroCounter, g, org, counter,
                                   myfile, tbd_list, changeTimeCleaned)
                    else:
                        print("")
                    break

                else:
                    print("No PR changes, no actions needed")
                    processed_pr.append(counter)
                    break
                print(
                    "--------------------------------------------------------------------------------------------------")
            elif (open_prs[counter] == "ON" and done_prs[counter] == "NONE"):
                print(f"==> NEW PR, going to build this:{counter}")
                processed_pr.append(counter)
                if (counter not in tbd_list):
                    tbd_list.append(counter)
                else:
                    print("not adding")

                timetoken = ""
                PRBuilding(data, ErroCounter, g, org, counter,
                           myfile, tbd_list, timetoken)
                break

            elif (open_prs[counter] == "OFF" and done_prs[counter] == "DONE"):
                print(f"==> OLD done PR:{counter}")
                processed_pr.append(counter)
                break

###################################################################################################################################
def GetEnv(variable):
    """
    Check that needed env variables are defined
    """

    definedVariable = os.getenv(variable)
    if (definedVariable is None and DRYRUNMODE is None):
        print(f"No {variable} env variable defined", file=sys.stderr)
        print("Check example setenv.sh file....Exiting now!!")
        sys.exit(3)
    else:

        definedVariable = str(definedVariable)
        if (VERBOSEMODE is not None):
            print(f"Set env variable:{variable} as {definedVariable}")
        else:
            definedVariable = str(definedVariable)
        return definedVariable

###################################################################################################################################
# pylint: disable=unused-argument
def main(argv):
    """ Main. Check parameters
    """

# pylint: disable=global-statement # used intentionally
    global CHERRYPICKEDPR
    global VERBOSEMODE
    global DRYRUNMODE
    global SERVICEMODE
    global TOKENFILE, TESTREPO, ORGANIZATION, BUILDPRSFILE, HYDRACTL, BUILDCHANGEDPRSFILE, EXT_PORT, SERVER, RUNDELAY, TESTPR

    current_time = datetime.now()
    formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
    print("----------------------------------------------------------------------------------------")
    print(f"---------- Execution started:{formatted_time}---------------")
    print("----------------------------------------------------------------------------------------")

    parser = argparse.ArgumentParser(
        description="Github PullRequest Hydra builder activator",

        epilog='''
    "Needs some env variables, see code for comments and setenv.sh as an example setter"
    ''')

    parser.add_argument('-v', help='Check Github open PRs and activate Ghaf Hydra build',
                        action='version', version=f"Version:{__version__}  ")
    parser.add_argument("-d", help='Dry run mode', metavar="dry")
    parser.add_argument('-t', help='Verbose, talking, mode', metavar="verbose")
    parser.add_argument('-s', help='Service mode, runtime delays in secs',
                        metavar="service", type=int, nargs=1)
    parser.add_argument('-p', help='Cherry pick PR number, ignore others',
                        metavar="cherrypick", type=int, nargs=1)

    args = parser.parse_args()

    VERBOSEMODE = args.t or None
    DRYRUNMODE = args.d or None
    SERVICEMODE = args.s or None

    if (args.s):
        SERVICEMODE = args.s[0]
    if (args.p):
        CHERRYPICKEDPR = args.p[0]

    if (VERBOSEMODE is not None):
        print("Verbose mode selected")
    if (DRYRUNMODE is not None):
        print("!!! Dryrun mode selected, no actions taken !!!")
    if (SERVICEMODE):
        print(f"Service mode selected with runtime delay:{SERVICEMODE}")
    if (CHERRYPICKEDPR is not None):
        print(f"Checking only PR:{CHERRYPICKEDPR} skpping other PRs")

    # pylint: disable=unused-variable
    username = GetEnv("HYDRACTL_USERNAME")  # env check only
    # pylint: disable=unused-variable
    passu = GetEnv("HYDRACTL_PASSWORD")  # env check only
    TOKENFILE = GetEnv("TOKENFILE")
    print(f"GOT Tokenfile file:{TOKENFILE}")
    TESTREPO = GetEnv("TESTREPO")
    ORGANIZATION = str(GetEnv("ORGANIZATION"))
    BUILDPRSFILE = GetEnv("BUILDPRSFILE")
    BUILDCHANGEDPRSFILE = GetEnv("BUILDCHANGEDPRSFILE")
    HYDRACTL = GetEnv("HYDRACTL")
    EXT_PORT = GetEnv("EXT_PORT")
    SERVER = f"http://localhost:{EXT_PORT}"
    RUNDELAY = GetEnv("RUNDELAY")
    TESTPR = f"https://api.github.com/repos/{TESTREPO}/pulls"

    print("")
    print(f"TESTPR:{TESTPR}")
    print(f"Tokenfile file:{TOKENFILE}")
    print(f"Build PRs db file:{BUILDPRSFILE}")
    print(f"Build and rebuild PRs due changes db file: {BUILDCHANGEDPRSFILE}")
    print(f"Observing Github repo (main) PRs: {TESTREPO}")
    print(
        f"Organization participation required for PR building:{ORGANIZATION}")
    print(f"Using Hydra build server:{SERVER}")
    print(f"Assuming Hydra CLI command to be:{HYDRACTL}")
    print("Only PRs to main branch are processed")
    print("")

    if (SERVICEMODE):
        print("Service mode starting!")
        schedule.every(RUNDELAY).minutes.do(Finder)
        while True:
            schedule.run_pending()
            time.sleep(SERVICEMODE)
    else:
        print("Running command just once")
        Finder()

#######################################################
# Entry point
if __name__ == "__main__":
    main(sys.argv[1:])


from django.urls import path
from . import views
app_name = 'cat'

urlpatterns = [
    path('genre_list/', views.GenreListView.as_view(), name="genre-list"),
    path('genre/<int:pk>/', views.GenreDetailView.as_view(), name="genre-det"),
    path('genre_add/', views.GenreAddView.as_view(), name="genre-add"),
    path('genre_delete/<int:pk>/', views.GenreDeleteView.as_view(), name="genre-del"),
    path('genre_edit/<int:pk>/', views.GenreUpdateView.as_view(), name="genre-edit"),

    path('series_list/', views.SeriesListView.as_view(), name="series-list"),
    path('series/<int:pk>/', views.SeriesDetailView.as_view(), name="series-det"),
    path('series_add/', views.SeriesAddView.as_view(), name="series-add"),
    path('series_delete/<int:pk>/', views.SeriesDeleteView.as_view(), name="series-del"),
    path('series_edit/<int:pk>/', views.SeriesUpdateView.as_view(), name="series-edit"),

    path('author_list/', views.TheAuthorListView.as_view(), name="author-list"),
    path('author/<int:pk>/', views.TheAuthorDetailView.as_view(), name="author-det"),
    path('author_add/', views.TheAuthorAddView.as_view(), name="author-add"),
    path('author_delete/<int:pk>/', views.TheAuthorDeleteView.as_view(), name="author-del"),
    path('author_edit/<int:pk>/', views.TheAuthorUpdateView.as_view(), name="author-edit"),

    path('publishinghouse_list/', views.PublishingHouseListView.as_view(), name="publishinghouse-list"),
    path('publishinghouse/<int:pk>/', views.PublishingHouseDetailView.as_view(), name="publishinghouse-det"),
    path('publishinghouse_add/', views.PublishingHouseAddView.as_view(), name="publishinghouse-add"),
    path('publishinghouse_delete/<int:pk>/', views.PublishingHouseDeleteView.as_view(), name="publishinghouse-del"),
    path('publishinghouse_edit/<int:pk>/', views.PublishingHouseUpdateView.as_view(), name="publishinghouse-edit"),

    path('status_list/', views.StatusListView.as_view(), name="status-list"),
    path('status/<int:pk>/', views.StatusDetailView.as_view(), name="status-det"),
    path('status_add/', views.StatusAddView.as_view(), name="status-add"),
    path('status_delete/<int:pk>/', views.StatusDeleteView.as_view(), name="status-del"),
    path('status_edit/<int:pk>/', views.StatusUpdateView.as_view(), name="status-edit"),
]


def letterToNumber(char):
    if (char.isupper()):
        return ord(char) - 65
    else:
        return ord(char) - 97

def caesarEncrypt(text, s):
    result = ""

    # traverse text
    for i in range(len(text)):
        char = text[i]

        # Encrypt uppercase characters
        if (char.isupper()):
            result += chr((ord(char) + s - 65) % 26 + 65)

            # Encrypt lowercase characters
        else:
            result += chr((ord(char) + s - 97) % 26 + 97)

    return result

def caesarDecrypt(text, s):
    result = ""
    s = 26 - s

    # traverse text
    for i in range(len(text)):
        char = text[i]

        # Encrypt uppercase characters
        if (char.isupper()):
            result += chr((ord(char) + s - 65) % 26 + 65)

            # Encrypt lowercase characters
        else:
            result += chr((ord(char) + s - 97) % 26 + 97)

    return result

def vigenereEncrypt(plainText, secret):
    result = ""

    for i in range(len(plainText)):
        char = plainText[i]
        result += caesarEncrypt(char, letterToNumber(secret[i % len(secret)]))

    return result

def vigenereDecrypt(plainText, secret):
    result = ""

    for i in range(len(plainText)):
        char = plainText[i]
        result += caesarDecrypt(char, letterToNumber(secret[i % len(secret)]))

    return result

def generateMatrix():
    matrix = []

    number = 97

    for i in range(5):
        line = []
        for j in range(5):
            line.append(chr(number))
            number += 1
        matrix.append(line)

    return matrix

def tranposeMatrix(matrix):
    aux = []

    for j in range(len(matrix[0])):
        line = []
        for i in range(len(matrix)):
            line.append(matrix[i][j])
        aux.append(line)
    return aux

def mostra_matriz(matriz):

    for i in range(len(matriz)):
        for j in range(len(matriz[0])):
            print(matriz[i][j] + '\t', end='')
        print("")
    print('_' * 10)

def polybusDecript(text):
    result = ""
    matrix = tranposeMatrix(generateMatrix())

    for i in range(0, len(text), 2):
        result += matrix[int(text[i]) - 1][int(text[i + 1]) - 1]

    return result

def convertBinToBase4(binaryString):
    result = ""

    for i in range(0, len(binaryString), 3):
        char = binaryString[i:i+3]
        result += str(int(char, 2))

    return result

if __name__ == '__main__':
    blockA = "gluhtlishjrvbadvyyplkaokqvbxjpwolypzavvdlhrvuuleatlzzhnlzdpajoavcpnlulyljpwolyrlfdvykpzaolopkkluzftivsvmklhaoputfmhcvypalovsilpuluk"
    blockB = "vwduwljudeehghyhubwklqjlfrxogilqgsohdvhuhwxuqdqbeoxhsulqwviruydxowdqgdodupghvljqedvhgrqzkifkedqnbrxghflghrqldpvhwwlqjxsvdihkrxvhfr"

    encryptedText = 'klkbnqlcytfysryucocphgbdizzfcmjwkuchzyeswfogmmetwwossdchrzyldsbwnydednzwnefydthtddbojicemlucdygicczhoadrzcylwadsxpilpiecskomoltejtkmqqymehpmmjxyolwpeewjckznpccpsvsxauyodhalmriocwpelwbcniyfxmwjcemcyrazdqlsomdbfljwnbijxpddsyoehxpceswtoxwbleecsaxcnuetzywfn'

    text = "445411345411233353445412424342443251412123113113531554425442444243443251415343543242344111255135533413424322534311445434534322513431421432513412533412155415345133514444112251444254424444153451235515432134511113112123514254315333214243514453153414345125425315443351543253414443513544"

    secret = "SSKKUULLLL"

    print("Bloco A : " + caesarEncrypt(blockA, 19))
    print("Bloco B : " + caesarEncrypt(blockB, 23))

    print("* " * 50)
    print("Dica 02 : " + vigenereDecrypt(encryptedText, secret))

    a = polybusDecript(text)
    print("* " * 50)
    print("Dica 03 : " + a)

    encryptedText = 'klkbnqlcytfysryucocphgbdizzfcmjwkuchzyeswfogmmetwwossdchrzyldsbwnydednzwnefydthtddbojicemlucdygicczhoadrzcylwadsxpilpiecskomoltejtkmqqymehpmmjxyolwpeewjckznpccpsvsxauyodhalmriocwpelwbcniyfxmwjcemcyrazdqlsomdbfljwnbijxpddsyoehxpceswtoxwbleecsaxcnuetzywfn'
    ux = ""

    simbolMessage = "20 33 22 21 00 33 30 01 02 20 22 02 32 20 11 33 03 30 03 32 03 00 22 01 33 23 23 10 03 22 13 13 20 01 11 03 22 20 20 20 22 33 20 13 23 13 33 22 30 33 01 20 21 10 12 11 00 32 23 13 22 02 00 10 31 02 33 20 31 03 12 01 11 33 32 23 02 01 00 32 10 10 30 01 10 23 31 10 02 00 30 23 31 10 03 03 01 02 33 02 23 21 30 12 03 12 22 00 03 13 31 00 10 11 21 03 23 02 20 13 02 32 30 31 23 33 20 02 12 33 30 00 30 12 30 13 03 01 03 03 23 22 02 30 20 03 22 23 32 23 02 02 31 20 23 13 30 02"

    simbolMessage = simbolMessage.replace(" ", "")

    key = ""

    for i in range(len(ux)):
        char = ux[i]
        if ord(char) == 97 or ord(char) == 101 or ord(char) == 105 or ord(char) == 111 or ord(char) == 117:
            key += "1"
        else:
            key += "0"

    print(simbolMessage)

    simbolBinary = ""
    for bit in range(len(simbolMessage)):
        bin = ""
        if simbolMessage[bit] == '0':
            bin = "00"
        if simbolMessage[bit] == '1':
            bin = "01"
        if simbolMessage[bit] == '2':
            bin = "10"
        if simbolMessage[bit] == '3':
            bin = "11"

        simbolBinary += bin

    print(simbolBinary)

    simbolBase4 = convertBinToBase4(simbolBinary)
    print()
    print(simbolBase4)


'''
乱序字符串是指一个字符串只是另一字符串的重新排列
前提：字符串是由26个小写字母集合组成，长度相同
比如：python    typhon    head    deah
目的：
    写一个布尔函数（返回值是布尔值的函数）
    solutionsl('abcd','dbca)

'''
#1，穷举法：排除   原因：如果字符串过长，所写的for循环要写很多

#2，检查 第一个字符串是不是出现在第二个字符串中  o(n^2)

# def soultions(s1,s2):
#     alist = list(s2)

#     pos1 = 0
#     flag = True

#     while flag and pos1 < len(s1):
#         pos2 = 0
#         found = False
#         while pos2 < len(s2) and not found:
#             if s1[pos1] == alist[pos2]:
#                 pass
#             else:
#                 pos2 = pos2 + 1

#         if found:
#             alist[pos2] = None

#             pos1 = pos1 + 1
#         else:
#             flag = False

#     return flag

# print(soultions('abcd','dbca'))

#3,计数和比较法         aaaabbbbcccc     ccccaaaabbbb
#计算每个字符出现的次数，

# def solutions2(s1,s2):
#     c1 = [0] * 26 #记录s1中字母出现的次数 [4,4,4,0,0,0,0,0,0,0,0,0,,,,]
#     c2 = [0] * 26 #记录s2中字母出现的次数 [4,4,4,0,0,0,0,0,0,0,0,0,,,,]

#     #ord()    返回的是字符在阿斯克码中的数字

#     for i in range(len(s1)):
#         pos = ord(s1(i)) - ord('a')
#         c1[pos] = c1[pos] + 1

#     for i in range(len(s2)):
#         pos = ord(s1(i)) - ord('a')
#         c2[pos] = c2[pos] + 1

#     count = 0  #字符出现的次数,如果某个字符出现在s1和s2中出现的次数相同那么，content就+1

#     flag = True
#     while count < 26 and flag:
#         if c1[count] == c2[count]:
#             count = count + 1
#         else:
#             flag = False

#     return flag

# print(solutions2('aaaabbbbcccc','ccccbbbbaaaa'))

# 4，通过排序和比较   :即使s1,s2不同  他们都是由完全相同的字符组成的。
#我们可以从a-z  排列每一个字符串，如果两个字符串相同，那么这两个字符串就是乱序字符串
#aaaabbbbcccc     bbbbaaaacccc
#算法复杂度：不是o(n) 是o(n^2)

def solutions3(s1,s2):
    alist1 = list(s1)
    alist2 = list(s2)

    #排序   o(n^2)
    alist1.sort()
    alist2.sort()

    pos = 0

    flag = True
    while pos < len(s1) and flag:

        if alist1[pos] == alist2[pos]:
            pos = pos + 1
        else:
            flag = False

    return flag

print(solutions3('aaaabbbbcccc','bbbbccccaaaa'))
print(solutions3('python','ythpna'))


class Banco:
    def __init__(self):
        self.contas = {}

    def adicionar(self, conta):
        self.contas[conta.nome] = conta

    def remover(self, nome):
        if nome in self.contas:
            del self.contas[nome]
        else:
            print("Conta nao encontrada")

    def alterar(self, nome):
        if nome in self.contas:
            conta = self.contas[nome]
            while True:
                print(" 1 alterar nome")
                print(" 2 alterar email")
                print(" 3 alterar numero")
                print(" 4 voltar")

                opcao = int(input("escolha a opcao: "))
                if opcao == 1:
                    conta.nome = input("Digite o seu nome: ")
                elif opcao == 2:
                    conta.email = input("Digite seu email: ")
                elif opcao == 3:
                    conta.numero = int(input("Digite um numero "))
                elif opcao == 4:
                    break
                else:
                    print("opcao invalida")
        else:
            print("Conta nao encontrada")

    def buscar(self, nome):
        if nome in self.contas:
            conta = self.contas[nome]
            print(f"Nome: {conta.nome}")
            print(f"Email: {conta.email}")
            print(f"Numero: {conta.numero}")
        else:
            print("Conta nao encontrada")

    def listar(self):
        for nome, conta in self.contas.items():
            print(f"Nome: {conta.nome}")
            print(f"Email: {conta.email}")
            print(f"Numero: {conta.numero}")

class Conta:
    def __init__(self):
        self.nome = ""
        self.agencia = ""
        self.saldo = 0
        self.numero = 0

    def depositar(self, valor):
        self.saldo += valor

    def sacar(self, valor):
        if self.saldo >= valor:
            self.saldo -= valor
        else:
            print("Saldo insuficiente")

    def transferir(self, valor, conta):
        if self.saldo >= valor:
            self.saldo -= valor
            conta.saldo += valor
        else:
            print("Saldo insuficiente")

    def extrato(self):
        print(f"Saldo: {self.saldo}")

def main():
    banco = Banco()
    while True:
        print(" 1 adicionar contato")
        print(" 2 remover contato")
        print(" 3 alterar contato")
        print(" 4 buscar contato")
        print(" 5 listar contatos")
        print(" 6 sair")
        opcao = int(input("escolha a opcao: "))
        if opcao == 1:
            conta = Conta()
            conta.nome = input("Digite o seu nome: ")
            conta.email = input("Digite seu email: ")
            conta.numero = int(input("Digite um numero "))
            banco.adicionar(conta)
        elif opcao == 2:
            nomepararemocao = input("Digite o nome do contato que voce quer remover: ")
            banco.remover(nomepararemocao)
        elif opcao == 3:
            nomeparaalterar = input("Qual contato voce quer alterar: ")
            banco.alterar(nomeparaalterar)
        elif opcao == 4:
            nomeparabuscar = input("Digite o nome do contato que voce quer buscar: ")
            banco.buscar(nomeparabuscar)
        elif opcao == 5:
            banco.listar()
        elif opcao == 6:
            break
        else:
            print("opcao invalida")

if __name__ == "__main__":
    main()


#!/usr/bin/env python3

import altair as alt
import pandas  # http://pandas.pydata.org
import numpy
import datetime

from fileops import save, getChartHTML
from filters import *
from logic import *

name = "graphblast-pull-pr-200901"
# begin user settings for this script
roots = ["../gunrock-output/v1-0-0", "../gunrock-output/v0-5-1/cc"]
fnFilterInputFiles = [
    fileEndsWithJSON,
    fileNotInArchiveDir,
]

fnPreprocessDF = [
    mergeAlgorithmIntoPrimitive,
    lowercasePrimitives,
    mergeMTEPSToAvgMTEPS,
    lambda df: merge(df, dst="num-vertices", src="num_vertices", delete=True),
    lambda df: merge(df, dst="num-edges", src="num_edges", delete=True),
    mergeElapsedIntoAvgProcessTime,
    mergeGunrockVersionWithUnderscoreIntoHyphen,
    normalizePRByIterations,
    renameColumnsWithMinus,
    equateNVIDIAGPUs,
]
fnFilterDFRows = [
    undirectedOnly,
    selectAnyOfThese("primitive", ["pr", "bfs", "sssp", "tc", "cc"]),
    selectAnyOfThese("gpuinfo_name", ["TITAN V", "Tesla K40/80"]),
    # get rid of PR push
    lambda df: df[(df["primitive"] != "pr") | (df["pull"] == True)],
    # soc-ork soc-lj h09 i04 rmat-22 rmat-23 rmat-24 rgg road_usa
    selectAnyOfThese(
        "dataset",
        [
            "cit-Patents",
            "coAuthorsCiteseer",
            "coPapersDBLP",
            "com-orkut",
            "hollywood-2009",
            "indochina-2004",
            "rgg_n_2_24_s0",
            "rmat_n22_e64.000000",
            "rmat_n23_e32.000000",
            "rmat_n24_e16.000000",
            "road_central",
            "road_usa",
            "soc-LiveJournal1",
            "soc-orkut",
        ],
    ),
    keepFastestAvgProcessTime(
        [
            "primitive",
            "dataset",
            "undirected",
            "gpuinfo_name",
        ],
        sortBy="avg_process_time",
    ),
]
fnPostprocessDF = [
    addJSONDetailsLink,
    gunrockVersionGPU,
]
# end user settings for this script

# actual program logic
# do not modify

# choose input files
df = filesToDF(roots=roots, fnFilterInputFiles=fnFilterInputFiles)
for fn in fnPreprocessDF:  # alter entries / compute new entries
    df = fn(df)
for fn in fnFilterDFRows:  # remove rows
    df = fn(df)
for fn in fnPostprocessDF:  # alter entries / compute new entries
    df = fn(df)

# end actual program logic

columnsOfInterest = [
    "primitive",
    "dataset",
    "avg_mteps",
    "avg_process_time",
    "engine",
    "gunrock_version",
    "gpuinfo_name",
    "pull",
    "num_vertices",
    "num_edges",
    "undirected",
    "time",
    "details",
]
# would prefer a cleanup call https://github.com/altair-viz/altair/issues/183
# without this, output is gigantic
df = (keepTheseColumnsOnly(columnsOfInterest))(df)

c = alt.Chart(df)
plotname = name

save(
    chart=c,
    df=df,
    plotname=plotname,
    formats=[
        "tablehtml",
        "tablemd",
    ],
    sortby=[
        "primitive",
        "dataset",
        "gpuinfo_name",
        "undirected",
        "gunrock_version",
    ],
    columns=columnsOfInterest,
)

columnsOfInterest = [
    "primitive",
    "dataset",
    "avg_process_time",
    "gpuinfo_name",
    "undirected",
    "details",
]

df = (keepTheseColumnsOnly(columnsOfInterest))(df)

df = df[df["undirected"] == True]

save(
    chart=c,
    df=df,
    plotname=plotname + "_abbrev",
    formats=[
        "tablehtml",
        "tablemd",
    ],
    sortby=[
        "primitive",
        "dataset",
        "gpuinfo_name",
    ],
    columns=columnsOfInterest,
)

# pandoc -i graphblast-pull-pr-200901_table.html -t gfm -o graphblast-pull-pr-200901_table.md


# -*- coding: utf-8 -*-
codigo1, numPeca1, valorPeca1 = input().split()
codigo2, numPeca2, valorPeca2 = input().split()
c1 = int(codigo1)
c2 = int(codigo2)
n1 = int(numPeca1)
n2 = int(numPeca2)
valor1 = float(valorPeca1)
valor2 = float(valorPeca2)
valorTotal = (n1 * valor1) + (n2 * valor2)
print('VALOR A PAGAR: R$ {:.2f}'.format(valorTotal))


from tkinter import *

def run():
    name_1 = name_storage.get()
    print(name_1)
    new_text = Label(text=name_1, fg="black", bg="white")
    new_text.place(x=50, y=100)
    name.delete(0, END)

screen = Tk()
screen.title("My first graphics")
screen.geometry("500x500")

welcome_text = Label(text="Hello world", fg="green", bg="blue")
welcome_text.pack()

click_me = Button(text="Click me", fg="black", bg="white", command=run)
click_me.place(x=50, y=80)

name_storage = StringVar()
name = Entry(textvariable=name_storage)
name.place(x=125, y=30)

screen.mainloop()


import cv2
import numpy as np
import imutils
import time
import cv2

prototxt = "MobileNetSSD_deploy.prototxt.txt"
model = "MobileNetSSD_deploy.caffemodel"
confThresh = 0.2

CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair",
           "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor", "mobilephone"]
COLORS = np.random.uniform(0,255,size=(len(CLASSES), 3))

print("Loading Model...")
net = cv2.dnn.readNetFromCaffe(prototxt,model)
print("Model Loaded...")
print("Starting Camera Feed...")

cam = cv2.VideoCapture(0)
time.sleep(2.0)

while True:
    _,img = cam.read()
    img = imutils.resize(img,width = 500)

    (h,w) = img.shape[:2]
    imResizeBlob = cv2.resize(img,(300,300))
    blob = cv2.dnn.blobFromImage(imResizeBlob, 0.007843, (300,300), 127.5)

    net.setInput(blob)
    detections = net.forward()
    detShape = detections.shape[2]
    for i in np.arange(0,detShape):
        confidence = detections[0, 0, i, 2]
        if confidence > confThresh:
            idx = int(detections[0, 0, i, 1])
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            label = "{}: {:.2f}%".format(CLASSES[idx], confidence*100)
            cv2.rectangle(img, (startX,startY), (endX, endY), COLORS[idx], 2)
            if startY - 15 > 15:
                y = startY - 15
            else:
                startY + 15
            cv2.putText(img, label, (startX, y),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.7, COLORS[idx], 2)

            if CLASSES[idx] == "bottle":
                cv2.putText(img, "I need Water", (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2)

    cv2.imshow("Frame", img)
    key = cv2.waitKey(1)
    if key == ord("w"):
        break

cam.release()
cv2.destroyAllWindows()

Real Time Object Detection using PreTrained Model/Assignment.py


import pandas as pd
import numpy as np
from keras.layers import LSTM, Dense
from keras.models import Sequential

# Load the dataset
df = pd.read_csv("data/tour/E0.csv")

# Create new columns for the points
df["HomePoints"] = 0
df["AwayPoints"] = 0
# Home team goals
df["HomeTeamGoals"] = 0
# Away team goals
df["AwayTeamGoals"] = 0

# Create a dict to store the accumulated points
points = {}

# Iterate over the rows of the dataset
for index, row in df.iterrows():
    # Check the result of the match
    if row["FTHG"] > row["FTAG"]:
        # Home team wins
        points[row["HomeTeam"]] = points.get(row["HomeTeam"], 0) + 3
    elif row["FTHG"] == row["FTAG"]:
        # Draw
        points[row["HomeTeam"]] = points.get(row["HomeTeam"], 0) + 1
        points[row["AwayTeam"]] = points.get(row["AwayTeam"], 0) + 1
    else:
        # Away team wins
        points[row["AwayTeam"]] = points.get(row["AwayTeam"], 0) + 3
    df.at[index, "HomePoints"] = points.get(row["HomeTeam"], 0)
    df.at[index, "AwayPoints"] = points.get(row["AwayTeam"], 0)

# Drop all the columns except FTHG, FTAG, HomePoints, AwayPoints, Tour
df = df[["Date", "HomeTeam", "AwayTeam", "FTHG", "FTAG", "HomePoints", "AwayPoints"]]

# Save the dataset
df.to_csv("data/tour/E0_1.csv", index=False)

# Transorm Date to_datetime
df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')

# Sort by Date
df = df.sort_values(by=['Date'])

# Drop the unnecessary columns
df = df.drop(["FTHG", "FTAG"], axis=1)

# Create a new dataset with points for each team
df_points = pd.DataFrame(columns=["Date", "Team", "Points"])

# Iterate over the rows of the dataset
for index, row in df.iterrows():
    # Create a new row for the home team
    df_points = df_points.append({
        "Date": row["Date"],
        "Team": row["HomeTeam"],
        "Points": row["HomePoints"]
    }, ignore_index=True)
    # Create a new row for the away team
    df_points = df_points.append({
        "Date": row["Date"],
        "Team": row["AwayTeam"],
        "Points": row["AwayPoints"]
    }, ignore_index=True)

# Group by Date and Team
df_points = df_points.groupby(["Team","Date"]).sum().reset_index()

df = df_points

data = df[['Points']].values

# create a function to split the data into input and output sequences
def split_sequence(sequence, n_steps):
    X, y = list(), list()
    for i in range(len(sequence)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the sequence
        if end_ix > len(sequence)-1:
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
        X.append(seq_x)
        y.append(seq_y)
    return np.array(X), np.array(y)

# choose number of previous values to use as input
n_steps = 5

# split the data into input and output sequences
X, y = split_sequence(data, n_steps)

# reshape the input data
n_features = 1
X = X.reshape((X.shape[0], X.shape[1], n_features))

# define the LSTM model
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(n_steps, n_features)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')

# fit the model to the data
model.fit(X, y, epochs=200, verbose=1)

# make predictions
x_input = data[-n_steps:]
x_input = x_input.reshape((1, n_steps, n_features))

print(x_input)
yhat = model.predict(x_input, verbose=1)

# print the prediction
print(yhat)


numbers = [2,3,4,5,6]

def cube_number(number):
    new_number_cubed = number*number*number
    return new_number_cubed

#normal function in map()
cubed_list = list(map(cube_number, numbers))
print(f"Using normal function {cubed_list}")

#Use of Lambda function in map()
lambda_square_numbers = list(map(lambda x: x**2, numbers))
print(f"Using lambda function {lambda_square_numbers}")


def addname():
	print("1.add at the end")
	print("2.add at given position")
	ch=int(input("Enter choice"))
	if ch==1:
		nm=input("enter name")
		lst.append(nm)
	else:
		pos=int(input("enter the position"))
		nm=input("enter name")
		lst.insert(pos,nm)
		print ("display sucessfully at",pos,"position")
def namecountoccurance():
	nm=input("enter name")
	c=lst.count(nm)
	if c==0:
		print("name does not exist")
	else:
		print(nm,"occurs",c,"times")

def deletebyname(nm):
	if nm in lst:
		lst.remove(nm)
		print(nm,"removed sucessfully")
	else:
		print("name found")
def deletebyposition():
	print("1.delete from end")
	print("2.delete from given position")
	ch=int(input("enter choice"))
	if ch==1:
		name=lst.pop()
		print(name,"deleted sucessfully")
	else:
		pos=int(input("enter position"))
		if pos < len(lst):
			lst.pop(pos)
		else:
			print("position",pos,"out of bound")

def ifexist():

	name=input("enter the name to search")
	if name in lst:
		print("name exist")
	else:
		print("name not found")

lst=[]
choice=0;
while choice!=6:
	print("1.add new user")
	print("2.accept a name and count occurance ")
	print("3.delete a name")
	print("4.delete from given position")
	print("5.check weather name exist")
	print("6.display all")
	print("7.exit")
	choice=int(input("Enter choice"))
	if choice==1:
		addname()
	elif choice==2:
 		passnamecountoccurance()
	elif choice==3:
		nm=input("enter name")
		deletebyname(nm)
	elif choice==4:
		deletebyposition()
	elif choice==5:
       		ifexist()
	elif choice==6:
        	print (lst)
	else:
		exit (0)


'''
个人中心->上传头像
'''
import  requests
#  上传一个图片文件
url = "http://www.httpbin.org/post"
file_path = r"C:\Users\DELL\Desktop\人脸识别的测试用例.png"
# with open(file_path,mode='rb') as f:
#     # 二元组：'name':file-tuple,  file-tuple为('filename', fileobj)
#     file = {"人脸识别的测试用例.png":(file_path,f)}
#     # 三元组 'name':file-tuple,  file-tuple为('filename', fileobj,'content_type')
#     # content_type是MIME类型
#     # file = {"人脸识别的测试用例.png": (file_path, f,'image/png')}
#     r = requests.post(url,files = file)
#     print(r.text)
#  上传多个文件
# url = "http://www.httpbin.org/post"
# file_path1 = r"C:\Users\DELL\Desktop\人脸识别的测试用例.png"
# file_path2 = r"C:\Users\DELL\Desktop\ttt.txt"
# with open(file_path1,mode='rb') as f1:
#     with open(file_path2, mode='r',encoding='UTF-8') as f2:
#         files = {"人脸识别的测试用例.png":(file_path1,f1,"image/png"),
#                  "ttt.txt":(file_path2,f2,"text/plain")}
#         r = requests.post(url, files=files)
#         print(r.text)

#  使用data参数上传文件，一次只能传一个文件
with open(file_path,mode='rb') as f:
    r = requests.post(url,data = f)
    print(r.text)


r"""
Compare outputs of different implementations of the interface.

See test_all_extended_properties.py for more information
about the scenario being tested.

"""
from __future__ import division, print_function, absolute_import

import time

import numpy as np
from numpy.testing import assert_allclose, assert_equal

from jsonctmctree import impl_naive, impl_v2
from jsonctmctree.common_unpacking_ex import gen_valid_extended_properties

#TODO share this across test files, in particular test_all_extended_properties
def _get_scene():
    a = 0.2
    b = 0.3
    x = 0.4
    return dict(
            node_count = 5,
            process_count = 2,
            state_space_shape = [2, 2],
            tree = dict(
                row_nodes = [0, 0, 2, 2],
                column_nodes = [1, 2, 3, 4],
                edge_rate_scaling_factors = [1.0, 2.0, 3.0, 4.0],
                edge_processes = [0, 1, 1, 2],
                ),
            root_prior = dict(
                states = [[0, 0], [0, 1], [1, 0]],
                probabilities = [0.25, 0.25, 0.5],
                ),
            process_definitions = [
                dict(
                    row_states = [
                        [0, 0], [0, 0], [0, 1], [0, 1],
                        [1, 0], [1, 0], [1, 1], [1, 1]],
                    column_states = [
                        [0, 1], [1, 0], [0, 0], [1, 1],
                        [0, 0], [1, 1], [0, 1], [1, 0]],
                    transition_rates = [a, a, a, b, b, a, b, b],
                    ),
                dict(
                    row_states = [
                        [0, 0], [0, 0], [0, 1], [0, 1],
                        [1, 0], [1, 0], [1, 1], [1, 1]],
                    column_states = [
                        [0, 1], [1, 0], [0, 0], [1, 1],
                        [0, 0], [1, 1], [0, 1], [1, 0]],
                    transition_rates = [a, a, a+x, b+x, b+x, a+x, b, b],
                    ),
                dict(
                    row_states = [[0, 0], [0, 1], [1, 1], [1, 0]],
                    column_states = [[0, 1], [1, 1], [1, 0], [0, 0]],
                    transition_rates = [1, 1, 1, 1],
                    ),
                ],
            observed_data = dict(
                nodes = [1, 1, 3, 3, 2, 4],
                variables = [0, 1, 0, 1, 1, 1],
                iid_observations = [
                    [0, 0, 0, 0, 0, 0],
                    [1, 1, 1, 1, 1, 1],
                    [0, 1, 0, 1, 0, 1],
                    [1, 1, 0, 0, 1, 1],
                    [1, 1, 1, 0, 0, 0],
                    ],
                ),
            )

def test_all_properties():

    # Initialize the scene dictionary.
    scene_dict = _get_scene()

    # hard-code all reductions
    observation_reduction = dict(
            observation_indices=[0, 1, 2, 4, 3, 2],
            weights=[0.1, 0.1, 0.2, 0.3, 0.5, 0.8])
    edge_reduction = dict(
            edges=[0, 3, 2],
            weights=[0.4, 0.5, 2.0])
    state_reduction = dict(
            states=[[0, 0], [0, 1], [1, 0]],
            weights=[3, 3, 3])
    transition_reduction = dict(
        row_states = [[0, 0], [0, 1], [1, 0]],
        column_states = [[1, 1], [1, 1], [0, 1]],
        weights = [1, 2, 3])

    # test every extended property
    elapsed_naive = 0
    elapsed_v2 = 0
    for extended_property in gen_valid_extended_properties():

        # Interpret the extended property.
        prefix = extended_property[:3]
        core_property = extended_property[-4:]
        observation_code, edge_code, state_code = prefix

        # Define the keyword arguments according to the extended property.
        # The 'tran' core property will always include
        # the 'transition_reduction' keyword argument.
        kwargs = dict()
        reductions = (observation_reduction, edge_reduction, state_reduction)
        names = ('observation_reduction', 'edge_reduction', 'state_reduction')
        codes = (observation_code, edge_code, state_code)
        for code, name, reduction in zip(codes, names, reductions):
            if code == 'w':
                kwargs[name] = reduction
        if core_property == 'tran':
            kwargs['transition_reduction'] = transition_reduction

        # Define the single request.
        request_dict = dict(property=extended_property)
        request_dict.update(kwargs)

        # Define the input structure including the scene and the single request.
        j_in = dict(
                scene=scene_dict,
                requests=[request_dict])

        # Compute outputs using the naive implementation.
        tm = time.time()
        j_out_naive = impl_naive.process_json_in(j_in)
        elapsed_naive += (time.time() - tm)

        # Compute outputs using the less naive implementation.
        tm = time.time()
        j_out_v2 = impl_v2.process_json_in(j_in)
        elapsed_v2 += (time.time() - tm)

        # Check some basic properties of the outputs.
        for j_out in j_out_naive, j_out_v2:
            assert_equal(set(j_out), {'status', 'responses'})
            assert_equal(j_out['status'], 'feasible')
            assert_equal(len(j_out['responses']), 1)

        # Compare the outputs for near equality.
        response_pairs = zip(j_out_naive['responses'], j_out_v2['responses'])
        for (response_naive, response_v2) in response_pairs:
            assert_allclose(response_naive, response_v2)


from __future__ import annotations

from typing import TYPE_CHECKING

from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render, redirect
from django.views.decorators.http import require_http_methods

from core.models import User
from core.business_logic.services import subscribe_and_unsubscribe
from core.business_logic.dto import SubscriberDTO

if TYPE_CHECKING:
    from django.http import HttpRequest

@require_http_methods(request_method_list=["GET","POST"])
def subscriber_controller(request: HttpRequest, username: str) -> HttpResponse:
    user = get_object_or_404(User, username=username)
    subscriber_user = request.user
    if request.method == "POST":
        data = SubscriberDTO(username=user.username, subscriber_username=subscriber_user.username)
        subscribe_and_unsubscribe(data=data)
    current_page = request.META.get('HTTP_REFERER')
    return redirect(current_page)

@require_http_methods(request_method_list=["GET"])
def followings_controller(request: HttpRequest, username: str) -> HttpResponse:
    user = get_object_or_404(User, username=username)
    following_users = user.subscriptions.all()

    context = {
        "user": user,
        "following_users": following_users,
    }

    return render(request=request, template_name='followings.html', context=context)

@require_http_methods(request_method_list=["GET"])
def followers_controller(request: HttpRequest, username: str) -> HttpResponse:
    user = get_object_or_404(User, username=username)
    followers = user.subscriber.all()

    context = {
        "user": user,
        "followers": followers,
    }

    return render(request=request, template_name='followers.html', context=context)


#!/usr/bin/env python3
import re

INPUT_FILE = 'input_p1.txt'

def main():
    # Read in IPs
    with open(INPUT_FILE, 'r') as f:
        ips = [l.rstrip() for l in f]

    # Regex for hypernet sequences
    hypernet_re = re.compile(r'\[(.+?)\]')

    tls_ips = list()
    for ip in ips:
        # Extract hypernet
        if any(abba_search(a) for a in hypernet_re.findall(ip)):
            continue

        # Extract non-hypernet
        if any(abba_search(s) for s in hypernet_re.sub(' ', ip).split()):
            tls_ips.append(ip)

    # Print number of tls ips
    print(len(tls_ips))

def abba_search(string):
    for i in range(len(string)-3):
        # Both characters can't be the same
        if string[i] == string[i+2]:
            continue

        # If we find any abba return True else at the end return False
        if string[i:i+2] == string[i+2:i+4][::-1]:
            return True
    return False

if __name__ == '__main__':
    main()


#!/usr/bin/python3
""" """
import requests
from sys import argv

if __name__ == "__main__":
    try:
        resps = requests.get(argv[1])
        resps.raise_for_status()
        print(resps.text)
    except:
        print("Error code: {}".format(resps.status_code))


#!/usr/bin/python3
# module with method that cleans specified number of archives

from fabric.api import *

env.user = 'ubuntu'
env.hosts = ['35.231.100.106', '35.237.151.115']

def do_clean(number=0):
    """ deletes out of date archives """
    number = int(number)
    with lcd('versions'):
        if number == 0 or number == 1:
            local('ls -tr | head -n -1 | xargs rm -rfv')
        else:
            local('ls -tr | head -n -{} | xargs rm -rfv'.format(number))
    with cd('/data/web_static/releases'):
        if number == 0 or number == 1:
            run('ls -tr | head -n - 1 | xargs rm -rfv')
        else:
            run('ls -tr | head -n -{} | xargs rm -rfv'.format(number))


from dataclasses import dataclass

import pytest

from anaximander.descriptors.attributes import Attribute

def test_attribute():
    x = Attribute("x", retriever=lambda s: getattr(s, "_x"))
    y = Attribute("y", retriever=lambda s: getattr(s, "_y"), transformer=round)

    # Test on simple class

    class C:
        _x: float = 0.99
        _y: float = 0.99

    setattr(C, "x", x)
    setattr(C, "y", y)

    assert isinstance(C.x, Attribute)
    c = C()
    assert c.x == 0.99
    assert c.y == 1

    with pytest.raises(AttributeError):
        c.x = 1

    # Test with metaclass

    class Meta(type):
        _x: float = 0.01
        _y: float = 0.01

    setattr(Meta, "x", x)
    setattr(Meta, "y", y)

    @dataclass
    class C(metaclass=Meta):
        _x: float
        _y: float = 0.99

    assert C.x == 0.01
    assert C.y == 1

    # This doesn't raise because the supplied values are attributes
    setattr(C, "x", x)
    setattr(C, "y", y)

    # However the return values remain the same, driven by the metaclass

    assert C.x == 0.01
    assert C.y == 1

    c = C(1)
    assert c.x == 1
    assert c.y == 1

    c._y = 1.99
    assert C.y == 1
    assert c.y == 2


from rimu import document, options
from rimu.options import RenderOptions
from typing import Optional

def render(source: str, opts: Optional[RenderOptions] = None) -> str:
    '''Exported render() API.'''
    if opts is None:
        opts = RenderOptions()
    # Implicit first-call API initialisation.
    if options.safeMode == -1:
        document.init()
    options.updateFrom(opts)
    return document.render(source)


import logging

from django.urls import reverse
from django.utils.text import slugify
from core.settings.contrib import STOP_WORDS

from django.db import models
from django.utils.translation import ugettext_lazy as _
from changes.models.entry import Entry

logger = logging.getLogger(__name__)

# noinspection PyUnresolvedReferences
class Category(models.Model):
    """A category model e.g. gui, backend, web site etc."""
    name = models.CharField(
        help_text=_('Name of this category.'),
        max_length=255,
        null=False,
        blank=False,
        unique=False)  # there is a unique together rule in meta class below

    sort_number = models.SmallIntegerField(
        help_text=(
            'The order in which this category is listed within a '
            'project'),
        default=0
    )
    slug = models.SlugField()
    project = models.ForeignKey('base.Project', on_delete=models.CASCADE)
    objects = models.Manager()

    # noinspection PyClassicStyleClass
    class Meta:
        """Meta options for the category class."""
        unique_together = (
            ('name', 'project'),
            ('project', 'slug')
        )
        app_label = 'changes'
        ordering = ['name']

    def save(self, *args, **kwargs):
        if not self.pk:
            words = self.name.split()
            filtered_words = [t for t in words if t.lower() not in STOP_WORDS]
            new_list = ' '.join(filtered_words)
            self.slug = slugify(new_list)[:50]
        super(Category, self).save(*args, **kwargs)

    def __unicode__(self):
        return u'%s : %s' % (self.project.name, self.name)

    def __str__(self):
        return '%s : %s' % (self.project.name, self.name)

    def get_absolute_url(self):
        return reverse('category-detail', kwargs={
            'slug': self.slug,
            'project_slug': self.project.slug
        })

    def has_entries(self):
        """Does this Category have related Entries?

        :return: True or False
        :rtype: bool
        """
        if Entry.objects.filter(category=self).exists():
            return True
        else:
            return False


#!/usr/bin/python
#
# lhm0101.py : log_hander_module for python
# -----------------------------------------
#
### Libraries #################################################################
#
import sys
import io
import os
import socket
import subprocess
import shlex
import pwd
#
from datetime  import datetime
from time      import time, sleep, gmtime, strftime
from threading import Thread
#
### Variables #################################################################
#
#
### Functions #################################################################
#------------------------------------------------------------------------------
#
# sub : print_log_header
#
def print_log_header(wrklog, appl_name):
#    sys_name         =  socket.getfqdn()	# <-very slow!
    currentFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name
#
    sys_name         =  socket.gethostname()
    pgm_name         =  os.path.basename(sys.argv[0])
    curfunc          =  currentFuncName(1)		#(current function caller is currentFuncName(1))
    pid              =  os.getpid()
    uid              =  os.getuid()
    user_name        =  pwd.getpwuid(uid)[0]
    pgm_pwd          =  os.getcwd()

    current_datetime = datetime.now()
    line_dashes  =  "--------------------------------------------------------------------------------\n"
    line_titel   =  "\nSYSTEM - PROGRAMM - FILE INFORMATION \n------------------------------------ \n\n"
    line_pgminfo1 =  "Program call ..................: " + pgm_name + "\n"
    line_pgminfo2 =  "Start-Date and Time ...........: " + str(current_datetime) + "\n\n"
    line_pgminfo3 =  "System name ...................: " + sys_name + "\n"
    line_pgminfo4 =  "Process ID ....................: " + str(pid) + "\n"
    line_pgminfo5 =  "User name .....................: " + user_name + "\n"
    line_pgminfo6 =  "Working Directory .............: " + pgm_pwd + "\n"
    line_pgminfo7 =  "Application Name ..............: " + appl_name + "\n"
    line_pgminfo8 =  "Program Name...................: " + pgm_name + "\n"
    line_pgminfo9 =  "Function Name..................: " + curfunc + "\n"
    line_pgminfo10 =  "Logfile Name...................: " + wrklog   + "\n\n"
    line_pgminfo11 = "\n"
    try:
        File = open(wrklog, 'w') 			# Open binary output file
        File.writelines(line_dashes) 			# Write byte string
        File.writelines(line_titel) 			# Write byte string
        File.writelines(line_pgminfo1) 			# Write byte string
        File.writelines(line_pgminfo2) 			# Write byte string
        File.writelines(line_pgminfo3) 			# Write byte string
        File.writelines(line_pgminfo4) 			# Write byte string
        File.writelines(line_pgminfo5) 			# Write byte string
        File.writelines(line_pgminfo6) 			# Write byte string
        File.writelines(line_pgminfo7) 			# Write byte string
        File.writelines(line_pgminfo8) 			# Write byte string
        File.writelines(line_pgminfo9) 			# Write byte string
        File.writelines(line_pgminfo10) 		# Write byte string
        File.writelines(line_dashes) 			# Write byte string
        File.writelines(line_pgminfo11)			# Write byte string
        File.close()					#
        #os.chmod(wrklog, 33270)				# chmod to 766
    except Exception as e:
        print ("Log_Header write was not successful.")
        print(e)
        raise(e)
    return
#
#------------------------------------------------------------------------------
#
# sub : print_log_line
#
def print_log_line(wrklog,statyp,status,statxt):
    pgm_name =  (sys.argv[0])
    currentFuncName = lambda n=0: sys._getframe(n + 1).f_code.co_name
#    curfunc          =  currentFuncName(1) +"_"+ currentFuncName(2) +"+"+ currentFuncName(3) +"+"+ currentFuncName(4)+"+"+ currentFuncName(5)		#(current function caller is currentFuncName(1))
    curfunc          =  currentFuncName(1)
    current_datetime = datetime.now()
#    string = str(current_datetime) + ":" + statyp + ":" + pgm_name + ":" + status + ":" + statxt + "\n"
    string = str(current_datetime) + ":" + statyp + ":" + curfunc + ":" + status + ":" + statxt + "\n"
    try:
        File = open(wrklog, 'a') 			# Open binary output file
        File.writelines(string)	 			# Write byte string
        File.close()					#
    except Exception as e:
        print ("Log_Line write was not successful.")
        print(e)
        raise(e)
    return
#
#------------------------------------------------------------------------------
#
# sub : print_log_footer
#
def print_log_footer(wrklog,start_time):
    current_datetime = datetime.now()
    line_endtim =  "\nEnd-Date and Time: ............: " ":" + str(current_datetime) + ""
    line_elatim =  "\nElapsed Time: .................: " ":" + str(time() - start_time) + "\n"
    line_dashes  =  "\n--------------------------------------------------------------------------------\n\n"
    try:
        File = open(wrklog, 'a') 			# Open binary output file
        File.writelines(line_endtim) 			# Write byte string
        File.writelines(line_elatim) 			# Write byte string
        File.writelines(line_dashes) 			# Write byte string
        File.close()					#
        os.chmod(wrklog, 33270)				# chmod to 766
    except Exception as e:
        print ("Log_Footer write was not successful.")
        print(e)
        raise(e)
    return
#
### END #######################################################################


# Basierend auf: https://github.com/pronobis/libspn-keras/blob/master/examples/notebooks/Sampling%20with%20conv%20SPNs.ipynb
import libspn_keras as spnk
from tensorflow import keras

spnk.set_default_accumulator_initializer(
    spnk.initializers.Dirichlet()
)

import numpy as np
import tensorflow_datasets as tfds
from libspn_keras.layers import NormalizeAxes
import tensorflow as tf

def take_first(a, b):
  return tf.reshape(tf.cast(a, tf.float32), (-1, 28, 28, 1))

normalize = spnk.layers.NormalizeStandardScore(
    input_shape=(28, 28, 1), axes=NormalizeAxes.GLOBAL,
    normalization_epsilon=1e-3
)

mnist_images = tfds.load(name="mnist", batch_size=32, split="train", as_supervised=True).map(take_first)

normalize.adapt(mnist_images)
mnist_normalized = mnist_images.map(normalize)
location_initializer = spnk.initializers.PoonDomingosMeanOfQuantileSplit(
    mnist_normalized
)

def build_spn(sum_op, return_logits, infer_no_evidence=False):
  spnk.set_default_sum_op(sum_op)
  return spnk.models.SequentialSumProductNetwork([
    normalize,
    spnk.layers.NormalLeaf(
        num_components=4,
        location_trainable=True,
        location_initializer=location_initializer,
        scale_trainable=True
    ),
    spnk.layers.Conv2DProduct(
        depthwise=False,
        strides=[2, 2],
        dilations=[1, 1],
        kernel_size=[2, 2],
        padding='valid'
    ),
    spnk.layers.Local2DSum(num_sums=256),
    spnk.layers.Conv2DProduct(
        depthwise=True,
        strides=[2, 2],
        dilations=[1, 1],
        kernel_size=[2, 2],
        padding='valid'
    ),
    spnk.layers.Local2DSum(num_sums=512),
    # Pad to go from 7x7 to 8x8, so that we can apply 3 more Conv2DProducts
    tf.keras.layers.ZeroPadding2D(((0, 1), (0, 1))),
    spnk.layers.Conv2DProduct(
        depthwise=True,
        strides=[2, 2],
        dilations=[1, 1],
        kernel_size=[2, 2],
        padding='valid'
    ),
    spnk.layers.Local2DSum(num_sums=512),
    spnk.layers.Conv2DProduct(
        depthwise=True,
        strides=[2, 2],
        dilations=[1, 1],
        kernel_size=[2, 2],
        padding='valid'
    ),
    spnk.layers.Local2DSum(num_sums=1024),
    spnk.layers.Conv2DProduct(
        depthwise=True,
        strides=[2, 2],
        dilations=[1, 1],
        kernel_size=[2, 2],
        padding='valid'
    ),
    spnk.layers.LogDropout(rate=0.5),
    spnk.layers.DenseSum(num_sums=10),
    spnk.layers.RootSum(return_weighted_child_logits=return_logits)
  ], infer_no_evidence=infer_no_evidence, unsupervised=False)

sum_product_network = build_spn(spnk.SumOpEMBackprop(), return_logits=True)
sum_product_network.summary()

import tensorflow_datasets as tfds

batch_size = 128

mnist_train = (
    tfds.load(name="mnist", split="train", as_supervised=True)
    .shuffle(1024)
    .batch(batch_size)
)

mnist_test = (
    tfds.load(name="mnist", split="test", as_supervised=True)
    .batch(100)
)

optimizer = spnk.optimizers.OnlineExpectationMaximization(learning_rate=0.05, accumulate_batches=1)
metrics = []
loss = spnk.losses.NegativeLogJoint()

sum_product_network.compile(loss=loss, metrics=metrics, optimizer=optimizer)

import tensorflow as tf

sum_product_network.fit(mnist_train, epochs=20, callbacks=[tf.keras.callbacks.ReduceLROnPlateau(monitor="loss", min_delta=0.1, patience=2, factor=0.5)])
sum_product_network.evaluate(mnist_test)

sum_product_network_sample = build_spn(spnk.SumOpSampleBackprop(), return_logits=False, infer_no_evidence=True)
sum_product_network_sample.set_weights(sum_product_network.get_weights())

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(12., 12.))
grid = ImageGrid(
    fig, 111,
    nrows_ncols=(10, 10),
    axes_pad=0.1,
)

sample = sum_product_network_sample.zero_evidence_inference(100)

print("Sampling done... Now ploting results")
for ax, im in zip(grid, sample):
    ax.imshow(np.squeeze(im), cmap="gray")
plt.show()


# Longest Substring Without Repeating Characters

# Given a string, find the length of the longest substring without repeating characters.

# Working Example 1:

# start = 5
# max_length = 3
# {a: 3,
# b: 7,
# c: 5
# }

# Input: "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
# Example 2:

# Input: "bbbbb"
# Output: 1
# Explanation: The answer is "b", with the length of 1.
# Working Example 3:

# start = 3
# max_length = 3
# {p: 0,
# w: 5,
# k: 3,
# e: 4
# }

# Input: "pwwkew"
# Output: 3
# Explanation: The answer is "wke", with the length of 3.
#              Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        usedchar = {}
        max_length, start = 0
        for i, c in enumerate(s):
            if c in usedchar and start <= usedchar[c]:
                start = usedchar[c] + 1
            else:
                max_length = max(max_length, i - start + 1)

            usedchar[c] = i

        return max_length


import logging
from datetime import datetime, timedelta
from dateutil.tz import tzutc

import pytest

from services.core.ActuatorAgent.actuator import agent
from services.core.ActuatorAgent.actuator.agent import ActuatorAgent
from services.core.ActuatorAgent.actuator.scheduler import RequestResult, DeviceState
from services.core.ActuatorAgent.tests.actuator_fixtures import MockedAsyncResult, get_actuator_agent
from volttrontesting.utils.utils import AgentMock
from volttron.platform.vip.agent import Agent

pytestmark = [pytest.mark.actuator_unit, pytest.mark.unit]

PEER = "peer-1"
SENDER = "sender-1"
HEADERS = {"requesterID": "id-12345"}
MESSAGE = "message-1"
BUS = "bus-1"
GET_TOPIC = "devices/actuators/get/somepath/actuationpoint"
SET_TOPIC = "devices/actuators/set/somepath/actuationpoint"
REQUEST_TOPIC = "devices/actuators/schedule/request"
REVERT_DEVICE_TOPIC = "devices/actuators/revert/device/somedevicepath"
REVERT_POINT_TOPIC = "actuators/revert/point/somedevicepath/someactuationpoint"

agent._log = logging.getLogger("test_logger")
ActuatorAgent.__bases__ = (AgentMock.imitate(Agent, Agent()),)

def test_handle_get_should_succeed():
    with get_actuator_agent() as actuator_agent:
        actuator_agent.handle_get(PEER, SENDER, BUS, GET_TOPIC, HEADERS, MESSAGE)

        actuator_agent.vip.rpc.call.assert_called_once()
        actuator_agent.vip.pubsub.publish.assert_called_once()

def test_handle_get_should_handle_standard_error(caplog):
    with get_actuator_agent(vip_identity=None) as actuator_agent:
        actuator_agent.handle_get(PEER, SENDER, BUS, GET_TOPIC, HEADERS, MESSAGE)

        actuator_agent.vip.rpc.call.assert_not_called()
        actuator_agent.vip.pubsub.publish.assert_called_once()
        assert (
            caplog.records[-1].message
            == "Actuator Agent Error: {'type': 'AttributeError', "
            "'value': \"'ActuatorAgent' object has no attribute 'driver_vip_identity'\"}"
        )

@pytest.mark.parametrize(
    "sender, device_state",
    [
        (
            SENDER,
            {"somepath": DeviceState("sender-1", "task-id-1", "anytime")},
        ),
        (
            "pubsub.compat",
            {"somepath": DeviceState("pubsub.compat", "task-id-1", "anytime")},
        ),
    ],
)
def test_handle_set_should_succeed(sender, device_state):
    with get_actuator_agent(vip_rpc_call_res=MockedAsyncResult({"foo": "bar"}), device_state=device_state) as actuator_agent:

        actuator_agent.handle_set(PEER, sender, BUS, SET_TOPIC, HEADERS, MESSAGE)

        actuator_agent.vip.rpc.call.assert_called_once()
        actuator_agent.vip.pubsub.publish.assert_called()

def test_handle_set_should_return_none_on_none_message(caplog):
    with get_actuator_agent(vip_identity=None) as actuator_agent:
        result = actuator_agent.handle_set(PEER, SENDER, BUS, SET_TOPIC, HEADERS, None)

        assert result is None
        actuator_agent.vip.pubsub.publish.assert_called_once()
        actuator_agent.vip.rpc.call.assert_not_called()
        assert (
            caplog.records[-1].message
            == "ValueError: {'type': 'ValueError', 'value': 'missing argument'}"
        )

def test_handle_set_should_handle_type_error_on_invalid_sender(caplog):
    with get_actuator_agent(vip_identity=None) as actuator_agent:
        actuator_agent.handle_set(PEER, None, BUS, SET_TOPIC, HEADERS, MESSAGE)

        actuator_agent.vip.rpc.call.assert_not_called()
        actuator_agent.vip.pubsub.publish.assert_called_once()
        assert (
            caplog.records[-1].message == "Actuator Agent Error: {'type': 'TypeError', "
            "'value': 'Agent id must be a nonempty string'}"
        )

def test_handle_set_should_handle_lock_error(caplog):
    with get_actuator_agent(vip_identity=None) as actuator_agent:
        actuator_agent.handle_set(PEER, SENDER, BUS, SET_TOPIC, HEADERS, MESSAGE)

        actuator_agent.vip.rpc.call.assert_not_called()
        actuator_agent.vip.pubsub.publish.assert_called_once()
        assert (
            caplog.records[-1].message == "Actuator Agent Error: {'type': 'LockError', "
            "'value': 'caller (sender-1) does not have this lock'}"
        )

def test_handle_revert_point_should_succeed():
    device_state = {
        "actuators/revert/point/somedevicepath": DeviceState(
            "sender-1", "task-id-1", "anytime"
        )
    }

    with get_actuator_agent(device_state=device_state, vip_rpc_call_res=MockedAsyncResult({"foo": "bar"})) as actuator_agent:
        actuator_agent.handle_revert_point(
            PEER, SENDER, BUS, REVERT_POINT_TOPIC, HEADERS, MESSAGE
        )

        actuator_agent.vip.rpc.call.assert_called_once()
        actuator_agent.vip.pubsub.publish.assert_called_once()

def test_handle_revert_point_should_handle_lock_error(caplog):
    with get_actuator_agent(vip_identity=None) as actuator_agent:
        actuator_agent.handle_revert_point(
            PEER, SENDER, BUS, REVERT_POINT_TOPIC, HEADERS, MESSAGE
        )

        actuator_agent.vip.rpc.call.assert_not_called()
        actuator_agent.vip.pubsub.publish.assert_called_once()
        assert (
            caplog.records[-1].message == "Actuator Agent Error: {'type': 'LockError', "
            "'value': 'caller does not have this lock'}"
        )

def test_handle_revert_device_should_succeed():
    device_state = {
        "somedevicepath": DeviceState("sender-1", "task-id-1", "anytime")
    }

    with get_actuator_agent(device_state=device_state,
                            vip_rpc_call_res=MockedAsyncResult({"foo": "bar"})) as actuator_agent:
        actuator_agent.handle_revert_device(
            PEER, SENDER, BUS, REVERT_DEVICE_TOPIC, HEADERS, MESSAGE
        )

        actuator_agent.vip.rpc.call.assert_called_once()
        actuator_agent.vip.pubsub.publish.assert_called_once()

def test_handle_revert_device_should_handle_lock_error(caplog):
   with get_actuator_agent(vip_identity=None) as actuator_agent:
        actuator_agent.handle_revert_device(
            PEER, SENDER, BUS, REVERT_DEVICE_TOPIC, HEADERS, MESSAGE
        )

        actuator_agent.vip.rpc.call.assert_not_called()
        actuator_agent.vip.pubsub.publish.assert_called_once()
        assert (
            caplog.records[-1].message == "Actuator Agent Error: {'type': 'LockError', "
            "'value': 'caller does not have this lock'}"
        )

@pytest.mark.parametrize(
    "priority, success",
    [
        ("HIGH", True),
        ("LOW", True),
        ("LOW_PREEMPT", True),
        ("HIGH", False),
        ("LOW", False),
        ("LOW_PREEMPT", False),
    ],
)
def test_handle_schedule_request_should_succeed_on_new_schedule_request_type(
    priority, success
):
    headers = {
        "type": "NEW_SCHEDULE",
        "requesterID": "id-123",
        "taskID": "12345",
        "priority": priority,
    }

    with get_actuator_agent(slot_requests_res=RequestResult(success, {}, "")) as actuator_agent:
        actuator_agent.handle_schedule_request(
            PEER, SENDER, BUS, REQUEST_TOPIC, headers, create_message()
        )

        actuator_agent.vip.pubsub.publish.assert_called()

@pytest.mark.parametrize("success", [True, False])
def test_handle_schedule_request_should_succeed_on_cancel_schedule_request_type(success):
    headers = {"type": "CANCEL_SCHEDULE", "requesterID": "id-123", "taskID": "12345"}

    with get_actuator_agent(slot_requests_res=RequestResult(success, {}, "")) as actuator_agent:
        actuator_agent.handle_schedule_request(
            PEER, SENDER, BUS, REQUEST_TOPIC, headers, create_message()
        )

        actuator_agent.vip.pubsub.publish.assert_called()

@pytest.mark.parametrize("invalid_request_type", ["bad request type", None])
def test_handle_schedule_request_should_log_invalid_request_type(
    invalid_request_type, caplog
):
    headers = {
        "type": invalid_request_type,
        "requesterID": "id-123",
        "taskID": "12345",
        "priority": "HIGH",
    }

    with get_actuator_agent(vip_identity=None) as actuator_agent:
        actuator_agent.handle_schedule_request(
            PEER, SENDER, BUS, REQUEST_TOPIC, headers, create_message()
        )

        actuator_agent.vip.pubsub.publish.assert_called()
        assert caplog.records[-1].message == "handle-schedule_request, invalid request type"

def create_message():
    start = str(datetime.now(tz=tzutc()) + timedelta(seconds=10))
    end = str(datetime.now(tz=tzutc()) + timedelta(seconds=20))
    return ["campus/building/device1", start, end]


import spacy
from spacy.matcher import Matcher
nlp = spacy.load('en_core_web_sm')

# 1
story = ''
with open('..\\Material\\TextFiles\\owlcreek.txt', 'r') as f:
    story = f.read()
doc = nlp(story)
print(doc[:36])

# 2
print(len(doc))

# 3
sents = list(doc.sents)
print(len(sents))

# 4
print(sents[1])

# 5
for t in sents[1]:
    print(f'{t.text:{10}} {t.pos_:{10}} {t.lemma_:{10}}  {t.dep_:{10}}')

# 6
matcher = Matcher(nlp.vocab)
pattern = [[{'LOWER': 'swimming'}, {'IS_SPACE':True, 'OP':'*'}, {'LOWER': 'vigorously'}]]
matcher.add('Swimming',pattern)
found_matches = matcher(doc)
print(found_matches)

# 7
for found in found_matches:
    print(str(doc[found[1]-5:found[2]+5]).replace('\n', ' '))


import csv

Entity = "http://www.student-mat.com/entity/"
Property = "http://www.student-mat.com/pred/"

triples = []

filename = "clean_data/" + input("Filename: ")
file_in = open(filename, 'r', encoding='utf-8')

reader = csv.reader(file_in)
for sub, pred, obj in reader:
    triples.append((sub, pred, obj))
file_in.close()

file_out = open('filent.nt', 'w')
for sub, pred, obj in triples:
    uri_sub = '<' + Entity + str(sub).lower().replace(' ', '_') + '>'
    uri_pred = '<' + Property + str(pred).lower().replace(' ', '_') + '>'
    obj_uri = '"' + obj + '"'
    file_out.write('{} {} {} .\n'.format(uri_sub, uri_pred, obj_uri))
file_out.close()
print("filent.nt created")


FUNC_PROTO = """\
#include "vendor/unity.h"

extern uint64_t square(int64_t number);
extern uint64_t total(void);
"""

def gen_func_body(prop, inp, expected):
    if type(expected) is not int:
        expected = 0
    if prop == "square":
        square = inp["square"]
        s = f"TEST_ASSERT_EQUAL_UINT64(UINT64_C({expected}), {prop}({square}));\n"
    elif prop == "total":
        s = f"TEST_ASSERT_EQUAL_UINT64(UINT64_C({expected}), {prop}());\n"
    return s


import tensorflow as tf

from linear import Linear

class MLP(tf.Module):
    def __init__(self, num_inputs, num_outputs, num_hidden_layers,
                 hidden_layer_width, hidden_activation=tf.identity,
                 output_activation=tf.identity):
        self.num_inputs = num_inputs
        self.num_outputs = num_outputs
        self.num_hidden_layers = num_hidden_layers
        self.hidden_layer_width = hidden_layer_width
        self.hidden_activation = hidden_activation
        self.output_activation = output_activation
        self.hidden_linear = Linear(self.hidden_layer_width,
                                    self.hidden_layer_width)
        self.first_linear = Linear(num_inputs, hidden_layer_width)
        self.final_linear = Linear(self.hidden_layer_width, self.num_outputs)

    def __call__(self, x):
        x = self.hidden_activation(self.first_linear(x))
        for i in range(self.num_hidden_layers):
            x = self.hidden_activation(
                self.hidden_linear(x)
            )
        return self.output_activation(self.final_linear(x))

if __name__ == "__main__":
    import argparse
    from math import pi
    from pathlib import Path

    import matplotlib.pyplot as plt
    import yaml
    from tqdm import trange

    from linear import grad_update

    parser = argparse.ArgumentParser(
        prog="Multi Layer Perceptron",
        description="Uses a multi layer perceptron on some data, \
              given a config",
    )
    parser.add_argument(
        "-c",
        "--config",
        type=Path,
        default=Path("config.yaml")
    )
    args = parser.parse_args()

    config = yaml.safe_load(args.config.read_text())

    rng = tf.random.get_global_generator()
    rng.reset_from_seed(0x43966E87BD57227011B5B03B58785EC1)

    num_samples = config["data"]["num_samples"]
    num_inputs = 2
    num_outputs = 1

    noise_stddev = config["data"]["noise_stddev"]
    e1 = rng.normal(shape=(num_samples, 1), stddev=noise_stddev)
    e2 = rng.normal(shape=(num_samples, 1), stddev=noise_stddev)
    r = tf.linspace(pi/4, 4*pi, num_samples)[:, tf.newaxis]

    x1 = (r + e1)*tf.math.cos(r)
    y1 = (r + e1)*tf.math.sin(r)
    x2 = -(r + e2)*tf.math.cos(r)
    y2 = -(r + e2)*tf.math.sin(r)

    num_hidden_layers = config["mlp"]["num_hidden_layers"]
    hidden_layer_width = config["mlp"]["hidden_layer_width"]

    def relu(x):
        return tf.maximum(x, 0)

    def sigmoid(x):
        return tf.math.sigmoid(x)

    mlp = MLP(num_inputs, num_outputs, num_hidden_layers, hidden_layer_width,
              relu, sigmoid)

    num_iters = config["learning"]["num_iters"]
    step_size = config["learning"]["step_size"]
    decay_rate = config["learning"]["decay_rate"]
    batch_size = config["learning"]["batch_size"]

    refresh_rate = config["display"]["refresh_rate"]

    l2_scale = config["learning"]["l2_scale"]

    bar = trange(num_iters)

    for i in bar:
        batch_indices = rng.uniform(
            shape=[batch_size*2], maxval=num_samples*2, dtype=tf.int32
        )
        with tf.GradientTape() as tape:
            output1 = tf.zeros((num_samples, 1))
            output2 = tf.ones((num_samples, 1))

            input1 = tf.concat((x1, y1), axis=1)
            input2 = tf.concat((x2, y2), axis=1)

            output_combined = tf.concat((output1, output2), axis=0)
            input_combined = tf.concat((input1, input2), axis=0)

            output_batch = tf.gather(output_combined, batch_indices)
            input_batch = tf.gather(input_combined, batch_indices)

            y_hat = mlp(input_batch)

            weightTensor = tf.concat([tf.reshape(weight, [-1]) for weight in
                                      mlp.trainable_variables if weight.name ==
                                      "Linear/w:0"], axis=0)

            l2_norm = tf.norm(weightTensor, ord=2)
            loss = tf.math.reduce_mean(
                -output_batch*tf.math.log(y_hat + 1e-7) -
                (1 - output_batch)*tf.math.log(1 - y_hat + 1e-7)
            ) + l2_scale*l2_norm

        grads = tape.gradient(loss, mlp.trainable_variables)
        grad_update(step_size, mlp.trainable_variables, grads)

        step_size *= decay_rate

        if i % refresh_rate == (refresh_rate - 1):
            bar.set_description(
                f"Step {i}; Loss => {loss.numpy():0.4f}, \
                    step_size => {step_size:0.4f}"
            )
            bar.refresh()

    fig, ax = plt.subplots()

    ax.plot(x1.numpy().squeeze(), y1.numpy().squeeze(), "x", label="Inputs")
    ax.plot(x2.numpy().squeeze(), y2.numpy().squeeze(), "x", label="Inputs")

    x1_quiet = r*tf.math.cos(r)
    y1_quiet = r*tf.math.sin(r)
    ax.plot(
        x1_quiet.numpy().squeeze(),
        y1_quiet.numpy().squeeze(),
        "-",
        label="Clean"
    )

    x2_quiet = -r*tf.math.cos(r)
    y2_quiet = -r*tf.math.sin(r)
    ax.plot(
        x2_quiet.numpy().squeeze(),
        y2_quiet.numpy().squeeze(),
        "-",
        label="Clean"
    )

    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.legend()
    ax.set_title("Nonlinear fit using SGD")

    h = ax.set_ylabel("y", labelpad=10)
    h.set_rotation(0)

    import numpy as np
    from sklearn.inspection import DecisionBoundaryDisplay
    xx, yy = np.meshgrid(
        np.linspace(-15., 15., 100),
        np.linspace(-15., 15., 100)
    )

    input_grid = tf.stack(tf.convert_to_tensor((xx.ravel(), yy.ravel()),
                                               dtype=tf.float32), axis=1,)
    zz = mlp(input_grid)
    zz = zz.numpy().reshape(xx.shape)

    dbd = DecisionBoundaryDisplay(xx0=xx, xx1=yy, response=zz)
    dbd.plot(ax=ax, cmap="RdBu", alpha=0.9)

    fig.savefig("artifacts/mlp.pdf")


import sqlite3
def delete_data():
    with sqlite3.connect("Coffe_shop.db") as db:
        cursor=db.cursor()
        sql="""Select * from Product"""
        cursor.execute(sql)
        products=cursor.fetchall()
        for prod in products:
            print(prod)
        i=input("Wich prod do you want to delete: ")

        sql="""Delete from Product where ProductID=?"""
        cursor.execute(sql,i)
        sql = """Select * from Product"""
        cursor.execute(sql)
        products = cursor.fetchall()
        for prod in products:
            print(prod)
        db.commit()
if __name__ == '__main__':
    delete_data()


def pair_with_sum(arr, s):
	pairs = []
	for i in range(0, len(arr) - 1):
		for j in range(i + 1, len(arr)):
			if(arr[i] + arr[j] == s):
				pairs.append((arr[i], arr[j]))

	if(len(pairs) == 0):
		return -1
	else:
		return pairs

T = input()
ans = []

for i in range(T):
	N = input()
	arr = [int(x) for x in raw_input().split(" ")]
	s = input()
	ans.append(pair_with_sum(arr, s))

for a in ans:
	print(a)


global_var = 2

class Vehicle:

    def start_engine(self):
        print('Engine started!')

class Car(Vehicle):

    def start(self):
        self.start_engine()  # definido en la clase padre
        print('Vroom Vroom')

car = Car()
car.start()
car.start_engine()

print(globals())


# review-analytics
data = []
#count = 0
with open('reviews.txt', 'r') as f:
    for line in f:
        data.append(line)
        #count += 1
        #if count % 10000 == 0:
        #    print(len(data))
print('檔案讀取結束共有', len(data), '筆資料')

world_count = {}
for d in data:
    words = d.strip().split()
    #print(words)
    for word in words:
        if word in world_count:
            world_count[word] += 1
        else:
            world_count[word] = 1

sum_len = 0
for d in data:
    sum_len += len(d)
print('平均留言長度為:', sum_len/len(data))

new = []
counter_100 = 0
for s in data:
    if len(s) < 100:
        new.append(s)
        counter_100 += 1
print('共有', len(new), '筆資料字數少於100')

for word in world_count:
    if world_count[word] > 1000000:
        print(word, world_count[word])

while True:
    word = input('please enter keyword: ')
    if word == 'q':
        print('離開')
        break
    if word in world_count:
        print(word, '出現過次數:', world_count[word])
    else:
        print('這個字未出現過!')


from datetime import datetime
from typing import Any, Dict
from uuid import UUID

from oauth.backends import UnionIdBackend
from rest_framework_simplejwt.serializers import PasswordField
from users.models import User
from zq_auth_sdk import UserNotFoundException
from zq_django_util.exceptions import ApiException
from zq_django_util.response import ResponseType
from zq_django_util.utils.auth.backends import OpenIdBackend
from zq_django_util.utils.auth.serializers import (
    OpenIdLoginSerializer as DefaultOpenIdLoginSerializer,
)

import server.business.ziqiang.auth as zq_auth
from server.business.wechat.wxa import get_openid

def generate_token_result(
    user: User,
    user_id_field: str,
    expire_time: datetime,
    access: str,
    refresh: str,
) -> dict:
    return dict(
        id=getattr(user, user_id_field),
        username=user.username,
        is_active=user.is_active,
        is_staff=user.is_staff,
        expire_time=expire_time,
        access=access,
        refresh=refresh,
    )

class OpenIdLoginSerializer(DefaultOpenIdLoginSerializer):
    """
    OpenID Token 获取序列化器 (直接用 openid 获取登录 token，用于测试)
    """

    backend = OpenIdBackend(User)  # 自定义验证后端，用于指定不同类型的用户模型

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def generate_token_result(
        self,
        user: User,
        user_id_field: str,
        expire_time: datetime,
        access: str,
        refresh: str,
    ) -> dict:
        return generate_token_result(
            user, user_id_field, expire_time, access, refresh
        )

class WechatLoginSerializer(OpenIdLoginSerializer):
    """
    微信登录序列化器
    """

    code = PasswordField(label="前端获取code")  # 前端传入 code

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields.pop("openid")  # 删除 openid 字段

    def get_open_id(self, attrs: Dict[str, Any]) -> str:
        """
        重写获取 open_id 方法
        """
        return get_openid(attrs["code"])

class UnionIdLoginSerializer(DefaultOpenIdLoginSerializer):
    """
    自强Auth union id 登录序列化器
    """

    backend = UnionIdBackend(User)
    openid = None
    openid_field = "union_id"
    union_id = PasswordField(label="union_id")  # union_id

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def generate_token_result(
        self,
        user: User,
        user_id_field: str,
        expire_time: datetime,
        access: str,
        refresh: str,
    ) -> dict:
        return generate_token_result(
            user, user_id_field, expire_time, access, refresh
        )

    def get_open_id(self, attrs: Dict[str, Any]) -> UUID:
        """
        重写获取 open_id 方法
        """
        return UUID(attrs["union_id"])

    def handle_new_openid(self, union_id: UUID) -> User:
        """
        重写处理新 union id 方法
        """
        try:
            user_data = zq_auth.fetch_user_info(union_id)
            data = {
                "union_id": union_id,
                "username": f"{user_data['name']}_{user_data['student_id']}",
                "name": user_data["name"],
                "phone": user_data["phone"],
                "student_id": user_data["student_id"],
                "contact": [{"type": "phone", "value": user_data["phone"]}],
            }
            instance = User.objects.create(
                **data, is_active=True, is_staff=False
            )
            return instance
        except UserNotFoundException:
            raise ApiException(ResponseType.ThirdServiceError, "用户不存在")

class ZqAuthLoginSerializer(UnionIdLoginSerializer):
    """
    自强Auth登录序列化器
    """

    code = PasswordField(label="前端获取code")  # 前端传入 code
    union_id = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def get_open_id(self, attrs: Dict[str, Any]) -> UUID:
        """
        重写获取 open_id 方法
        """
        return zq_auth.get_union_id(attrs["code"])