import pandas
import os
import time
import adjust.dict as dict

acos = 0.13
beilv = 1
bili = 0.6
maxbid = 0.5
minbid = 0.03
max_cpc_bizhi = 2

shop = "PASAMER_MX"
no_impressions = False
min_clicks = False
low_acos_add = True

def get_dp(shop):
#    shop = shop.replace("_","-")
    dp = shop.split("_")[0]
    return dp

def get_area(shop):
#    shop = shop.replace("_","-")
    area = shop.split("_")[1]
    return area

dp = get_dp(shop)
area = get_area(shop)

root_path = "D:/待处理/"+dp+"/"+shop+"/"

if area=="JP":
    beilv=100
elif area=="MX":
    beilv=20

nowtime = time.strftime("%y%m%d",time.localtime(time.time()))

def get_data(path):
    global area
    for root,folds,files in os.walk(path):
        for file in files:
            if "$" not in file:
                if "BusinessReport" in file:
                    BusinessReport_filename = path+file
                elif "bulksheet" in file:
                    ca_filename = path+file
                elif "Active" in file and "Listings" in file:
                    Active_Listings_filename = path+file

    campaign_data = pandas.read_excel(ca_filename, encoding="unicode_escape", sheet_name="Sponsored Products Campaigns")

    Active_Listings = pandas.read_table(Active_Listings_filename,sep="\t",engine="python",encoding="utf-8-sig")
    BusinessReport = pandas.read_csv(open(BusinessReport_filename,encoding='utf-8'))
    return campaign_data,Active_Listings,BusinessReport

campaign_data,Active_Listings,BusinessReport = get_data(root_path)

tihuan_flag = False
# if area in ["US", "CA", "UK"]:
#     tihuan_flag = False

def replace_dict(x):
    global area_to_dict
    global area
    for old, new in area_to_dict[area].items():
        x = x.replace(old, new)
    return x

def get_dict():
    global area_to_dict
    global area
    return area_to_dict[area]

def campaign_dh_repalce(x):
    if isinstance(x, str):
        x = x.replace(",", ".")
    return x

def replace_bfh(x):
    if isinstance(x, str):
        x = x.replace("%", "")
    return x

if tihuan_flag:
    data_columns = [x for x in campaign_data.columns.map(lambda x: x.strip()) if x in list(get_dict().keys())]
    campaign_data.columns = campaign_data.columns.map(lambda x: x.strip())
    campaign_data = campaign_data[data_columns]
    campaign_data.columns = campaign_data.columns.map(lambda x: x.strip()).map(get_dict())
    if area == "FR":
        campaign_data["Record Type"] = campaign_data["Record Type"].map(lambda x: x.strip())
    campaign_data = campaign_data.apply(replace_dict)

if area in ["DE", "FR", "ES", "IT"]:
    campaign_data["ACoS"] = campaign_data["ACoS"].map(campaign_dh_repalce)
    campaign_data[["Max Bid", "Spend", "Sales"]] = campaign_data[["Max Bid", "Spend", "Sales"]].applymap(
        campaign_dh_repalce).astype(float)

def business_dh_repalce(x):
    if isinstance(x, str):
        x = x.replace(",", "")
    return x

def replace_other(x):
    other_dict = {"Can$": "", "Can": "", "$": "", "€": "", "￥": "", "%": "", "£": "", "MXN": ""}
    for old, new in other_dict.items():
        x = x.replace(old, new)
    return x

def tihuan_business(BusinessReport):
    br = BusinessReport.copy()
    br[["Sessions", "Units Ordered", "Ordered Product Sales", "Unit Session Percentage"]] = br[
        ["Sessions", "Units Ordered", "Ordered Product Sales", "Unit Session Percentage"]].applymap(business_dh_repalce)
    br[["Sessions", "Units Ordered"]] = br[["Sessions", "Units Ordered"]].applymap(business_dh_repalce).astype(float)
    br[["Unit Session Percentage", "Ordered Product Sales"]] = br[
        ["Unit Session Percentage", "Ordered Product Sales"]].applymap(replace_other).astype(float)
    return br

BusinessReport = tihuan_business(BusinessReport)

def get_sku_asin_price_fb(Active_Listings):
    if area=="JP":
        Active_Listings = Active_Listings.rename(columns={
        "出品者SKU": "seller-sku", "ASIN 1": "asin1", "商品名": "item-name", "価格": "price", "数量": "quantity",
        "フルフィルメント・チャンネル": "fulfillment-channel"
    })
    sku_asin_price_fb = Active_Listings[["seller-sku","asin1","price","fulfillment-channel"]]
    return sku_asin_price_fb

Active_Listings = get_sku_asin_price_fb(Active_Listings)

def get_avg_data(BusinessReport):
    avgsale = round((BusinessReport["Ordered Product Sales"].sum()/BusinessReport["Units Ordered"].sum()),2)
    avgzhl = round((BusinessReport["Units Ordered"].sum()/BusinessReport["Sessions"].sum()),4)
    return avgsale,avgzhl

avgsale,avgzhl = get_avg_data(BusinessReport)

def get_zhl_xs(price):
    zhl_xs = 1.71+(-4.9)*0.01*price+5.81*0.0001*price*price+(-2.13)*0.000001*price*price*price
    if zhl_xs>1.6:
        zhl_xs=1.6
    elif zhl_xs<0.2:
        zhl_xs=0.2
    return zhl_xs

avg_zhl_xs = get_zhl_xs((avgsale/beilv))

def get_sku_no_order_zhl(price):
    global avg_zhl_xs
    global avgzhl
    no_order_zhl = round((get_zhl_xs(price)/avg_zhl_xs)*avgzhl,3)
    return no_order_zhl

def get_sku_zhl(Unit_Session_Percentage):
    zhl = round((Unit_Session_Percentage/100),3)
    return zhl

def get_auto_campaign(campaign_data):
    auto_campaign = campaign_data[(campaign_data["Record Type"]=="Campaign")&(campaign_data["Campaign Targeting Type"]=="Auto")][["Campaign"]]
    return auto_campaign

def get_all_adgroup(campaign_data):
    auto_campaign = get_auto_campaign(campaign_data)
    all_adgroup = campaign_data[campaign_data["Record Type"]=="Ad Group"]
    all_auto_adgroup = all_adgroup.merge(auto_campaign,left_on="Campaign",right_on="Campaign",how="inner")
    return all_auto_adgroup

def get_all_enabale_auto_adgroup(campaign_data):
    enabale_auto_adgroup = get_all_adgroup(campaign_data)
    enabale_auto_adgroup = enabale_auto_adgroup[(enabale_auto_adgroup["Campaign Status"]!="paused")&(enabale_auto_adgroup["Ad Group Status"]!="paused")&(enabale_auto_adgroup["Status"]!="paused")]
    return enabale_auto_adgroup

def get_all_auto_ad(campaign_data):
    auto_campaign = get_auto_campaign(campaign_data)
    all_ad = campaign_data[campaign_data["Record Type"]=="Ad"]
    all_auto_ad = all_ad.merge(auto_campaign,left_on="Campaign",right_on="Campaign",how="inner")
    return all_auto_ad

def get_cpc(clicks,spend):
    if clicks>0:
        cpc = spend/clicks
    else:
        cpc = 0
    return cpc

def get_ctr(Clicks,Impressions):
    if Clicks>0:
        ctr = round(Clicks/Impressions,4)
    else:
        ctr = 0
    return ctr

enabale_auto_adgroup = get_all_enabale_auto_adgroup(campaign_data)
enabale_auto_adgroup["cpc"] =  enabale_auto_adgroup.apply(lambda row:get_cpc(row["Clicks"],row["Spend"]),axis=1)
enabale_auto_adgroup["ctr"] = enabale_auto_adgroup.apply(lambda row:get_ctr(row["Clicks"],row["Impressions"]),axis=1)
enabale_auto_adgroup["ACoS"] = round((enabale_auto_adgroup["ACoS"].map(replace_bfh).astype(float))/100,3)

all_auto_ad = get_all_auto_ad(campaign_data)

all_auto_ad = all_auto_ad[["Campaign","Ad Group","SKU"]]

act_ad = Active_Listings.merge(all_auto_ad,left_on="seller-sku",right_on="SKU",how="outer")

BusinessReport = BusinessReport[["SKU","Sessions","Units Ordered","Ordered Product Sales","Unit Session Percentage"]]

act_ad =act_ad.merge(BusinessReport,left_on="SKU",right_on="SKU",how="outer")

act_ad["avgsale"] = act_ad["Ordered Product Sales"]/act_ad["Units Ordered"]

act_ad["no_order_zhl"] = act_ad["price"].map(lambda price:get_sku_no_order_zhl((price/beilv)))
act_ad["zhl"] = act_ad["Unit Session Percentage"].map(get_sku_zhl)
act_ad["Units Ordered"] = act_ad["Units Ordered"].fillna(0)

act_ad["fulfillment-channel"] = act_ad["fulfillment-channel"].fillna("OTHER")

def get_cpc(Units_Ordered, price, avgsale, zhl, no_order_zhl, fulfillment_channel):
    global maxbid
    global minbid
    global bili
    global acos
    if Units_Ordered > 0:
        cpc = round(zhl * avgsale * bili * acos, 2)
    else:
        cpc = round(no_order_zhl * price * bili * acos * 0.8, 2)
        if fulfillment_channel == "DEFAULT":
            cpc = cpc * 0.7
        elif "AMAZON" in fulfillment_channel:
            cpc = cpc * 1.5

    if cpc > maxbid * beilv:
        cpc = maxbid * beilv
    if cpc < minbid * beilv:
        cpc = minbid * beilv

    cpc = round(cpc, 2)
    return cpc

act_ad["maxcpc"] = act_ad.apply(lambda row:get_cpc(row["Units Ordered"],row["price"],row["avgsale"],row["zhl"],row["no_order_zhl"],row["fulfillment-channel"]),axis=1)

act_ad = act_ad[["Campaign","Ad Group","SKU","maxcpc","price","Units Ordered"]]

act_ad["maxcpc"] = act_ad["maxcpc"]*max_cpc_bizhi

act_ad = act_ad[act_ad["Ad Group"].notnull()]

act_ad = act_ad.fillna(0)

enabale_auto_adgroup = enabale_auto_adgroup.merge(act_ad,left_on=["Campaign","Ad Group"],right_on=["Campaign","Ad Group"],how="left")

def get_bid_by_acos(acos, now_acos, cpc, max_bid, bili1, bili2):
    tmpbid = min(round(pow((acos / now_acos), bili1) * cpc, 2), round(pow((acos / now_acos), bili2) * max_bid, 2))
    newbid = max(tmpbid, ((acos / now_acos) * cpc))
    return newbid

