from turtle import color, right
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
from dash_bootstrap_components._components.Navbar import Navbar

# Connect to main app.py file
from app import app
from app import server

# Connect to your app pages
from apps import vendas, produto, home, notfound

import montaGraficoVendas
import montaGraficoPedidos

nav_link1 = {
    "color": "white",
    "textAlign": "right",
    "fontSize": 15,
    "marginLeft": "600",
    "backgroundColor": "black",
}

nav_link2 = {
    "color": "white",
    "textAlign": "right",
    "fontSize": 15,
    "marginRight": "50",
    "backgroundColor": "black",
}

nav_name = {
    "color": "white",
    "textAlign": "left",
    "fontSize": 18,
    "margin": "auto",
    "fontFamily": "cursive",
    #"backgroundColor": "red",
}

nav_item_01 = dbc.NavLink('Vendas', href='/apps/vendas')
nav_item_02 = dbc.NavLink('Produtos', href='/apps/produto')

navbar = dbc.Navbar(dbc.Container(
         [
             html.A(
                 # Use row and col to control vertical alignment of logo / brand
                 dbc.Row(
                     [
                         dbc.Col(html.Img(src='/assets/EasyDash.png', height="20px")),
                         dbc.Col(dbc.NavbarBrand("2JR Multimarcas", className="ms-2", style=nav_name)),

                     ],
                     align="center",
                     className="g-0",

                 ),
                 href="/",
                 style={"textDecoration": "none"},
             ),
             dbc.Nav([
                                               nav_item_01,nav_item_02
                                             ],

                                             className="ms-auto",
                                             navbar=True,
                                            ),

         ]
     ),
     color="primary",
     dark=True

)

app.layout = html.Div([navbar,
     dcc.Location(id='url', refresh=False),
    #  html.Div([

    #      dbc.NavLink('Video Games|', href='/apps/vendas'),

    #      dbc.NavLink('Other', href='/apps/produto'),

    # ], className="row"),
     html.Div(id='page-content', children=[])

 ])

@app.callback(Output('page-content', 'children'),
              [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/apps/vendas':
        return vendas.layout
    if pathname == '/apps/produto':
        return produto.layout
    if pathname == '/':
        return home.layout
    else:
        return notfound.layout

if __name__ == '__main__':
    app.run_server(debug=False)


import pygame
import sys
import csv
import copy
import time

pygame.init()

WIDTH = 800
HEIGHT = 600
COLOR = (0,101,149)

screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Sudoku')
title_font = pygame.font.Font('MachineGunk-nyqg.ttf',80)
path_font = pygame.font.Font('MachineGunk-nyqg.ttf',15)
inp_font = pygame.font.SysFont('calibri',12)

menu_bg = pygame.image.load('bg.jpg')
title = title_font.render('Sudoku',False,COLOR)
path = path_font.render('Enter Puzzle path :',False,COLOR)
inp_txt = ''
inp_field = pygame.Rect(80,280,300,15)
menu_flag = True

def empty(puzzle):
    empties = []
    for i in range(len(puzzle)):
        for j in range(len(puzzle)):
            if puzzle[i][j]=='0':
                empties.append((i,j))
    return empties

def menu():
    inp = inp_font.render(inp_txt, False, 'White')
    screen.blit(menu_bg, (0, 0))
    screen.blit(title, (80, 180))
    screen.blit(path, (80, 260))
    screen.blit(inp, (85, 282.5))
    pygame.draw.rect(screen, 'White', inp_field, 2)

def board(puzzle):
    board_origin = (200,100)
    tile_size = 40

    for i in range(len(puzzle)):
        for j in range(len(puzzle)):
            rect = pygame.Rect(
                board_origin[0] + j*tile_size,
                board_origin[1] + i* tile_size,
                tile_size, tile_size
            )
            pygame.draw.rect(screen,'White',rect,3)
            if puzzle[i][j]!='0':
                cell = path_font.render(puzzle[i][j],True,COLOR)
                cellRect = cell.get_rect()
                cellRect.center = rect.center
                screen.blit(cell,cellRect)

def revise(puzzle):
    maps = {}
    rank = []
    empties = empty(puzzle)
    for cell in empties:
        domain= list(range(1,10))
        maps[cell] = list(range(1,10))
        (i,j) = cell
        vert = [puzzle[a][j] for a in range(len(puzzle))]
        i_start = (i//3)*3
        j_start = (j//3)*3
        grid = [puzzle[c][b] for c in range(i_start,i_start+3) for b in range(j_start,j_start+3)]
        for val in domain:
            if str(val) in puzzle[i]:
                maps[cell].remove(val)
            elif str(val) in vert:
                maps[cell].remove(val)
            elif str(val) in grid:
                maps[cell].remove(val)
        rank_cell = len(maps[cell])
        if rank_cell==0:
            return (maps,False)
        if len(rank)==0:
            rank.append(cell)
        for r in range(len(rank)):
            if len(maps[rank[r]])>rank_cell:
                if cell not in rank:
                    rank = rank[:r]+[cell]+rank[r:]
        if cell not in rank:
            rank.append(cell)

    return (maps,rank)

def backtrack(puzzle,rank,maps):
    domains = copy.deepcopy(maps)
    empties = empty(puzzle)
    if len(empties)==0:
        return puzzle
    cell = rank[0]
    (i,j) = cell
    domain = copy.deepcopy(maps[cell])
    for val in domain:
        maps = copy.deepcopy(domains)
        puzzle[i][j] = str(val)
        out = revise(puzzle)
        if out[-1]==False:
            puzzle[i][j] = '0'
            maps[cell].remove(val)
            continue
        solved = backtrack(puzzle,out[-1],out[0])
        if solved!=False:
            return solved
        puzzle[i][j] = '0'
        maps[cell].remove(val)
    maps = domains
    return False

def solve(puzzle):
    (maps,rank) = revise(puzzle)
    #if rank==False:
    solved = backtrack(puzzle,rank,maps)
    return solved

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_BACKSPACE:
                inp_txt = inp_txt[:-1]
            else:
                if len(inp_txt)<=45:
                    inp_txt += event.unicode
        if event.type == pygame.KEYDOWN:
            if event.key == 13:
                try:
                    with open(inp_txt.strip()) as file:
                        f = csv.reader(file)
                        puzzle = []
                        for row in f:
                            puzzle.append(row)
                    menu_flag = False
                except:
                    pass
            if event.key == pygame.K_q:
                menu_flag = True
    if menu_flag:
        menu()
    else:
        screen.fill((35, 31, 32))
        board(puzzle)
        time.sleep(3)
        puzzle = solve(puzzle)

    pygame.display.update()


import requests, os
from typing import List
import time
from google.cloud import storage

def blobDownloader(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""

    client = storage.Client()
    bucket = client.get_bucket(bucket_name)
    blob = bucket.get_blob(source_blob_name)

    blob.download_to_filename(destination_file_name)

    print('Blob {} downloaded to {}.'.format(
        source_blob_name,
        destination_file_name))

def getJsonData(days_ago: int, env='PROD'):
    '''days_ago is number of days ago'''

    if env == 'PROD':
        receiving_function_url = 'https://europe-west1-optimum-time-233909.cloudfunctions.net/api_private'
    elif env == 'DEV':
        receiving_function_url = ' https://europe-west1-syncvr-dev.cloudfunctions.net/api_private'
    else:
        print('Select a working environment, DEV or PROD')

    # Set up metadata server request
    metadata_server_token_url = 'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience='

    token_request_url = metadata_server_token_url + receiving_function_url
    token_request_headers = {'Metadata-Flavor': 'Google'}

    end: int = int(time.time() ) *1000  # milliseconds
    start: int = end - (1000 * 60 * 60 * 24 * days_ago)  # milliseconds

    # Fetch the token
    token_response = requests.get(token_request_url, headers=token_request_headers)
    jwt = token_response.content.decode("utf-8")

    print('Received token response as {}'.format(jwt))

    request_url = receiving_function_url + "/v1/results?start=" + str(start) + "&end=" + str(end)

    # Provide the token in the request to the receiving function
    receiving_function_headers = {'Authorization': f'bearer {jwt}'}
    function_response = requests.get(request_url, headers=receiving_function_headers)

    print('Received function response')

    return function_response.json()

class MailgunClient:

    def __init__(self, api_key: str = None):
        if api_key is None:
            try:
                self.__api_key__ = os.environ["MAILGUN_API_KEY"]
            except:
                self.__api_key__ = ""
        else:
            self.__api_key__ = api_key

    def send_mail(self,
                  subject: str,
                  text: str,
                  html: str,
                  from_address: str = None,
                  to_addresses: List[str] = None,
                  attachment: str= None,
                  path: str = None) -> bool:

        if from_address is None:
            try:
                from_address = os.environ["FROM_ADDRESS"]
            except:
                return
        to: str = ""
        if to_addresses is None:
            try:
                to = os.environ["TO_ADDRESSES"]
            except:
                return
        else:
             to = ",".join(to_addresses)

        if attachment is None:
            print('No attachments')
        else:
            if path is None:
                attached_file=("attachment", (attachment, open(attachment, "rb").read()))
            else:
                attached_file=("attachment", (attachment, open(path+attachment, "rb").read()))

        r: requests.Response = requests.post(
            "https://api.eu.mailgun.net/v3/mg.syncvr.tech/messages",
            auth=("api", self.__api_key__),
            files = [attached_file],
            data={
                "from": from_address,
                "to": to,
                "subject": subject,
                "text": text,
                "html": html
            }
        )

        if r.status_code >= 200 and r.status_code < 300:
            return True
        else:
            return False


#請先將selenium版本設定為3.141.0版
# !pip install selenium == 3.141.0

# 操作 browser 的 API
from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# 處理逾時例外的工具
from selenium.common.exceptions import TimeoutException

from selenium.common.exceptions import ElementNotInteractableException

# 面對動態網頁，等待某個元素出現的工具，通常與 exptected_conditions 搭配
from selenium.webdriver.support.ui import WebDriverWait

# 搭配 WebDriverWait 使用，對元素狀態的一種期待條件，若條件發生，則等待結束，往下一行執行
from selenium.webdriver.support import expected_conditions as EC

# 期待元素出現要透過什麼方式指定，通常與 EC、WebDriverWait 一起使用
from selenium.webdriver.common.by import By

from selenium.common.exceptions import NoSuchElementException

# 強制等待 (執行期間休息一下)
from time import sleep

# 執行 command 的時候用的
import os

from selenium.webdriver.support.ui import Select

def web_setting(foldername):
    # 啟動瀏覽器工具的選項
    my_options = webdriver.ChromeOptions()
    my_options.add_argument("--start-maximized")         #最大化視窗
    my_options.add_argument("--incognito")               #開啟無痕模式
    my_options.add_argument("--disable-popup-blocking") #禁用彈出攔截
    my_options.add_argument("--disable-notifications")  #取消 chrome 推播通知
    my_options.add_argument("--lang=zh-TW")  #設定為正體中文
    # 建立儲存檔案的資料夾
    folderPath = foldername
    if not os.path.exists(folderPath):
        os.makedirs(folderPath)

    # os.getcwd()為抓到當前目錄的路徑，windows的路徑會用\做分隔，但在Python裡\為跳脫字元，所以下面要放\\
    fullDownloadPath = os.getcwd() + '\\' + folderPath

    # 設定WebDriver的行為，"prefs"為偏好設定
    my_options.add_experimental_option("prefs", {

        # 將fullDownloadPath的路徑設定為默認下載檔案會放的路徑
        "download.default_directory": fullDownloadPath,

        # 可以設定要不要禁用詢問如何處理下載的提示。
        "download.prompt_for_download": False,

        # 在訪問危險網站或下載危險文件時，不會收到任何警告(須確定網頁是否安全再關閉這個功能)
        "safebrowsing.enabled": False,
    })

    # 使用 Chrome 的 WebDriver(請先到https://chromedriver.chromium.org/downloads下載與自己Chrome版本相符的chromedriver)
    # 將driver_path變更為chromedriver.exe的所在路徑
    driver_path = r'C:\\Users\\Ethen\\GitHub程式\\iSpan_BDSE30_final_project\\weather_wep_scraping\\chromedriver.exe'
    driver = webdriver.Chrome(executable_path=driver_path, options=my_options)

    return driver

# 走訪頁面
def visit():
    driver.get('https://e-service.cwb.gov.tw/HistoryDataQuery/DayDataController.do?command=viewMain&station=467770&stname=%25E6%25A2%25A7%25E6%25A3%25B2&datepicker=2013-01-01&altitude=31.73m')

# 手動或其他原因停止執行此方法
def visit1(url):
    #將網址會成停止的日期的測站網址
    driver.get(url)

# 將csv下載下來
def download_weather_csv(stop_point):
    error = False
    try:
        # 等待元素出現
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR, "select#selectStno")
            )
        )

        # 找到下拉式選單元素
        select_element = driver.find_element(By.CSS_SELECTOR, "select#selectStno")

        # 創建 Select 對象
        select = Select(select_element)

        # 獲取下拉式選單的選項数量
        options_count = len(select.options)

        sleep(1)

        #如果停止將0變為停止的數字
        for j in range(stop_point,options_count+1):
            print(j)
            # 等待元素出現
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (By.CSS_SELECTOR, "select#selectStno")
                )
            )

            # 找到下拉式選單元素
            select_element = driver.find_element(By.CSS_SELECTOR, "select#selectStno")

            # 創建 Select 對象
            select = Select(select_element)

            # 選擇選項
            select.select_by_index(j)

            while True:
                try:
                    url = driver.current_url
                    # 等待CSV下載的按件出現
                    WebDriverWait(driver, 10).until(
                        EC.presence_of_element_located(
                            (By.CSS_SELECTOR, "a#downloadCSV input")
                        )
                    )

                    # 點擊CSV下載的按件
                    driver.find_element(
                        By.CSS_SELECTOR,
                        "a#downloadCSV input"
                    ).click()

                # 等待下一天的按件出現
                    WebDriverWait(driver, 10).until(
                        EC.presence_of_element_located(
                            (By.CSS_SELECTOR, "a#nexItem input")
                        )
                    )
                    # 點擊下一天的按件
                    driver.find_element(
                        By.CSS_SELECTOR,
                        "a#nexItem input"
                    ).click()

                except ElementNotInteractableException:
                    break

            driver.get('https://e-service.cwb.gov.tw/HistoryDataQuery/DayDataController.do?command=viewMain&station=467770&stname=%25E6%25A2%25A7%25E6%25A3%25B2&datepicker=2013-01-01&altitude=31.73m')

            sleep(1)

        not_done = False

    except TimeoutException:
        error = True
        print("等待逾時")

    return error ,url, j, not_done

    # 最一開始執行的主程式
