from . import bp_accallbk
from flask import redirect, request,make_response, jsonify
#from flask_cors import CORS, cross_origin
from assetscube.common import dbfunc as db
from assetscube.common import error_logics as errhand
from assetscube.common import jwtfuncs as jwtf
from assetscube.common import settings as settings
from datetime import datetime
import pkgutil
import firebase_admin
from firebase_admin import credentials
from firebase_admin import auth
import json
import requests
import jwt

@bp_accallbk.route("/callback",methods=["GET","POST","OPTIONS"])
def callback():
    if request.method=="OPTIONS":
            print("inside callback options")
            response = "inside callback options"
            #print(request.headers)
            response1 = make_response(jsonify(response))
            return response1

    elif request.method=="GET":
        print("inside callback get")
        params = request.args
        print(params)
        callbk_proc_data = callback_handler(params)
        print(callbk_proc_data)
        print(type(callbk_proc_data))
        '''
                callbk_proc_data ={
                "typ": "signup",
                "regdata": "401",
                "msg": email + " registered failed.  Please retry.  If problem persists, please conatact support"
            }
        '''
        typ = callbk_proc_data["typ"]
        regdata = callbk_proc_data["regdata"]
        msg = callbk_proc_data["msg"]
        print(typ, regdata, msg)
        print(settings.MYNOTIPG[settings.LIVE])

        response1 = make_response(redirect(settings.MYNOTIPG[settings.LIVE]+"?type="+typ+"&regdata="+regdata+"&msg="+msg, code=302))
        response1.headers['Origin'] = "http://localhost:5000"
        del response1.headers['entityid']
        del response1.headers['coutnrycode']
        response1.headers['Access-Control-Allow-Origin'] = "*"
        response1.headers['Access-Control-Allow-Methods'] = "GET, POST, PATCH, PUT, DELETE, OPTIONS"
        response1.headers['Access-Control-Allow-Headers'] = "Origin, entityid, Content-Type, X-Auth-Token, countryid"
        print(response1.headers)
        return response1
        #return redirect(settings.MYNOTIPG[settings.LIVE]+"?type="+typ+"&regdata="+regdata+"&msg="+msg, code=302)

        '''
        #
        if res_to_send == 'success':
            resps = make_response(jsonify(resp), 200)
            #resps = make_response(jsonify(response), 200 if res_to_send == 'success' else 400)
        else:
            resps = make_response(jsonify(resp), 400)

        return resps
        '''
    elif request.method=="POST":
        print("inside callback POST")
        payload = request.get_json()
        print("payload 11111111")
        print(payload)
        #payload
        #{type: "signup", callbkfrm: "nawalcube", regdata: "a96f2d792641cd049c974e3c9e330f99", msg: "success"}

        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        entityid = request.headers.get("entityid", None)
        countryid = request.headers.get("countryid", None)
        payload["entityid"] = entityid
        payload["countryid"] = countryid
        #payload
        #{type: "signup", callbkfrm: "nawalcube", regdata: "a96f2d792641cd049c974e3c9e330f99", msg: "success", "entityid": "ac", countryid: "IN"}

        res_status, res_to_send = callback_handler(payload)
        print(res_status, res_to_send)
        if res_status == 'success':
            resps = make_response(jsonify(res_to_send), 200)
            #resps = make_response(jsonify(response), 200 if res_to_send == 'success' else 400)
        else:
            resps = make_response(jsonify(res_to_send), 400)

        return resps

def callback_handler(callback_data):
    #Common handler to handle any callback from oauth
    #callback_data
    #{type: "signup", callbkfrm: "nawalcube", regdata: "a96f2d792641cd049c974e3c9e330f99", msg: "success", "entityid": "ac", countryid: "IN"}

    print("inside callback_handler")
    print(callback_data)
    print(callback_data["callbkfrm"])
    if callback_data["callbkfrm"] == "nawalcube":
        print("Inside nawalcube")
        return ncallbk_handler(callback_data)
    elif callback_data["callbkfrm"] == "upstox":
        #callbk_proc_data, status = clbk_auth_handler(callback_data)
        print("upstox")
    return  None, None

def ncallbk_handler(callback_data):
    #Common handler to handle any callback from nawalcube
    #callback_data
    #{type: "signup", callbkfrm: "nawalcube", regdata: "a96f2d792641cd049c974e3c9e330f99", msg: "success", "entityid": "ac", countryid: "IN"}

    if callback_data["type"] == "signup":
        return ncclbk_singup_handler(callback_data)
    elif callback_data["type"] == "code":
        return ncclbk_login_handler(callback_data)