def get_new_bid(max_bid, cpc, now_acos, Orders, Impressions, Clicks, maxcpc, Units_Ordered, Sales):
    global acos, no_impressions, min_clicks, max_cpc_bizhi, area
    newbid = max_bid
    if Orders > 0:
        if now_acos >= acos * 1.3:
            if max_bid < (acos / now_acos) * cpc + 0.01 * beilv:
                newbid = max_bid
            else:
                if now_acos >= acos * 1.3 and now_acos < acos * 1.6:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = max_bid
                    if max_bid - newbid > 0.03 * beilv:
                        newbid = max_bid - 0.03 * beilv
                elif now_acos >= acos * 1.6 and now_acos < acos * 1.9:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = round(pow((acos / now_acos), 0.25) * cpc, 2)
                    if max_bid - newbid > 0.05 * beilv:
                        newbid = max_bid - 0.05 * beilv
                elif now_acos >= acos * 1.6 and now_acos < acos * 1.9:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = round(pow((acos / now_acos), 0.25) * cpc, 2)
                    if max_bid - newbid > 0.07 * beilv:
                        newbid = max_bid - 0.07 * beilv
                elif now_acos >= acos * 1.9 and now_acos < acos * 2.2:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = round(pow((acos / now_acos), 0.25) * cpc, 2)
                    if max_bid - newbid > 0.09 * beilv:
                        newbid = max_bid - 0.09 * beilv
                elif now_acos >= acos * 2.2 and now_acos < acos * 2.5:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = round(pow((acos / now_acos), 0.25) * cpc, 2)
                    if max_bid - newbid > 0.10 * beilv:
                        newbid = max_bid - 0.10 * beilv
                elif now_acos >= acos * 2.5 and now_acos < acos * 2.8:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = round(pow((acos / now_acos), 0.3) * cpc, 2)
                    if max_bid - newbid > 0.12 * beilv:
                        newbid = max_bid - 0.12 * beilv
                elif now_acos >= acos * 2.8 and now_acos < acos * 3.1:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = round(pow((acos / now_acos), 0.3) * cpc, 2)
                    if max_bid - newbid > 0.13 * beilv:
                        newbid = max_bid - 0.13 * beilv
                elif now_acos >= acos * 3.1 and now_acos < acos * 3.4:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.38, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 2:
                        newbid = round(pow((acos / now_acos), 0.3) * cpc, 2)
                    if max_bid - newbid > 0.15 * beilv:
                        newbid = max_bid - 0.15 * beilv
                elif now_acos >= acos * 3.4 and now_acos < acos * 3.7:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.41, 0.27)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 1:
                        newbid = round(pow((acos / now_acos), 0.3) * cpc, 2)
                    if max_bid - newbid > 0.16 * beilv:
                        newbid = max_bid - 0.16 * beilv
                elif now_acos >= acos * 3.7 and now_acos < acos * 4.0:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.43, 0.30)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 1:
                        newbid = round(pow((acos / now_acos), 0.3) * cpc, 2)
                    if max_bid - newbid > 0.18 * beilv:
                        newbid = max_bid - 0.18 * beilv
                elif now_acos >= acos * 4.0 and now_acos < acos * 4.3:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.46, 0.33)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 1:
                        newbid = round(pow((acos / now_acos), 0.3) * cpc, 2)
                    if max_bid - newbid > 0.22 * beilv:
                        newbid = max_bid - 0.22 * beilv
                elif now_acos >= acos * 4.3 and now_acos < acos * 4.6:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.5, 0.36)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 1:
                        newbid = round(pow((acos / now_acos), 0.3) * cpc, 2)
                    if max_bid - newbid > 0.25 * beilv:
                        newbid = max_bid - 0.25 * beilv
                elif now_acos >= acos * 4.6 and now_acos < acos * 4.9:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.53, 0.43)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 1:
                        newbid = round(pow((acos / now_acos), 0.35) * cpc, 2)
                    if max_bid - newbid > 0.29 * beilv:
                        newbid = max_bid - 0.29 * beilv
                elif now_acos >= acos * 4.9:
                    newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.58, 0.46)
                    if Units_Ordered > 5 and (maxcpc / max_cpc_bizhi) > max_bid and Orders <= 1:
                        newbid = round(pow((acos / now_acos), 0.35) * cpc, 2)
                    if max_bid - newbid > 0.35 * beilv:
                        newbid = max_bid - 0.35 * beilv

            if Sales < (20 * beilv) and now_acos >= acos * 5:
                newbid = get_bid_by_acos(acos, now_acos, cpc, max_bid, 0.75, 0.6)

            if newbid > max_bid:
                newbid = max_bid

        elif now_acos <= acos * 0.7 and low_acos_add:
            if Orders <= 2:
                if max_bid - cpc > 0.25 * beilv:
                    newbid = max_bid
                else:
                    if now_acos > acos * 0.3 and now_acos <= acos * 0.7:
                        newbid = max_bid + 0.02 * beilv
                    elif now_acos > acos * 0.1 and now_acos <= acos * 0.3:
                        newbid = max_bid + 0.02 * beilv
                    elif now_acos <= acos * 0.1:
                        newbid = max_bid + 0.03 * beilv
            elif Orders > 2 and Orders <= 4:
                if max_bid - cpc > 0.35 * beilv:
                    newbid = max_bid
                else:
                    if now_acos > acos * 0.3 and now_acos <= acos * 0.7:
                        newbid = max_bid + 0.03 * beilv
                    elif now_acos > acos * 0.1 and now_acos <= acos * 0.3:
                        newbid = max_bid + 0.04 * beilv
                    elif now_acos <= acos * 0.1:
                        newbid = max_bid + 0.05 * beilv
            elif Orders > 4:
                if now_acos > acos * 0.3 and now_acos <= acos * 0.7:
                    newbid = max_bid + 0.03 * beilv
                elif now_acos > acos * 0.1 and now_acos <= acos * 0.3:
                    newbid = max_bid + 0.05 * beilv
                elif now_acos <= acos * 0.1:
                    newbid = max_bid + 0.07 * beilv
        else:
            newbid = max_bid
    else:
        if no_impressions and Impressions > 0 and Impressions < 30:
            newbid = max_bid + 0.01 * beilv
            if newbid > maxcpc:
                newbid = max_bid
            elif newbid < (maxcpc / max_cpc_bizhi):
                newbid = max_bid + 0.02 * beilv
        else:
            if min_clicks and Clicks > 0 and Clicks <= 3:
                newbid = max_bid + 0.01 * beilv
                if newbid > maxcpc:
                    newbid = max_bid
                elif newbid < (maxcpc / max_cpc_bizhi):
                    newbid = max_bid + 0.02 * beilv
            else:
                if Clicks > 3 and Clicks <= 15:
                    newbid = max_bid
                elif Clicks > 15 and Clicks <= 20:
                    newbid = round(max_bid * 0.95, 2)
                    if max_bid - newbid > 0.03 * beilv:
                        newbid = max_bid - 0.03 * beilv
                elif Clicks > 20 and Clicks <= 25:
                    newbid = round(max_bid * 0.8, 2)
                    if max_bid - newbid > 0.06 * beilv:
                        newbid = max_bid - 0.06 * beilv
                elif Clicks > 25 and Clicks <= 30:
                    newbid = round(max_bid * 0.65, 2)
                    if max_bid - newbid > 0.08 * beilv:
                        newbid = max_bid - 0.08 * beilv
                elif Clicks > 30 and Clicks <= 35:
                    newbid = round(max_bid * 0.6, 2)
                    if max_bid - newbid > 0.1 * beilv:
                        newbid = max_bid - 0.1 * beilv
                elif Clicks > 35 and Clicks <= 40:
                    newbid = round(max_bid * 0.5, 2)
                    if max_bid - newbid > 0.11 * beilv:
                        newbid = max_bid - 0.11 * beilv
                elif Clicks > 40 and Clicks <= 45:
                    newbid = round(max_bid * 0.4, 2)
                    if max_bid - newbid > 0.13 * beilv:
                        newbid = max_bid - 0.13 * beilv
                elif Clicks > 45 and Clicks <= 50:
                    newbid = round(max_bid * 0.35, 2)
                    if max_bid - newbid > 0.16 * beilv:
                        newbid = max_bid - 0.16 * beilv
                elif Clicks > 50:
                    newbid = round(max_bid * 0.35, 2)
                    if max_bid - newbid > 0.2 * beilv:
                        newbid = max_bid - 0.2 * beilv

    if area == "MX":
        if newbid < 0.1:
            newbid = 0.1
    else:
        if newbid < (0.02 * beilv):
            newbid = 0.02 * beilv

    newbid = round(newbid, 2)
    return newbid

enabale_auto_adgroup["newbid"] = enabale_auto_adgroup.apply(lambda row:get_new_bid(row["Max Bid"],row["cpc"],row["ACoS"],row["Orders"],row["Impressions"],row["Clicks"],row["maxcpc"],row["Units Ordered"],row["Sales"]),axis=1)

enabale_auto_adgroup["bid_change"] = enabale_auto_adgroup["newbid"] - enabale_auto_adgroup["Max Bid"]
to_tmp_path = root_path + "tmp.xlsx"
enabale_auto_adgroup.to_excel(to_tmp_path,index=False)

enabale_auto_adgroup = enabale_auto_adgroup[enabale_auto_adgroup["bid_change"]!=0]
print(enabale_auto_adgroup.shape)

enabale_auto_adgroup = enabale_auto_adgroup.drop_duplicates(subset=["Campaign","Ad Group","newbid"],keep="first")
print(enabale_auto_adgroup.shape)

def cab_to_xls(cab):
    data = pandas.DataFrame(columns=["Campaign Name","Campaign Daily Budget","Campaign Start Date",
                                     "Campaign End Date","Campaign Targeting Type","Ad Group Name",
                                     "Max Bid","SKU","Keyword","Product Targeting ID","Match Type",
                                     "Campaign Status","Ad Group Status","Status","Bid+"])
    for index,row in cab.iterrows():
        data = data.append(pandas.DataFrame({"Campaign Name":row["Campaign"],"Campaign Daily Budget":"","Campaign Start Date":"",
                                     "Campaign End Date":"","Campaign Targeting Type":"","Ad Group Name":row["Ad Group"],
                                     "Max Bid":row["newbid"],"SKU":"","Keyword":"","Product Targeting ID":"","Match Type":"",
                                     "Campaign Status":"enabled","Ad Group Status":"enabled","Status":"","Bid+":""},index=[0]))
    return data

lastdata = cab_to_xls(enabale_auto_adgroup)

lastdata_path = root_path+"/report/"+shop+"_bidchange_auto"+"_"+nowtime+".xlsx"
lastdata.to_excel(lastdata_path,index=False)
print('------------------------end------------------------')


import time
from sys import exit

def room():
	print("Go to next room")

def countdown(p, q):
	i = p
	j = q
	k = 0

	while True:
		if j == -1:
			j = 59
			i -= 1
		if j > 9:
			print(str(k)+str(i)+":"+str(j), end = "\r")
		else:
			print(str(k)+str(i)+":"+str(k)+str(j), end = "\r")
		time.sleep(1)
		j -= 1
		if i == 0 and j == -1:
			break

	if i == 0 and j == -1:
		print("")
		time.sleep(10000)

countdown(0,10)


# 컴파일 옵션 MULTILINE, M
import re
p = re.compile("^python\s\w+", re.M)
#^는 맨처음이라는 뜻.
data = """python one
life is too short
python two
you need python
python three"""

print(p.findall(data))


import pyaudio

def record():
    p = pyaudio.PyAudio()
    stream = p.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=44100,
        input=True,
        output=True,
        frames_per_buffer=1024)

    frames = []

    while True:
        frames.append(stream.read(1024))


import os.path,time
from pathlib import Path
from datetime import datetime

home = str(Path.home())

os.chdir(home)
os.mkdir('os_lab_0')
os.chdir('os_lab_0')

fdir=open("merve1.txt","w+")
fdir=open("merve2.txt","w+")
fdir=open("python.py","w+")
f.close()

for root,dirs,files in os.walk("."):
	for filename in files:
		print(filename,  time.ctime(os.path.getmtime(filename)))

for file in os.listdir("."):
	if file.endswith(".txt"):
		print (os.path.join("os_lab_0",file))


import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import easygui
from keras.datasets import mnist
from keras.models import load_model
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# Load model
model = load_model('model.h5')
print('load ok')
# Load data
#--------------------------data from MMIST
#(X_train, y_train), (X_test, y_test) = mnist.load_data()
#test = X_test[0].reshape(1,28,28,1)
# Show
# print(X_test.shape)
# plt.imshow(X_test[0])
# plt.show()
#--------------------------------------------------C2
# data tự chuẩn bị
# Mode "L" :greyscale (8-bit pixels, black and white)
path = easygui.fileopenbox()
print(path)
img = Image.open(path).convert('RGB')
img = img.resize((64,64))
imgArr = np.array(img)
print(imgArr.shape)
# shape that CNN expects is a 4D array (batch, height, width, channels) <batch: số samples>
imgArr = imgArr.reshape(1,imgArr.shape[0],imgArr.shape[1],3)
# Predicting the Test set results
y_pred = model.predict(imgArr)
#print("Predict results: \n", y_pred[0])
fig,ax = plt.subplots()
if(np.argmax(y_pred[0]) == 0):
    ax.set(title = 'Hình vừa đưa vào là mèo')