# if __name__ == '__main__':
#     visit()
#     download_weather_csv(0)

# 停止後主程式
if __name__ == '__main__':
    # 放入想建立的資料夾名稱
    driver = web_setting("台中市天氣")
    stop_point = 0
    #"放入要爬的縣市網址"
    url = 'https://e-service.cwb.gov.tw/HistoryDataQuery/DayDataController.do?command=viewMain&station=467770&stname=%25E6%25A2%25A7%25E6%25A3%25B2&datepicker=2013-01-01&altitude=31.73m'
    not_done = True
    visit1(url)
    while not_done:
        error_stop, stop_url, stop_point, not_done = download_weather_csv(stop_point)
        if error_stop == True:
            visit1(stop_url)
            error_stop, stop_url, stop_point, not_done = download_weather_csv(stop_point)


import xml.etree.ElementTree as ET
from collections import Counter

fieldList = ['Class', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY']
inputPath = r'C:\Users\danie\Desktop\GEOG 575\GEOG-575-Lab-2\data'
files = ['AllClasses.txt', 'BodyAttack.txt', 'BodyCombat.txt', 'BodyPump.txt', 'BodyStep.txt', 'Sprint.txt']
outputPath = r'C:\Users\danie\Desktop\GEOG 575\GEOG-575-Lab-2\data'
outputFileName = 'classes.csv'

def get_state_from_address(text):
    input = text.split(",")
    cityStateZip = input[-2]
    state = cityStateZip.split(" ")[-2]
    return state

def get_count(path, filename):

    file = open(r'{}\{}'.format(path, filename), 'r')
    data = file.read()
    file.close()

    root = ET.fromstring(data)

    states = []
    addressList = [] # To check for duplicate addresses

    for li in root:
        for item in li:
            if item.tag == "address" and item.text.endswith("United States"):
                address = item.text
                if address not in addressList:
                    addressList.append(address)
                    state = get_state_from_address(item.text)
                    states.append(str.upper(str(state)))

    c = Counter(states)

    countDict = dict(c)
    print(countDict)
    return countDict

def create_output_line(countDict, filename):
    className = filename.split('.')[0]
    output = className + ','
    countValues = []
    for state in fieldList[1:]:
        if state in countDict.keys():
            curValue = countDict[state]
            output += str(curValue) + ','
        else:
            output += '0,'
    output += '\n'
    return output

output = ''
for field in fieldList:
    output += field + ','
output = output[:-1] + '\n'

for file in files:
    countDict = get_count(inputPath, file)
    record = create_output_line(countDict, file)
    output += record

with open('{}\{}'.format(outputPath, outputFileName), 'w') as file:
          file.write(output)


#########################################################

import heroku3

from os import environ

from json import dumps

from utils.ansi import pretty

#########################################################

def prettyconfig(configobj):
    config = configobj.__dict__["_ConfigVars__data"]
    for key in list(config.keys()):
        if ( "FBSACCKEY" in key ) or ( "BOT_TOKENS" in key ):
            del config[key]
    return pretty(config, indent = 2)

#########################################################

def showconfig():
    handywebprojectsconn = heroku3.from_key(environ["FBSERV_TOKEN"])

    fbservapp = handywebprojectsconn.apps()["fbserv"]

    fbservconfig = fbservapp.config()

    print("fbserv config", prettyconfig(fbservconfig))

    handychessapplicationsconn = heroku3.from_key(environ["FBSERV2_TOKEN"])

    fbserv2app = handychessapplicationsconn.apps()["fbserv2"]

    fbserv2config = fbserv2app.config()

    print("fbserv2 config", prettyconfig(fbserv2config))

if __name__ == "__main__":
    showconfig()

#########################################################


import pyspark
from pyspark.context import SparkContext
from pyspark.sql.session import SparkSession
import os
import sys
sc = SparkContext.getOrCreate()
spark = SparkSession(sc)

df = spark.read.csv("airports.csv", inferSchema = True, header = True )

c=str(sys.argv[1])
outp=str(sys.argv[2])

os.environ["SPARK_WORKER_CORES"]=c
os.system("echo $SPARK_WORKER_CORES")

orig_stdout = sys.stdout
f = open(outp, 'w')
sys.stdout = f

df.filter(df["LATITUDE"] >= '10').filter(df["LATITUDE"] <= '90').filter(df["LONGITUDE"] <= '-10').filter(df["LONGITUDE"] >= '-90').select('NAME').show(20000)
sys.stdout = orig_stdout
f.close()

print("number of CPUs used:",c)
print("output written to:",outp)


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

# In[5]:

import pandas as pd
import numpy as np
import scipy.stats as st
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

# In[2]:

df=pd.read_csv("D:/Karir/HIGO - Data Scientist/Data_HIGO.csv",converters={'No Telp': lambda x: str(x)})
df.info()
df.head()

# In[3]:

#Top 9 Nama Tempat dengan Pengguna Terbanyak
Place1=df['Nama Lokasi'].value_counts()
Place1=Place1[:9]

plt.rcdefaults()
fig, ax = plt.subplots()

ax.barh(Place1.index, Place1, align='center', color='brown')
ax.set_yticklabels(Place1.index)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_ylabel('Nama Tempat Lokasi')
ax.set_title('Jumlah Pengguna Berdasarkan Tempat Lokasi', size=16)

rects=ax.patches

labels=[f"{i}" for i in Place1]

#Make Labels
for rect,label in zip(rects,labels):
    width=rect.get_width()
    ax.text(width,rect.get_y()+rect.get_height()/2,label,ha='left',va='center')

plt.show()

# In[4]:

#Jumlah Pengguna Berdasarkan Hari
D=df['Hari'].value_counts()
day=['Senin','Selasa','Rabu','Kamis','Jumat','Sabtu','Minggu']
Day=D[day]

plt.rcdefaults()
fig, ax = plt.subplots()

ax.bar(day, Day, align='center')
ax.set_xticklabels(day)
#ax.invert_yaxis()  # labels read top-to-bottom
ax.set_ylabel('Jumlah Pengguna')
ax.set_title('Jumlah Pengguna Berdasarkan Hari', size=16)

rects=ax.patches

labels=[f"{i}" for i in Day]

#Make Labels
for rect,label in zip(rects,labels):
    height=rect.get_height()
    ax.text(rect.get_x()+rect.get_width()/2,height+5,label,ha='center',va='bottom')

plt.show()

# In[8]:

#Membuat Confidence Interval untuk populasi rata - rata pengguna per hari
#n=7 => Cofidence Interval menggunakan distribusi t
CI1=st.t.interval(alpha=0.95,df=len(Day)-1,loc=np.mean(Day),scale=st.sem(Day))
CI1

# In[9]:

print('Jumlah pengguna yang menggunakan Wifi HIGOspot paling banyak di hari',D.index[0],'dengan jumlah',max(Day),'pengguna')
print('Jumlah pengguna yang menggunakan Wifi HIGOspot paling sedikit di hari',D.index[-1],'dengan jumlah',min(Day),'pengguna')
print('Rata - rata pengguna per hari adalah',Day.sum()/len(Day.index))
print('Confidence Interval rata - rata jumlah pengguna per hari adalah',CI1[0],'-',CI1[1])

# In[10]:

#Jumlah Pengguna Berdasarkan Jenis Kelamin
gender=df['Jenis Kelamin'].value_counts()
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(gender,labels=gender.index,autopct='%1.2f%%')
plt.title('Presentase Jenis Kelamin Pengguna', size=16)
plt.show()

# In[11]:

print('Pengguna',gender.index[0],'lebih banyak daripada pengguna',gender.index[1],'dengan jumlah',gender[0],'pengguna',gender.index[0])

# In[12]:

#Jumlah Pengguna Berdasarkan Kelompok Usia
tahun=df['Tahun Lahir'].value_counts()
now_year=2021
umur=[now_year-i for i in df['Tahun Lahir']]

#Membuat kelompok interval umur
gol_16_22=0
gol_23_29=0
gol_30_36=0
gol_37_43=0
gol_44_51=0
for i in umur:
    if i in range(16,23):
        gol_16_22+=1
    elif i in range(23,30):
        gol_23_29+=1
    elif i in range(30,37):
        gol_30_36+=1
    elif i in range(37,44):
        gol_37_43+=1
    elif i in range(44,52):
        gol_44_51+=1
Umur=pd.Series(data={'16-22':gol_16_22,'23-29':gol_23_29,'30-36':gol_30_36,'37-43':gol_37_43,'44-51':gol_44_51})

#make pie chart
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(Umur,labels='Usia '+Umur.index+' Tahun',autopct='%1.2f%%')
plt.title('Presentase Jumlah Pengguna Berdasarkan Kelompok Usia', size=16)
plt.show()

# In[13]:

#Membuat Confidence Interval untuk populasi rata - rata umur pengguna
#n=5832 => Cofidence Interval menggunakan distribusi z (normal)
CI2=st.norm.interval(alpha=0.95,loc=np.mean(umur),scale=st.sem(umur))
CI2

# In[16]:

Umur=Umur.sort_values()
print('Jumlah pengguna terbanyak adalah pengguna dengan usia',Umur.index[-1],'Tahun, dengan jumlah',Umur.max(),'pengguna')
print('Jumlah pengguna terkecil adalah pengguna dengan usia',Umur.index[0],'dan usia',Umur.index[1],'Tahun, dengan jumlah',Umur.min(),'pengguna')
print('Rata-rata usia pengguna adalah',np.mean(umur),'Tahun')
print('Confidence Interval rata - rata usia pengguna adalah',CI2[0],'-',CI2[1])

# In[17]:

#Jumlah Pengguna Berdasarkan Provider Seluler
provider=df['Provider Seluler'].value_counts(sort=False)

plt.rcdefaults()
fig, ax = plt.subplots()

ax.bar(provider.index, provider, align='center',color='gray')
ax.set_xticklabels(provider.index, rotation=45)
ax.set_ylabel('Jumlah Pengguna')
ax.set_title('Jumlah Pengguna Berdasarkan Provider Seluler', size=16)

rects=ax.patches

labels=[f"{i}" for i in provider]

#Make Labels
for rect,label in zip(rects,labels):
    height=rect.get_height()
    ax.text(rect.get_x()+rect.get_width()/2,height+5,label,ha='center',va='bottom')

plt.show()

# In[18]:

print('Provider dengan jumlah pengguna terbanyak adalah',provider.idxmax(),'dengan total',provider.max(),'pengguna')
print('Provider dengan jumlah pengguna terkecil adalah',provider.idxmin(),'dengan total',provider.min(),'pengguna')

# In[19]:

#Jumlah Pengguna Berdasarkan Merk HP
merk=df['Merek HP'].value_counts()

plt.rcdefaults()
fig, ax = plt.subplots(figsize=(8,8))

ax.barh(merk.index, merk, align='center', color='green')
ax.set_yticklabels(merk.index)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_ylabel('Merek HP')
ax.set_title('Jumlah Pengguna Berdasarkan Merk HP', size=16)

rects=ax.patches

labels=[f"{i}" for i in merk]

#Make Labels
for rect,label in zip(rects,labels):
    width=rect.get_width()
    ax.text(width,rect.get_y()+rect.get_height()/2,label,ha='left',va='center')

plt.show()

# In[20]:

print(merk.index[0],'adalah merk HP yang paling banyak digunakan oleh pengguna Wifi HIGO dengan jumlah',max(merk),'pengguna')
print(merk.index[-1],'adalah merk HP yang paling sedikit digunakan oleh pengguna Wifi HIGO dengan jumlah',min(merk),'pengguna')

# In[21]:

#Jumlah Pengguna Berdasarkan Digital Interest
interest=df['Digital Interest'].value_counts(sort=False)

plt.rcdefaults()
fig, ax = plt.subplots()

ax.bar(interest.index, interest, align='center',color='red')
ax.set_xticklabels(interest.index, rotation=45)
ax.set_ylabel('Jumlah Pengguna')
ax.set_title('Jumlah Pengguna Berdasarkan Digital Interest', size=16)

rects=ax.patches

labels=[f"{i}" for i in interest]

#Make Labels
for rect,label in zip(rects,labels):
    height=rect.get_height()
    ax.text(rect.get_x()+rect.get_width()/2,height+5,label,ha='center',va='bottom')

plt.show()

# In[22]:

print('Pengguna memiliki ketertarikan terhadap',interest.idxmax(),'ketika menggunakan Wifi HIGO dengan jumlah',interest.max(),'pengguna')
print('Pengguna kurang tertarik terhadap',interest.idxmin(),'ketika menggunakan Wifi HIGO dengan jumlah',interest.min(),'pengguna')

# In[23]:

#Jumlah Pengguna Berdasarkan Location Type
LT=df['Location Type'].value_counts()

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(LT,labels=LT.index,autopct='%1.2f%%')
plt.title('Jumlah Pengguna Berdasarkan Jenis Tempat', size=16)
plt.show()

# In[24]:

print('Pengguna lebih banyak mengunjungi',LT.idxmax(),'dengan total',LT.max(),'pengguna')
print('Pengguna lebih sedikit mengunjungi',LT.idxmin(),'dengan total',LT.min(),'pengguna')

# In[31]:

#Analisis Durasi Pengguna Dalam Menggunakan Wifi HIGO
maksimal=max(df['Durasi'])
minimal=min(df['Durasi'])
print('Pengguna menggunakan wifi HIGO paling lama selama',int(maksimal[:2]),'jam',int(maksimal[3:5]),'menit',int(maksimal[6:8]),'detik')
print('Pengguna menggunakan wifi HIGO paling cepat selama',int(minimal[:2]),'jam',int(minimal[3:5]),'menit',int(minimal[6:8]),'detik')
durasi_s=[]
for i in df['Durasi']:
    jam=int(i[:2])*60*60
    menit=int(i[3:5])*60
    detik=int(i[6:8])
    waktu=jam+menit+detik
    durasi_s.append(waktu)
rata2=np.mean(durasi_s)

import time
waktu_rata=time.strftime('%H:%M:%S', time.gmtime(rata2))
print('Rata - rata durasi pengguna menggunakan wifi HIGO adalah',waktu_rata[:2],'jam',waktu_rata[3:5],'menit',waktu_rata[6:8],'detik')

#Membuat Confidence Interval untuk populasi rata - rata durasi yang digunakan oleh setiap pengguna
#n=5832 => Cofidence Interval menggunakan distribusi z (normal)
CI3=st.norm.interval(alpha=0.95,loc=rata2,scale=st.sem(durasi_s))
CI3_1=time.strftime('%H:%M:%S', time.gmtime(CI3[0]))
CI3_2=time.strftime('%H:%M:%S', time.gmtime(CI3[1]))
print('Confidence Interval rata - rata durasi penggunaan Wifi HIGO adalah',CI3_1[:2],'jam',CI3_1[3:5],'menit',CI3_1[6:8],'detik hingga',CI3_2[:2],'jam',CI3_2[3:5],'menit',CI3_2[6:8],'detik')

# In[32]:

#Analisis Interval Jam Dengan Pengguna Terbanyak
all_time=df['Jam Login']
all_jam=[int(i[:2]) for i in all_time]
all_jam=pd.Series(all_jam)
K=list(range(7,22))
All_Jam=all_jam.value_counts()
All_Jam=All_Jam[K]
indeks=[]
for i in K:
    indeks.append(str(i)+'-'+str(i+1))

plt.rcdefaults()
fig, ax = plt.subplots(figsize=(12,6))
ax.plot(indeks,All_Jam,marker='o')
ax.set_title('Jumkah Pengguna Berdasarkan Interval Waktu Login')
ax.set_xlabel('Interval Jam')
ax.set_ylabel('Jumlah Pengguna')
ax.set_xticklabels(indeks,rotation=45)
ax.set_ylim(ymin=0,ymax=455)

rects=ax.lines[0]
for x_value,y_value in zip(indeks,All_Jam):
    label="{:.2f}".format(y_value)
    ax.annotate(label,(x_value,y_value),xytext=(0,5),textcoords='offset points',ha='center',va='bottom')

plt.show()

# In[38]:

print('Pengguna terbanyak terjadi pada jam',str(All_Jam.idxmax())+'.00','sampai jam',str(All_Jam.idxmax()+1)+'.00')

#Membuat Confidence Interval untuk populasi rata - rata pengguna per jam
#n=15 => Cofidence Interval menggunakan distribusi t
CI4=st.t.interval(alpha=0.95,df=len(All_Jam),loc=np.mean(All_Jam),scale=st.sem(All_Jam))
print('Confidence Interval rata - rata pengguna per jam adalah',CI4[0],'-',CI4[1],'pengguna')

#Confidence Interval untuk populasi rata-rata jam login
#n=5832 => Confidence Interval menggunakan distribusi z (normal)
CI5=st.norm.interval(alpha=0.95,loc=np.mean(all_jam),scale=st.sem(all_jam))
print('Confidence Interval rata - rata jam login pengguna adalah jam',CI5[0],'-',CI5[1])

# In[39]:

Ramai=[]
Jumlah=[]
for i in day:
    j=df[(df['Hari']==i)]
    l=[int(ii[:2]) for ii in j['Jam Login']]
    l=pd.Series(l)
    m=l.value_counts()
    idx=str(m.idxmax())+' - '+str(m.idxmax()+1)
    Ramai.append(idx)
    Jumlah.append(m.max())

Data_Ramai_Pengguna=pd.DataFrame(data={'Interval Jam':Ramai,'Jumlah':Jumlah},index=day)

# In[41]:

print('Berikut adalah data tentang interval jam yang paling banyak pengguna melakukan login ke Wifi HIGO')
Data_Ramai_Pengguna

# In[42]:

#Analisis Digital Interest Berdasarkan Rata-Rata Durasi
rata_rata=[]
for i in df['Digital Interest'].unique():
    Data1=df[df['Digital Interest']==i]
    x=0
    for j in Data1['Durasi']:
        dur=int(j[:2])*3600+int(j[3:5])*60+int(j[6:8])
        x+=dur
    rata=time.strftime('%H:%M:%S', time.gmtime(x/len(Data1)))
    rata_rata.append(rata)
df3=pd.Series(rata_rata,index=df['Digital Interest'].unique())

# In[43]:

print('Berikut adalah rata - rata durasi yang dihabiskan pengguna terhadap Digital Interest')
df3

# In[44]:

#Analisis Jenis Lokasi Berdasarkan Rata-Rata Durasi
rata_rata=[]
for i in df['Location Type'].unique():
    Data1=df[df['Location Type']==i]
    x=0
    for j in Data1['Durasi']:
        dur=int(j[:2])*3600+int(j[3:5])*60+int(j[6:8])
        x+=dur
    rata=time.strftime('%H:%M:%S', time.gmtime(x/len(Data1)))
    rata_rata.append(rata)
df4=pd.Series(rata_rata,index=df['Location Type'].unique())

# In[45]:

print('Berikut adalah rata - rata durasi yang dihabiskan pengguna ditempat lokasi')
df4

# In[46]:

#Analisis Kelompok Usia Pada Setiap Digital Interest
now_year=2021
df6=[]
idks=df['Digital Interest'].unique()
for i in idks:
    df_intr=df[df['Digital Interest']==i]
    umur=[now_year-i for i in df_intr['Tahun Lahir']]

    #Membuat kelompok interval umur
    gol_16_22=0
    gol_23_29=0
    gol_30_36=0
    gol_37_43=0
    gol_44_51=0
    for i in umur:
        if i in range(16,23):
            gol_16_22+=1
        elif i in range(23,30):
            gol_23_29+=1
        elif i in range(30,37):
            gol_30_36+=1
        elif i in range(37,44):
            gol_37_43+=1
        elif i in range(44,52):
            gol_44_51+=1
    Umur=pd.Series(data={'16-22':gol_16_22,'23-29':gol_23_29,'30-36':gol_30_36,'37-43':gol_37_43,'44-51':gol_44_51})
    df6.append(Umur)

# In[49]:

#make pie chart df['Digital Interest'].unique()[0]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(df6[0],labels='Usia '+df6[0].index+' Tahun',autopct='%1.2f%%')
plt.title('Presentase Jumlah Pengguna Yang Tertarik Dengan\n'+idks[0]+' Berdasarkan Kelompok Usia', size=16)
plt.show()

# In[50]:

#make pie chart df['Digital Interest'].unique()[1]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(df6[1],labels='Usia '+df6[1].index+' Tahun',autopct='%1.2f%%')
plt.title('Presentase Jumlah Pengguna Yang Tertarik\nDengan '+idks[1]+' Berdasarkan Kelompok Usia', size=16)
plt.show()

# In[51]:

#make pie chart df['Digital Interest'].unique()[2]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(df6[2],labels='Usia '+df6[2].index+' Tahun',autopct='%1.2f%%')
plt.title('Presentase Jumlah Pengguna Yang Tertarik\nDengan '+idks[2]+' Berdasarkan Kelompok Usia', size=16)
plt.show()

# In[52]:

#make pie chart df['Digital Interest'].unique()[3]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(df6[3],labels='Usia '+df6[3].index+' Tahun',autopct='%1.2f%%')
plt.title('Presentase Jumlah Pengguna Yang Tertarik\nDengan '+idks[3]+' Berdasarkan Kelompok Usia', size=16)
plt.show()

# In[53]:

#make pie chart df['Digital Interest'].unique()[4]
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.axis('equal')
ax.pie(df6[4],labels='Usia '+df6[4].index+' Tahun',autopct='%1.2f%%')
plt.title('Presentase Jumlah Pengguna Yang Tertarik\nDengan '+idks[4]+' Berdasarkan Kelompok Usia', size=16)
plt.show()

# In[56]:

#Jumlah Pengguna Berdasarkan Jenis Kelamin Pada Setiap Digital Interest
df7=pd.crosstab(df['Digital Interest'],df['Jenis Kelamin'])
x = np.arange(len(df7.index))
width = 0.35

fig, ax = plt.subplots(figsize=(12,10))

male = ax.bar(x - width/2, df7['Laki-laki'], width, label='Laki-laki')
female = ax.bar(x + width/2, df7['Perempuan'], width, label='Perempuan')

ax.set_title('Jumlah Pengguna Berdasarkan Jenis Kelamin Pada Setiap Digital Interest', size=16)
ax.set_ylabel('Jumlah Pengguna', size=14)
ax.set_xticks(x)
ax.set_xticklabels(df7.index, size=12)
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",rotation_mode="anchor")
ax.legend(fontsize=14)

fig.tight_layout()

rects1=male.patches
rects2=female.patches

labels1=[f"{i}" for i in df7['Laki-laki']]
labels2=[f"{i}" for i in df7['Perempuan']]

#Make Labels
for rect,label in zip(rects1,labels1):
    height=rect.get_height()
    ax.text(rect.get_x()+rect.get_width()/2,height+5,label,ha="center",va="bottom",size=16)
for rect,label in zip(rects2,labels2):
    height=rect.get_height()
    ax.text(rect.get_x()+rect.get_width()/2,height+5,label,ha="center",va="bottom",size=16)

plt.show()

# In[ ]:

Analisis Data HIGO/Fuad Maulana_Analisis Data HIGO.py


from __future__ import print_function, division, absolute_import, unicode_literals

import numpy as np
import pandas as pd
import pickle as pkl
import cupy as cp
import os

from cupy.cuda import Device

import argparse
import tqdm

import utils as wb

parser = argparse.ArgumentParser(description='Evaluate ranks and MAP on hypernym reconstruction')

parser.add_argument('--data', '-d', type=str, help='csv file containing the relations')
parser.add_argument('--embeddings', '-e', type=str,
                    help='folder containing the embeddings')
parser.add_argument('--max_n', type=int, default=None, help = 'number of items to evaluate')
parser.add_argument('--metric', type=str, default="bures_product")
parser.add_argument('--device', type=int, default=7)
parser.add_argument('--verbose', action='store_true')
args = parser.parse_args()

def get_positive_relation_ranks_and_avg_prec(all_distances, positive_relations):
    """
    Given a numpy array of all distances from an item and indices of its positive relations,
    compute ranks and Average Precision of positive relations.
    Parameters
    ----------
    all_distances : numpy.array (float)
        Array of all distances (floats) for a specific item.
    positive_relations : list
        List of indices of positive relations for the item.
    Returns
    -------
    tuple (list, float)
        The list contains ranks (int) of positive relations in the same order as `positive_relations`.
        The float is the Average Precision of the ranking.
        e.g. ([1, 2, 3, 20], 0.610).
    """
    positive_relation_distances = all_distances[positive_relations]
    negative_relation_distances = np.ma.array(all_distances, mask=False)
    negative_relation_distances.mask[positive_relations] = True
    # Compute how many negative relation distances are less than each positive relation distance, plus 1 for rank
    ranks = (negative_relation_distances < positive_relation_distances[:, np.newaxis]).sum(axis=1) + 1
    map_ranks = np.sort(ranks) + np.arange(len(ranks))
    avg_precision = ((np.arange(1, len(map_ranks) + 1) / np.sort(map_ranks).astype(float)).mean())
    return list(ranks), avg_precision

def evaluate_mean_rank_and_map(hypernym_df, max_n=None):
    """Evaluate mean rank and MAP for reconstruction.
    Parameters
    ----------
    max_n : int or None
        Maximum number of positive relations to evaluate, all if `max_n` is None.
    Returns
    -------
    tuple (float, float)
        Contains (mean_rank, MAP).
        e.g (50.3, 0.31)
    """
    pass

def main(embedding_file=args.embeddings, hypernym_file=args.data, device=args.device, max_n = args.max_n):

    Device(device).use()

    print("Reading embedding file:", embedding_file)

    with open(embedding_file, 'rb') as embed_file:
        embeddings = pkl.load(embed_file)

    means = embeddings['means']
    vars = embeddings["vars"]

    words_to_idx = embeddings['word_to_idx']

    hypernym_df = pd.read_csv(hypernym_file, header=None, sep='\t')
    hypernym_df[2] = hypernym_df[0].apply(lambda x: words_to_idx[x])
    hypernym_df[3] = hypernym_df[1].apply(lambda x: words_to_idx[x])
    hypernym_couples = []

    print("Ranking distances")

    idxs1 = hypernym_df[2].values
    idxs2 = hypernym_df[3].values

    n = np.max(idxs1) + 1
    m = np.max(idxs2) + 1

    idxs = np.arange(m)

    ranks = []
    avg_precision_scores = []

    idxs1 = list(set(idxs1))
    np.random.shuffle(idxs1)

    for i, idx in tqdm.tqdm(enumerate(idxs1)):
        x = [idx] * m
        if args.metric == "bures_distance":
            dists_ = wb.batch_W2(cp.array(means[x]), cp.array(means[idxs]), cp.array(vars[x]), cp.array(vars[idxs]))[0]
            item_distances = cp.asnumpy(dists_)
        elif args.metric == "bures_cosine":
            scores_ = wb.bures_cosine(cp.array(means[x]), cp.array(means[idxs]), cp.array(vars[x]), cp.array(vars[idxs]))
            item_distances = -cp.asnumpy(scores_)
        elif args.metric == "bures_product":
            scores_ = wb.batch_W2(cp.array(means[x]), cp.array(means[idxs]), cp.array(vars[x]), cp.array(vars[idxs]), prod=True)[0]
            item_distances = -cp.asnumpy(scores_)

        assert(not (np.isnan(item_distances.any()) or np.isinf(item_distances).any()))

        item_relations = list(set(hypernym_df[hypernym_df[2] == idx][3]).union(set(hypernym_df[hypernym_df[3] == idx][2])))
        positive_relation_ranks, avg_precision = \
            get_positive_relation_ranks_and_avg_prec(item_distances, item_relations)
        ranks += positive_relation_ranks
        avg_precision_scores.append(avg_precision)
        if max_n is not None and i > max_n:
            break
        if args.verbose:
            print('Positive relation distances: ', item_distances[item_relations])
            print('Ranks: ', positive_relation_ranks)
            print('AP:', avg_precision)

        if (i+1) % 10000 == 0:
            print("Rank moving average: %f" % (np.mean(ranks)))
            print("MAP moving average: %f" % (np.mean(avg_precision_scores)))

    print('Mean rank: %f\t MAP: %f\t Rank std: %f\t AP std: %f' % (np.mean(ranks), np.mean(avg_precision_scores), np.std(ranks), np.std(avg_precision_scores)))

    with open(os.path.join(os.path.dirname(embedding_file), "rank_summary"), "a") as result_file:
        result_file.write("File: %s \t Sample size %u\t Metric: %s\t Full Mean rank: %f\t MAP: %f\t Rank std: %f\t AP std: %f\n" % (
        embedding_file.split('/')[-1], len(avg_precision_scores), args.metric, np.mean(ranks), np.mean(avg_precision_scores), np.std(ranks), np.std(avg_precision_scores)))

    if args.max_n is None:
        with open(embedding_file + "_ranks.pkl", "wb") as ranks_file:
            pkl.dump(ranks, ranks_file)
        with open(embedding_file + "_precisons.pkl", "wb") as precision_file:
            pkl.dump(avg_precision_scores, precision_file)

if __name__ == '__main__':
    main()


from django.conf.urls import url

from cms.apphook_pool import apphook_pool
from cms.cms_menus import SoftRootCutter
from menus.menu_pool import menu_pool

from shop.cms_apphooks import CatalogListCMSApp, OrderApp, PasswordResetApp
from dshop.views import DshopProductListView, OrderView

class CatalogListApp(CatalogListCMSApp):
    """
    Create a useable list of urls with Product's slug.
    """
    def get_urls(self, page=None, language=None, **kwargs):
        from dshop.catalog import AddToCartView
        from dshop.catalog import ProductRetrieveView
        from dshop.serializers import AddProductVariableToCartSerializer

        return [
            # Product loading page
            url(
                r'^category/(?P<category_id>[0-9]+)-(?P<category_slug>.+)$',
                DshopProductListView.as_view(),
            ),
            url(
                r'^brand/(?P<brand_id>[0-9]+)-(?P<brand_slug>.+)$',
                DshopProductListView.as_view(),
            ),
            url(
                r'^(?P<slug>[\w-]+)/add-to-cart',
                AddToCartView.as_view(), name="add_to_cart"
            ),
            url(
                r'^(?P<slug>[\w-]+)/add-productvariable-to-cart',
                AddToCartView.as_view(
                    serializer_class=AddProductVariableToCartSerializer,
                ), name="add_productvariable_to_cart"
            ),
            url(
                r'^(?P<slug>[\w-]+)',
                ProductRetrieveView.as_view(use_modal_dialog=False)
            ),
            url(
                r'^',
                DshopProductListView.as_view(),
                name='produits'
            ),
        ]

class OrderApp(OrderApp):

    def get_urls(self, page=None, language=None, **kwargs):
        from django.conf.urls import url

        return [
            url(r'^(?P<slug>[\w-]+)/(?P<secret>[\w-]+)',
                OrderView.as_view(many=False)),  # publicly accessible
            url(r'^(?P<slug>[\w-]+)',
                OrderView.as_view(many=False)),  # requires authentication
            url(r'^',
                OrderView.as_view()),  # requires authentication
        ]

apphook_pool.register(CatalogListApp)

apphook_pool.register(OrderApp)
apphook_pool.register(PasswordResetApp)

def _deregister_menu_pool_modifier(Modifier):
    index = None
    for k, modifier_class in enumerate(menu_pool.modifiers):
        if issubclass(modifier_class, Modifier):
            index = k
    if index is not None:
        menu_pool.modifiers.pop(index)

_deregister_menu_pool_modifier(SoftRootCutter)


from django.urls import path
from django.shortcuts import render
from . import views
from django.contrib.auth.views import LoginView,LogoutView

urlpatterns = [
    # customer view
    path('',views.indexView,name="index"),
    path('home/',views.homeView.as_view(),name="home"),
    path('dashboard/',views.dashboardView,name="dashboard"),
    path('product_display/<pk>',views.productView,name="product_display"),
    path('buy_product/<pk>',views.buyProductView,name="buy_item"),
    path('add_balance/',views.addBalanceView.as_view(),name="add_balance"),
    path('customer_orders/',views.customerOrdersView,name='customer_orders'),
    path('vendor_profile/<pk>',views.vendorProfileView,name='vendor_profile'),
    path('customer_profile/',views.customerProfileView,name='customer_profile'),
    path('add_review/<pk>',views.addReview,name='add_review'),
    path('add_to_cart/<pk>/<is_wished>',views.addToCartView,name='add_to_cart'),
    path('show_cart_items/<is_wished>',views.showCartItemView,name='show_cart_items'),
    path('remove_cart_item/<pk>',views.removeCartItem,name='remove_cart_item'),
    path('buy_multiple_item/',views.buyMultiItemView,name='buy_multiple_item'),
    path('order_detail/<pk>',views.orderDetailView,name='order_detail'),
    path('switch_cart/<pk>',views.switchCartView,name='switch_carts'),

    # seller view
    path('seller/order_list/',views.listOrdersView,name="order_list"),
    path('seller/item_list/',views.listItemView,name="item_list"),
    path('seller/add_item/',views.addItemView.as_view(),name="add_item"),
    path('seller/delete_item/<pk>',views.deleteItemView,name = "delete_item"),
    path('seller/edit_item/<pk>',views.editItemView.as_view(),name = "edit_item"),
    path('seller/get_sales_report/',views.salesReportView,name = "get_sales_report"),

]


from motor.motor_asyncio import AsyncIOMotorClient

client = AsyncIOMotorClient('localhost', 27017)
db = client['test-database']
collection = db['citizen_mongo']

class MongoClient:

    async def do_insert(self, doc):
        result = await collection.insert_one(doc)
        return result.inserted_id

    async def do_count(self):
        res = await collection.estimated_document_count()
        # print(res)
        return res

    async def find(self, r={}, limit=0):
        cursor = collection.find(r).limit(limit)
        docs = await cursor.to_list(length=100)
        res = []
        while docs:
            for doc in docs:
                # print(doc)
                res.append(doc)
            docs = await cursor.to_list(length=100)
        return res

if __name__ == '__main__':
    import asyncio

    loop = asyncio.get_event_loop()
    loop.run_until_complete(MongoClient().do_count())
    loop.run_until_complete(MongoClient().do_insert({'name': 'barrrr', 'coordinates': {'lon': 55, 'lat': 55}}))


from os import path

from libparse import Error, Head, Loc, Maybe, Result, Span, Spanned, SpanResult, Stream, Text
from typing import Callable, TypeVar
from sylex_ast import *

Chars = Stream[str]

def chars_of_raw(raw: str) -> Chars:
    text = Text(raw)
    loc = Loc(0, 0)
    chars: Chars = Stream.empty()
    for c in raw:
        chars.append(Span.unit(loc, text).with_data(c))
        if c == "\n":
            loc = loc.newline()
        else:
            loc = loc.newcol()
    return chars

class Blank:
    pass

Token = Symbol | Ident
Tokens = Stream[Token]
HToken = Head[Token]

def next_token(hd: Head[str]) -> Result[Token | Blank | None]:
    # About the return type
    #   Error -> something wrong happened
    #   None -> no more tokens
    #   Blank -> this is whitespace
    start = hd.span()
    read = hd.take()
    if read is None:
        return None

    if read == "<":
        # Left arrow
        # '<' '-'
        hd.bump()
        read = hd.peek()
        if read == "-":
            _ = hd.take()
            return Symbol.LEFT
        return hd.err("Unknown token", "'<' unterminated, expected '-' after", start)

    if read == "#":
        # Line comment
        # '#' [^'\n']* '\n'
        while True:
            hd.bump()
            read = hd.take()
            if read is None:
                return None
            if read == "\n":
                return Blank()

    if read in [" ", "\n", "\t"]:
        # Whitespace
        return Blank()

    if read == ":":
        # ':' ':'
        read1 = hd.peek(1)
        if read1 == ":":
            _ = hd.take(1)
            hd.bump()
            return Symbol.SCOPE
        # Else is a fallthrough: will be handled by 1-char symbols

    if read == "-":
        # '-' '>'
        read1 = hd.peek(1)
        if read1 == ">":
            _ = hd.take(1)
            hd.bump()
            return Symbol.RIGHT
        # Else is a fallthrough so that an identifier can still be caught

    # The following loop takes care of all 1-char symbols
    for sym in Symbol:
        if read == sym.value:
            return sym

    # Identifier contains 'a-z' or 'A-Z' or '-' '.' '_'
    # Can also take the form `'` ... `'` with escaped characters
    if isname(read):
        ident_chars = [read]
        while True:
            read = hd.peek(1)
            if read is None:
                break
            if not isname(read):
                break
            _ = hd.take(1)
            hd.bump()
            ident_chars.append(read)
        return Ident.concat(ident_chars)

    if read != "'":
        return hd.err(
            "Unknown token", "character does not begin any valid token", start
        )

    ident_chars = []
    while True:
        read = hd.peek(1)
        if read is None:
            # premature EOF
            return hd.err(
                "Unterminated literal",
                "`'` opened but unclosed before end of file",
                start,
            )
        if read == "\\":
            # escape next character
            hd.bump()
            read = hd.peek(1)
            if read is None:
                return hd.err("Unterminated escape", "'\\' at end of file", start)
            ident_chars.append(read)
        elif read == "'":
            # end literal
            hd.bump()
            break
        else:
            # default is a single normal character
            hd.bump()
            ident_chars.append(read)

    return Ident.concat(ident_chars)

def tokens_of_chars(chars: Chars) -> Result[Tokens]:
    # Call next_token repeatedly until the whole stream is consumed
    toks: Tokens = Stream.empty()
    hd = Head.start(chars)

    while True:
        fwd = hd.clone()
        print(f"Enter: {fwd.peek()}")
        res = next_token(fwd)
        print(f"Exit: {fwd.peek()}")
        print(f"With: {res}")
        print()

        if isinstance(res, Error):
            inner = res
            if inner.span is None:
                inner.span = hd.until(fwd)
                print(hd.span(), fwd.span(), hd.until(fwd))
            return inner

        if res is None:
            break

        elif isinstance(res, Blank):
            fwd.bump()
            hd.commit(fwd)
            continue

        else:
            spanned = hd.until(fwd).with_data(res)
            toks.append(spanned)
            fwd.bump()
            hd.commit(fwd)

    return toks

U = TypeVar("U")
def ast_of_tokens(tokens: Tokens, target: Callable[[HToken], Result[U]]) -> SpanResult[U]:
    hd = Head.start(tokens)
    start = hd.span()
    res: SpanResult[U] = hd.sub(target)
    read = hd.peek()
    if read is None:
        return res
    else:
        return Error("Extra text", f"expected end of file, found {read}", hd.until(start), None)
    return res

def parse_deflist(hd: HToken) -> Result[DefList]:
    # DefList := Def *
    start = hd.span()
    defs: list[Spanned[Def] | Spanned[Target]] = []
    while True:
        read = hd.peek()
        if read is None:
            break
        elif read == Symbol.DECLARE:
            item_def: SpanResult[Def] = hd.sub(parse_def)
            if isinstance(item_def, Error):
                return item_def
            print(item_def)
            defs.append(item_def)
        elif read == Symbol.OPENBRACK:
            item_target: SpanResult[Target] = hd.sub(parse_target)
            if isinstance(item_target, Error):
                return item_target
            print(item_target)
            defs.append(item_target)
        else:
            return hd.err("Unknown token", "expected '$' or '['", start)
    return DefList(defs)

def parse_def(hd: HToken) -> Result[Def]:
    # Def := '$' Ident '=' ItemList ';'
    start = hd.span()

    # '$'
    read = hd.take()
    if read != Symbol.DECLARE:
        return hd.err("Invalid Def", "expect a Def to start with a '$'", start)
    hd.bump()

    # Ident
    read = hd.take()
    if not isinstance(read, Ident):
        return hd.err("Invalid Def", "'$' should be followed by a name", start)

    # TODO: Waiting mypy 0.940
    name: Spanned[Ident] = hd.span().with_data(read)
    hd.bump()

    # '='
    read = hd.take()
    if read != Symbol.EQUAL:
        return hd.err("Invalid Def", "expected an '=' sign", start)
    hd.bump()

    # ItemList
    val: SpanResult[ItemList] = hd.sub(parse_itemlist)
    if isinstance(val, Error):
        return val
    value = val

    # ';'
    read = hd.take()
    if read != Symbol.SEMI:
        return hd.err("Invalid Def", "expected ';' at the end", start)
    hd.bump()

    return Def(name, value)

def parse_itemlist(hd: HToken) -> Result[ItemList]:
    # ItemList := '{' Item ','* '}'
    #           | Item
    start = hd.span()
    read = hd.peek()
    if read is None:
        return hd.err(
            "Invalid ItemList", "EOF reached while trying to read a list", start
        )

    if read != Symbol.OPENBRACE:
        # did not start with a '{' so it should be a single Item
        obj: SpanResult[Expand | Maybe[Item]] = hd.sub(parse_item)
        if isinstance(obj, Error):
            return obj

        # TODO: Waiting mypy 0.940
        if isinstance(obj.data, Expand):
            return ItemList([obj.span.with_data(obj.data)])
        else:
            return ItemList([obj.span.with_data(obj.data.data)])

    # Case of '{' Item ','* '}'
    _ = hd.take()
    hd.bump()
    # TODO: list[Spanned[Item|Expand]]
    lst: list[Spanned[Item | Expand]] = []
    latest_error = None
    while True:
        read = hd.peek()
        if read is None:
            return hd.err(
                "Invalid ItemList", "EOF reached while trying to read a list", start
            )
        if read == Symbol.CLOSEBRACE:
            # Reached the closing '}'
            _ = hd.take()
            hd.bump()
            return ItemList(lst)
        # otherwise read an Item then maybe a ','
        # if no ',' then it has to stop afterwards
        item: SpanResult[Expand | Maybe[Item]] = hd.sub(parse_item)
        if isinstance(item, Error):
            return item

        # TODO: Waiting mypy 0.940
        if isinstance(item.data, Expand):
            data: Expand | Item = item.data
        else:
            data = item.data.data
        lst.append(item.span.with_data(data))

        read = hd.peek()
        if read is None:
            if latest_error is not None:
                return latest_error
            return hd.err("Invalid ItemList", "unclosed '{' before EOF", start)
        if read == Symbol.COMMA:
            _ = hd.take()
            hd.bump()
        else:
            # No trailing comma, it should be the end
            if read != Symbol.CLOSEBRACE:
                if latest_error is not None:
                    return latest_error
                return hd.err(
                    "Invalid ItemList",
                    "expected '}' after no trailing comma",
                    start,
                )
            # (next iteration will take care of actually returning)

def parse_item(hd: HToken) -> Result[Expand | Maybe[Item]]:
    # Item := '$' Ident
    #       | Entry
    #       | Entry '::' ItemList
    start = hd.span()
    # if it starts with a '$' then it's an expansion
    read = hd.peek()
    if read == Symbol.DECLARE:
        _ = hd.take()
        hd.bump()
        read = hd.take()
        if not isinstance(read, Ident):
            return hd.err("Invalid expansion", "expected identifier after '$'", start)

        # TODO: Waiting mypy 0.940
        ident: Spanned[Ident] = hd.span().with_data(read)
        hd.bump()
        return Expand(ident)

    # otherwise it should be an Entry
    entry: SpanResult[Maybe[Entry]] = hd.sub(parse_entry)
    if isinstance(entry, Error):
        return entry
    # optionally '::' then ItemList
    read = hd.peek()
    if read != Symbol.SCOPE:
        return Maybe(Item(entry.map(lambda x: x.data), None), entry.data.diagnostic)
    _ = hd.take()
    hd.bump()
    tail: SpanResult[ItemList] = hd.sub(parse_itemlist)
    if isinstance(tail, Error):
        return tail
    return Maybe(Item(entry.map(lambda x: x.data), tail), entry.data.diagnostic)

def parse_entry(hd: HToken) -> Result[Maybe[Entry]]:
    # Entry := Ident Tag*
    start = hd.span()
    # Ident
    read = hd.take()
    if not isinstance(read, Ident):
        return hd.err("Invalid Entry", "should start with an Ident", start)

    # TODO: Waiting mypy 0.940
    name: Spanned[Ident] = hd.span().with_data(read)
    hd.bump()

    entry = Entry.from_name(name)
    # list of Tag
    while True:
        print(f"next: {hd.peek()}")
        read = hd.peek()
        if read not in [Symbol.LEFT, Symbol.RIGHT, Symbol.COLON]:
            err = hd.err(
                "Expected tag marker",
                f"tags should begin with '<-' or '->' or ':', not '{hd.peek()}'",
                start,
            )
            return Maybe(entry, err)
        tag: SpanResult[Tag] = hd.sub(parse_tag)
        if isinstance(tag, Error):
            return tag
        entry.push(tag)

def parse_tag(hd: HToken) -> Result[Tag]:
    start = hd.span()
    # '<-' or ':' or '->'
    read = hd.take()
    if read not in [Symbol.LEFT, Symbol.RIGHT, Symbol.COLON]:
        return hd.err(
            "Invalid Tag", "should start with either ':', '<-' or '->'", start
        )
    symbol = read
    hd.bump()

    # Ident
    read = hd.take()
    if not isinstance(read, Ident):
        return hd.err("Invalid Tag", "should have a name", start)

    # TODO: Waiting mypy 0.940
    name: Spanned[Ident] = hd.span().with_data(read)
    hd.bump()

    # If there are params they start with '('
    read = hd.peek()
    if read != Symbol.OPENPAREN:
        params = hd.span().with_data(Params([]))
    else:
        read_params: SpanResult[Params] = hd.sub(parse_params)
        if isinstance(read_params, Error):
            return read_params
        else:
            params = read_params
    # decide type of return value depending on value of symbol
    if symbol == Symbol.COLON:
        return Label(name, params)
    elif symbol == Symbol.LEFT:
        return Induce(name, params)
    else:
        return Depend(name, params)

def parse_params(hd: HToken) -> Result[Params]:
    start = hd.span()
    # Start with '('
    read = hd.take()
    if read != Symbol.OPENPAREN:
        return hd.err("Invalid Params", "should start with '('", start)
    hd.bump()
    inner: list[Spanned[Ident]] = []
    # Comma-separated list of Idents
    while True:
        read = hd.take()
        if read is None:
            return hd.err("Invalid Params", "unclosed '(' at end of file", start)

        if read == Symbol.CLOSEPAREN:
            hd.bump()
            return Params(inner)

        if isinstance(read, Ident):
            # TODO: Waiting mypy 0.940
            inner.append(hd.span().with_data(read))
            hd.bump()

            read = hd.peek()
            if read is None:
                return hd.err("Invalid Params", "unclosed '(' at end of file", start)
            if read == Symbol.COMMA:
                _ = hd.take()
                hd.bump()
            elif read != Symbol.CLOSEPAREN:
                return hd.err("Invalid Params", "expected ',' or ')'", start)

        # (next iteration will return)

def parse_target(hd: HToken) -> Result[Target]:
    # Target := '[' Ident ']' ';'
    start = hd.span()
    # '['
    read = hd.take()
    if read != Symbol.OPENBRACK:
        return hd.err("Invalid Target", "should begin with '['", start)
    hd.bump()

    # Ident
    read = hd.take()
    if not isinstance(read, Ident):
        return hd.err("Invalid Target", "should have a name", start)

    # TODO: Waiting mypy 0.940
    name = hd.span().with_data(read)
    hd.bump()

    # ']'
    read = hd.take()
    if read != Symbol.CLOSEBRACK:
        return hd.err("Invalid Target", "target name should be followed by ']'", start)
    hd.bump()

    # ';'
    read = hd.take()
    if read != Symbol.SEMI:
        return hd.err("Invalid Target", "should be ended by ';'", start)
    hd.bump()

    return Target(name)

def main(raw: str, target: Callable[[HToken], Result[U]]) -> SpanResult[U]:
    chars = chars_of_raw(raw)
    toks = tokens_of_chars(chars)
    if isinstance(toks, Error):
        return toks
    ast = ast_of_tokens(toks, target)
    if isinstance(ast, Error):
        return ast
    return ast

if __name__ == "__main__":
    with open("sylex.conf") as f:
        raw = f.read()
    print(main(raw, parse_deflist))


# -*- coding: utf-8 -*-
"""
Created on Tue May 14 17:44:56 2019

@author: Narayan Devpura
"""

# Create a new Code Challenge to POST data

# Research the below wesbite and post some data on it

# https://requestbin.com

import requests

Host = "http://httpbin.org"

data = {"firstname":"abx","language":"Urdu"}

headers = {"Content-Type":"application/json","Content-Length":len(data)}

def post_method():
    response = requests.post(Host+"/post",json=data)
    return response

print ( post_method().text )

def get_method():
    response = requests.get("http://httpbin.org/get?q=firstname=dev023")
    return response

print (get_method().json())


from crible_eratosthene import eratosthene
import numpy as np
import matplotlib.pyplot as plt

def pi(n):
    """La fonciton qui compte les nombres premiers"""
    L = eratosthene(n)
    return len(L)

th_nb_prem = lambda n : n/np.log(n)  # x-> x/(log x), l'approximation fournie par le théorème des nomrbes premiers

def Li(x, n = 10**4):

    """On utilise la méthode des rectangles à gauche pour approximer l'intégrale
    de 2 à x de dt/ln(t) """

    f = lambda t : 1/np.log(t)
    h = (x-2)/n
    s = 0
    t = 2
    for k in range(n):
        s+=f(t)
        t+=h
    return h*s

N = np.array(list(range(2,1000)))
P = np.array([pi(n) for n in N ])
A = th_nb_prem(N)
L= np.array([Li(n) for n in N])
plt.plot(N,P, label='pi(x)')
plt.plot(N,A, label = 'x/log(x)')
plt.plot(N,L,label= 'Li(x)')
plt.legend()
plt.title("Comparaison des approximations de pi(x)")

plt.show()


import json
import unittest

from app import app, db
from apps.downloads.models import DownloadsReleases
from apps.releases.models import Releases
from apps.utils.time import get_datetime

class TestDownloadsReleasesViews(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()
        # Add 2 releases
        release1 = Releases(
            Title="UnitTest 1",
            Date=get_datetime(),
            Artist="UnitTest Arts 1",
            Credits="UnitTest is a good and fun activity",
            Created=get_datetime(),
            ReleaseCode="TEST001"
        )
        release2 = Releases(
            Title="UnitTest 2",
            Date=get_datetime(),
            Artist="UnitTest 2 Arts",
            Credits="UnitTest too is good for testing",
            Created=get_datetime(),
            ReleaseCode="TEST002"
        )
        db.session.add(release1)
        db.session.add(release2)
        db.session.commit()
        self.release_ids = [release1.ReleaseID, release2.ReleaseID]

        # Add downloads for them
        rel1_dl1 = DownloadsReleases(
            ReleaseID=self.release_ids[0],
            DownloadDate="2017-01-01 12:00:15"
        )
        rel1_dl2 = DownloadsReleases(
            ReleaseID=self.release_ids[0],
            DownloadDate="2017-01-02 12:00:15"
        )
        rel1_dl3 = DownloadsReleases(
            ReleaseID=self.release_ids[0],
            DownloadDate="2017-01-03 12:00:15"
        )
        rel2_dl1 = DownloadsReleases(
            ReleaseID=self.release_ids[1],
            DownloadDate="2017-03-02 01:00:15"
        )
        rel2_dl2 = DownloadsReleases(
            ReleaseID=self.release_ids[1],
            DownloadDate="2017-04-02 12:00:15"
        )
        db.session.add(rel1_dl1)
        db.session.add(rel1_dl2)
        db.session.add(rel1_dl3)
        db.session.add(rel2_dl1)
        db.session.add(rel2_dl2)
        db.session.commit()

    def tearDown(self):
        # Will also delete the downloads
        for release in Releases.query.filter(Releases.Title.like("UnitTest%")).all():
            db.session.delete(release)
        db.session.commit()

    def test_getting_all_download_counts(self):
        """Should return the download counts for all releases."""
        response = self.app.get("/api/1.0/downloads/releases/")
        data = json.loads(response.data.decode())

        self.assertEqual(200, response.status_code)
        self.assertNotEqual(None, data)
        self.assertEqual(2, len(data["downloads"]))

        self.assertEqual(self.release_ids[0], data["downloads"][0]["releaseID"])
        self.assertEqual(3, data["downloads"][0]["count"])
        self.assertEqual("2017-01-01 12:00:15", data["downloads"][0]["since"])

        self.assertEqual(self.release_ids[1], data["downloads"][1]["releaseID"])
        self.assertEqual(2, data["downloads"][1]["count"])
        self.assertEqual("2017-03-02 01:00:15", data["downloads"][1]["since"])

    def test_getting_download_count_for_specific_release(self):
        """Should return the download count for the specified release."""
        response = self.app.get("/api/1.0/downloads/releases/{}".format(self.release_ids[1]))
        data = json.loads(response.data.decode())

        self.assertEqual(200, response.status_code)
        self.assertNotEqual(None, data)
        self.assertEqual(1, len(data["downloads"]))

        self.assertEqual(self.release_ids[1], data["downloads"][0]["releaseID"])
        self.assertEqual(2, data["downloads"][0]["count"])
        self.assertEqual("2017-03-02 01:00:15", data["downloads"][0]["since"])

    def test_adding_a_download(self):
        """Should add the entry to DB using the release ID specified in the JSON."""
        response = self.app.post(
            "/api/1.0/downloads/releases/",
            data=json.dumps(
                dict(
                    releaseID=self.release_ids[0],
                )
            ),
            content_type="application/json"
        )

        downloads = DownloadsReleases.query.filter_by(ReleaseID=self.release_ids[0]).all()

        self.assertEqual(201, response.status_code)
        self.assertTrue("Location" in response.data.decode())
        self.assertEqual(4, len(downloads))


import numpy as np
import random as rd
from Scene import Scene
from Snake import Snake
import pygame, random
from pygame.locals import *
from feedfoward import feedfoward
from normalize import preparateInputData

def ConvertDirection(vector):
    if vector == [-1,-1,-1,1]:
        my_direction = 'UP'
    elif vector == [-1,-1,1,-1]:
        my_direction = 'DOWN'
    elif vector == [-1,1,-1,-1]:
        my_direction = 'LEFT'
    #elif vector == [1,-1,-1,-1]:
    else:
        my_direction = 'RIGHT'
    return my_direction

def ChooseBest(population,offspring,fitness,fitness_offspring):
    fitness_sorted = np.argsort(np.array(fitness+fitness_offspring))[-1:-int(len(population)+1):-1]
    population_merge = population + offspring
    fitness_merge = fitness+fitness_offspring
    #ziped = zip(population + offspring, fitness+fitness_offspring)
    new_population = [population_merge[i] for i in fitness_sorted]
    new_fitness = [fitness_merge[i] for i in fitness_sorted]
    return new_population,new_fitness

def SaveBestSelection(population,offspring,fitness,fitness_offspring):
    new_population = []
    new_fitness = []

    best_index = np.argsort(np.array(fitness))[-1]

    new_population.append(population[best_index])
    new_fitness.append(fitness[best_index])

    for i in range(len(population) - 1):
        pop,fit = Roulette(offspring,fitness_offspring)
        new_population.append(pop)
        new_fitness.append(fit)

    return new_population,new_fitness

def Roulette(population,fitness):

    ## Criar roleta
    roulette = fitness/np.sum(fitness) # ver a questão da quantidade de casas numérica
    # Sortear número
    num = rd.random()

    acc = 0
    for index in range(len(fitness)):
        acc += roulette[index]
        if num < acc:
            return population[index],fitness[index]

'''
def Roulette(population,fitness):

    newParents = []
    ## Criar roleta

    roulette = fitness/np.sum(fitness) # ver a questão da quantidade de casas numérica
    for i in range(2):

        # Sortear número
        num = rd.random()

        acc = 0
        for index in range(len(fitness)):
            acc += roulette[index]
            if num < acc:
                newParents.append(population[index])
                break
    return newParents
'''
def crossoverBlx(parents,tax):
    ##Verificar se deve haver cruzamento
    num = rd.random()

    if num <= tax:
        offspring = []
        ##Gerar dois novos novos filhos
        for index in range(2):
            child = []
            for layer in range(len(parents[0])):
                ## b variando entre -0,5 e 1,5
                b = 2*rd.random() -0.5
                if index == 0:
                    weigth = parents[0][layer] + b*(parents[1][layer] - parents[0][layer])
                else:
                    weigth = parents[1][layer] + b*(parents[0][layer] - parents[1][layer])
                child.append(weigth)
            offspring.append(child)

        return offspring
    else:
        return parents

def GaussMatation(offspring,tax,mean,std):
    #print(offspring)

    for son in offspring:
        r = rd.random()
        if r<tax:
            #print("mutação:")
            #print("Antes:")
            #print(offspring)
            for layer in range(len(son)):
                #print(son)
                #print(son[layer])
                ##Quantidade de elementos da matriz de pesos para todas as linhas e colunas
                for line in range(np.shape(son[layer])[0]):
                    for column in range(np.shape(son[layer])[1]):
                        ##Verificar se vai haver mutação
                        #r = rd.random()
                        #if r<tax:
                            #print("mutacao")
                        ##Etapa de mutação utilizando distribuição gaussiana
                            son[layer][line][column] += std*rd.random() + mean
            #print("Depois:")
            #print(offspring)

    return offspring

def PlayGame(scene,snake,population,topology,fps):

    clock = pygame.time.Clock()
    while True:
        clock.tick(fps)

        coord = preparateInputData(scene.CalculateMetrics(snake),60)

        dir = feedfoward(population,topology,coord,4)

        direction = ConvertDirection(dir)

        snake.UpdateDirection(direction)

        scene.CheckCatchApple(snake)

        snake.UpdateSnake()

        ret = scene.CheckColisson(snake)
        if ret == False and scene.CheckFinalStep() == False:
            scene.UpdateScreen(snake)
        else:
            fit,score = scene.GameOver()
            return fit,score

def Main(topology,mutation_tax,crossover_tax,qtd_population,qtd_offspring,generations,std):
    x_train_length = 26
    d_train_length = 4
    screen_length = 600
    x_screen = 600
    y_screen = 600

    fps = 2

    population = []
    fitness = []
    offspring_population = []
    offspring_fitness = []

    max_score = 0

    for i in range(qtd_population):
        population.append(init_weigth(topology,x_train_length,d_train_length))
        offspring_population.append(init_weigth(topology,x_train_length,d_train_length))
        fitness.append(0)
        offspring_fitness.append(0)
    '''
    for i in range(qtd_offspring):
        offspring_population.append(init_weigth(topology,x_train_length,d_train_length))
        offspring_fitness.append(0)
    '''
    ##Repetir o sistema pela quantidade de gerações especificadas

    ## Calcular fitness
    for index in range(qtd_population):
        scene = Scene(x_screen,y_screen)
        snake = Snake()

        fit,score = PlayGame(scene,snake,population[index],topology,fps)

        fitness[index] = fit
        if (score>max_score):
            max_score = score
        break

    for gen in range(generations):
        print("Começou a geração " + str(gen+1))

        score_gen = 0
        ctrMortesPassos = 0

        ##Gerar novos filhos
        for index in range(int(qtd_population/2)):

            ##Roleta
            offspring=[]
            for i in range(2):
                pop,fit = Roulette(population,fitness)
                offspring.append(pop)

            ##Crossover
            offspring = crossoverBlx(offspring,crossover_tax)

            ##Mutação
            offspring = GaussMatation(offspring,mutation_tax,0,std)

            for i in range(2):
                offspring_population[2*index + i] = offspring[i]
                #population[2*index + i] = offspring[i]

        ## Calcular fitness dos novos filhos
        for index in range(qtd_population):
            scene = Scene(x_screen,y_screen)
            snake = Snake()

        fit,score = PlayGame(scene,snake,offspring_population[index],topology,fps)

        fitness[index] = fit
        if (score>max_score):
            max_score = score
        break

        ## Escolher os melhores entre pais e filhos
        population,fitness  = SaveBestSelection(population,offspring_population,fitness,offspring_fitness)
        print("Média: " + str(sum(fitness)/len(fitness)))
        print("Máximo: " + str(max(fitness)))
        print("Score Máximo: " + str(max_score))
        print("Score Geracao: " + str(score_gen))
        print("Mortes por excesso: " + str(ctrMortesPassos))

def init_weigth(topology,x_train_length,d_train_length):
    weights = []
    # Inicializar as matrizes de pesos e o acumulador
    for index in range(len(topology)+1):
        if index == 0:
            weight = np.random.rand(topology[index], x_train_length+1)-0.5
        elif index == len(topology):
            weight = np.random.rand(d_train_length,topology[index-1] + 1)-0.5
        else:
            weight = np.random.rand(topology[index], topology[index-1]+1)-0.5

        weights.append(weight)

    return weights

Main([15,15],0.05,0.9,2000,20,30,0.2)


import argparse
import os

def parse_common_args(parser):
    parser.add_argument('--model_type', type=str, default='resnet50',
                        help='used in model_entry.py')  # default='base_model'
    parser.add_argument('--data_type', type=str, default='base_dataset', help='used in data_entry.py')
    parser.add_argument('--save_prefix', type=str, default='no_squeeze',
                        help='some comment for model or test result dir')
    parser.add_argument('--load_model_path', type=str,
                        default='checkpoints/amazon2dslr_a_1.0_b_1.0_c_1.0_d_1.0/best_checkpoint.pth',
                        help='model path for pretrain or test')  # checkpoints/base_model_pref/0.pth
    parser.add_argument('--load_not_strict', action='store_true', help='allow to load only common state dicts')

    parser.add_argument('--gpus', default=[0, ], nargs='+', type=int)
    parser.add_argument('--seed', type=int, default=3407)

    # datasets
    parser.add_argument('--data_path_source', type=str, default='./data/office31/',
                        help='root of the source dataset')
    parser.add_argument('--data_path_target_tr', type=str, default='./data/office31/',
                        help='root of the target dataset (for training)')
    parser.add_argument('--data_path_target_te', type=str, default='./data/office31/',
                        help='root of the target dataset (for test)')
    parser.add_argument('--src', type=str, default='amazon', help='source domain')
    parser.add_argument('--tar_tr', type=str, default='dslr', help='target domain (for training)')
    parser.add_argument('--tar_te', type=str, default='dslr', help='target domain (for test)')
    parser.add_argument('--num_classes', type=int, default=31, help='class number')

    parser.add_argument('--eps', type=float, default=1e-6, help='a small value to prevent underflow')
    parser.add_argument('--no_da', action='store_true', help='whether using data augmentation')
    parser.add_argument('--gray_tar_agree', action='store_true',
                        help='whether to enforce the consistency between RGB and gray images on the target domain')
    parser.add_argument('--aug_tar_agree', action='store_true',
                        help='whether to enforce the consistency between RGB and augmented images on the target domain')
    parser.add_argument('--workers', default=0, type=int, metavar='N',
                        help='number of data loading workers (default: 4)')
    parser.add_argument('--remain', default=0.7, type=float,
                        help='the remaining weight of centroid of last epoch at this epoch (a number in [0, 1))')
    parser.add_argument('--print_freq', default=20, type=int,
                        metavar='N', help='print frequency (default: 10)')
    # architecture
    parser.add_argument('--arch', type=str, default='resnet50', help='model name')
    parser.add_argument('--resume', type=str, default='', help='checkpoint path to resume (default: '')')
    parser.add_argument('--pretrained', default=True, action='store_true', help='whether using pretrained model')
    parser.add_argument('--num_neurons', type=int, default=128, help='number of neurons in the fc1 of a new model')
    return parser

def parse_train_args(parser):
    parser = parse_common_args(parser)
    parser.add_argument('--lr', type=float, default=1e-3, help='learning rate')
    parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
                        help='momentum for sgd, alpha parameter for adam')
    parser.add_argument('--beta', default=0.999, type=float, metavar='M',
                        help='beta parameters for adam')
    parser.add_argument('--weight-decay', '--wd', default=0, type=float,
                        metavar='W', help='weight decay')
    parser.add_argument('--model_dir', type=str, default='', help='leave blank, auto generated')
    parser.add_argument('--train_list', type=str, default='/data/dataset1/list/base/train.txt')
    parser.add_argument('--batch_size', type=int, default=64)
    parser.add_argument('--epochs', type=int, default=3)

    # loss coefficient
    parser.add_argument('--alpha1', type=float, default=1.0)
    parser.add_argument('--alpha2', type=float, default=1.0)
    parser.add_argument('--alpha3', type=float, default=1.0)
    parser.add_argument('--alpha4', type=float, default=1.0)
    return parser

def parse_test_args(parser):
    parser = parse_common_args(parser)
    parser.add_argument('--save_viz', action='store_true', help='save viz result in eval or not')
    parser.add_argument('--result_dir', type=str, default='', help='leave blank, auto generated')

    parser.add_argument('--batch_size', type=int, default=64)
    return parser

def get_train_args():
    parser = argparse.ArgumentParser()
    parser = parse_train_args(parser)
    args = parser.parse_args()
    return args

def get_test_args():
    parser = argparse.ArgumentParser()
    parser = parse_test_args(parser)
    args = parser.parse_args()
    return args

def get_train_model_dir(args):
    model_dir = os.path.join('checkpoints', args.src + '2' + args.tar_tr + '_a_' + str(args.alpha1) + '_b_' + str(
        args.alpha2) + '_c_' + str(args.alpha3) + '_d_' + str(args.alpha4))
    if not os.path.exists(model_dir):
        os.system('mkdir -p ' + model_dir)
    args.model_dir = model_dir

def get_test_result_dir(args):
    # ext = os.path.basename(args.load_model_path).split('.')[-1]  # 返回path最后的文件名
    model_dir = args.load_model_path.replace('.pth', '')
    # os.path.dirname 去掉文件名，返回目录 val_info = val

    # val_info = os.path.basename(os.path.dirname(args.val_list)) + '_' \
    #            + os.path.basename(args.val_list.replace('.txt', ''))
    val_info = args.src + '2' + args.tar_te
    # result_dir = os.path.join(model_dir, val_info + '_' + args.save_prefix)
    result_dir = model_dir
    if not os.path.exists(result_dir):
        os.system('mkdir -p ' + result_dir)
    args.result_dir = result_dir

def save_args(args, save_dir):
    args_path = os.path.join(save_dir, 'args.txt')
    with open(args_path, 'w') as fd:
        fd.write(str(args).replace(', ', ',\n'))

def prepare_train_args():
    args = get_train_args()
    get_train_model_dir(args)
    save_args(args, args.model_dir)
    return args

def prepare_test_args():
    args = get_test_args()
    get_test_result_dir(args)
    save_args(args, args.result_dir)
    return args

if __name__ == '__main__':
    args = get_test_args()
    get_test_result_dir(args)
    print(args.result_dir)
    exit()

    args = prepare_test_args()
    # train_args = get_train_args()
    test_args = get_test_args()

    parser = argparse.ArgumentParser()
    parser = parse_common_args(parser)

    args = parser.parse_args()
    print(args.gpus)