def ncclbk_singup_handler(callback_data):
    # handler for nawalcube signup
    #callback_data
    #{type: "signup", callbkfrm: "nawalcube", regdata: "a96f2d792641cd049c974e3c9e330f99", msg: "success", "entityid": "ac", countryid: "IN"}

    print("inside ncclbk_singup_handler function")
    s = 0
    f = None
    t = None #message to front end
    usrmsg = None
    rec_status ="fail"
    print("nc signup handler")
    if callback_data["regdata"] == '401':
        # show error page
        print("signup handler error")
        callbk_proc_data ={
                "typ": "signup",
                "regdata": "401",
                "msg": "Registered failed.  Please retry.  If problem persists, please conatact support"
            }
        return "fail", callbk_proc_data
    else:
        # Please register user and confirm
        #Get data from nawalcube
        entityid = callback_data["entityid"]
        countryid = callback_data["countryid"]

        headers = {"entityid": entityid, "countryid": countryid}
        req_payload = {"userauthtkn": callback_data["regdata"], "appid": settings.NCAPPID[settings.LIVE],"appkey":settings.NCAPPKEY[settings.LIVE]}
        print("###########################")
        print(req_payload)
        print(type(req_payload))
        print("###########################")
        r = requests.post(settings.NCSIGNUPDATAFETCHURL[settings.LIVE], headers=headers, data=json.dumps(req_payload))
        nc_usr_data = json.loads(r.content.decode("utf-8") )
        print(json.loads(r.content.decode("utf-8")))
        # Response we get:
        #     Field Name         success                     fail
        # -----------------------------------------------------------
        #  {
        #    "userauthtkn":  new_userauthtkn,                BLANK
        #     "tknexpiry":   usr_db_rec["tknexpiry"],        BLANK
        #     "userid":      more_usr_db_rec["userid"],      BLANK
        #     "username":    more_usr_db_rec["username"],    BLANK
        #     "emailid":     more_usr_db_rec["sinupemail"],  BLANK
        #     "status":      success                         fail
        #     "msg":         BLANK                           fail message
        #   }
        print('i see')

        if nc_usr_data["status"] == "success":
            nc_email = nc_usr_data["emailid"]
            nc_userauthtkn = nc_usr_data["userauthtkn"]
            nc_tknexpiry = nc_usr_data["tknexpiry"]
            nc_usrid = nc_usr_data["userid"]
            nc_usrname = nc_usr_data["username"]
            uid = None
            #initialise the Firebase app
            try:
                print('inside try')
                default_app = firebase_admin.get_app('acfbapp')
                print('about inside try')
            except ValueError:
                print('inside value error')
                #cred = credentials.Certificate(os.path.dirname(__file__)+'/serviceAccountKey.json')
                cred = credentials.Certificate(settings.FBSERVICEAC)
                default_app = firebase_admin.initialize_app(credential=cred,name='acfbapp')
                s, f, t= errhand.get_status(s, 0, f, "Firebase app initialised", t, "no")
            else:
                pass

            print('app initialisation completed')
            #TO check if the email already exists
            useridex = False
            if s <= 0:
                try:
                    user = auth.get_user_by_email(nc_email,app=default_app)
                except auth.AuthError as e:
                    print(str(e.args))
                    s, f, t= errhand.get_status(s, 0, f, ''.join(e.args), t, "no")
                except Exception as inst:
                    print(inst.args)
                    print(inst)
                    s, f, t= errhand.get_status(s, 0, f, inst, t, "no")
                else:
                    print('Successfully fetched user data: {0}'.format(user.uid))
                    if user.uid != None or user.uid != "":
                        useridex = True
                        uid = user.uid
                    print("user details fetch successful")
                    s, f, t= errhand.get_status(s, 0, f, " email already registered.", t, "no")
                    #usrmsg = "email already registered."
            print(useridex)
            #If email already exists skip fb user creation
            if s <= 0 and (not useridex):
                try:
                    user = auth.create_user(email=nc_email,app=default_app)
                except auth.AuthError as e:
                    print(auth.ErrorInfo)
                    #e.code == "USER_CREATE_ERROR":
                    print(e.code)
                    print(e.detail)
                    print("Auth error while creating user")
                    s, f, t= errhand.get_status(s, 100, f, "User registration failed.  Please cotact support [ac error]", t, "yes")
                except ValueError as e:
                    print("value error while creating user")
                    s, f, t= errhand.get_status(s, 0, f, "Firebase app user details fetch failed", t, "no")
                    s, f, t= errhand.get_status(s, 100, f, "User registration failed.  Please cotact support [ac error]", t, "yes")
                else:
                    print(user.uid)
                    print(format(user))
                    uid = user.uid
            print("inside callback singup success")

        else:
            s, f, t= errhand.get_status(s, 100, f, "User registration failed.
  Please contact support [nc fetch].", t, "yes")

        if s <= 0:
            sav_usr = {
                "uid": uid,
                "nc_email" : nc_email,
                "nc_userauthtkn" : nc_userauthtkn,
                "nc_tknexpiry" : nc_tknexpiry,
                "nc_usrid" : nc_usrid,
                "nc_usrname" : nc_usrname,
                "nc_entity": "NAWALCUBE",
                "entityid" : entityid,
                "countryid": countryid
            }
            sav_status, sav_resp_rec = save_usr_details(sav_usr)
            if sav_status != "success":
                print(sav_resp_rec)
                s, f, t= errhand.get_status(s, 100, f, "User registration failed.
  Please contact support [ac db update].", t, "yes")

        if s <= 0:
            rec_status ="success"
            if usrmsg == None:
                usrmsg = "User registered successfully.  Please reset password before first login"
            else:
                usrmsg = "User registered successfully.  Please reset password before first login. "+ usrmsg
            callbk_proc_data = {
                "typ": "signup",
                "regdata": "200",
                "email" : nc_email,
                "msg": usrmsg
            }
        else:
            rec_status ="fail"
            usrmsg = "Registration failed.   Please retry.
  If problem persists, please conatact support"
            callbk_proc_data ={
                "typ": "signup",
                "regdata": "401",
                "email" : nc_email,
                "msg": usrmsg
            }

        return  rec_status, callbk_proc_data

def save_usr_details(sav_usr):
    print("inside save_usr_details function")
    s = 0
    f = None
    t = None #message to front end
    rec_status ="fail"

    con, cur, s1, f1 = db.mydbopncon()
    s, f, t = errhand.get_status(s, s1, f, f1, t, "no")
    s1, f1 = 0, None
    print("DB connection established", s,f,t)

    #validate user existence
    if s <= 0:
        command = cur.mogrify("""
                                SELECT json_agg(a) FROM (
                                SELECT userid, username, useremail, logintype
                                FROM acusr.userlogin
                                WHERE userstatus NOT IN ('I')
                                AND (
                                        userid = %s OR  useremail = %s
                                    )
                                AND entityid = %s AND countryid = %s
                                ) as a
                            """,(sav_usr["uid"],sav_usr["nc_email"],sav_usr["entityid"],sav_usr["countryid"],))
        print(command)
        cur, s1, f1 = db.mydbfunc(con,cur,command)
        s, f, t = errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None
        print('----------------')
        print(s)
        print(f)
        print('----------------')
        if s > 0:
            s, f, t = errhand.get_status(s, 200, f, "User data fetch failed with DB error", t, "no")
    print(s,f)

    if s <= 0:
        db_json_rec = cur.fetchall()[0][0]
        print(db_json_rec)

        reg_status, reg_data = allow_regis_user(db_json_rec, sav_usr)
        print(reg_status)
        print(reg_data)
        if reg_status == "fail":
            s, f, t= errhand.get_status(s, 101, f, reg_data, t, "yes")

    print(s,f)

    if s <= 0:
        s1, f1 = db.mydbbegin(con, cur)
        print(s1,f1)

        s, f, t= errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None

    if s <= 0:
        command = cur.mogrify("""
                    INSERT INTO acusr.userlogin (userid, username, useremail, logintype, userstatus, userstatlstupdt, octime, lmtime, entityid, countryid)
                    VALUES (%s,%s,%s,'I','A',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,%s,%s);
                    """,(sav_usr["uid"], sav_usr["nc_usrname"], sav_usr["nc_email"],settings.INSTALLDATA[settings.LIVE]["entityid"],settings.INSTALLDATA[settings.LIVE]["countryid"],))
        print(command)

        cur, s1, f1 = db.mydbfunc(con,cur,command)
        s, f, t= errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None
        print("end of ")
        if s > 0:
            s, f, t= errhand.get_status(s, 200, f, "SIGNUP userlogin insert failed", t, "no")

        print('userlogin Insert or update completed')

    if s <= 0:
        command = cur.mogrify("""
                    INSERT INTO acusr.linkedapps (userid, lnk_app, lnk_userid, lnk_email,  lnkstatus, octime, lmtime, entityid, countryid)
                    VALUES (%s,%s,%s,%s,'L',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,%s,%s);
                    """,(sav_usr["uid"], sav_usr["nc_entity"], sav_usr["nc_usrid"], sav_usr["nc_email"],settings.INSTALLDATA[settings.LIVE]["entityid"],settings.INSTALLDATA[settings.LIVE]["countryid"],))
        print(command)

        cur, s1, f1 = db.mydbfunc(con,cur,command)
        s, f, t= errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None

        if s > 0:
            s, f, t= errhand.get_status(s, 200, f, "SIGNUP linkedapps insert failed", t, "no")

        print('linked app Insert or update completed')

    if s <= 0:
        con.commit()
        db.mydbcloseall(con,cur)

    if s<= 0:
        rec_status = "success"
        msg = "User data saved successfully"
    else:
        rec_status = "fail"
        tt = errhand.front_end_msg if errhand.front_end_msg != None else ""
        msg = "User data save failed " + tt

    return rec_status, msg

def allow_regis_user(db_json_rec, pyld):
    print("inside allow_regis_user")
    s = 0
    f = None
    t = None #message to front end
    stat = "success"
    usrmsg = None

    if db_json_rec:
        for rec in db_json_rec:
            if rec['userid'] != '':
                if rec['userid'] == pyld["uid"]:
                    s, f, t= errhand.get_status(s, 100, f, "Userid Already exists for the Email id", t, "yes")
                    stat = "fail"

            if rec['useremail'] != '':
                if rec['useremail'] == pyld["nc_email"]:
                    s, f, t= errhand.get_status(s, 100, f, "Email Already registered", t, "yes")
                    stat = "fail"
            '''
            if stat != "fail":
                if rec['sinupadhaar'] != '':
                    if rec['sinupadhaar'] == pyld["sinupadhaar"]:
                        s, f, t= errhand.get_status(s, 100, f, "Adhaar Already registered", t, "no")

                if rec['sinuppan'] != '':
                    if rec['sinuppan'] == pyld["sinuppan"]:
                        s, f, t= errhand.get_status(s, 100, f, "PAN Already registered", t, "no")

                if rec['sinuparn'] != '':
                    if rec['sinuparn'] == pyld["sinuparn"]:
                        s, f, t= errhand.get_status(s, 100, f, "ARN Already registered", t, "no")

                if rec['sinupmobile'] != '':
                    if rec['sinupmobile'] == pyld["sinupmobile"]:
                        s, f, t= errhand.get_status(s, 100, f, "Mobile Already registered", t, "no")

                if s > 0: #incase one of the above already exists
                    if rec["usercusttype"] == pyld["usercusttype"]:
                        s, f, t= errhand.get_status(s, 100, f, "Userid Already exists with same Adhaar/PAN/ARN/MOBILE for selected cust type (ie...Resigter as)", t, "yes")
                        stat = "fail"
            '''
    else:
        print("no records satifying the current user inputs")

    print(pyld)
    print(db_json_rec)

    if stat == "fail":
        usrmsg = errhand.error_msg_reporting(s, t)

    return stat, usrmsg

def ncclbk_login_handler(pyldjson):
    print("inside ncclbk_login_handler function")
    s = 0
    f = None
    t = None #message to front end
    usrmsg = None
    rec_status ="fail"
    callback_data = pyldjson
    print("nc ncclbk_login_handler handler")
    if callback_data["regdata"] == '401':
        # show error page
        print("login handler error")
        callbk_proc_data ={
                "typ": "login",
                "regdata": "401",
                "msg": "Login failed.  Please retry.  If problem persists, please conatact support"
            }
        return "fail", callbk_proc_data
    else:
        #Get pass token from nawalcube
        data_for_passtkn = {
            "entityid" : callback_data["entityid"],
            "countryid" : callback_data["countryid"],
            "userauthtkn" : callback_data["regdata"]
        }

        status,linked_apps_lst = nc_pass_tkn(data_for_passtkn)
        if status > 0:
             s, f, t = errhand.get_status(s, 200, f, "NC pass token get failed", t, "no")

        if s <= 0:
            rec_status, callbk_proc_data = what_pg_to_show(linked_apps_lst)

        if s > 0:
            rec_status = "fail"
            callbk_proc_data = ""

    return  rec_status, callbk_proc_data

def what_pg_to_show(linked_apps_lst):
    #check if any expired pass tokens.  If yes, ask user to login
    #if no create custom token for client to login
    any_exp_tkn = chk_for_expired_tkns(linked_apps_lst)

    if any_exp_tkn == False:
        #All app has valid tokens so allowing app to login
        custom_token = get_custom_token(linked_apps_lst[0]["userid"])
        rec_status = "success"
        callbk_proc_data = {
            "type": "jwt",
            "jwt": custom_token
        }
    else:
        rec_status = "success"
        callbk_proc_data = {
            "type": "applist",
            "apps_list": linked_apps_lst
        }

    return rec_status, callbk_proc_data

def chk_for_expired_tkns(linked_apps_lst):
    #Check for any app with expired token
    print("Inside chk_for_expired_tkns")
    print(linked_apps_lst)
    any_exp_tkn = False
    for lk_app in linked_apps_lst:
        print("******************")
        print(lk_app)
        print("******************")
        if lk_app["pass_tkn_status"] != "active":
            any_exp_tkn = True

    print(any_exp_tkn)
    return any_exp_tkn

def nc_pass_tkn(callback_data):
    #get pass token from nc
    s = 0
    f = None
    t = None #message to front end
    lnkd_app_data = None
    entityid = callback_data["entityid"]
    countryid = callback_data["countryid"]

    headers = {"entityid": entityid, "countryid": countryid}
    req_payload = {
                    "userauthtkn": callback_data["userauthtkn"],
                    "appid": settings.NCAPPID[settings.LIVE],
                    "appkey":settings.NCAPPKEY[settings.LIVE],
                    "redirecturi":settings.MYREDIRURI[settings.LIVE]
                    }
    print("###########################")
    print(req_payload)
    print(type(req_payload))
    print("###########################")
    #r = requests.post(settings.NCPASSURL[settings.LIVE], headers=headers, data=json.dumps(req_payload))

    try:
        r = requests.post(settings.NCPASSURL[settings.LIVE], headers=headers, data=json.dumps(req_payload))
    except requests.exceptions.Timeout:
        print("timeout exception")
        s, f, t = errhand.get_status(s, 100, f, "Timeout error in sending request to nc", t, "yes")
        #pan_data = {"pan_name": None, "kyc_status": None}
    except requests.exceptions.RequestException as e:
        print("exception")
        print(e)
        s, f, t = errhand.get_status(s, 100, f, "error in sending request to nc", t, "yes")
    else:
        print(r.content)
        nc_usr_data = json.loads(r.content.decode("utf-8") )
        print(json.loads(r.content.decode("utf-8")))
        print('i see')
        print(type(nc_usr_data))
        nc_usr_data = json.loads(nc_usr_data)
        print(nc_usr_data)
        print(type(nc_usr_data))

    jwtdecoded = jwt.decode(nc_usr_data.get("ncjwt"), verify=False)
    print(jwtdecoded)
    ncuid = jwtdecoded["ncuserid"]
    nc_pass_tkn_exp = jwtdecoded["exp"]

    #Get acuserid from ncuserid
    con, cur, s1, f1 = db.mydbopncon()
    s, f, t = errhand.get_status(s, s1, f, f1, t, "no")
    s1, f1 = 0, None
    print("DB connection established", s,f,t)

    #get acuid from ncuid
    if s <= 0:
        command = cur.mogrify("""
                                SELECT userid
                                FROM acusr.linkedapps
                                WHERE lnkstatus = 'L'
                                AND lnk_userid = %s
                                AND entityid = %s AND countryid = %s
                            """,(ncuid,entityid,countryid,))
        print(command)
        cur, s1, f1 = db.mydbfunc(con,cur,command)
        s, f, t = errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None
        print('----------------')
        print(s)
        print(f)
        print('----------------')
        if s > 0:
            s, f, t = errhand.get_status(s, 200, f, "User data fetch failed with DB error", t, "no")
            print(s,f)

    if s <= 0:
        print("rowcount")
        print(cur.rowcount)
        print("rowcount")
        if cur.rowcount > 0:
            uid = cur.fetchall()[0][0]
            print(uid)

    print(s,f)
    print("rowcount")

    #Check for other linked apps
    linked_apps_input = {
        "acuid": uid,
        "entityid": entityid,
        "countryid": countryid,
        "pass_tkn_exp" : nc_pass_tkn_exp,
        "pass_tkn": nc_usr_data.get("ncjwt"),
        "lnk_userid": ncuid
    }
    rec_status, linked_apps_lst = get_linked_apps_nd_save(linked_apps_input)
    if rec_status > 0:
        s, f, t = errhand.get_status(s, rec_status, f, "Linked app data fetch failed with error", t, "no")
        print(s,f)

    return s, linked_apps_lst

def get_linked_apps_nd_save(linked_apps_input):
    #Get all the linked apps for a acuid
    print("inside get_linked_apps function")
    s = 0
    f = None
    t = None #message to front end
    lnkd_app_data = None

    lnk_passtkn = linked_apps_input["pass_tkn"]
    lnk_pass_exp = datetime.strptime(linked_apps_input["pass_tkn_exp"],'%d%m%Y%H%M%S%f')
    acusrid = linked_apps_input["acuid"]
    lnk_app_uid = linked_apps_input["lnk_userid"]
    entityid = linked_apps_input["entityid"]
    countryid = linked_apps_input["countryid"]

    #Get con and cur
    con, cur, s1, f1 = db.mydbopncon()
    s, f, t = errhand.get_status(s, s1, f, f1, t, "no")
    s1, f1 = 0, None
    print("DB connection established", s,f,t)

    if s <= 0:
        s1, f1 = db.mydbbegin(con, cur)
        print(s1,f1)

        s, f, t= errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None

    if s <= 0:
        command = cur.mogrify("""
                    UPDATE acusr.linkedapps SET lnk_passtkn = %s, lnk_pass_exp = %s
                    WHERE userid = %s AND lnk_userid = %s AND entityid= %s AND countryid = %s;
                    """,(lnk_passtkn, lnk_pass_exp, acusrid, lnk_app_uid, entityid, countryid,))
        print(command)
        cur, s1, f1 = db.mydbfunc(con,cur,command)
        s, f, t= errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None

        if s > 0:
            s, f, t= errhand.get_status(s, 200, f, "SIGNUP update failed", t, "no")

        print('Insert or update is successful')

    if s <= 0:
        con.commit()

    #get the linked apps for the acuid
    #Check for Token expiry of all the apps inside CASE
    if s <= 0:
        command = cur.mogrify("""
                                SELECT json_agg(a) FROM (
                                SELECT *,
                                    CASE
                                        WHEN (lnk_pass_exp < CURRENT_TIMESTAMP) THEN 'expired' ELSE 'active'
                                    END AS pass_tkn_status
                                FROM acusr.linkedapps
                                WHERE lnkstatus = 'L'
                                AND userid = %s
                                AND entityid = %s AND countryid = %s
                                ) as a
                            """,(linked_apps_input["acuid"],linked_apps_input["entityid"],linked_apps_input["countryid"],))
        print(command)
        cur, s1, f1 = db.mydbfunc(con,cur,command)
        s, f, t = errhand.get_status(s, s1, f, f1, t, "no")
        s1, f1 = 0, None
        print('----------------')
        print(s)
        print(f)
        print('----------------')
        if s > 0:
            s, f, t = errhand.get_status(s, 200, f, "User data fetch failed with DB error", t, "no")
            print(s,f)

    if s <= 0:
        print("rowcount")
        print(cur.rowcount)
        print("rowcount")
        if cur.rowcount > 0:
            lnkd_app_data = cur.fetchall()[0][0]
        else:
            lnkd_app_data = None
    print(lnkd_app_data)
    print(s,f)

    if s <= 0:
        return s, lnkd_app_data
    else:
        return s, lnkd_app_data

#def ncapp_auto_auth_processing(lnkd_app_data):
     #Check for Nawalcube app in the linked app list.
     #If present get authorise token

def get_custom_token(uid):
    print("inside get_custom_token function")
    s = 0
    f = None
    t = None #message to front end
    usrmsg = None
    rec_status ="fail"
    #create firebase custom token for users.
    #nc_usr_data
    #initialise the Firebase app
    try:
        print('inside try')
        default_app = firebase_admin.get_app('acfbapp')
        print('about inside try')
    except ValueError:
        print('inside value error')
        #cred = credentials.Certificate(os.path.dirname(__file__)+'/serviceAccountKey.json')
        cred = credentials.Certificate(settings.FBSERVICEAC)
        default_app = firebase_admin.initialize_app(credential=cred,name='acfbapp')
        s, f, t= errhand.get_status(s, 0, f, "Firebase app initialised", t, "no")
    else:
        pass

    print('app initialisation completed')

    if s <= 0:
        rec_status ="success"
        custom_token = auth.create_custom_token(uid,app=default_app)

    return custom_token.decode("utf-8")


import os
from torch.utils.data import Dataset
from transformers import BertTokenizer
import tqdm
import torch

extra = [
    "[PAD]",
    "[SEP]",
    "[CLS]",
    "[UNK]",
    "[MASK]"]

class TextDatasetHugStatic:
    max_len = None

class TextDatasetHug(Dataset):
    def __init__(self, root, split, src, tgt, vocab_share=False, max_len=80, **kwargs):
        self.root = root
        self.split = split
        self.samples = self.make_samples(root, split, src, tgt)
        src_vocab_file = os.path.join(self.root, 'vocab_src.txt')
        tgt_vocab_file = os.path.join(self.root, 'vocab_tgt.txt')

        if split == 'train':
            src_vocab = self.get_vocab(map(lambda x: x[0], self.samples))
            tgt_vocab = self.get_vocab(map(lambda x: x[1], self.samples))

            open(src_vocab_file, "w").write("\n".join(str(word) for word in extra + src_vocab))
            open(tgt_vocab_file, "w").write("\n".join(str(word) for word in extra + tgt_vocab))

            TextDatasetHugStatic.max_len = max_len
            self.src_len, self.tgt_len = max_len, 999

            print("Vocab(#vocab={}, #extra={}, src_train_len={})".format(len(src_vocab), len(extra), self.src_len))
            print("Vocab(#vocab={}, #extra={}, tgt_train_len_len={})".format(len(tgt_vocab), len(extra), self.tgt_len))

        else:
            self.src_len, self.tgt_len = TextDatasetHugStatic.max_len, 999

        self.src_tokenizer = BertTokenizer(vocab_file=src_vocab_file, do_basic_tokenize=False)
        self.tgt_tokenizer = BertTokenizer(vocab_file=tgt_vocab_file, do_basic_tokenize=False)

        # self.processed_samples = []
        # for idx in tqdm.tqdm(range(len(self.samples))):
        #     src, tgt = self.samples[idx]
        #     self.processed_samples.append((self.src_tokenizer(' '.join(src)), self.tgt_tokenizer(' '.join(tgt))))

    def __getitem__(self, index):
        # src, tgt = self.processed_samples[index]
        # print(self.samples[index])
        src, tgt = self.samples[index]
        return {
            'src': src,
            'tgt': tgt,
        }

    def get_collate_fn(self):
        def collate_fn(batch):
            # src = self.src_tokenizer([s['src'] for s in batch], padding=True, truncation=True, return_tensors="pt",
            #                          max_length=self.src_len)
            # tgt = self.tgt_tokenizer([s['tgt'] for s in batch], padding=True, truncation=True, return_tensors="pt",
            #                          max_length=self.tgt_len)
            # v = batch[0]["tgt"]
            # print(len(v))
            # print(v)
            src = self.src_tokenizer([s['src'] for s in batch], padding=True, return_tensors="pt")
            tgt = self.tgt_tokenizer([s['tgt'] for s in batch], padding=True, return_tensors="pt")
            # print(src)
            # print(tgt)
            # sys.exit()
            # print("####")
            # print(tgt["input_ids"].shape)
            # print(tgt["input_ids"][0])
            # print(len(tgt["input_ids"][0]))
            # print(self.tgt_tokenizer.decode(tgt["input_ids"][0], skip_special_tokens=False, clean_up_tokenization_spaces=False))
            collated = {'input_ids': src.input_ids,
                        'attention_mask': src.attention_mask,
                        'decoder_input_ids': tgt.input_ids,
                        'decoder_attention_mask': tgt.attention_mask}

            return collated

        return collate_fn

    def make_samples(self, root, split, src, tgt):
        src = self.load_file(os.path.join(root, split + '.' + src))
        tgt = self.load_file(os.path.join(root, split + '.' + tgt))
        return list(zip(src, tgt))

    def load_file(self, path):
        """Default loading function, which loads nth sentence at line n.
        """
        with open(path, 'r') as f:
            content = f.read().strip()
        return [s.strip() for s in content.split('\n')]

    def get_vocab(self, sentences):
        vocab = []
        for sentence in sentences:
            vocab += sentence.split()
        return sorted(set(vocab))

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


nome = input('Digite seu nome completo: ')
nome_splitado = nome.lower().split()
tem_silva = False
for i in range(len(nome_splitado)):
    if (nome_splitado[i] == "silva"):
        tem_silva = True
        break
    i = i + 1

if (tem_silva == True) :
    print('Que legal, você tem "Silva" em seu nome!')
else:
    print('Verifiquei e você não tem "Silva" em seu nome! Era só curiosidade mesmo :SMILES:')


import copy
import re

data = [(lambda a,b : [a, b])(*re.findall('\+?\-?\w+', line)) for line in open('input.txt').readlines() ]

def compute(x):
  lineOp = 0
  lineCount = []
  accumulator = 0

  while lineOp not in lineCount:
    instruction = x[lineOp][0]
    lineCount.append(lineOp)
    if instruction == 'acc':
      accumulator += int(x[lineOp][1])
      lineOp += 1
    elif instruction == 'jmp':
      lineOp += int(x[lineOp][1])
    elif instruction == 'nop':
      lineOp += 1

    if lineOp == len(x):
      print('Last instruction before exit.')
      return True, accumulator

  return False, accumulator

lenData = len(data)
success = False
value = 0
for i in range(lenData):
  td = copy.deepcopy(data)
  if td[i][0] == 'nop':
    td[i][0] = 'jmp'
    success, value = compute(td)
  elif td[i][0] == 'jmp':
    td[i][0] = 'nop'
    success, value = compute(td)
  else:
    success, value = compute(td)

  if success:
    break

print(value)


functions = {
            'amax': 'AMAX',
            'bar': 'BAR',
            'bar_sum': 'BAR_SUM',
            'hist': 'HIST',
            'donut': 'DONUT',
            'amin': 'AMIN',
            'med_for': 'MED_FOR',
            'avg': 'AVG',
            'avg_for': 'AVG_FOR',
            'sum': 'SUM',
            'occur': 'OCCUR',
            'scatter': 'SCATTER',
            'scatter_group': 'SCATTER_GROUP',
            'line_multi': 'LINE_MULTI',
            'line': 'LINE'
        }


# 백준 2164번
import sys

N = int(sys.stdin.readline())
q = [i for i in range(1, N + 1)]

f = 0
b = N-1

while f != b:
    q.append(q[f+1])
    f += 2
    b += 1

print(q[f])


##Lecture 6
##09/21/2022
#object types
# int: short for integer, a whole number of unlimited size
# float: floating point number
# str: short of string
# function

def f():
    return 42

code = 180
"ESC" + str(code)
"ESC" + "code"

str(3.14)

print("ESC", 180, "H1")
print("ESC", 180, "H1", sep = "!!!")

#########################################3

float(4)
int(4.0)

int(4.7) # truncation: throwing away the fractional part
int(-4.7)

# if the float is positive, can use the following
# to round it:
a = 4.7
int(a + 0.5)

float("3.14")
int("5")
#int("3.14")

##naming conventions

# legal identifier name: anything that starts with a letter
# or an underscore _ and is composed of letters, digits
# and underscores

_asdfasdfasdfasdfsadf = 5 # legal

# pothole/snake case

num_courses_engsci = 6 # moral way of naming variable

## return statements

# f(x) = x^2
def f(x):
    return 42
    print("hi")
    return x**2

def artsie_math(arg1, arg2, op):
    '''Return arg1 <op> arg2 if op is "+" or "-",
    print an error message otherwise'''
    if op == "+":
        return arg1 + arg2
    elif op == "-":
        return arg1 - arg2
    else:
        print("This is too difficult for me :(")

def artsie_math2(arg1, arg2, op):
    if op != "+" and op != "-":
        print("This is too difficult for me :(")
        return

    if op == "+":
        return arg1 + arg2
    elif opreturn == "-":
        return arg1 - arg2

if __name__ == '__main__':
    # a = f(5)
    # print(a)

    res = artsie_math (3, 2, "+") # res: 5
    res = artsie_math(3, 2, "*") # prints an error message

    if res == None:
        print("artscis screwed up")
    else:
        print(res)


from django.shortcuts import render
from . import forms
# Create your views here.
'''
def studentinputview(request):
    form=forms.StudentForm()
    my_dict={'form':form}
    return render(request,'formApp/input.html',context=my_dict)
'''
def studentinputview(request):
    form=forms.StudentForm()
    if request.method=='POST':
        form=forms.StudentForm(request.POST)
        if form.is_valid():
            print('Form validation success and printing data')
            print('Name:',form.cleaned_data['name'])
            print('Marks:',form.cleaned_data['marks'])
    return render(request,'formApp/input.html',{'form':form})


#!/usr/local/bin/python3

""" manipulating strings
 upper() - string property that makes all letters uppercase
 lower() - string property that makes all letters lowercase
 split() - string property that returns a list of strings separated by argument
 strip() - by default remotes white spaces from begining and end.
             look at lstrip and rstrip and arguments
"""

" letters ".upper()
" LeTteRs ".lower()
"a|delimited|string".split('|')
" a string with spaces   ".strip()

""" reading files
 with - creates a "context". keeps the file open while executing code "chunk"
 this is the idiomatic way, python is very idiomatic
"""

with open('filename.txt', 'r') as fh:
    line = fh.readline()
    while line:
        if not line:
            break
        data = line.split(',')
        print(data[0])
        line = fh.readline()

""" reading files
 the less idiomatic way
 just an example of an alternative way, also to demonstrate why
"""
fh = open('filename.txt', 'r')
for line in fh.readlines():
    data = line.split(',')
    print(data[1])
fh.close()


"""
Problem:
----------
https://animemusicquiz.com/
Given target song T try to identify it from a database of songs D
Abstraction: song is a list of ints (less of an abstraction and more of a fact)

suppose you have an array A of ints of size N
and an array B of size M where M >= N

find the offset i (0 <= i <= M - N)
such that it minimizes \sum^{N - 1}_{j = 0} |A_j - B_{j + i}|
(intuitively, the sum of pointwise differences between the waveform of the songs)
----------
observation #1:
this seems like a two pointer/sliding window problem
(compute the value for a certain window at start, end then compute the delta
for the shifted window start + 1, end + 1)

observation #2:
change |x - y| to (x - y)^2 because the latter is easier to work with
expanding yields x^2 - 2xy + y^2

tracking over the window shifts (s, e) -> (s + 1, e + 1):
sum of x^2 doesn't change  (dx^2 = 0)
sum of y^2 should increase from the new element and decrease from losing the start
(dy^2 = y_{e + 1} - y{s})
how does -2xy change??

observation #3:
this seems very similar to the discrete convolution:
https://en.wikipedia.org/wiki/Convolution
Discrete convolution equal to polynomial multiplication
Calculated in n log n (n = degree of the polynomial) via FFT

construct a polynomial from A
P1(x) = A_0 + A_1 x + A_2 x^2 + ... + A_N x^N

construct a polynomial from B (IN REVERSE)
P2(x) = B_M + B_{M - 1} x + ... + B_0 x^M

why? when computing P1*P2, we're going to look at the coefficients of the polynomial
the coefficients are determined by the degree of the term they're attached to,
e.g. if we constructed P2 like P1 it would look like:
P1*P2 = (A_0 B_0) + (A_0 B_1 + A_1 B_0) x + (A_0 B_2 + A_1 B_1 + A_2 B_0) x^2
for a A_i B_j term, it's attached to x^{i + j} (obviously)
what we WANT is
A_0 B_0 + A_1 B_1 + A_2 B_2
A_0 B_1 + A_1 B_2 + A_2 B_3
A_0 B_2 + A_1 B_3 + A_2 B_4
...
what we HAVE is when i increases, j DECREASES
thus if we reverse the polynomial, j increases as i increases, in line
we can just discard the first N - 1 and the last N - 1 terms,
and read the dot products (the xy we're trying to compute) straight off the coefficients
----------
Example #1:

A = 1 3 2
B = 2 1 4 3 5 2

i = 0: [1, 3, 2]*[2, 1, 4] = 13
i = 1: [1, 3, 2]*[1, 4, 3] = 19
i = 2: [1, 3, 2]*[4, 3, 5] = 23
i = 3: [1, 3, 2]*[3, 5, 2] = 22

compute (1 + 3x + 2x^2)(2 + 5x + 3x^2 + 4x^3 + x^4 + 2x^5)
= 4x^7 + 8x^6 + 13x^5 + 19x^4 + 23x^3 + 22x^2 + 11x + 2
disregarding the last 2 and first 2 terms (they're "incomplete")
= 13x^5 + 19x^4 + 23x^3 + 22x^2 = [13 19 23 22]
----------
What about volume?
Suppose the target song is softer or louder than the songs in our database
abstract away our previous stuff as f(x) - what we computed before was
x = 0, aka no volume changes to the target song
if x = 5, think of that as adding 5 to each number in the target song
and recomputing out DFT

Assume the function is convex (questionable) and treat it as 1D convex min
https://ljk.imag.fr/membres/Anatoli.Iouditski/cours/convex/chapitre_22.pdf
1D convex function optimization - runs in O(log(V/epsilon))
where V is the maximum value of f and epsilon is the wanted precision
V ~= 2^16, epsilon = 1
"""
import subprocess
from amqlib import PATH
from .fft import fft

PATH = PATH[0]

def load_arrays(fname: str) -> tuple:
    """ Gets arrays from a file. """
    with open(fname) as f:
        f.readline()
        l1 = list(map(int, f.readline().split()))
        f.readline()
        return l1, list(map(int, f.readline().split()))

def save_arrays(fname: str, l1: list, l2: list) -> None:
    """ Dumps arrays to a file. """
    with open(fname, "w") as f:
        f.write(str(len(l1)) + "\n")
        f.write(" ".join(map(str, l1)) + "\n")
        f.write(str(len(l2)) + "\n")
        f.write(" ".join(map(str, l2)) + "\n")

def min_offset(a: list, b: list) -> tuple:
    """ Computes the offset that minimizes the l2 norm. """
    N, M = len(a), len(b)
    p = fft(a[::-1], b)[N - 1:]
    x2, xy, y2 = sum(x*x for x in a), p[0], sum(b[i]*b[i] for i in range(N))
    best, l2 = 0, -2*xy + y2
    for i in range(1, M - N + 1):
        y2 += b[N - 1 + i]*b[N - 1 + i] - b[i - 1]*b[i - 1]
        xy = p[i]
        d = -2*xy + y2
        if d < l2:
            best, l2 = i, d
    return best, x2 + l2

def max_cosine(a: list, b: list) -> tuple:
    """ Computes the offset that maximizes the cosine similarity. """
    N, M = len(a), len(b)
    p = fft(a[::-1], b)[N - 1:]
    x2, xy, y2 = sum(x*x for x in a), p[0], sum(b[i]*b[i] for i in range(N))
    best, cos = 0, xy/y2
    for i in range(1, M - N + 1):
        y2 += b[N - 1 + i]*b[N - 1 + i] - b[i - 1]*b[i - 1]
        xy = p[i]
        d = xy/y2
        if d > cos:
            best, cos = i, d
    return best, 1 - cos/x2 # loss means lower is better

def solve(a: list, b: list) -> tuple:
    """ Same thing as min_offset, but with a cpp executable. """
    save_arrays(f"{PATH}/song.in", a, b)
    subprocess.call(["./a.out"], cwd=PATH)
    with open(f"{PATH}/song.out") as f:
        return tuple(map(int, f.readline().split()))

def loss_func(a, b):
    return lambda v: solve((v*a).astype(int), b)[-1]

def one_d_min(f, a, d, epsilon=10**-2):
    while abs(a - d) > epsilon:
        t = (d - a)/3
        b = a + t
        c = a + 2*t
        if f(b) < f(c):
            a, d = a, c
        else:
            a, d = b, d
    return (a + d)/2

if __name__ == "__main__":
    a, b = load_arrays("song.in")
    # print(min_offset(a, b))
    print(solve(a, b))


import datetime

from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, redirect

import diploms
from diploms.models import Message, Comment, Vacansia, City, Interview, News
from diploms.forms import CommentForm, InterviewForm, MessageForm  # , VacansiaForm
from django.contrib import messages as mes

# Create your views here.
def index(request):
    news = News.objects.order_by("date_published")[:3]
    context = {'news': news}
    return render(request, 'diploms/index.html', context)

def about(request):
    comments = Comment.objects.order_by('-date_added')
    for comment in comments:
        if compare_owner_user(comment.owner, request.user):
            comment.is_editing = True
        else:
            comment.is_editing = False
    if request.method != 'POST':
        form = CommentForm()
    else:
        form = CommentForm(data=request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.owner = request.user
            new_comment.save()
            return redirect('about')

    context = {
        'form': form,
        'comments': comments,
    }
    return render(request, 'diploms/about.html', context)

def partner(request):
    return render(request, 'diploms/partner.html')

def connect(request):
    return render(request, 'diploms/connect.html')

@login_required
def messages(request):
    messages = Message.objects.filter(owner=request.user)
    context = {'messages': messages}
    return render(request, 'diploms/messages.html', context)

def compare_owner_user(owner, user):
    if owner == user:
        return True
    else:
        return False

@login_required
def delete(request, comment_id):
    comment = Comment.objects.get(id=comment_id)
    if not compare_owner_user(comment.owner, request.user):
        raise Http404
    comment.delete()
    mes.success(request, 'Ваш комментарий был успешно удален!')
    return redirect('about')

@login_required
def edit(request, comment_id):
    comment = Comment.objects.get(id=comment_id)
    if not compare_owner_user(comment.owner, request.user):
        raise Http404
    if request.method != 'POST':
        form = CommentForm(instance=comment)
    else:
        form = CommentForm(instance=comment, data=request.POST)
        if form.is_valid():
            form.save()
            mes.success(request, 'Комментарий успешно изменен.')
            return redirect('about')
    context = {
        'comment': comment,
        'form': form,
    }
    return render(request, 'diploms/edit.html', context)

def vacansies(request):
    if request.POST.get('city') and request.POST.get('city') != 'Любой':
        city_name = request.POST.get('city')
        try:
            picked_city = City.objects.get(city=city_name)
            vacs = Vacansia.objects.filter(is_active=True, city=picked_city)
        except diploms.models.City.DoesNotExist:
            vacs = None

    else:
        vacs = Vacansia.objects.filter(is_active=True)

    cities = City.objects.all()
    context = {
        'vacs': vacs,
        'cities': cities,

    }
    return render(request, 'diploms/vacansies.html', context)

@login_required
def vacansia(request, vacansia_id):
    vacansia_h = Vacansia.objects.get(id=vacansia_id)
    form = InterviewForm()

    available_times = [datetime.time(i, 0, 0).isoformat(timespec='minutes') for i in range(9, 16)]
    context = {
        'today': str(datetime.datetime.date(datetime.datetime.today() + datetime.timedelta(1))),
        'max_date': str(datetime.datetime.date(datetime.datetime.today() + datetime.timedelta(8))),
        'available_times': available_times,
        'vacansia': vacansia_h,
        'form': form,
    }
    if request.method == 'POST':
        if Interview.objects.filter(date=request.POST.get('date'), time=request.POST.get('time')):
            mes.error(request, 'Выбранное время уже занято!Выберите другое время!')
            return render(request, 'diploms/vacansia.html', context)
        else:
            form = InterviewForm(data=request.POST)
            if form.is_valid():
                new_сandidate = form.save(commit=False)
                new_сandidate.сandidate = request.user
                new_сandidate.save()
                mes.success(request, 'Запись на собеседование прошла успешно.Ожидайте звонка.')
                return render(request, 'diploms/vacansia.html', context)
    return render(request, 'diploms/vacansia.html', context)

def news(request):
    newsSet = News.objects.order_by("date_published")
    context = {'news': newsSet}
    return render(request, 'diploms/news.html', context)

def new(request, new_id):
    new = News.objects.get(id=new_id)
    context = {'new': new}
    return render(request, 'diploms/new.html', context)

@login_required
def support(request):
    if request.method != 'POST':
        form = MessageForm()
    else:
        form = MessageForm(request.POST,request.FILES)
        if form.is_valid():
            new_mes = form.save(commit=False)
            new_mes.owner = request.user

            new_mes.save()
            mes.success(request,'Ваше обращение успешно отправлено')
            return redirect('support')
    context = {
        'form': form
    }
    return render(request, 'diploms/support.html', context)


import time
import json
from decimal import Decimal
from datetime import datetime

from sqlobject import DecimalCol, SQLObject
from sqlobject.col import pushKey

import beerlog

class JSONable(object):
    """ Mixin for SQLObject classes. Allows you to export the object
    as a JSON or dict representation, controlling the data returned
    from the call.

    You can either provide a list that enumerates the fields that
    are visible (meaning that all not listed are hidden) or enumerating
    fields that are hidden (meaning that all not listed are visible)

    ex:
        private = ['password', 'last_login']

    would mean all fields that AREN'T password or last_login will be in the
    json representation

        exports = ['email', 'first_name', 'last_name']

    would mean all that all fields that AREN'T email, first_name nor last_name
    will be hidden from the json respresetation

    TODO: set up roles and allow views specific to users with a specified role

    """

    def dict(self, view=None):
        return_dict = {}
        cls = type(self)
        props = [p for p in vars(cls) if isinstance(getattr(cls, p), property)]
        columns = type(self).sqlmeta.columns
        for prop in props:
            if hasattr(self, 'no_recurse'):
                no_recurse = self.no_recurse
            else:
                no_recurse = []
            if prop not in no_recurse:
                attr = getattr(self, prop)
                try:
                    # this means it's not a piece of derrived data nor is it a
                    # related object
                    column = columns[prop]
                except KeyError:
                    # this means it's a related object or a piece of derrived data
                    # if it's derrived data, we'll worry about it then, if it's
                    # a related object, we'll use it's `dict` method. if it's a list
                    # we'll iterate over the items and use their `dict` methods
                    if isinstance(attr, list):
                        value = [o.dict() for o in attr]
                    elif SQLObject in type(attr).__bases__ and hasattr(attr, "dict"):
                        value = attr.dict()
                    else:
                        value = attr
                else:
                    try:
                        c_type = column.type
                    except AttributeError:
                        value = None
                    else:
                        # this is just plain old data to convert.  we only care about
                        # the datatypes that `json.dumps` can't convert itself
                        if c_type == 'datetime':
                            value = time.mktime(attr.timetuple())*1000
                        elif c_type == 'sqlobject' and hasattr(attr, "dict"):
                            value = attr.dict()
                        elif c_type == 'decimal':
                            value = float(attr)
                        else:
                            value = attr
                if value:
                    return_dict[prop] = value
        return return_dict

    def json(self, view=None):
        return json.dumps(self.dict(view))

class SGCol(DecimalCol):
    """ Stores Specific Gravity in a decimal column
    Size is fixed at 4, and the precision is set to 3

    ex: 1.045

    """

    def __init__(self, **kw):
        pushKey(kw, 'size', 4)
        pushKey(kw, 'precision', 3)
        super(DecimalCol, self).__init__(**kw)

class PercentCol(DecimalCol):
    """Stores percentages in a decimal column
    Size is fixed at 5, and the precision is set to 2.

    *nb* size is fixed at 5 to allow for 100.00%

    """

    def __init__(self, **kw):
        pushKey(kw, 'size', 5)
        pushKey(kw, 'precision', 2)
        super(DecimalCol, self).__init__(**kw)

class SRMCol(DecimalCol):
    """ Stores the Standard Reference Method color value in a decimal column
    Size is fixed at 5, precision is set to 1

    ex: 2.0, 300.5

    """

    def __init__(self, **kw):
        pushKey(kw, 'size', 5)
        pushKey(kw, 'precision', 1)
        super(DecimalCol, self).__init__(**kw)

class IBUCol(DecimalCol):
    """ Stores the International Bitterness Units value in a decimal column
    Size is fixed at 4, precision is set to 1

    ex: 2.0, 300.5

    """

    def __init__(self, **kw):
        pushKey(kw, 'size', 4)
        pushKey(kw, 'precision', 1)
        super(DecimalCol, self).__init__(**kw)

class BatchIsNotMaster(Exception):
    def __init__(self,value):
        self.value = value
    def __unicode__(self,value):
        return repr(self.value)

class AmountSetError(Exception):
    def __init__(self, value):
        self.value = value
    def __unicode__(self, value):
        return repr(self.value)


import csv
import itertools
import pandas as pd
#from __future__ import division
#from sklearn.metrics.scorer import _PredictScorer
from math import floor,ceil

import numpy as np

from Demo import ReadFile

class ReadFile:

    def __init__(self):
        self.Data=[]
        self.dataDictionary={}
        self.TrainSample=118
        self.TestSample=28
        self.dictPredicted={}

    def UpdateFile(self):
        r=ReadFile()
        dict=r.FileRead('product_distribution_training_set.txt')
        plist=r.fileReadNormal('key_product_IDs.txt')
        plist.sort()
        tempList=[]
        for x in plist:
            if x!=0:
                tempList.append(dict[x])
        Overall=[sum(i) for i in zip(*tempList)]
        f=open('product_distribution_training_set.txt','a+')
        strngs=''
        for x in Overall:
            strngs=strngs+" "+str(x)
        strngs="0"+" "+strngs
        f.write("\n"+strngs)
        f.close()
        f = open('key_product_IDs.txt', 'a+')
        f.write('\n0')
        f.close()

    def FileRead(self,filename):
        for line in open(filename,'r'):
            self.Data.append(line.strip())

        for data in range(len(self.Data)):
            temp_str=str(self.Data[data].strip())
            temp_result=temp_str.split()
            self.dataDictionary[int(temp_result[0])]=list(map(int,temp_result[1:]))

        return self.dataDictionary

    def fileReadNormal(self,filename):
        self.Data=[]
        for line in open(filename,'r'):
            self.Data.append(line.strip())

        list1=list(map(int,self.Data))
        return list1

    def CalculateValueAB(self):
        r=ReadFile()
        prodQuantity=r.FileRead('product_distribution_training_set.txt')
        Products = r.fileReadNormal('key_product_IDs.txt')
        Products.sort()
        DictCoef = {}
        for prod in prodQuantity:
            PList = prodQuantity[prod]
            Y=PList[2:]
            X1=PList[1:len(PList)-1]
            X2=PList[:len(PList)-2]
            X1Y=[a*b for a,b in zip(X1,Y)]
            X2Y = [a * b for a, b in zip(X2, Y)]
            X1X2=[a*b for a,b in zip(X1,X2)]
            X1X1 = [a * b for a, b in zip(X1, X1)]
            X2X2 = [a * b for a, b in zip(X1, X2)]
            YY=[a*b for a,b in zip(Y,Y)]
            SumX1Y=sum(X1Y)
            sumX2Y=sum(X2Y)
            sumX1X2=sum(X1X2)
            sumX1X1=sum(X1X1)
            summX2X2=sum(X2X2)
            sumX1=sum(X1)
            sumX2=sum(X2)
            sumY=sum(Y)
            sumYY=sum(YY)
            y=max(Y)
            sumx1y=r.CalculateProducts(len(Y),sumX1,sumY,SumX1Y)

            sumx2y=r.CalculateProducts(len(Y),sumX2,sumY,sumX2Y)
            sumx1x2=r.CalculateProducts(len(Y),sumX1,sumX2,sumX1X2)
            sumyy=r.CalculateProducts(len(Y),sumY,sumY,sumYY)
            sumx1x1=r.CalculateProducts(len(Y),sumX1,sumX1,sumX1X1)
            sumx2x2=r.CalculateProducts(len(Y),sumX2,sumX2,summX2X2)

            B1=((sumx2x2*sumx1y)-(sumx1x2*sumx2y))/(((sumx1x1*sumx2x2)-(sumx1x2*sumx1x2)))
            B2=((sumx1x1*sumx2y)-(sumx1x2*sumx1y))/(((sumx1x1*sumx2x2)-(sumx1x2*sumx1x2)))
            Ybar=sum(Y)/(len(Y)*1.0)
            X1bar = sum(X1) / (len(X1) * 1.0)
            X2bar=sum(X2)/(len(X2)*1.0)
            A=Ybar-(B1*X1bar)-(B2*X2bar)
            coefficient=str(A)+","+str(B1)+","+str(B2)
            YPredict=[]
            for i in range(1,len(Y)):
                Yd=A+B1*X1[i]+B2*X2[i]
                if(Yd<0):
                    Yd=0
                YPredict.append(int(np.rint(abs(Yd%y))))

            DictCoef[prod]=coefficient;
            self.dictPredicted[prod]=YPredict

        return DictCoef

    def CalculateProducts(self,N,sumx1,sumy1,sumX1Y1):
        div=(sumx1*sumy1)/(N*1.0)
        finals=sumX1Y1-(div)
        return finals

    def predict(self):
        r=ReadFile()
        wieghtdict=r.CalculateValueAB()
        predictedValues={}
        prodQuantity = r.FileRead('product_distribution_training_set.txt')
        Products=r.fileReadNormal('key_product_IDs.txt')
        Products.sort()
        for x in Products:
            TempList=[]
            listAB=wieghtdict[x].split(',')
            PList = prodQuantity[x]
            Y = PList[2:]
            A=float(listAB[0])
            B1=float(listAB[1])

            B2=float(listAB[2])
            y=max(Y)
            for i in range(1,29,1):
                Yd=A+B1*Y[-1]+B2*Y[-2]
                Y.append(int(np.rint(abs(Yd%y))))
            predictedValues[x]=Y[116:]

            f = open("ARoutput.txt", "w+")
        for x in Products:
            sr=''
            lis = predictedValues[x]
            for y in lis:
                sr=sr+" "+str(y)
            f.write(str(x)+" "+sr+"\n")
        f.close()
        return predictedValues

r=ReadFile()
f=r.UpdateFile()
h=r.CalculateValueAB()
hh=r.predict()
print(hh)

Product Sales Prediction/Product Sales Prediction/DataMiningProject.py


import numpy as np
import pandas as pd
import time
from sklearn.linear_model import LogisticRegression
from save_grid_search_results import save_grid_search_results
import joblib

def log_regression(X_train, y_train, X_test, y_test, metrics=['accuracy'], class_weight=None, save_model = False, predict_rating=True, using_tfidf=True):

    #class weights
    class_weight = None if not class_weight else 'balanced'
    weighted = 'False' if not class_weight else 'True'
    predict = 'rating' if predict_rating else 'category'

    #create model and fit
    model = LogisticRegression(C=1e5, tol=1e-5, solver='liblinear', multi_class = 'ovr',\
                            random_state=3, max_iter=1000, class_weight=class_weight)
    model.fit(X_train,y_train)
    #evaluate the model
    accuracy = model.score(X_test, y_test)

    #save model and results
    path = r'./grid_search_results/' if using_tfidf else r'./doc2vec_grid_search_results/'
    file_name = ''
    if save_model:
        file_name = str(int(time.time())) + '.pkl'
        joblib.dump(model, path + file_name)
    results = save_grid_search_results(path, dict(file_name=file_name, predict=predict, predictor_type='log_regression', weighted=weighted, accuracy=accuracy))

    return results


# -*- coding: utf-8 -*-
import urllib.parse
from Common.Db import Db
from scrapy import Selector
from Config.Config import RUNTIME_DIR
from scrapy_redis.spiders import RedisSpider
from FirstChapter.FirstChapterItems import FirstChapterLoader
#从redis待采集链接队列中获取链接并采集
class FirstChapterspider(RedisSpider):
    name = 'fcSpider'
    redis_key = 'fcSpider_urls'
    currKey = 1
    workerFileName = 'fc_worker.txt'

    def __init__(self, *args, **kwargs):
        domain = kwargs.pop('domain', '')
        self.allowed_domains = filter(None, domain.split(','))
        super(FirstChapterspider, self).__init__(*args, **kwargs)

    def parse(self, response):
        #记录检测爬虫状态
        self.writeCurrNum()
        el = FirstChapterLoader(response=response)
        #根据链接域名查询数据库中的对应规则信息
        db = Db()
        sql = "SELECT * from zs_mirror WHERE m_domain='%s'" % self.extractDomainFromURL(response.url)
        row = db.query(sql, 'one')
        db.close()
        if row:
            #采集获取书籍章节等数据
            return self.contactItemInfo(response,row,el)

    # 获取Url中的域名
    def extractDomainFromURL(self, url):
        parsed_uri = urllib.parse.urlparse(url)
        domain = '{uri.netloc}'.format(uri=parsed_uri)
        return domain

    def contactItemInfo(self,response,row,el):
        # 检查书名是否正确
        bookName = self.getBookName(response, row['m_cp_title_rule'])
        if bookName != False:
            db = Db()
            sql = "SELECT id from zs_book where b_name='%s'" % bookName
            find = db.query(sql, 'one')
            db.close()
            if find:
                el = self.getItemInfo(response, row,el)
                if el != None:
                    el.add_value('b_id', str(find['id']))
                    return el.load_item()

    #根据数据库中配置的规则获取书籍名称
    def getBookName(self,response,tags):
         selector = Selector(response)
         try:
             path = selector.xpath(tags)
             if path:
                 bookName = path.xpath('./text()').extract_first('').strip()
                 if bookName != '':
                     return bookName
         except Exception:
             return False
         return False

    #获取源站数据与最新章节信息
    def getItemInfo(self,response,row,el):
        # 获取书籍对应源站链接标识
        bookInfoPath = ((urllib.parse.urlparse(response.url)).path).strip('/')
        if row['m_cp_last_rule'] != '':
            # 获取书籍最新章节信息
            lastChapter = self.getLastChapter(response, row['m_cp_last_rule'])
            if lastChapter:
                el.add_value('m_id',str(row['id']))
                el.add_value('m_name',row['m_name'] + '(' + row['m_domain'] + ')')
                el.add_value('b_no',bookInfoPath)
                el.add_value('last_title',lastChapter['title'])
                el.add_value('last_url',lastChapter['url'])
                return el

    #获取最新章节信息
    def getLastChapter(self,response,tags):
        lastChapter = Selector(response).xpath(tags)
        lastInfo = {}
        lastInfo['title'] = lastChapter.xpath('./text()').extract_first('').strip()
        lastInfo['url'] = lastChapter.xpath('.//@href').extract_first('').strip()
        if lastInfo['title'] != '' and lastInfo['url'] != '' :
            return lastInfo

    def writeCurrNum(self):
        self.currKey = self.currKey+1
        file = open(RUNTIME_DIR+self.workerFileName, 'w')
        file.write(str(self.currKey))
        file.close()


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

"""
This module handles custom testing library generating.
"""

from robot.libdoc import libdoc
from robot.testdoc import testdoc

from sqa_engine.utilities.workspace_vars import inter_path
from sqa_engine.utilities.test_cases_management.test_suite_retriever import\
    get_module_children

def generate_docs(test_module: str, test_design: str) -> None:
    """Generate documentation.

    This function uses robot libdoc and robot testdoc to generates
    documentation of custom keyword library and test cases documentations,
    base on module and test domain.

    Parameters
    ----------
    test_module : str
        Test module {mobile_app, web_portal, rest_api}
    test_design : str
        Test domain specification

    Returns
    -------
    None
    """
    packages = get_module_children(module_name=test_module)
    test_suite = f'{packages["test_design"]}/{test_design}'
    robot_file = f'{test_suite}/{test_design}.robot'
    keywords_file = f'{packages["lib"]}/common_keywords.py'

    doc_out_file = f'{inter_path().current_doc_folder}/\
{test_design}_document.html'
    lib_out_file = f'{inter_path().current_doc_folder}/keywords_document.html'

    libdoc(library_or_resource=keywords_file, outfile=lib_out_file,
           name='', version='', format=None, docformat='HTML')
    testdoc(robot_file, doc_out_file, title='',
            name='', version='', format=None, docformat='HTML')
    return


"""Services for the Pod Point integration."""
from typing import List

from homeassistant.core import HomeAssistant, ServiceCall
import homeassistant.helpers.config_validation as cv
from podpointclient.client import PodPointClient
from podpointclient.pod import Pod
import voluptuous as vol

from .const import (
    ATTR_CONFIG_ENTRY_ID,
    ATTR_HOURS,
    ATTR_MINUTES,
    ATTR_SECONDS,
    DOMAIN,
    SERVICE_CHARGE_NOW,
)
from .coordinator import PodPointDataUpdateCoordinator

class PodPointServiceException(Exception):
    """Exception for Pod Point services."""

async def async_register_services(hass: HomeAssistant) -> None:
    """Register services for the Pod Point integration, if not registered yet."""

    if hass.services.has_service(DOMAIN, SERVICE_CHARGE_NOW):
        return

    async def async_charge_now_service(call: ServiceCall):
        coordinator = await get_coordinator(hass, call.data[ATTR_CONFIG_ENTRY_ID])
        await handle_charge_now(hass, coordinator, call)

    hass.services.async_register(
        DOMAIN,
        SERVICE_CHARGE_NOW,
        async_charge_now_service,
        schema=vol.Schema(
            {
                vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
                vol.Optional(ATTR_HOURS): vol.All(vol.Coerce(int), vol.Range(min=0,max=24)),
                vol.Optional(ATTR_MINUTES): vol.All(vol.Coerce(int), vol.Range(min=0,max=59)),
                vol.Optional(ATTR_SECONDS): vol.All(vol.Coerce(int), vol.Range(min=0,max=59))
            }
        ),
    )

async def async_deregister_services(hass: HomeAssistant) -> None:
    """Deregister services for the Pod Point integration"""

    hass.services.async_remove(
        DOMAIN,
        SERVICE_CHARGE_NOW
    )

async def get_coordinator(hass: HomeAssistant, config_entry_id: str) -> PodPointDataUpdateCoordinator:
    """Get the right Pod Point Data Coordinator based on the device id, else get the default one."""
    if config_entry_id not in hass.data[DOMAIN]:
        raise ValueError(f"Config entry with id {config_entry_id} not found!")

    coordinator: PodPointDataUpdateCoordinator = hass.data[DOMAIN][config_entry_id]
    return coordinator

async def handle_charge_now(
    hass: HomeAssistant, coordinator: PodPointDataUpdateCoordinator, call: ServiceCall
) -> None:
    """Handle the call for the add_product service."""
    api: PodPointClient = coordinator.api
    pods: List[Pod] = coordinator.pods
    pod: Pod
    if len(pods) == 1:
        pod = pods[0]
    else:
        PodPointServiceException(f"Service only supports accounts with 1 Pod attached, found {len(pods)} Pods!")

    hours = call.data.get(ATTR_HOURS, 0)
    minutes = call.data.get(ATTR_MINUTES, 0)
    seconds = call.data.get(ATTR_SECONDS, 0)

    hours_set = 0 < hours <= 24
    minutes_set = 0 < minutes <= 59
    seconds_set = 0 < seconds <= 59
    valid_time_passed = (
        hours_set
        or minutes_set
        or seconds_set
    )

    if valid_time_passed is False:
        raise PodPointServiceException("Please pass an hours, minutes or seconds value. Cannot set 'charge now' with 0 values.")

    await api.async_set_charge_override(pod=pod, hours=hours, minutes=minutes, seconds=seconds)

    await coordinator.async_request_refresh()


import unittest
from my_labs.lab7.lab7_8 import MyStack

class Test_stack(unittest.TestCase):
    def test_push(self):
        A = MyStack()
        for i in range(10):
            self.assertTrue(A.push(i))
        self.assertFalse(A.push(11))

    def test_pop(self):
        A = MyStack()
        self.assertEqual(A.pop(), None)
        for i in range(10):
            A.push(i)
        self.assertEqual(A.pop(), 9)

    def test_is_empty(self):
        A = MyStack()
        self.assertTrue(A.isEmpty())
        for i in range(10):
            A.push(i)
        self.assertFalse(A.isEmpty())


import os, sys
import pandas as pd
import numpy as np
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Embedding, Reshape, Merge
from keras.callbacks import EarlyStopping, ModelCheckpoint

# path
data_train = 'train.csv'
data_test = 'test.csv'
data_users = 'users.csv'
data_movies = 'movies.csv'
data_directory = sys.argv[1] + os.sep if len(sys.argv) > 1 else './data/'
prediction_file = sys.argv[2] if len(sys.argv) > 2 else 'predict.csv'

# user parameter
K_FACTORS = 120
best_model_weight_path = './model/mf_weight_best.h5'

# load data
df_train = pd.read_csv(data_directory + data_train)
df_test = pd.read_csv(data_directory + data_test)
df_users = pd.read_csv(data_directory + data_users, sep='::')
df_movies = pd.read_csv(data_directory + data_movies, sep='::')

# get numpy array for train and test
train_UserID = df_train['UserID'].values
train_MovieID = df_train['MovieID'].values
train_Rating = df_train['Rating'].values.astype('float32')

test_DataID = df_test['TestDataID'].values
test_UserID = df_test['UserID'].values
test_MovieID = df_test['MovieID'].values

# max id
max_userid = np.max(train_UserID).astype('int')
max_movieid = np.max(train_MovieID).astype('int')

# shuffle train data
indices = np.arange(train_UserID.shape[0])
np.random.shuffle(indices)
train_UserID = train_UserID[indices]
train_MovieID = train_MovieID[indices]
train_Rating = train_Rating[indices]

# split validation
valid_size = 5000
valid_UserID = train_UserID[:valid_size]
valid_MovieID = train_MovieID[:valid_size]
valid_Rating = train_Rating[:valid_size]
train_UserID  = train_UserID[valid_size:]
train_MovieID  = train_MovieID[valid_size:]
train_Rating  = train_Rating[valid_size:]

# data info
print('-'*30)
print('valid_UserID:', valid_UserID.shape)
print('valid_MovieID:', valid_MovieID.shape)
print('valid_Rating:', valid_Rating.shape)
print('train_UserID:', train_UserID.shape)
print('train_MovieID:', train_MovieID.shape)
print('train_Rating:', train_Rating.shape)
print('test_UserID:', test_UserID.shape)
print('test_MovieID:', test_MovieID.shape)
print('-'*30)

# build model
def build_model():
	model = Sequential()
	P = Sequential()
	P.add(Embedding(max_userid + 1, K_FACTORS, input_length=1))
	P.add(Reshape((K_FACTORS,)))
	Q = Sequential()
	Q.add(Embedding(max_movieid + 1, K_FACTORS, input_length=1))
	Q.add(Reshape((K_FACTORS,)))
	model.add(Merge([P, Q], mode='dot', dot_axes=1))
	model.compile(loss='mean_squared_error', optimizer='adam', metrics=[])
	model.summary()
	return model

model = build_model()

# train
earlystopping = EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='min')
checkpoint = ModelCheckpoint(
				filepath=best_model_weight_path,
				verbose=1,
				save_best_only=True,
				save_weights_only=True,
				monitor='val_loss',
				mode='min'
			)
model.fit(
		[train_UserID, train_MovieID], train_Rating,
		batch_size=512, epochs=1000,
		validation_data=([valid_UserID,valid_MovieID],valid_Rating),
		callbacks=[earlystopping, checkpoint]
	)

# load best model
model = build_model()
model.load_weights(best_model_weight_path)

# predict
y_preds = model.predict([test_UserID, test_MovieID]).reshape(-1)
df_pred = pd.DataFrame({'TestDataID': test_DataID, 'Rating': y_preds})
df_pred.to_csv(prediction_file, columns=['TestDataID','Rating'], index=False)


import re
#regular expression(re)
class Textfile():

    def fileread(self):
        f = open("C:\\Users\\SaranyaV\\OneDrive - Specialist Lending\\Desktop\\selenium with python\\project\\input.txt","r")
        #print(f.read())
        #print(f.read(10))
        #print(f.read(10))
        #print(f.readline())
        #print(f.readlines())
        iterate = f.readlines()
        for xc in iterate:
            x=re.split("\S",xc)
            print(x)
            print(xc)
        f.close()

obj=Textfile()
obj.fileread()


from prolog_structures import Rule, RuleBody, Term, Function, Variable, Atom, Number
from typing import List
from functools import reduce

import sys
import random

class Not_unifiable(Exception):
	pass

'''
Please read prolog_structures.py for data structures
that represent Prolog terms, rules, and goals.
'''
class Interpreter:
	def __init__(self):
		pass

	'''
	Example
	occurs_check (v, t) where v is of type Variable, t is of type Term.
	occurs_check (v, t) returns true if the Prolog Variable v occurs in t.
	Please see the lecture note Control in Prolog to revisit the concept of
	occurs-check.
	'''
	def occurs_check (self, v : Variable, t : Term) -> bool:
		if isinstance(t, Variable):
			return v == t
		elif isinstance(t, Function):
			for t in t.terms:
				if self.occurs_check(v, t):
					return True
			return False
		return False

	'''
	Problem 1
	variables_of_term (t) where t is of type Term.
	variables_of_clause (c) where c is of type Rule.

	The function should return the Variables contained in a term or a rule
	using Python set.

	The result must be saved in a Python set. The type of each element (a Prolog Variable)
	in the set is Variable.
	'''
	def variables_of_term (self, t : Term) -> set :
		if isinstance(t, Variable):
			return set(([t]))
		elif isinstance(t, Function):
			x = set()
			for t in t.terms:
				if isinstance(t, Variable):
					x.add(t)
			return x
		return set()

	def variables_of_clause (self, c : Rule) -> set :
		x = self.variables_of_term(c.head)
		for i in c.body.terms:
			x.union(self.variables_of_term(i))

		return x

	'''
	Problem 2
	substitute_in_term (s, t) where s is of type dictionary and t is of type Term
	substitute_in_clause (s, t) where s is of type dictionary and c is of type Rule,

	The value of type dict should be a Python dictionary whose keys are of type Variable
	and values are of type Term. It is a map from variables to terms.

	The function should return t_ obtained by applying substitution s to t.

	Please use Python dictionary to represent a subsititution map.
	'''
	def substitute_in_term (self, s : dict, t : Term) -> Term:
		if s =={}:
			return t
		elif isinstance(t, Function):
			term_helper = []
			for x in t.terms:
				term_helper.append(self.substitute_in_term(s,x))
			return Function(t.relation, term_helper)
		elif isinstance(t, Variable):
			term_helper = s.get(t,t)
			return term_helper
		elif isinstance(t, Atom):
			term_helper = s.get(t,t)
			return term_helper
		elif isinstance(t, Number):
			term_helper = s.get(t.value,t.value)
			term_helper = str(term_helper)
			return Number(term_helper)

	def substitute_in_clause (self, s : dict, c : Rule) -> Rule:
		if s == {}:
			return c
		head_helper = self.substitute_in_term(s, c.head)
		term_helper = []
		for x in c.body.terms:
			term_helper.append(self.substitute_in_term(s,x))
		return Rule(head_helper, RuleBody(term_helper))

	'''
	Problem 3
	unify (t1, t2) where t1 is of type term and t2 is of type Term.
	The function should return a substitution map of type dict,
	which is a unifier of the given terms. You may find the pseudocode
	of unify in the lecture note Control in Prolog useful.

	The function should raise the exception raise Not_unfifiable (),
	if the given terms are not unifiable.

	Please use Python dictionary to represent a subsititution map.
	'''
	def funct (self, s, tup):
		x = tup[0]
		y = tup[1]
		return self.unify_helper(x,y,s)

	def unify_helper(self, prevx, prevy, s:dict):
		x = self.substitute_in_term(s, prevx)
		y = self.substitute_in_term(s, prevy)
		if isinstance(x, Variable) and (self.occurs_check(x,y) == False):
			Snew = {x:y}
			for key,value in s.items():
				ValNew = self.substitute_in_term(Snew, value)
				s[key] = ValNew
			s[x] = y
			return s
		elif isinstance(y, Variable) and (self.occurs_check(x,y) == False):
			Snew = {y:x}
			for key,value in s.items():
				ValNew = self.substitute_in_term(Snew, value)
				s[key] = ValNew
			s[y] = x
			return s
		elif x == y:
			return s
		elif isinstance(x, Function) and isinstance(y, Function):
			if x.relation != y.relation:
				raise Not_unifiable
			TermsOfX = []
			for i in x.terms:
				TermsOfX.append(i)
			TermsOfY = []
			for i in y.terms:
				TermsOfY.append(i)
			if len(TermsOfY) != len(TermsOfX):
				raise Not_unifiable
			tupes = []
			for i in range(len(TermsOfX)):
				tupes.append((TermsOfX[i],TermsOfY[i]))
			return(reduce(self.funct, tupes, s))
		else:
			raise Not_unifiable
	def unify (self, t1: Term, t2: Term) -> dict:
		return self.unify_helper(t1,t2,{})

	fresh_counter = 0
	def fresh(self) -> Variable:
		self.fresh_counter += 1
		return Variable("_G" + str(self.fresh_counter))
	def freshen(self, c: Rule) -> Rule:
		c_vars = self.variables_of_clause(c)
		theta = {}
		for c_var in c_vars:
			theta[c_var] = self.fresh()

		return self.substitute_in_clause(theta, c)

	'''
	Problem 4
	Following the Abstract interpreter pseudocode in the lecture note Control in Prolog to implement
	a nondeterministic Prolog interpreter.

	nondet_query (program, goal) where
		the first argument is a program which is a list of Rules.
		the second argument is a goal which is a list of Terms.

	The function returns a list of Terms (results), which is an instance of the original goal and is
	a logical consequence of the program. See the tests cases (in src/main.py) as examples.
	'''
	def nondet_query (self, program : List[Rule], pgoal : List[Term]) -> List[Term]:
		while(1):
			goal= pgoal[:]
			res = goal[:]
			while(res):
				x = random.randint(0, len(res)-1)
				y = res[x]
				unify = []
				for i in range(len(program)):
					NewY = self.freshen(program[i])
					try:
						self.unify(y,NewY.head)
						unify.append(NewY)
					except Not_unifiable:
						pass
				if unify == []:
					break
				k = random.randint(0, len(unify)-1)
				w = self.unify(y, unify[k].head)
				res.remove(res[x])
				for term in unify[k].body.terms:
					res.append(term)
				for term in range(len(goal)):
					new = self.substitute_in_term(w, goal[term])
					goal[term] = new
				for term in range(len(res)):
					new = self.substitute_in_term(w, res[term])
					res[term] = new
			if res == []:
				return goal

	'''
	Challenge Problem

	det_query (program, goal) where
		the first argument is a program which is a list of Rules.
		the second argument is a goal which is a list of Terms.

	The function returns a list of term lists (results). Each of these results is
	an instance of the original goal and is a logical consequence of the program.
	If the given goal is not a logical consequence of the program, then the result
	is an empty list. See the test cases (in src/main.py) as examples.
	'''
	def det_query (self, program : List[Rule], pgoal : List[Term]) -> List[List[Term]]:
		return [pgoal]


num = int(input('1º número da PA: '))
r = int(input('Razão: '))
print('')
qnt = 10
PA = num
c = 0
while c < qnt:
    print(f'\033[1:36m{PA}\033[m', end = '\033[1:35m → \033[m')
    PA += r
    c += 1
    if c == qnt:
        print('')
        alt = int(input('\nQUANTOS TERMOS A MAIS DESEJA ADICIONAR? (0 PARA FINALIZAR)'))
        print('')
        c += alt
        if alt != 0:
            qnt += alt
            PA = num
            c = 0
print(f'\033[1:36m{c} ELEMENTOS FORAM INSERIDOS.\033[m ')
print('')
print('\033[1:32mPROGRAMA FINALIZADO.\033[m')


from enum import Enum # for api enumeration
import hashlib

class ApiError(Exception):
    '''
        for all class using models
    '''
    def __init__(self, msg):
        super(ApiError, self).__init__(msg)

class _APIFactoryError(Exception):
    '''
        @ Exception : FactoryError
        --------------------------
        low level api instantiation error
    '''
    def __init__(self, msg):
        super(_APIFactoryError, self).__init__(msg)

class _APIs(Enum):
    '''
        @ enum : _APIs
        --------------
        for mapping the api object for instantiation
    '''
    Coinbase, Cexio, Rocktrade, Poloniex, Bitstamp, Gdax = range(6)

class _APImeta(type):
    '''
        @ metaclass : _APImeta
        -----------------------
        @ reqs : api_key
        @ reqs : api_secret
        @ reqs : api type
        @ reqs : api base endpoint
        @ suff : api_pass => optional for 3rd arg
    '''

    def __new__(meta, name, bases, clsdct):
        '''
            @ meta   => the `this` instance for metaclass
            @ name   => the name of concrete class
            @ bases  => the class meta
            @ clsdct => cls's `static` vars and method prototypes dict
        '''
        if not '_api_enumid' in clsdct:
            raise _APIFactoryError('The api type was not defined')
        e = clsdct['_api_enumid']
        if not _APImeta._verify_enumid(e):
            raise _APIFactoryError('The api enum id is invalid')
        return super(_APImeta, meta).__new__(meta, name, bases, clsdct)

    def __init__(cls, name, bases, dct):
        '''
            @ cls   : an api class
            @ name  : api class name
            @ bases : cls's namespace (prototype)
            @ dct   : cls's __dict__
        '''
        eid = dct['_api_enumid']
        if eid == _APIs.Rocktrade or eid == _APIs.Poloniex:
            dct['_digestmod'] = hashlib.sha512
        elif eid == _APIs.CoinBase or eid == _APIs.Cexio or \
            eid == _APIs.Bitstamp or eid == _APIs.Gdax:
            dct['_digestmod'] = hashlib.sha256
        super(_APImeta, cls).__init__(name, bases, dct)

    def _verify_enumid(eid):
        if eid != _APIs.CoinBase or \
            eid != _APIs.Cexio or \
            eid != _APIs.Rocktrade or \
            eid != _APIs.Bitstamp or \
            eid != _APIs.Gdax or \
            eid != _APIs.Poloniex:
            return False
        return True


from collections import Counter

def part_1():
    grid_counter = Counter()
    with open("inputs/day5", "r") as file:
        for line in file:
            start, end = line.strip().split("->")
            x1, y1 = map(int, start.split(","))
            x2, y2 = map(int, end.split(","))

            if x1 == x2 or y1 == y2:
                for x in range(min(x1, x2), max(x1, x2) + 1):
                    for y in range(min(y1, y2), max(y1, y2) + 1):
                        grid_counter[(x, y)] += 1

    return len([x for _, count in grid_counter.items() if count > 1])

def part_2():
    grid_counter = Counter()
    with open("inputs/day5", "r") as file:
        for line in file:
            start, end = line.strip().split("->")
            x1, y1 = map(int, start.split(","))
            x2, y2 = map(int, end.split(","))

            slope_x = 1 if x2 > x1 else -1
            slope_y = 1 if y2 > y1 else -1
            if x1 == x2:
                slope_x = 0
            if y1 == y2:
                slope_y = 0

            grid_counter[(x1, y1)] += 1
            while x1 != x2 or y1 != y2:
                x1 += slope_x
                y1 += slope_y
                grid_counter[(x1, y1)] += 1

    return len([_ for _, count in grid_counter.items() if count > 1])

print(part_1())
print(part_2())


#-*- coding=utf-8 -*-
from flask import render_template,redirect,abort,make_response,jsonify,request,url_for,Response,send_from_directory,stream_with_context,send_file
from flask_sqlalchemy import Pagination
from ..utils import *
from ..extend import *
from . import front

################################################################################
###################################前台函数#####################################
################################################################################

@front.before_request
def before_request():
    bad_ua=['Googlebot-Image','FeedDemon ','BOT/0.1 (BOT for JCE)','CrawlDaddy ','Java','Feedly','UniversalFeedParser','ApacheBench','Swiftbot','ZmEu','Indy Library','oBot','jaunty','YandexBot','AhrefsBot','MJ12bot','WinHttp','EasouSpider','HttpClient','Microsoft URL Control','YYSpider','jaunty','Python-urllib','lightDeckReports Bot','PHP','vxiaotou-spider','spider']
    global referrer
    try:
        ip = request.headers['X-Forwarded-For'].split(',')[0]
    except:
        ip = request.remote_addr
    try:
        ua = request.headers.get('User-Agent')
    except:
        ua="null"
    if sum([i.lower() in ua.lower() for i in bad_ua])>0:
        return redirect('http://www.baidu.com')
    # print '{}:{}:{}'.format(request.endpoint,ip,ua)
    referrer=request.referrer if request.referrer is not None else 'no-referrer'

@front.errorhandler(500)
def page_not_found(e):
    # note that we set the 500 status explicitly
    msg,status=CheckServer()
    return render_template('error.html',msg=msg,code=500), 500

@front.errorhandler(404)
def page_not_found(e):
    # note that we set the 404 status explicitly
    msg,status=CheckServer()
    return render_template('error.html',msg=msg,code=404), 404

@front.route('/favicon.ico')
def favicon():
    resp=MakeResponse(send_from_directory(os.path.join(config_dir, 'app/static/img'),'favicon.ico',mimetype='image/vnd.microsoft.icon'))
    return resp

@front.route('/<path:path>',methods=['POST','GET'])
@front.route('/',methods=['POST','GET'])
@limiter.limit("200/minute;50/second")
def index(path=None):
    balance=eval(GetConfig('balance'))
    if path is None:
        path='{}:/'.format(GetConfig('default_pan'))
    path=urllib.parse.unquote(path).split('?')[0]
    if not os.path.exists(os.path.join(config_dir,'.install')):
        resp=redirect(url_for('admin.install',step=0,user=GetConfig('default_pan')))
        return resp
    try:
        user,n_path=path.split(':')
    except:
        if path==GetConfig('admin_prefix'):
            return redirect(url_for('admin.setting'))
        else:
            return MakeResponse(abort(404))
    if balance:
        if user!=GetConfig('default_pan'):
            return MakeResponse(abort(404))
    if n_path=='':
        path=':'.join([user,'/'])
    page=request.args.get('page',1,type=int)
    image_mode=GetCookie(key='image_mode',default=0)
    sortby=GetCookie(key='sortby',default=GetConfig('default_sort'))
    order=GetCookie(key='order',default=GetConfig('order_m'))
    action=request.args.get('action','download')
    token=request.args.get('token')
    data,total = FetchData(path=path,page=page,per_page=50,sortby=sortby,order=order,action=action,dismiss=True)
    #是否有密码
    password,_,cur=has_item(path,'.password')
    md5_p=md5(path)
    has_verify_=has_verify(path)
    if request.method=="POST":
        password1=request.form.get('password')
        if password1==password:
            resp=MakeResponse(redirect(url_for('.index',path=path)))
            resp.delete_cookie(md5_p)
            resp.set_cookie(md5_p,password)
            return resp
    if password!=False:
        if (not request.cookies.get(md5_p) or request.cookies.get(md5_p)!=password) and has_verify_==False:
            if total=='files' and GetConfig('encrypt_file')=="no":
                if GetConfig("verify_url")=="True" and action not in ['share','iframe']:
                    if token is None:
                        return abort(403)
                    elif VerifyToken(token,path):
                        return show(data['id'],data['user'],action,token=token)
                    else:
                        return abort(403)
                else:
                    return show(data['id'],data['user'],action,token=token)
            resp=MakeResponse(render_template('theme/{}/password.html'.format(GetConfig('theme')),path=path,cur_user=user))
            return resp
    if total=='files':
        if GetConfig("verify_url")=="True" and action not in ['share','iframe']:
            if token is None:
                return abort(403)
            elif VerifyToken(token,path):
                return show(data['id'],data['user'],action,token=token)
            else:
                return abort(403)
        else:
            return show(data['id'],data['user'],action,token=token)
    readme,ext_r=GetReadMe(path)
    head,ext_d=GetHead(path)
    #参数
    all_image=False if sum([file_ico(i)!='image' for i in data])>0 else True
    pagination=Pagination(query=None,page=page, per_page=50, total=total, items=None)
    if path.split(':',1)[-1]=='/':
        path=':'.join([path.split(':',1)[0],''])
    resp=MakeResponse(render_template('theme/{}/index.html'.format(GetConfig('theme'))
                    ,pagination=pagination
                    ,items=data
                    ,path=path
                    ,image_mode=image_mode
                    ,readme=readme
                    ,ext_r=ext_r
                    ,head=head
                    ,ext_d=ext_d
                    ,sortby=sortby
                    ,order=order
                    ,cur_user=user
                    ,all_image=all_image
                    ,endpoint='.index'))
    resp.set_cookie('image_mode',str(image_mode))
    resp.set_cookie('sortby',str(sortby))
    resp.set_cookie('order',str(order))
    return resp

@front.route('/file/<user>/<fileid>/<action>/<token>')
def show(fileid,user,action='download',token=None):
    if token is None:
        token=request.args.get('token')
    path=convert2str(GetPath(fileid))
    name=convert2str(GetName(fileid))
    ext=name.split('.')[-1].lower()
    url=request.url.replace(':80','').replace(':443','').split('?')[0]
    url='/'.join(url.split('/')[:3])+'/'+urllib.parse.quote('/'.join(url.split('/')[3:]))
    if GetConfig("verify_url")=="True":
        url=url+'?token='+GenerateToken(path)
        if action not in ['share','iframe']:
            if token is None:
                return abort(403)
            elif VerifyToken(token,path)==False:
                return abort(403)
    if request.method=='POST' or action in ['share','iframe']:
        InfoLogger().print_r(u'share page:{}'.format(path))
        if ext in GetConfig('show_redirect').split(','):
            downloadUrl,play_url=GetDownloadUrl(fileid,user)
            resp=MakeResponse(redirect(downloadUrl))
        elif ext=='pdf':
            if action=='share':
                resp=MakeResponse(render_template('theme/{}/show/pdf.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
            else:
                resp=MakeResponse(render_template('show/pdf.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
        elif ext in GetConfig('show_doc').split(','):
            downloadUrl,play_url=GetDownloadUrl(fileid,user)
            url = 'https://view.officeapps.live.com/op/view.aspx?src='+urllib.parse.quote(downloadUrl)
            resp=MakeResponse(redirect(url))
        elif ext in GetConfig('show_image').split(','):
            if action=='share':
                resp=MakeResponse(render_template('theme/{}/show/image.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
            else:
                resp=MakeResponse(render_template('show/image.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))

        elif ext in GetConfig('show_video').split(','):
            if action=='share':
                resp=MakeResponse(render_template('theme/{}/show/video.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
            else:
                resp=MakeResponse(render_template('show/video.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
        elif ext in GetConfig('show_dash').split(','):
            if action=='share':
                resp=MakeResponse(render_template('theme/{}/show/video2.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
            else:
                resp=MakeResponse(render_template('show/video2.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
        elif ext in GetConfig('show_audio').split(','):
            if action=='share':
                resp=MakeResponse(render_template('theme/{}/show/audio.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
            else:
                resp=MakeResponse(render_template('show/audio.html'.format(GetConfig('theme')),url=url,path=path,cur_user=user,name=name))
        elif ext in GetConfig('show_code').split(','):
            content=common._remote_content(fileid,user)
            if action=="share":
                resp=MakeResponse(render_template('theme/{}/show/code.html'.format(GetConfig('theme')),content=content,url=url,language=CodeType(ext),path=path,cur_user=user,name=name))
            else:
                resp=MakeResponse(render_template('show/code.html'.format(GetConfig('theme')),content=content,url=url,language=CodeType(ext),path=path,cur_user=user,name=name))
        elif name=='.password':
            resp=MakeResponse(abort(404))
        else:
            downloadUrl,play_url=GetDownloadUrl(fileid,user)
            resp=MakeResponse(redirect(downloadUrl))
        return resp
    if name=='.password':
        resp=MakeResponse(abort(404))
    if 'no-referrer' in GetConfig('allow_site').split(',') or sum([i in referrer for i in GetConfig('allow_site').split(',')])>0:
        downloadUrl,play_url=GetDownloadUrl(fileid,user)
        if not downloadUrl.startswith('http'):
            return MakeResponse(downloadUrl)
        else:
            if GetConfig('redirect_file')=='True' or ext=='pdf':
                resp=redirect_file(user,fileid)
            else:
                resp=MakeResponse(redirect(play_url))
    else:
        resp=MakeResponse(abort(404))
    return resp

# @front.route('/py_redirect/<user>/<fileid>')
def redirect_file(user,fileid):
    filename=GetName(fileid)
    downloadUrl,play_url=GetDownloadUrl(fileid,user)
    req = browser.get(play_url, stream = True)
    headers = dict([(name, value) for (name, value) in req.raw.headers.items()])
    cache_root=os.path.join(GetConfig('config_dir'),'cache')
    if not os.path.exists(cache_root):
        os.mkdir(cache_root)
    filepath=os.path.join(cache_root,filename)
    if not os.path.exists(filepath):
        with open(filepath,'wb') as f:
            for chunk in req.iter_content(1024):
                if chunk:
                    f.write(chunk)
                    f.flush()
    resp=send_file(filepath,conditional=True)
    return resp

@front.route('/py_find/<key_word>')
def find(key_word):
    page=request.args.get('page',1,type=int)
    ajax=request.args.get('ajax','no')
    image_mode=request.args.get('image_mode')
    sortby=request.args.get('sortby')
    order=request.args.get('order')
    action=request.args.get('action','download')
    data,total=FetchData(path=key_word,page=page,per_page=50,sortby=sortby,order=order,dismiss=True,search_mode=True)
    pagination=Pagination(query=None,page=page, per_page=50, total=total, items=None)
    if ajax=='yes':
        retdata={}
        retdata['code']=0
        retdata['msg']=""
        retdata['total']=total
        retdata['data']=[]
        for d in data:
            info={}
            if d['type']=='folder':
                info['name']=''+d['name']+''
            else:
                info['name']=''+d['name']+''
            info['type']=d['type']
            info['lastModtime']=d['lastModtime']
            info['size']=d['size']
            info['path']=d['path']
            info['id']=d['id']
            retdata['data'].append(info)
        return jsonify(retdata)
    resp=MakeResponse(render_template('theme/{}/find.html'.format(GetConfig('theme'))
                    ,pagination=pagination
                    ,items=data
                    ,path='/'
                    ,sortby=sortby
                    ,order=order
                    ,key_word=key_word
                    ,cur_user='搜索:"{}"'.format(key_word)
                    ,endpoint='.find'))
    resp.set_cookie('image_mode',str(image_mode))
    resp.set_cookie('sortby',str(sortby))
    resp.set_cookie('order',str(order))
    return resp

@front.route('/robots.txt')
def robot():
    resp=GetConfig('robots')
    resp=MakeResponse(resp)
    resp.headers['Content-Type'] = 'text/javascript; charset=utf-8'
    return resp