else:
    ax.set(title = 'Hình vừa đưa vào là chó')
plt.imshow(img)
plt.show()


class NodoStack:

    def __init__(self, valor=None):
        self.valor = None
        self.anterior = None

class Stack:

    def __init__(self):
        self.tope = None

    def push(self, valor):
        """Agrega un elemento al tope del stack"""
        nodo = NodoStack()
        nodo.valor = valor
        nodo.anterior = self.tope
        self.tope = nodo

    def pop(self):
        """Retorna y extrae el elemento del tope del stack"""
        nodo = self.tope
        self.tope = nodo.anterior
        return nodo.valor

    def peek(self):
        """Retorna el elemento del tope del _stack_ sin extraerlo de la estructura"""
        return self.tope.valor

    def is_empty(self):
        """Retorna True si el stack está vacío"""
        return not bool(self.tope)

if __name__ == '__main__':
    mi_stack = Stack()
    mi_stack.push(1) # 1
    mi_stack.push(2) # 1, 2
    mi_stack.push(3) # 1, 2, 3
    mi_stack.push(4) # 1, 2, 3, 4
    mi_stack.push(5) # 1, 2, 3, 4, 5
    print(mi_stack.pop()) # 5
    print(mi_stack.pop()) # 4
    mi_stack.push(6) # 1, 2, 3, 6
    print(mi_stack.peek()) # 6
    mi_stack.push(7) # 1, 2, 3, 6, 7
    print(mi_stack.pop()) # 7
    print(mi_stack.pop()) # 6
    print(mi_stack.pop()) # 3
    print(mi_stack.is_empty()) # False


import random # For random number generation
from fuzzywuzzy import fuzz # for string similarity
import string # to get access to some utility functions

# Ideally store these variables and such in a config file

population = 25
generations = 8000
target_str = None # input string that we target towards
target_len = None # length of that string
do_mutations = True
mutation_chance = 0.1
fitness_threshold = 89 # if reached you can stop

# Representation of an individual (A.K.A. agent)
class Individual:

    def __init__(self, length):

        self.string = ''.join(random.choice(string.ascii_letters) for _ in range(length)) # Each initialized with a random string
        self.fitness = -1 # No evaluation had been done on object yet

    def __str__(self): # like toString in java

        return 'String (Guess): ' + str(self.string) + ' Fitness Score: ' + str(self.fitness)

def init_Individuals(population, length):

    return [Individual(length) for _ in range(population)]

# If the problem can exhibit some form of partial correctness, then a genetic algorithm works just fine
def ga():

    Individuals = init_Individuals(population, target_len)

    for generation in range(generations):

        print()
        print('!!! Generation: ' + str(generation) + ' !!!')
        print()

        Individuals = fitness(Individuals)
        Individuals = selection(Individuals)
        Individuals = crossover(Individuals)
        if do_mutations:
            # I could actually define different mutation functions, or maybe I'd add a second 'type' parameter for the mutation function, and therefoer enable other mutation choices to be analysed (would've been better for the submission)
            Individuals = mutation(Individuals)

        if any(Individual.fitness >= fitness_threshold for Individual in Individuals):

            print('Threshold had been met!')
            exit(0)

def fitness(Individuals):

    for Individual in Individuals:

        Individual.fitness = fuzz.ratio(Individual.string, target_str)

    return Individuals

def selection(Individuals):

    Individuals = sorted(Individuals, key=lambda Individual: Individual.fitness, reverse=True)

    print('\n'.join(map(str, Individuals)))

    Individuals = Individuals[:int(0.2 * len(Individuals))] # 0.2 -> percentage of Individuals that will be moving on for reproduction

    return Individuals

def crossover(Individuals):

    offspring = []

    for _ in range((population - len(Individuals)) // 2):

        parent1 = random.choice(Individuals)
        parent2 = random.choice(Individuals) # Here we may select the same parent twice, but it isn't that crucial for the purpose of this analyse

        child1 = Individual(target_len)
        child2 = Individual(target_len)

        split = random.randint(0, target_len)
        child1.string = parent1.string[0:split] + parent2.string[split:target_len]
        child2.string = parent2.string[0:split] + parent1.string[split:target_len]

        offspring.append(child1)
        offspring.append(child2)

    Individuals.extend(offspring)

    return Individuals

def mutation(Individuals):

    for Individual in Individuals:

        for idx, param in enumerate(Individual.string):

            if random.uniform(0.0, 1.0) <= mutation_chance:

                Individual.string = Individual.string[0:idx] + random.choice(string.ascii_letters) + Individual.string[idx+1:target_len] # Here we simply 'flip' a value, we could also use inversion (swap) etc...

    return Individuals

if __name__ == '__main__':

    target_str = 'batikanor'
    target_len = len(target_str)
    ga()


from copy import deepcopy
T = int(input())

for tc in range(1, T+1):
    N = int(input())
    results = []
    arr= []

    for _ in range(N):
        temp = [int(a) for a in input().split()]
        arr.append(temp)
    temp = [[0] * N for _ in range(N)]
    for _ in range(3):
        for i in range(N):
            for j in range(N):
                temp[i][j] = arr[N-1-j][i]
        arr = deepcopy(temp)
        results.append(arr)
    print('#{}'.format(tc))
    for i in range(N):
        for arr in results:
            for item in arr[i]:
                print(item, end='')
            print(end=' ')
        print()


from tempfile import mkdtemp
from shutil import rmtree
from os import path

from nose.tools import *
from distdb.obj import ValueSet, Object
from distdb.database import DB, Starts, ANY

class TempDir:
    def __init__(self):
        self.name = mkdtemp()

    def __enter__(self):
        return self

    def __exit__(self, type, value, tb):
        rmtree(self.name)

def test_DB_file_backed():
    with TempDir() as d:
        db_path = path.join(d.name, 'db')

        db1 = DB(db_path)
        assert_true(path.exists)
        obj1 = db1.get('aia')
        assert_is_not_none(path.exists)
        obj1[u'name'] = ValueSet(u'Test Person')
        db1.update(obj1)
        assert_is_not_none(db1['aia'][u'name'])
        db1.commit()

        db2 = DB(db_path)
        obj2 = db2[u'aia']
        assert_equal(obj1[u'name'], obj2[u'name'])

class TestInRam():
    def setup(self):
        self.db = db = DB(':memory:')
        self.o = o = db.get('some_id')
        o[u'key'] = ValueSet([u'Test Person', u'And alternatives'], t=1)
        db.update(o)

    def test_simple_object_put_get(self):
        assert_is_not_none(self.o)
        self.o[u'name'] = ValueSet(u'Test Person')
        self.db.update(self.o)
        assert_equal(self.db[self.o.id], self.o)

    def test_get_with_fields(self):
        o = self.db.get('some_id', fields="noexisting")
        assert_not_in(u'key', o)
        assert_not_in(u'noexisting', o)

    def test_failed_transaction(self):
        try:
            with self.db.transaction():
                self.o[u'name'] = ValueSet(u'Test Person')
                self.db.update(self.o)
                raise KeyError
        except:
            pass
        assert_not_in(u'name', self.db[self.o.id])

    def test_success_transaciton(self):
        with self.db.transaction():
            self.o[u'name'] = ValueSet(u'Test Person')
            self.db.update(self.o)
        assert_in(u'name', self.db[self.o.id])

    def test_query(self):
        assert_not_in(self.o, self.db.query({u'key': 'Not here'}))
        assert_not_in(self.o, self.db.query({u'nokey': ANY}))
        assert_in(self.o, list(self.db.query({u'key': u'Test Person'})))
        assert_in(self.o, list(self.db.query({u'apa': None})))
        assert_in(self.o, list(self.db.query({u'key': Starts('Test')})))

    def test_query_objids(self):
        assert_not_in(self.o.id, self.db.query_ids({u'key': 'Not here'}))
        assert_in(self.o.id, list(self.db.query_ids({u'key': u'Test Person'})))
        assert_in(self.o.id, list(self.db.query_ids({u'apa': None})))
        assert_in(self.o.id, list(self.db.query_ids({u'key': Starts('Test')})))

    def test_update_empty(self):
        self.o[u'key'] = ValueSet([])
        self.db.update(self.o)
        o = self.db.get(self.o.id)
        assert_not_in(u'key', o)

    def test_update_with_same_t(self):
        self.o[u'key'] = ValueSet([u'Something completely differrent'], t=1)
        self.db.update(self.o)
        assert_equal(self.db[self.o.id][u'key'], ValueSet([u'Something completely differrent'], t=1))

    def test_update_attr(self):
        db, o = self.db, self.o
        db.update_attr(o.id, 'key', ValueSet([], t=1))
        assert_equal(db.get(o.id), o)
        db.update_attr(o.id, 'key', ValueSet([u'apa']))
        assert_equal(db.get(o.id)[u'key'], ValueSet([u'apa']))
        db.update_attr(o.id, 'key', ValueSet(o[u'key']))
        assert_equal(db.get(o.id)[u'key'], o[u'key'])

    def test_del_attr(self):
        db, o1 = self.db, self.o
        db.update_attr(o1.id, 'deleted', ValueSet([u'apa'], t=1))
        o2 = db.get(o1.id)
        assert_equal(o2[u'deleted'], ValueSet([u'apa']))
        del o2[u'deleted']
        db.update(o2)
        assert_equal(db.get(o1.id), o1)

    def test_del_obj(self):
        db, o = self.db, self.o

        del db[o]
        assert_equal(db[o.id], Object(o.id))
        assert_equal(list(db.query({"key": ANY})), [])

    def test_vacuum(self):
        db, o = self.db, self.o
        del db[o]
        assert_is_not_none(db._get_list_id(o[u'key']))
        assert_is_not_none(db._get_id('key', u'key'))
        assert_is_not_none(db._get_id('obj', o.id))
        db.vacuum()
        assert_is_none(db._get_list_id(self.o[u'key']))
        assert_is_not_none(db._get_id('key', u'key'))
        assert_is_not_none(db._get_id('obj', o.id))
        db.vacuum(0)
        assert_is_none(db._get_list_id(self.o[u'key']))
        assert_is_not_none(db._get_id('key', u'key'))
        assert_is_not_none(db._get_id('obj', o.id))

    def test_get_public_mappings_after(self):
        items = self.db.get_public_mappings_after()
        item = next((x for x in items if x[0] == u'some_id'), None)
        assert_is_not_none(item)
        item_serial = item[3]
        assert_equal(self.db.last_serial(), item_serial)
        assert_false(list(self.db.get_public_mappings_after(item_serial)))
        del self.db[self.o]
        items = self.db.get_public_mappings_after(item_serial)
        del_item = next((x for x in items if x[0] == u'some_id'), None)
        assert_equal(del_item[0], item[0])
        assert_equal(del_item[1], item[1])
        assert_equal(del_item[3], self.db.last_serial())
        assert_equal(del_item[4], set([]))

    def test_sync_state(self):
        assert_equal(self.db.get_sync_state('my_peer'), {"last_received": 0})
        self.db.set_sync_state('my_peer', 2)
        assert_equal(self.db.get_sync_state('my_peer'), {"last_received": 2})


# _*_ coding: utf-8 _*_
"""This file is a Cmbchina spider created on top of the ATSSpider

scrapy crawl cmbchina -a url="http://career.cmbchina.com/PositionList.aspx" -a mining_job_id=999 -a iteration=1 -a extract=1
sample url:
    http://career.cmbchina.com/PositionList.aspx
"""

from urlparse import urljoin
from re import compile

from scrapy.selector import Selector
from scrapy.http import Request

from brightcorp.base.atsspiders import ATSSpider
from brightcorp.items import BrightcorpItemLoader
from brightcorp.processors import ConvertDateString, Prefix

class Cmbchina(ATSSpider):

    name = "cmbchina"
    ref_reg = compile('id=(.*)&?')

    responsibilities = "//p/span[contains(text(),'%s')]/following-sibling::node()" % unicode("岗位职责", 'utf-8')
    qualifications = "//p/span[contains(text(),'%s')]/following-sibling::node()" % unicode("任职要求", 'utf-8')
    description = "//div[@class='c_article']/p[not(@id='examplace' or span[contains(text(),'%s') or contains(text(),'%s')])]" % (unicode("岗位职责", 'utf-8'), unicode("任职要求", 'utf-8'))

    def parse(self, response):

        sel = Selector(response)
        # Set expected job count
        if not self.expected_job_count_set:
            expected_count = sel.xpath(
                "//span[@id='totalcount']/text()"
                ).extract()
            if expected_count:
                    self.expected_job_count = expected_count[0]

        jobs = sel.xpath("//div[@class='poslist']/table//tr")
        for job in jobs:
            job_link = job.xpath("./td[1]/a/@href").extract()
            if job_link:
                job_url = urljoin(response.url, job_link[0])
                meta = {
                    'title': job.xpath("./td[1]/a/text()").extract(),
                    'location': job.xpath("./td[3]/text()").extract(),
                    'date': job.xpath("./td[4]/text()").extract(),
                    }
                yield Request(
                    job_url, meta=meta, callback=self.parse_job_callback()
                    )

        next_page = sel.xpath("//a[@id='nextpage']/@href").extract()
        if next_page:
            next_url = urljoin(response.url, next_page[0])
            yield Request(next_url, callback=self.parse)

    def parse_job(self, response):
        loader = BrightcorpItemLoader(response=response)
        loader.add_value('url', response.url)
        loader.add_value('apply_url', response.url)
        loader.add_value('title', response.meta['title'])
        loader.add_value('location', response.meta['location'])
        loader.add_value(
            'date', response.meta['date'], ConvertDateString("%Y-%m-%d")
            )
        loader.add_xpath('responsibilities', self.responsibilities)
        loader.add_xpath('qualifications', self.responsibilities)
        loader.add_xpath('description', self.description)
        loader.add_value(
            'referencenumber', response.url, Prefix(self.name+"-"),
            re=self.ref_reg
            )
        yield loader.load_item()


import os
import subprocess
from os.path import join

def merge_and_fade(videos_dir, n_DAs, fade_out_frame, name, fade_duration=2, verbose=False,
                   opacity=0.99):
    """Creates bash file to merge the HL videos and add fade in fade out effects using ffmpeg"""

    """Create the necissary files"""
    f1 = open(join(videos_dir, "addFadeAndMerge.sh"), "w+")
    f1.write("#!/bin/bash\n")

    """merge with section before disagreement"""
    for i in range(n_DAs):
        f1.write(f"ffmpeg -f concat -safe 0 -i temp/together{i}.txt -c copy temp/merged{i}.mp4\n")

    """fade in/out"""
    for i in range(n_DAs):
        f1.write(f"ffmpeg -i temp/merged{i}.mp4 -filter:v "
                 f"'fade=in:{0}:{fade_duration},fade=out:{fade_out_frame}:{fade_duration}' "
                 f"-c:v libx264 -crf 22 -preset veryfast -c:a copy temp/fadeInOut_DA_{i}.mp4\n")

    """concatenate videos"""
    f1.write(f"ffmpeg -f concat -safe 0 -i temp/final_list.txt -c copy {name}_DA.mp4")
    f1.close()

    """create files of videos to concatenate"""
    f2 = open(join(videos_dir, "temp/final_list.txt"), "w+")
    for i in range(n_DAs):
        f2.write(f"file fadeInOut_DA_{i}.mp4\n")
    f2.close()

    """create files of videos to concatenate"""
    for i in range(n_DAs):
        f = open(join(videos_dir, f"temp/together{i}.txt"), "w+")
        f.write(f"file together{i}.mp4\n")
        f.write(f"file a1_DA{i}.mp4\n")
        f.close()

    """make executable"""
    current_dir = os.getcwd()
    os.chdir(videos_dir)
    subprocess.call(["chmod", "+x", "addFadeAndMerge.sh"])
    """call ffmpeg"""
    if verbose:
        subprocess.call("./addFadeAndMerge.sh")
    else:
        subprocess.call("./addFadeAndMerge.sh", stdout=subprocess.DEVNULL,
                        stderr=subprocess.STDOUT)
    os.chdir(current_dir)  # return


#coding=utf-8
"""
    python 3
"""
from urllib.parse import parse_qs as parse_qs
import base64
import json
import re
import yaml
from shutil import copyfile
from downloadFile import *
from image_help import downloadImage_By_urllist
RES_FILE = None
IMAGE_PREFIX = None
IMAGE_COUNT = None
CONFIG = None

def parseImage(raw_query=None):
    req = parse_qs(raw_query)
    url = req['url'][0]
    url = base64.urlsafe_b64decode(url).decode('utf-8')
    if len(url.split('?')) > 2:
        raise Exception("url error : %s" % (url))
    url = url[:url.find('?')]
    return url

def parseResbody(body=None):
    """
        body is string
    """
    res_dict = dict()
    body = json.loads(body)
    if 'code' not in body or body['code'] != 0 or 'fileList' not in body:
        return None
    label = body['fileList'][0]['label']
    rate = body['fileList'][0]['rate']
    review = body['fileList'][0]['review']
    res_dict['label'] = label
    res_dict['rate'] = rate
    res_dict['review'] = review
    if label == 2 and 'objects' in body['fileList'][0]:
        objects = body['fileList'][0]['objects']
        if len(objects) > 0:
            res_dict['objects'] = objects[0]
    return res_dict

def parseLine(line=None):
    global RES_FILE
    global IMAGE_COUNT
    global IMAGE_PREFIX
    line_json = json.loads(line)
    if line_json['response_code'] != 200 or not line_json['respbody'] or not line_json['raw_query']:
        return
    result_dict = dict()
    try:
        res_dict = parseResbody(body=line_json['respbody'])
        url = parseImage(raw_query=line_json['raw_query'])
        if res_dict is not None and url is not None:
            for key in res_dict:
                result_dict[key] = res_dict[key]
            result_dict['url'] = url
            result_dict['newImageName'] = IMAGE_PREFIX + \
                '{:0>8}'.format(str(IMAGE_COUNT)) + '.jpg'
            IMAGE_COUNT += 1
        RES_FILE.write(json.dumps(result_dict, ensure_ascii=False))
        RES_FILE.write('\n')
        RES_FILE.flush()
    except Exception as e:
        print(line_json)
        print(str(e))
        exit()

def downloadImageByResFile(file=None, imagePath=None):
    downloadImage_By_urllist(urlListFile=file, imageSaveDir=imagePath)
    pass

def parseFile(file=None):
    global RES_FILE
    global IMAGE_PREFIX
    global IMAGE_COUNT
    global CONFIG
    res_file = file.replace('origin', 'res')
    RES_FILE = open(res_file, 'w')
    IMAGE_PREFIX = CONFIG['prefix'].upper()+CONFIG['data']+'-'
    IMAGE_COUNT = 0
    with open(file, 'r') as f:
        for line in f:
            line = line.strip()
            parseLine(line=line)
            # break
    RES_FILE.close()
    saveLogPath = '../saveLogDir'
    if not os.path.exists(saveLogPath):
        os.makedirs(saveLogPath)
    copyfile(res_file, os.path.join(saveLogPath, os.path.basename(res_file)))
    saveImagePath = '../saveImageDir'
    if not os.path.exists(saveImagePath):
        os.makedirs(saveImagePath)
    saveImagePath_date = os.path.join(saveImagePath,CONFIG['data'])
    if not os.path.exists(saveImagePath_date):
        os.makedirs(saveImagePath_date)
    downloadImageByResFile(file=res_file, imagePath=saveImagePath_date)

def initConfig():
    global CONFIG
    CONFIG = yaml.load(open('config.yaml'))
# def updataConfig(config=None):
#     conf = yaml.load(open('config.yaml'))
#     print(conf)
#     reu

def main():
    initConfig()
    print(CONFIG)
    logFile = downloadFile(CONFIG)
    parseFile(file=logFile)

if __name__ == '__main__':
    main()


# -*- coding: utf8 -*-

import os
import sys, getopt
sys.path.insert(0, os.path.abspath('..'))
from time import sleep
import inspect
import traceback
import platform
import subprocess
import json
from collections import OrderedDict

import common.xutils as xutils
import common._global as _global

import unittest

from appium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import TimeoutException
from appium.webdriver.connectiontype import ConnectionType

#AndroidTestCase
class ATC_Payment(unittest.TestCase):
    "Android 测试用例 - 支付相关"

    def setUp(self):
        "Setup for the test"
        desired_caps = {}
        desired_caps['automationName'] = 'Appium' #Appium (default) or Selendroid(before Android4.2 API level17)
        desired_caps['platformName'] = 'ANDROID'
        desired_caps['noReset'] = True ###Don’t reset app state between sessions (IOS: don’t delete app plist files; Android: don’t uninstall app before new session)
        desired_caps['unicodeKeyboard'] = True #Enable Unicode input
        desired_caps['resetKeyboard'] = True #Reset keyboard to its original state, after running Unicode tests with unicodeKeyboard capability

        desired_caps['applicationName'] = _global.DEVICE[_global.device]["UDID"] ### MUST! grid redirect request based on it
        desired_caps['deviceName'] = _global.DEVICE[_global.device]["UDID"]
        desired_caps['udid'] = _global.DEVICE[_global.device]["UDID"]
        desired_caps['platformVersion'] = _global.DEVICE[_global.device]["VERSION"]

        #explicitly tell Appium which application package and activity to launch, so Appium does not need to run aapt dump badging
        #desired_caps['app'] = '/Users/xiaweixing/workspace/appium_test/tmp/Sample-3063-testpay0812.apk'
        desired_caps['appPackage'] = 'com.example.test'
        desired_caps['appActivity'] = 'com.example.test.MainActivity'
        desired_caps['appWaitActivity'] = 'com.example.test.LoginActivity'

        #desired_caps['autoWebview'] = True
        desired_caps['newCommandTimeout'] = 300

        driver_url = 'http://' + _global.HUB_HOST + ':4444/wd/hub' #use selenium grid hub IP
        #driver_url = 'http://' + _global.HUB_HOST + ':' +  _global.DEVICE[_global.device]["PORT"] + '/wd/hub' #use individual appium server
        self.driver = webdriver.Remote(driver_url, desired_caps)
        self.driver.implicitly_wait(15)

    def tearDown(self):
        "Tear down the test"
        try:
            _global.img_list.clear()
            self.driver.quit()
        except (NoSuchElementException, TimeoutException, WebDriverException) as e:
            pass

    def test_payment_run_sample_apk(self):
        "支付sdk重复调起（请选择android4.4以上设备！！）"
        try:
            sleep(5)
            xutils.take_screenshot(self.driver, 1, 1)
            self.driver.find_element_by_xpath("//android.widget.Button[contains(@text,'使用WiFi万能钥匙登录')]").click()
            WebDriverWait(self.driver, 120).until(EC.presence_of_element_located((By.XPATH, "//android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]")))
            xutils.take_screenshot(self.driver, 5, 2)

            #contexts=self.driver.contexts
            #for context in contexts:
            #    print(context)
            #self.driver.switch_to.context('WEBVIEW_com.snda.wifilocating')
            #sleep(10)
            #print("current context is: " + self.driver.current_context)
            #print("page source is: " + self.driver.page_source)

            self.driver.find_element_by_accessibility_id("确认登录").click()
            #self.driver.tap([(self.driver.get_window_size()['width']/2, self.driver.get_window_size()['height']*3/5)],500)
            WebDriverWait(self.driver, 120).until(EC.presence_of_element_located((By.XPATH, "//android.widget.Button[contains(@text,'去支付')]")))
            xutils.take_screenshot(self.driver, 1, 3)
            for i in range(10):
                self.driver.find_element_by_xpath("//android.widget.Button[contains(@text,'去支付')]").click()
                WebDriverWait(self.driver, 120).until(EC.presence_of_element_located((By.XPATH, "//android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]")))
                xutils.take_screenshot(self.driver, 1, i+4)
                self.driver.back()
                self.driver.find_element_by_xpath("//android.widget.Button[contains(@text,'返回商户')]").click()
                sleep(2)
        except (NoSuchElementException, TimeoutException, WebDriverException) as e:
            self.fail("Exception Occurred !!!")
            print(traceback.format_exc())
        finally:
            #最后退出登录
            self.driver.find_element_by_xpath("//android.widget.Button[contains(@text,'退出登录')]").click()
            #pass


import os
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
from Pdf_malware.Scripts.Metric import *
from Pdf_malware.Scripts.utils import *
import matplotlib.pyplot as plt

class GlobalTest():
    def __init__(self, x, y, model, testRuleNum=50):
        self.x = x
        self.y = y
        self.model = model
        self.mean_vec = np.mean(np.sum(x, axis=1))
        self.pred_y = (model.predict(x, batch_size = 500) > 0.5)
        self.pos_x = x[np.where(self.pred_y == 1)[0]]
        self.neg_x = x[np.where(self.pred_y == 0)[0]]
        self.DenasRule = ReadRuleSet('../RuleSet/RuleSet.pkl')
        self.DenasRule = [r[:5] for r in self.DenasRule]

        self.TreeRule = ReadRuleSet("../RuleSet/tre.pkl")
        self.LemnaRule  = ReadRuleSet("../RuleSet/lemna.pkl")
        self.LemnaRule = [r[:5] for r in self.LemnaRule]
        self.GradientRule = ReadRuleSet("../RuleSet/gradient.pkl")
        self.GradientRule = [r[:5] for r in self.GradientRule]
        self.IGRule = ReadRuleSet("../RuleSet/integrated_gradients.pkl")
        self.IGRule = [r[:5] for r in self.IGRule]
        self.DPDrule =  ReadRuleSet("../RuleSet/deep_taylor.pkl")
        self.DPDrule = [r[:5] for r in self.DPDrule]
        self.testRuleNum = testRuleNum

    def CompareCoverage(self):
        self.coverage = np.zeros([self.testRuleNum, 6])
        self.coverage[:, 0] = testCoverage(self.DenasRule, self.pos_x)[0:self.testRuleNum]
        self.coverage[:, 1] = testCoverage(self.TreeRule, self.pos_x)[0:self.testRuleNum]
        self.coverage[:, 2] = testCoverage(self.GradientRule, self.pos_x)[0:self.testRuleNum]
        self.coverage[:, 3] = testCoverage(self.IGRule, self.pos_x)[0:self.testRuleNum]
        self.coverage[:, 4] = testCoverage(self.DPDrule, self.pos_x)[0:self.testRuleNum]
        self.coverage[:, 5] = testCoverage(self.LemnaRule, self.pos_x)[0:self.testRuleNum]
        np.savetxt('../Results/coverage.csv', self.coverage, delimiter=',')
        print("get coverage result")

    def CompareConsistIn(self):
        self.consist_in = np.zeros([5, 6])
        for i in range(5):
            maxlen  = i * 1 + 1
            consistency_1 =  ConsistencyIn(self.x, self.DenasRule, self.pred_y, maxlength=maxlen)
            self.consist_in[i, 0] = np.mean(consistency_1)
            consistency_2 =  ConsistencyIn(self.x, self.TreeRule, self.pred_y, maxlength=maxlen)
            self.consist_in[i, 1] = np.mean(consistency_2)

            consistency_3 =  ConsistencyIn(self.x, self.GradientRule, self.pred_y, maxlength=maxlen)
            self.consist_in[i, 2] = np.mean(consistency_3)
            consistency_4 =  ConsistencyIn(self.x, self.IGRule, self.pred_y, maxlength=maxlen)
            self.consist_in[i, 3] = np.mean(consistency_4)
            consistency_5 =  ConsistencyIn(self.x, self.DPDrule, self.pred_y, maxlength=maxlen)
            self.consist_in[i, 4] = np.mean(consistency_5)
            consistency_6 = ConsistencyIn(self.x, self.LemnaRule, self.pred_y, maxlength=maxlen)
            self.consist_in[4, 5] = np.mean(consistency_6)

        self.DenasRule = [ self.DenasRule[i] for i in range(len(consistency_1)) if consistency_1[i] > 0.9][
                         0: self.testRuleNum]
        self.TreeRule =[ self.TreeRule[i] for i in range(len(consistency_2)) if consistency_2[i] != 0][
                        0 : self.testRuleNum]

        self.GradientRule = [ self.GradientRule[i] for i in range(len(consistency_3)) if consistency_3[i] > 0.9][
                            0: self.testRuleNum]
        self.IGRule = [self.IGRule[i] for i in range(len(consistency_4)) if consistency_4[i] > 0.9][
                            0: self.testRuleNum]
        self.DPDrule = [self.DPDrule[i] for i in range(len(consistency_5)) if consistency_5[i] > 0.9][
                            0: self.testRuleNum]
        self.LemnaRule = [self.LemnaRule[i] for i in range(len(consistency_6)) if consistency_6[i] != 0][
                         0: self.testRuleNum]
        #np.savetxt('..//Results//con_in.csv', self.consist_in, delimiter=',')
        #print("get consistency result in distribution")

    def CompareConsistOut(self):
        self.consist_out = np.zeros([5, 6])
        newx = self.x + np.int32(np.random.random(self.x.shape) < (self.mean_vec * 10 / FEANUM))
        newx = (newx != 0)
        newy = (self.model.predict(newx, batch_size=200) > 0.5)

        for i in range(5):
            maxlen = i * 1 + 1
            self.consist_out[i, 0] = np.mean(ConsistencyIn(newx, self.DenasRule, newy, maxlength=maxlen))
            self.consist_out[i, 1] = np.mean(ConsistencyIn(newx, self.TreeRule, newy, maxlength=maxlen))
            self.consist_out[i, 2] = np.mean(ConsistencyIn(newx, self.GradientRule, newy, maxlength=maxlen))
            self.consist_out[i, 3] = np.mean(ConsistencyIn(newx, self.IGRule, newy, maxlength=maxlen))
            self.consist_out[i, 4] = np.mean(ConsistencyIn(newx, self.DPDrule, newy, maxlength=maxlen))
            self.consist_out[4, 5] = np.mean(ConsistencyIn(newx, self.LemnaRule, newy, maxlength=maxlen))

        #np.savetxt('../Results/con_out.csv', self.consist_out, delimiter=',')
        #print("get consistency result out of distribution")

    def PlotResult(self):
        self.CompareConsistIn()
        self.CompareConsistOut()
        self.CompareCoverage()
        print(self.coverage)
        name = ['denas', 'tree', 'gradient', 'IG', 'deeptaylor', 'lemna']
        L = []
        for i in range(6):
            l, = plt.plot(self.coverage[:,i])
            L.append(l)
        plt.legend(handles=L, labels=name)
        plt.savefig('../Results/coverage.png')
        #plt.show()

def main():
    x, y = loaddata(filepath = "../data/test_model_data.pkl")
    model = load_model('../model/MLP_model.h5')
    g = GlobalTest(x, y, model,testRuleNum=10)
    g.PlotResult()

if __name__ == '__main__':
    main()


#By: Benji Saltz
#Date: 30/03/18
#Description: Tower of Hanoi Recursive- This program allows a user to find the most efficient way to  solve a tower of hanoi puzzle
#What is Tower of Hanoi? Towar of Hanoi is a puzzle game in which a user has to move all disks from one pillar to the farthest pillar. The trick is larger disks cannot stack ontop of a smaller disks while sorting.
class Stack: #Stack class
    def __init__(self):
        self.items = []
    def push(self,item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
############################################
Left = Stack()
Middle = Stack()         #Values are given (Left, Center, Right)
Right = Stack()
num = int(input("enter the number of disks you want: "))
for a in range(num,0,-1): #stack is filled
    Left.push(a)
#############################################
def printTower():
    printTower.counter += 1 #Adds one to built in counter
    print ("Move", printTower.counter,"\n",Left.items,"\n",Middle.items,'\n',Right.items,'\n')

def t(num,beg,end,aux):
    if num==1:
        end.push(beg.pop()) #The function takes the top value from A and moves it to C
        printTower()
    else:
        t(num-1,beg,aux,end)  #The function takes the next value and moves it from stack A moves it to B
        end.push(beg.pop()) #The function takes the top value from A and moves it to C
        printTower()
        t(num-1,aux,end,beg)  #The function takes the next value and moves it from stack B moves it to C

printTower.counter = 0
t(num,Left,Right,Middle)              #functions are called


import argparse
import datetime
import sys
import warnings
import model
import util
import tf_util
from data import DataManager, OrderedBatchProvider
from settings import Settings

warnings.filterwarnings("ignore")

parser = argparse.ArgumentParser()
# Number of epochs of training. (One epoch uses all training material)
parser.add_argument('--epoch', dest='epoch', type=int, default=20)
# Batch size for single training inference
parser.add_argument('--batch_size', dest='batch_size', type=int, default=160)
# Image height that neural net expects. (Images of differing sizes will be scaled)
parser.add_argument('--height', dest='height', type=int, default=32)
# Image width that neural net expects. (Images of differing sizes will be scaled)
parser.add_argument('--width', dest='width', type=int, default=32)
# Number of channels that the neural net expects. (If channels=1, conversion to grayscale is applied if necessary)
parser.add_argument('--channels', dest='channels', type=int, default=3)
# Initial learning rate
parser.add_argument('--lr', dest='learning_rate', type=float, default=0.0001)
# Learning rate decay (Factor with which learning rate decreases every epoch)
parser.add_argument('--lr_decay', dest='learning_rate_decay', type=float, default=0.99)
# Dropout, only applied to dense layers (Dropout=percentage of neurons randomly omitted in training)
parser.add_argument('--dropout', dest='dropout_probability', type=float, default=1.0)
# Whether to use batch norm, only applied to convolutional layers
parser.add_argument('--batch_norm', dest='batch_norm', type=bool, default=False, choices=[True, False])
# The name of the trained model (used for saving the model at desired path)
parser.add_argument('--model', dest='model_name', default=datetime.datetime.now().strftime("%I_%M%p_on_%B_%d,_%Y"))
# The name of the dataset used for training. If available, the dataset will be downloaded automatically.
# isf -> limited dataset with 4 signs, badly cropped.
# isf-new -> also limited, better crop, but strange lighting (red shimmer)
# isf-complete -> complete dataset, all signs, various lighting, precisely cropped
# gtsrb -> real street signs, (Not all classes from CC present, even contains new classes)
# mnist -> standard hand written digits dataset
# cifar10 -> standard 32x32 image classification dataset (may be used for pre-training a model)
parser.add_argument('--dataset', dest='dataset_name', default='isf', choices=['isf', 'isf-new', 'isf-complete', 'gtsrb', 'mnist', 'cifar', 'cifar100'])
# Whether to augment the available training data at the start of the training
parser.add_argument('--augment', dest='augment_dataset', type=bool, default=False, choices=[True, False])
# For each real image, how many augmented images should be generated? (Program keeps track of original images via
# index file. If scalar is decreased after initial augmentation, augmented images will be deleted)
parser.add_argument('--augment_scalar', dest='augment_scalar', type=float, default=2.0)
# Path to settings file. (Settings will be restored from the given file)
parser.add_argument('--settings', dest='path_to_settings', type=str, default=None)
# How to restore a previously trained model
# auto -> If a settings file was specified (--settings), automatically resume the corresponding training
# by_name -> find a model in the ./models folder by name specified via (--restore_argument)
# path -> restore a model through its .ckpt files given by path path/to/model/files.ckpt via (--restore_arguent)
# transfer -> Same as path, but only certain parts of the model (given by --lock) will be restored
# NOTICE: If not using auto, the current settings have to match with the settings of the model you want to restore!
parser.add_argument('--restore', dest='restore_type', default='auto', choices=['auto', 'by_name', 'path', 'transfer'])
# Multi purpose argument used for restoring a model, for usage see explanation of (--restore)
parser.add_argument('--restore_argument', dest='restore_argument', default='')
# If 'transfer' is used with (--restore), this argument decides which parts of the model will be restored and locked
parser.add_argument('--lock', dest='training_lock', type=str, default='none', choices=['none', 'cnn', 'dnn', 'cnn-dnn'])
# Seed for stochastic processes for better reproducibility
parser.add_argument('--seed', dest='seed', type=int, default=0)
# Name of final node in inference graph
parser.add_argument('--output_node_name', dest='output_node_name', type=str, default='output_soft')
# Name of input node in inference graph
parser.add_argument('--input_node_name', dest='input_node_name', type=str, default='input_placeholder')
# Skip training in execution
parser.add_argument('--no-train', dest='train', action='store_false', default=True)
# Freeze model after training
parser.add_argument('--freeze', dest='freeze', action='store_true', default=False)
# Export model (creates zip with settings and frozen model)
parser.add_argument('--export', dest='export', action='store_true', default=False)
# Execute trained model (shows images and their classifications)
parser.add_argument('--execute', dest='execute', action='store_true', default=False)
# Whether to use synthetic data for training (For each batch new images will be generated by randomly placing
# a foreground image (--foreground), on a background image/video (--background) and randomly cropping. A maximum number
# of synthetic images per batch can be specified via (--max_synthetic_per_epoch))
parser.add_argument('--synthetic_data', dest='use_synthetic_training_data', action='store_true', default=False)
# Path to folder with background images/videos
parser.add_argument('--background', dest='path_to_background_data', type=str, default=None)
# Path to folder with foreground images
parser.add_argument('--foreground', dest='path_to_foreground_data', type=str, default=None)
# Maximum number of synthetic images per batch. Remaining batch size will be used by real training data.
parser.add_argument('--max_synthetic_per_epoch', dest='maximum_synthetic_batches_per_epoch', type=int, default=50)

args = parser.parse_args()
train_path, test_path = util.get_necessary_dataset(args.dataset_name, Settings.data_path_from_root)

if args.augment_dataset:
    util.augment_data(scalar=args.augment_scalar, path_to_data=train_path, path_to_index=util.get_index(train_path), balance=True)

if args.path_to_settings is None:
    settings = Settings({
        'conv_filters': [32, 32, 64, 64, 128],
        'conv_kernels': [3, 3, 2, 2, 2],
        'pooling_after_conv': [False, True, False, True, True],
        'fc_hidden': [1024],
        'height': args.height,
        'width': args.width,
        'channels': args.channels,
        'batch_size': args.batch_size,
        'learning_rate': args.learning_rate,
        'learning_rate_decay': args.learning_rate_decay,
        'dropout': args.dropout_probability,
        'batch_norm': args.batch_norm,
        'training_lock': args.training_lock,
        'model_name': args.model_name,
        'input_node_name': args.input_node_name,
        'output_node_name': args.output_node_name,
        'train_data_dir': train_path,
        'test_data_dir': test_path,
        'use_synthetic_training_data': args.use_synthetic_training_data,
        'path_to_background_data': args.path_to_background_data,
        'path_to_foreground_data': args.path_to_foreground_data,
        'maximum_synthetic_batches_per_epoch': args.maximum_synthetic_batches_per_epoch
    })
else:
    settings = Settings(None, restore_from_path=args.path_to_settings)

settings.assess(args)
data_manager = DataManager(settings)

if args.train:
    try:
        model.train(settings, data_manager, n_epochs=args.epoch, restore_type=args.restore_type)
    except KeyboardInterrupt:
        print('Stop training..')

if args.freeze:
    tf_util.freeze_graph(settings)

if args.export:
    util.export_model_to_production(settings)

if args.execute:
    tf_util.execute_frozen_model(settings, data_manager.test_provider)


from utilities.read_xls import read_xl
from bs4 import BeautifulSoup
import requests
import lxml
from base.meothods import MyDriver as MD

from selenium import webdriver
from time import sleep
import re
from selenium.webdriver.common.action_chains import ActionChains
from page.AlLogin import ALoginPage as AL

#1 Read the Suite details from column 4 in Suits.xls.
Suite_Names_list= read_xl("BaseLine.xls","Sheet1",0)
Suite_Id=read_xl("BaseLine.xls","Sheet1",1)

URL_WO_ID="http://autolab.corp.intuit.net/autolab/task/DeploymentPlanView.php?id="
URL_List=[]

for ID in Suite_Id:
    ID=str(ID)
    ID=ID.split(".")[0]
    URL=URL_WO_ID+"{}".format(ID)
    URL_List.append(URL)

driver=webdriver.Firefox()
driver.get(URL_List[0])
driver.implicitly_wait(30)
sleep(120)
text=driver.page_source
suitename_machineID={}
machineID = re.findall('\d{5,7}', text)
#machineIDStr = [str(x).replace('::', "") for x in machineID]
suitename_machineID[Suite_Names_list[0]] = machineID
# with open("mapped.txt", 'w')as mapping:
#     mapping.write(Suite_Names_list[0]+"\n")
#     str1 = ','.join(machineIDStr)
#     mapping.write(str1+"\n")
#     mapping.write("************************"+"\n")
print(Suite_Names_list[0], "\n")
print(machineID)
print("#########################################################################","\n")

for i in range(1,len(URL_List)):
    driver.get(URL_List[i])
    sleep(5)
    text=driver.page_source
    machineID=re.findall('\d{5,7}', text)
    #machineIDStr = [str(x).replace('::', "") for x in machineID]
    suitename_machineID[Suite_Names_list[i]] = machineID
    print(Suite_Names_list[i], "\n")
    print(machineID)
    print("#########################################################################", "\n")

    # with open("mapped.txt", 'w')as mapping:
    #     mapping.write(Suite_Names_list[i]+"\n")
    #     str1 = ','.join(machineIDStr)
    #     mapping.write(str1+"\n")
    #     print(Suite_Names_list[i],"\n")
    #     print(str1, "\n")
    #     print("#########################################################################","\n")
print(suitename_machineID)


#ID5

#This program finds the smallest number divisible by each number from 1 to 20

def prime(n):
    for i in range(2, int(n ** .5)+ 1):
        if n % i == 0:
            return False
    return True

def get_prime_factors(num):
    n = num
    L1 = [] #list of prime factors
    L2 = [] #list of times each factor occurs in number
    #L1(i) ** L2(i) multiplied together for each i gives num
    for i in range(2, num // 2 + 1):
        if prime(i):
            while n // i == n / i:
                if i in L1:
                    index = L1.index(i)
                    L2[index] += 1
                else:
                    L1.append(i)
                    L2.append(1)
                n = n / i
    if L1 == []:
        return [num], [1]
    return L1, L2

def combine_factors(L11, L12, L21, L22):
    L1 = []
    L2 = []
    for i in L11:
        L1.append(i)
        if i in L21:
            numtimes = max(L12[L11.index(i)], L22[L21.index(i)])
            L2.append(numtimes)
        else:
            L2.append(L12[L11.index(i)])
    for i in L21:
        if i not in L1:
            L1.append(i)
            L2.append(L22[L21.index(i)])
    return L1, L2

def ID5():
    L11 = []
    L12 = []
    for i in range(2, 21):
        L21, L22 = get_prime_factors(i)
        L11, L12 = combine_factors(L11, L12, L21, L22)
    x = 1
    for i in range(len(L11)):
        x = x * (L11[i] ** L12[i])
    print('The smallest number divisible by every number from 2 to 20 is', x)

ID5()


"""
Kwic Trader trading system
Created by:
Robert (Alex) Spangler
Plant City, FL, USA
Spring of 2021
"""

"""
Title: broker module
contains the logic for connecting to the broker.

From : https://alpaca.markets/docs/api-documentation/api-v2/positions/
"The positions API provides information about an account’s current open positions.
Information such as cost basis, shares traded, and market value, updated live as price
information is updated. Once a position is closed, it will no longer be queryable
through this API."

Position JSON Object/Entity Example:
{
  "asset_id": "904837e3-3b76-47ec-b432-046db621571b",
  "symbol": "AAPL",
  "exchange": "NASDAQ",
  "asset_class": "us_equity",
  "avg_entry_price": "100.0",
  "qty": "5",
  "side": "long",
  "market_value": "600.0",
  "cost_basis": "500.0",
  "unrealized_pl": "100.0",
  "unrealized_plpc": "0.20",
  "unrealized_intraday_pl": "10.0",
  "unrealized_intraday_plpc": "0.0084",
  "current_price": "120.0",
  "lastday_price": "119.0",
  "change_today": "0.0084"
}

"""

import alpaca_trade_api as tradeapi
import environmentVars, dataStorage
import sqlite3

MY_API_KEY = environmentVars.API_KEY
MY_SECRET_KEY = environmentVars.SECRET_KEY
BASE_URL = "https://paper-api.alpaca.markets"

api = tradeapi.REST(MY_API_KEY, MY_SECRET_KEY, BASE_URL, api_version='v2')

# Get a list of all positions.
portfolio = api.list_positions()

#Portfolio methods are below.
#These methods/functions return values and most return and store values in
#dictionaries keyed by the asset symbol.The dictionaries are accessed
#in the "main" module to populate the brokerage table for display to the user.
#NOTE: a "position" is the collection of identical shares/contracts
#of a single financial asset, such as a stock,bond, or futures contract.
#For development purposes, only stocks are used.

def numShares():
    """
    Number of Shares
    Stores the number of shares comprising each position in a dictionary
    with the market symbol as the key.
    :return: dictionary
    """
    numshares = dict()
    for position in portfolio:
        numshares[position.symbol] = position.qty
    return numshares

def currentPrice():
    """
    Current Price
    Stores the current price for each share in a position in a dictionary
    with the market symbol as the key.
    :return: dictionary
    """
    currentprice = dict()
    for position in portfolio:
        currentprice[position.symbol] = position.current_price
    return currentprice

def costPerShare( ):
    """
    Cost per Share
    The amount paid at entry per share
    :return: dictionary
    """
    cstshare = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        cost = float(position.avg_entry_price)
        cstshare[position.symbol] = cost
    return cstshare

def currValue():
    """
    Current Position Value
    Store the current total market value of each portfolio position
    in a dictionary with the market symbol as the key.This is market_value
    from the Alpaca API and is equal to the current_price * qty (number of shares)
    of each asset position.
    :return: dictionary
    """
    currvalue = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        mktvalue = float(position.market_value)
        currvalue[position.symbol] = mktvalue
    return currvalue

def totalCost():
    """
    Total Cost
    This method returns a dictionary of the total price paid for each asset,
    which is cost_basis from the Alpaca API.
    :return: dictionary
    """
    totalcost = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        cost = float(position.cost_basis)
        totalcost[position.symbol] = cost
    return totalcost

def shareChange():
    """
    Share Change
    Calculates and stores in a dictionary the current change in asset
    price per share since yesterday, which is current_price - lastday_price
    :return: dictionary
    """
    sharechange = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        current = float(position.current_price)
        last = float(position.lastday_price)
        sharechange[position.symbol] = current - last
    return sharechange

def dayChange():
    """
    Day Change
    Calculates and stores in a dictionary the total current change in position
    value since yesterday, which is (current_price - lastday_price)* qty.
    :return: dictionary
    """
    daychange = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        current = float(position.current_price)
        last = float(position.lastday_price)
        quant = float(position.qty)
        daychange[position.symbol] = (current - last) * quant
    return daychange

def shareProfit():
    """
    Share Profit
    Calculates the total current amount of profit/loss per share of each asset
    which is current_price - avg_entry_price
    :return: dictionary
    """
    shareprofit = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        current = float(position.current_price)
        entry = float(position.avg_entry_price)
        shareprofit[position.symbol] = (current - entry )
    return shareprofit

def positionProfit():
    """
    Position Profit
    Calculates the current position profit of each asset which is
    (current_price - avg_entry_price) * qty
    :return: python dictionary
    """
    psnprofit = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        quant = float(position.qty)
        current = float(position.current_price)
        entry = float(position.avg_entry_price)
        psnprofit[position.symbol] = (current - entry) * quant
    return psnprofit

# Place portfolioValue method here
def portfolioValue():
    """
    Portfolio Value
    Calculates the current total portfolio value, the sum of value of all shares owned.
    This function returns a single total portfolio value.
    :return: float
    """
    portvalue = (sum(currValue().values()))
    return round(portvalue, 2)

def portDayChng():
    """
    Portfolio Day Change
    Calculates the change of the total portfolio value since yesterday
    This function returns single portfolio value change.
    :return: float
    """
    portdychng = (sum(dayChange().values()))
    return round(portdychng, 2)

def positionPctProfit():
    """
    Position Percent Profit
    The percentage profit/loss of each position. Returns a dictionary with
    market symbol keys and percent values.
    :return: dictionary
    """
    psnpct = dict()
    for position in portfolio:
        # Strings are returned from API; convert to floating point type
        current = float(position.current_price)
        entry = float(position.avg_entry_price)
        psnpct[position.symbol] = ((current - entry) / entry) * 100
    return psnpct

def portPctProfit():
    """
    Portfolio Percentage Profit
    The percentage profit/loss of the entire portfolio. Returns a single valued percentage
    :return: float
    """
    totcost = (sum(totalCost().values()))
    totvalue = portfolioValue()
    portpct = ((totvalue - totcost)/totcost) * 100
    return round(portpct, 2)

def portProfit():
    """
    Portfolio Total Profit
    The total profit/loss of the entire portfolio. Returns a single valued number
    :return: float
    """
    totcost = (sum(totalCost().values()))
    totvalue = portfolioValue()
    portprof = (totvalue - totcost)
    return round(portprof, 2)

# Todo: figure out how to integrate logic into main
#  for calling this method and inserting new markets
#  user has bought into table.
#  ( NOTE: THIS Will be DONE in later version)
def dataForBrokerageTable():
    """
    Creates records in brokerStats DB table
    :return: Void
    """

    # get all necessary values
    costPerShareDict = costPerShare()
    shareProfitDict = shareProfit()
    profitAndLossDict = positionProfit()
    quantityDict = numShares()
    priceDict = currentPrice()
    valueDict = currValue()
    dayChangeDict = dayChange()
    costDict = totalCost()
    pLPercentDict = positionPctProfit()

    # empty list to store market symbol.
    symList = []

    # get market symbols
    for key in quantityDict:
      symList.append(key)

    for mS in symList:

      dataStorage.brokerStatsRecord(mS, costPerShareDict[mS], round(shareProfitDict[mS], 2),
                                    round(profitAndLossDict[mS], 2), quantityDict[mS], priceDict[mS], valueDict[mS],
                                    round(dayChangeDict[mS], 2), costDict[mS], round(pLPercentDict[mS], 2))

# calls method to insert data into brokerStats table
# dataForBrokerageTable()


"""Progress Bar, by Al Sweigart al@inventwithpython.com

A sample progress bar animation that can be used in other programs."""
__version__ = 1

import random, time

def getProgressBar(progress, total, barWidth=40):
    """Returns a string that represents a progress bar that has `barWidth`
    bars and has progressed `progress` amount out of a `total` amount."""

    progressBar = '' # The progress bar will be a string value.
    progressBar += '[' # Create the left end of the progress bar.

    # Make sure that the amount of progress is between 0 and total:
    if progress > total:
        progress = total
    if progress < 0:
        progress = 0

    # Calculate the number of "bars" to display:
    numberOfBars = int((progress / total) * barWidth)

    progressBar += '*' * numberOfBars # Add the progress bar.
    progressBar += ' ' * (barWidth - numberOfBars) # Add the empty space.
    progressBar += ']' # Add the right end of the progress bar.

    # Calculate the percentage complete:
    percentComplete = round(progress / total * 100, 1)
    progressBar += ' ' + str(percentComplete) + '%' # Add the percentage.

    progressBar += ' ' + str(progress) + '/' + str(total) # Add the numbers.

    return progressBar # Return the progress bar string.

# Simulate a download:
bytesDownloaded = 0
downloadSize = 4098
while bytesDownloaded < downloadSize:
    # "Download" a random amount of "bytes":
    bytesDownloaded += random.randint(0, 100)

    # Get the progress bar string for this amount of progress:
    barStr = getProgressBar(bytesDownloaded, downloadSize)

    # Don't print a newline at the end, and immediately flush the
    # printed string to the screen:
    print(barStr, end='', flush=True)

    # Pause for a little bit:
    time.sleep(0.2)

    # Print backspaces to erase the previously printed progress bar:
    print('\b' * len(barStr), end='', flush=True)


from xai.brain.wordbase.nouns._flipper import _FLIPPER

#calss header
class _FLIPPERS(_FLIPPER, ):
	def __init__(self,):
		_FLIPPER.__init__(self)
		self.name = "FLIPPERS"
		self.specie = 'nouns'
		self.basic = "flipper"
		self.jsondata = {}


"""
order people records by age (ascending) and print them according to
(Mr.|Ms.) <First> <Last>
"""

from operator import itemgetter

def format_person(person_tuple):
    gender = person_tuple[3]
    title = "Mr." if gender == 'M' else "Ms."
    return "{} {} {}".format(title, person_tuple[0], person_tuple[1])

def parse_person(s):
    (first, last, age, gender) = s.split()
    return (first, last, int(age), gender)

n = int(input())
people = (parse_person(input()) for _ in range(n))

for person in sorted(people, key=itemgetter(2)):
    print(format_person(person))


import logging
import re

import pytest
import requests_mock as requests_mock_lib
from pytest_mock import MockerFixture
from requests_mock import Mocker as RequestsMocker

from corva import Logger
from corva.handlers import scheduled
from corva.models.scheduled.raw import (
    RawScheduledDataTimeEvent,
    RawScheduledDepthEvent,
    RawScheduledEvent,
    RawScheduledNaturalTimeEvent,
)
from corva.models.scheduled.scheduled import ScheduledDataTimeEvent, ScheduledEvent
from corva.models.scheduled.scheduler_type import SchedulerType

def test_set_completed_status(context, requests_mock):
    @scheduled
    def scheduled_app(event, api, state):
        pass

    event = [
        [
            RawScheduledDataTimeEvent(
                asset_id=int(),
                interval=int(),
                schedule=int(),
                schedule_start=int(),
                app_connection=int(),
                app_stream=int(),
                company=int(),
                scheduler_type=SchedulerType.data_time,
            ).dict(
                by_alias=True,
                exclude_unset=True,
            )
        ]
    ]

    # patch post request, that sets scheduled task as completed
    # looks for url path like /scheduler/123/completed
    post_mock = requests_mock.post(re.compile(r'/scheduler/\d+/completed'))

    scheduled_app(event, context)

    assert post_mock.called_once
    assert post_mock.last_request.path == '/scheduler/0/completed'

@pytest.mark.parametrize(
    'event',
    (
        RawScheduledDataTimeEvent(
            asset_id=int(),
            interval=int(),
            schedule=int(),
            schedule_start=int(),
            app_connection=int(),
            app_stream=int(),
            company=int(),
            scheduler_type=SchedulerType.data_time,
        ).dict(
            by_alias=True,
            exclude_unset=True,
        ),
        RawScheduledDepthEvent(
            asset_id=int(),
            depth_milestone=float(),
            schedule=int(),
            app_connection=int(),
            app_stream=int(),
            company=int(),
            scheduler_type=SchedulerType.data_depth_milestone,
            top_depth=0.0,
            bottom_depth=1.0,
            log_identifier='',
        ).dict(
            by_alias=True,
            exclude_unset=True,
        ),
        RawScheduledNaturalTimeEvent(
            asset_id=int(),
            interval=int(),
            schedule=int(),
            app_connection=int(),
            app_stream=int(),
            company=int(),
            scheduler_type=SchedulerType.natural_time,
            schedule_start=int(),
        ).dict(
            by_alias=True,
            exclude_unset=True,
        ),
    ),
)
@pytest.mark.parametrize('is_dict', (True, False))
def test_event_parsing(event, is_dict, requests_mock: RequestsMocker, context):
    @scheduled
    def scheduled_app(event, api, state):
        pass

    if not is_dict:
        event = [[event]]

    requests_mock.post(requests_mock_lib.ANY)

    scheduled_app(event, context)

@pytest.mark.parametrize(
    'event,attr',
    (
        [
            RawScheduledDataTimeEvent(
                asset_id=int(),
                interval=int(),
                schedule=int(),
                schedule_start=int(),
                app_connection=int(),
                app_stream=int(),
                company=int(),
                scheduler_type=SchedulerType.data_time,
            ),
            'end_time',
        ],
        [
            RawScheduledNaturalTimeEvent(
                asset_id=int(),
                interval=int(),
                schedule=int(),
                schedule_start=int(),
                app_connection=int(),
                app_stream=int(),
                company=int(),
                scheduler_type=SchedulerType.natural_time,
            ),
            'schedule_start',
        ],
    ),
)
@pytest.mark.parametrize(
    'value,expected',
    (
        # 31 December 9999 23:59:59 in sec
        [253402300799, 253402300799],
        # 1 January 10000 00:00:00 in sec
        [253402300800, 253402300],
        # 1 January 2021 00:00:00 in ms
        [1609459200000, 1609459200],
        # 1 January 2021 00:00:00 in sec
        [1609459200, 1609459200],
    ),
    ids=(
        'no cast performed',
        'casted from ms to sec',
        'casted from ms to sec',
        'no cast performed',
    ),
)
def test_set_schedule_start(
    event: RawScheduledEvent, attr: str, value, expected, context, mocker: MockerFixture
):
    @scheduled
    def app(e, api, state):
        return e

    event = event.copy(update={'schedule_start': value})
    event = (
        type(event)
        .parse_obj(
            event.dict(
                by_alias=True,
                exclude_unset=True,
            )
        )
        .dict(
            by_alias=True,
            exclude_unset=True,
        )
    )

    mocker.patch.object(RawScheduledEvent, 'set_schedule_as_completed')

    result_event: ScheduledEvent = app(event, context)[0]

    assert getattr(result_event, attr) == expected

@pytest.mark.parametrize(
    'schedule_start,interval,expected',
    (
        [2, 1, 2],
        [2, 2, 1],
    ),
)
def test_set_start_time(
    schedule_start, interval, expected, context, mocker: MockerFixture
):
    @scheduled
    def app(event, api, state):
        return event

    event = [
        [
            RawScheduledDataTimeEvent(
                asset_id=int(),
                interval=interval,
                schedule=int(),
                schedule_start=schedule_start,
                app_connection=int(),
                app_stream=int(),
                company=int(),
                scheduler_type=SchedulerType.data_time,
            ).dict(
                by_alias=True,
                exclude_unset=True,
            )
        ]
    ]

    mocker.patch.object(RawScheduledEvent, 'set_schedule_as_completed')

    result_event: ScheduledDataTimeEvent = app(event, context)[0]

    assert result_event.start_time == expected

def test_set_completed_status_should_not_fail_lambda(context, mocker: MockerFixture):
    @scheduled
    def scheduled_app(event, api, state):
        pass

    event = [
        [
            RawScheduledDataTimeEvent(
                asset_id=int(),
                interval=int(),
                schedule=int(),
                schedule_start=int(),
                app_connection=int(),
                app_stream=int(),
                company=int(),
                scheduler_type=SchedulerType.data_time,
            ).dict(
                by_alias=True,
                exclude_unset=True,
            )
        ]
    ]

    patch = mocker.patch.object(
        RawScheduledEvent, 'set_schedule_as_completed', side_effect=Exception
    )

    scheduled_app(event, context)

    patch.assert_called_once()

def test_log_if_unable_to_set_completed_status(context, mocker: MockerFixture, capsys):
    @scheduled
    def scheduled_app(event, api, state):
        pass

    event = [
        [
            RawScheduledDataTimeEvent(
                asset_id=int(),
                interval=int(),
                schedule=int(),
                schedule_start=int(),
                app_connection=int(),
                app_stream=int(),
                company=int(),
                scheduler_type=SchedulerType.data_time,
            ).dict(
                by_alias=True,
                exclude_unset=True,
            )
        ]
    ]

    patch = mocker.patch.object(
        RawScheduledEvent, 'set_schedule_as_completed', side_effect=Exception
    )

    scheduled_app(event, context)

    captured = capsys.readouterr()

    assert 'ASSET=0 AC=0' in captured.out
    assert 'Could not set schedule as completed.' in captured.out
    patch.assert_called_once()

def test_custom_log_handler(context, capsys, mocker: MockerFixture):
    @scheduled(handler=logging.StreamHandler())
    def app(event, api, cache):
        Logger.info('Info message!')

    event = RawScheduledDataTimeEvent(
        asset_id=0,
        interval=int(),
        schedule=int(),
        schedule_start=int(),
        app_connection=1,
        app_stream=int(),
        company=int(),
        scheduler_type=SchedulerType.data_time,
    )

    mocker.patch.object(RawScheduledEvent, 'set_schedule_as_completed')

    app(
        [
            [
                event.dict(
                    by_alias=True,
                    exclude_unset=True,
                )
            ]
        ],
        context,
    )

    captured = capsys.readouterr()

    assert captured.out.endswith('Info message!\n')
    assert captured.err == 'Info message!\n'


from aws_cdk import aws_iam, core
from common.common_stack import CommonStack
from common.region_aware_stack import RegionAwareStack

class SnsStack(RegionAwareStack):
    def __init__(self, scope: core.Construct, id: str, common_stack: CommonStack, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self._supported_in_region = self.is_service_supported_in_region()

        stack_policy = aws_iam.PolicyStatement(
            effect=aws_iam.Effect.ALLOW,
            actions=["sns:ListTopics"],
            resources=["*"],
        )
        common_stack.add_to_common_role_policies(self, policy_to_add=stack_policy)


#ex033
#Faça um programa que leia três números e mostra qual é o maior e qual é o menor

print('Digite 3 números diferentes!')
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
n3 = int(input('Digite o terceiro número: '))

#Verificando o menor
a = n1
b = n2
c = n3
menor = a
if b < a and b < c:
    menor = b
if c < a and c < b:
    menor = c
#Verificando o maior
maior = a
if b > a and b > c:
    maior = b
if c > a and c > b:
    maior = c
print('===' * 10)
print('maior é ', maior)
print('menor é ', menor)


# Copyright 2014 OpenStack Foundation
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import logging
import urwid

from mqtty import keymap
from mqtty import mywid
from mqtty.view import message_list as view_message_list
from mqtty.view import mouse_scroll_decorator

class ColumnInfo(object):
    def __init__(self, name, packing, value):
        self.name = name
        self.packing = packing
        self.value = value
        self.options = (packing, value)
        if packing == 'given':
            self.spacing = value + 1
        else:
            self.spacing = (value * 8) + 1

COLUMNS = [
    ColumnInfo('No.', 'given', 5),
    ColumnInfo('Topic', 'weight', 1),
    ColumnInfo('# of MSG', 'given', 9),
]

class TopicListHeader(urwid.WidgetWrap):
    def __init__(self):
        cols = [(5, urwid.Text(u' No.')),
                urwid.Text(u' Topic'),
                (9, urwid.Text(u'# of MSG')),
                ]
        super(TopicListHeader, self).__init__(urwid.Columns(cols))

@mouse_scroll_decorator.ScrollByWheel
class TopicListView(urwid.WidgetWrap, mywid.Searchable):
    title = "Topics"

    def getCommands(self):
        return [
            (keymap.TOGGLE_LIST_SUBSCRIBED,
             "Toggle whether only subscribed projects or all projects are"
             " listed"),
            (keymap.TOGGLE_LIST_REVIEWED,
             "Toggle listing of projects with unreviewed changes"),
            (keymap.TOGGLE_SUBSCRIBED,
             "Toggle the subscription flag for the selected project"),
            (keymap.REFRESH,
             "Sync subscribed projects"),
            (keymap.TOGGLE_MARK,
             "Toggle the process mark for the selected project"),
            (keymap.NEW_PROJECT_TOPIC,
             "Create project topic"),
            (keymap.DELETE_PROJECT_TOPIC,
             "Delete selected project topic"),
            (keymap.MOVE_PROJECT_TOPIC,
             "Move selected project to topic"),
            (keymap.COPY_PROJECT_TOPIC,
             "Copy selected project to topic"),
            (keymap.REMOVE_PROJECT_TOPIC,
             "Remove selected project from topic"),
            (keymap.RENAME_PROJECT_TOPIC,
             "Rename selected project topic"),
            (keymap.INTERACTIVE_SEARCH,
             "Interactive search"),
        ]

    def help(self):
        key = self.app.config.keymap.formatKeys
        commands = self.getCommands()
        return [(c[0], key(c[0]), c[1]) for c in commands]

    def __init__(self, app):
        super(TopicListView, self).__init__(urwid.Pile([]))
        self.log = logging.getLogger('mqtty.view.topic_list')
        self.searchInit()
        self.app = app
        self.unreviewed = True
        self.subscribed = True
        self.reverse = False
        self.project_rows = {}
        self.topic_rows = {}
        self.open_topics = set()
        self.sort_by = 'name'
        self.listbox = urwid.ListBox(urwid.SimpleFocusListWalker([]))
        self.refresh()
        self.header = TopicListHeader()
        self._w.contents.append((app.header, ('pack', 1)))
        self._w.contents.append((urwid.Divider(), ('pack', 1)))
        self._w.contents.append(
            (urwid.AttrWrap(self.header, 'table-header'), ('pack', 1)))
        self._w.contents.append((self.listbox, ('weight', 1)))
        self._w.set_focus(3)

    def selectable(self):
        return True

    def sizing(self):
        return frozenset([urwid.FIXED])

    def refresh(self):
        self.log.debug('topic_list refresh called ===============')

        len(self.listbox.body)
        # for row in self.listbox.body:
        #     self.listbox.body.remove(row)
        i = 0
        with self.app.db.getSession() as session:
            topic_list = session.getTopics(sort_by=self.sort_by)
            if self.reverse:
                topic_list.reverse()
            for topic in topic_list:
                num_msg = len(session.getMessagesByTopic(topic))
                key = topic.key
                row = self.topic_rows.get(key)
                if not row:
                    row = TopicRow(topic, num_msg, self.onSelect)
                    self.listbox.body.append(row)
                    self.topic_rows[key] = row
                else:
                    row.update(topic, num_msg)
                i = i + 1

        self.title = "Topics: " + str(i)
        self.app.status.update(title=self.title)

#            if i > 0:
#                self.listbox.body.pop()
        # for key in self.app.db.topics:
        #     self.log.debug(key)
        #     self.listbox.body.append(TopicRow(Topic(key, key + "_name")))

    def clearTopicList(self):
        for key, value in self.topic_rows.items():
            self.listbox.body.remove(value)
        self.topic_rows = {}

    def keypress(self, size, key):
        if self.searchKeypress(size, key):
            return None

        if not self.app.input_buffer:
            key = super(TopicListView, self).keypress(size, key)
        keys = self.app.input_buffer + [key]
        commands = self.app.config.keymap.getCommands(keys)
        ret = self.handleCommands(commands)
        if ret is True:
            if keymap.FURTHER_INPUT not in commands:
                self.app.clearInputBuffer()
            return None
        return key

    def handleCommands(self, commands):
        self.log.debug('handleCommands called')
        if keymap.REFRESH in commands:
            self.refresh()
            self.app.status.update()
            return True
        if keymap.SORT_BY_NUMBER in commands:
            if not len(self.listbox.body):
                return True
            self.sort_by = 'key'
            self.clearTopicList()
            self.refresh()
            return True
        if keymap.SORT_BY_TOPIC in commands:
            if not len(self.listbox.body):
                return True
            self.sort_by = 'name'
            self.clearTopicList()
            self.refresh()
            return True

            if not len(self.listbox.body):
                return True
            if self.reverse:
                self.reverse = False
            else:
                self.reverse = True
            self.clearTopicList()
            self.refresh()
            return True
        if keymap.INTERACTIVE_SEARCH in commands:
            self.searchStart()
            return True

    def onSelect(self, button, data):
        topic = data
        self.app.changeScreen(view_message_list.MessageListView(
            self.app, topic))

class TopicListColumns(object):
    def updateColumns(self):
        del self.columns.contents[:]
        cols = self.columns.contents
        options = self.columns.options

        for colinfo in COLUMNS:
            if colinfo.name in self.enabled_columns:
                attr = colinfo.name.lower().replace(' ', '_')
                cols.append((getattr(self, attr),
                             options(*colinfo.options)))

        for c in self.category_columns:
            cols.append(c)

class TopicRow(urwid.Button, TopicListColumns):
    topic_focus_map = {None: 'focused',
                       # 'subscribed-project': 'focused-subscribed-project',
                       # 'marked-project': 'focused-marked-project',
                       }

    def selectable(self):
        return True

    def _setName(self, name):
        self.topic_name = name
        name = name
        if self.mark:
            name = '%' + name
        else:
            name = ' ' + name
        self.name.set_text(name)

    def __init__(self, topic, num_msg, callback=None):
        super(TopicRow, self).__init__('', on_press=callback,
                                       user_data=(topic))
        self.mark = False
        self._style = None
        # self.topic_key = topic.key
        self.name = mywid.SearchableText('')

        self._setName(topic.name)
        # FIXME: showing 'topic_key' is just for debugging. This should be
        # removed.
        self.topic_key = urwid.Text(u'', align=urwid.RIGHT)
        self.name.set_wrap_mode('clip')
        self.num_msg = urwid.Text(u'', align=urwid.RIGHT)
        col = urwid.Columns([
            ('fixed', 5, self.topic_key),
            self.name,
            ('fixed', 9, self.num_msg),
        ])
        self.row_style = urwid.AttrMap(col, '')
        self._w = urwid.AttrMap(self.row_style, None,
                                focus_map=self.topic_focus_map)
        self._style = None  # 'subscribed-project'
        self.row_style.set_attr_map({None: self._style})
        # self.num_msg = num_msg
        self.update(topic, num_msg)

    def search(self, search, attribute):
        return self.name.search(search, attribute)

    def update(self, topic, num_msg):
        # FIXME: showing 'topic_key' is just for debugging. This should be
        # removed.
        self.topic_key.set_text('%i ' % topic.key)
        self.num_msg.set_text('%i ' % num_msg)
        # self._setName(str(topic.key) + " " + topic.name + " " + str(num_msg))

    def toggleMark(self):
        self.mark = not self.mark
        if self.mark:
            style = 'marked-topic'
        else:
            style = self._style
        self.row_style.set_attr_map({None: style})
        self._setName(self.topic_name)