# [Class]
# 繼承object
# 還沒有做繼承前可以不打 但不打最後執行會掛掉

class Fruit(object):
	# init = initial(Constructor)
	# 一開始建立時會執行的部分
	# self也可以改成my, this
	def __init__(self):
		# 如果沒有self 變數只會活在當前func裡面
		self.color = 'red'
		self.weight = 0
	# create method
	def setColor(self, color):
		self.color = color

# create instance
apple為Fruit的一個instance
apple = Fruit()
print(apple.color)
print(apple.weight)
apple.setColor('purple')
print(apple.color)

# 也可以在__init__提供預設值
class Fruit(object):
	def __init__(self, color):
		self.color = color
		self.weight = 0

apple = Fruit('red')
print(apple.color)

# label = QLabel('test')
lemon = Fruit('green')
print(lemon.color)

class Fruit(object):
	# init = initial(Constructor)
	# 一開始建立時會執行的部分
	# self也可以改成my, this
	def __init__(self):
		# 如果沒有self 變數只會活在當前func裡面
		self.color = 'red'
		self.weight = 0
	# create method
	def setColor(self, color):
		self.color = color

# apple繼承於fruit
class Apple(Fruit):
	def __init__(self):
		# 先去執行apple的init
		super(Apple, self).__init__('red')
		# 或者
		super(Apple, self).__init__('')
		self.setColor('red')

class Apple(Fruit):
	def __init__(self, weight):
		super(Apple, self).__init__('red')
		self.weight = weight

apple01 = Apple(10)
print(apple01.weight)
apple01.setColor('green')
print(apple01.color)

class Apple(Fruit):
	def __init__(self, weight):
		super(Apple, self).__init__('red')
		self.weight = weight
	# override method(如果不滿意原本的)
	def setColor(self, color):
		# 裡面可以加判斷式 跑super去做可逆
		self.color = 'red with %s' % color

apple01 = Apple(10)
apple01.setColor('green')
print(apple01.color)

class Lemon(Fruit):
	def __init__(self, weight):
		super(Lemon, self).__init__('green')
		self.weight = weight

	def setColor(self, color):
		self.color = 'green with %s' % color

lemon01 = Lemon(10)
lemon01.setColor('yellow')
print(lemon01.color)

# 繼承(inheritance)提高程式碼的重用性(reusable)
# 多形(polymorphism)讓各class有一致性的介面 易於擴充維護


import pandas as pd
import sqlite3

# Read data from CSV file
def read_csv_file(file_path: str) -> pd.DataFrame:
    data = pd.read_csv(file_path)
    return data

# Clean and transform data
def clean_transform_data(data: pd.DataFrame) -> pd.DataFrame:
    # Drop rows with missing values
    data = data.dropna()

    # Convert date column to datetime format
    data['date'] = pd.to_datetime(data['date'])

    # Create new columns for year, month, and day
    data['year'] = data['date'].dt.year
    data['month'] = data['date'].dt.month
    data['day'] = data['date'].dt.day

    # Convert categorical columns to uppercase
    data['category'] = data['category'].str.upper()
    data['sub_category'] = data['sub_category'].str.upper()

    return data

# Load data into SQLite database
def load_data_to_sqlite(data: pd.DataFrame, db_name: str):
    conn = sqlite3.connect(db_name)
    data.to_sql('sales_data', conn, if_exists='replace', index=False)
    conn.close()

# Main function
def main():
    file_path = 'sales_data.csv'
    db_name = 'sales_data.db'

    data = read_csv_file(file_path)
    clean_data = clean_transform_data(data)
    load_data_to_sqlite(clean_data, db_name)

if __name__ == '__main__':
    main()


import streamlit as st
import pandas as pd
import json

# Placeholder data for demonstration
data = {
    'Movie': ['Movie A', 'Movie A', 'Movie A', 'Movie B'],
    'Speaker': ['A', 'B', 'C', 'D'],
    'Dialogue': [
        ['Hello!', 'How are you?'],
        ['What is your name?'],
        ['Nice to meet you!'],
        ['What the fuck?']
    ],
}

df = pd.read_json('dialogs.json')
df['emotions'] = [[] for _ in range(df.shape[0])]
df['speakers'] = df['speakers'].apply(lambda x: x[0])
df['dialogue'] = df['dialogue'].apply(lambda x: x[:10])
MAX_ROWS = 2

# Movie selection
selected_movie = st.selectbox("Select a movie", df['movie_title'].unique())

if selected_movie:
    movie_df = df[df['movie_title'] == selected_movie]

    st.subheader(f"Annotate replicas for {selected_movie}")

    for i, row in movie_df.iterrows():
        if i == MAX_ROWS:
            break

        dialogue = row['dialogue']

        st.write(f"Speaker: {row['speakers']}")
        for j in range(len(dialogue)):
            previous_line = dialogue[j-1] if j > 0 else ''
            current_line = dialogue[j]

            st.write(f"Previous Line: {previous_line}")
            st.write(f"Current Line: {current_line}")

            emotions = st.multiselect(f"Select emotions that characterize the current line", ["Happy", "Sad", "Angry", "Neutral"], key=f"emotions_{i}_{j}")
            st.write("Selected emotions:", emotions)

            # Store annotations in the DataFrame
            movie_df.at[i, 'emotions'].append({current_line: emotions})

            st.write("---")

    # Export button
    if st.button("Export Annotations"):
        export_data = movie_df[['dialogue', 'emotions', 'speakers']].to_dict(orient='records')
        json_data = json.dumps(export_data, indent=4)
        st.write(f"Exported JSON:\n{json_data}")


# FIFO Queue implementation using a Python list as
# its underlying storage.
class QueueADT:
    # Create an empty queue.
    def __init__(self):
        self.data = []

    # Add element e to the back of the queue
    def enqueue(self, e):
        self.data.insert(0, e)

    # Remove and return the element from the front of the queue
    # (i.e., FIFO). Raise exception if the queue is empty.
    def dequeue(self):
        if self.is_empty():
            raise IndexError('Queue is empty')
        else:
            return self.data.pop()

    # Return (but do not remove) the first element of the
    # queue. Raise exception if the queue is empty.
    def peek(self):
        if self.is_empty():
            raise IndexError('Queue is empty')
        else:
            return self.data[-1]

    # Return True if the queue is empty.
    def is_empty(self):
        return len(self.data) == 0

    # Return the number of elements in the queue.
    def size(self):
        return len(self.data)

Q = QueueADT()
Q.enqueue("Q")
Q.enqueue("U")
Q.enqueue("E")
Q.enqueue("U")
Q.enqueue("E")
Q.peek()         # Q
Q.size()         # 5
Q.is_empty()     # False
Q.dequeue()      # Q
Q.dequeue()      # U
Q.dequeue()      # E
Q.dequeue()      # U
Q.dequeue()      # E
Q.is_empty()     # True
Q.size()         # 0
Q.peek()         # IndexError: Queue is empty


#!/usr/bin/env python

#import necessary libraries
#pip install flask
from flask import Flask, json,render_template,redirect,url_for
from bs4 import BeautifulSoup as bs
import requests
import pandas as pd

app  = Flask(__name__)

#decorator
@app.route("/")
def echo_hello():
    return_text = """
Web Scraping 50 restaurant near me from yelp!

/scrape endpoint will call the function to scrape yelp and store data in CSV file

/all endpoint will display scrapped data

                      """
    return return_text

@app.route("/scrape")
def web_scrape():
    #Call function
    scrape_restaurant_details()
    return redirect(url_for("show_data"))

# Scrape 50 yelp restaurants near you
def scrape_restaurant_details():
    i=0
    restaurant_list = []
    #each page has 10 restaurants. To get 50 restaurants loop thourgh 5 times
    while i<=40:
        yurl = f'https://www.yelp.com/search?find_desc=Restaurants&find_loc=Ballwin%2C+MO+63021&start={i}'
        response = requests.get(yurl)
        print(yurl)
        page_soup = bs(response.text, 'html.parser')

        #Get all the restaurant names in each page. One page has 10 restaurants
        business = page_soup.find_all("div",class_="container__09f24__sxa9- hoverable__09f24__3HkY2 margin-t3__09f24__hHZsm margin-b3__09f24__3h89A padding-t3__09f24__1VTAn padding-r3__09f24__11Xv2 padding-b3__09f24__2I83c padding-l3__09f24__1JEx9 border--top__09f24__37VAs border--right__09f24__Z9jGU border--bottom__09f24__3lElq border--left__09f24__akfOa border-color--default__09f24__3Epto")
        try:
            for b in business:
                #Restaurant Name
                rest_name = b.find("div",class_="businessName__09f24__3Ml2X display--inline-block__09f24__3SvIn border-color--default__09f24__3Epto").find("a").text

                #Price range
                price = b.find("span",class_="priceRange__09f24__2GspP css-xtpg8e")
                if price!=None:
                    price = price.text
                else:
                    price = "Not Specified"

                #Facilities like - takeout, dinein, delivery etc
                #facility = b.find_all("span",class_="raw__09f24__3Azrj")
                #f_list=[]
                #if facility!=None:
                #    for f in facility:
                #        f_list.append(f.text)
                #else:
                #    f_list.append("Not Specified")

                #Facilities like - takeout, dinein, delivery etc
                facility =  b.find_all("ul",class_="undefined list__09f24__36n6_")
                #print(len(facility))
                f_list=[]
                if facility!=None:
                    for f in facility:
                        f_list.append(f.find("span",class_="raw__09f24__3Azrj").text)
                else:
                    f_list.append("Not Specified")

                #First review
                first_review = b.find("p",class_="css-e81eai").text

                #rating
                ratings = b.find("span", class_="display--inline__09f24__nqZ_W border-color--default__09f24__3Epto").div.get('aria-label')

                #Review Count
                review_count = b.find("span",class_="reviewCount__09f24__3GsGY css-e81eai")
                if review_count!=None:
                    review_count = review_count.text
                else:
                    review_count = "Not specified"

                #Get list of food category
                food_category = b.find_all("p",class_="css-1j7sdmt")
                #print(len(food_category))
                fc_list=[]
                if food_category!=None:
                    for fc in food_category:
                        #Find text for each food category
                        fcat = fc.find_all("p",class_="text__09f24__2NHRu css-1hx6l2b")
                        if(fcat!=None):
                            for c in fcat:
                                if(c!=None):
                                    fc_list.append(c.text)
                                else:
                                    fc_list.append("Not Specified")
                        else:
                            fc_list.append("Not Specified")
                else:
                    fc_list.append("Not Specified")

                #Phone number and address:
                address = b.find_all("p" ,class_="css-8jxw1i")
                cnt = 0
                phone_number="Not Specified"
                addr="Not Specified"
                if address!=None:
                    for a in address:
                        if cnt==0:
                            phone_number = a.text
                        if cnt==1:
                            addr = a.find("span",class_="raw__09f24__3Azrj").text
                        cnt = cnt + 1
                    #print("Phone and address",phone_number,addr)

                #Dictionary of restaurant name, rating etc.
                rest_dict = {"Name":rest_name,
                            "Phone Number":phone_number,
                            "Address":addr,
                            "Price range":price,
                            "Facility":f_list,
                            "1st Review": first_review,
                            "Ratings":ratings,
                            "Review Count":review_count,
                            "Food Category":fc_list
                            }

                restaurant_list.append(rest_dict)
        except AttributeError as e:
                print(e)

        #Go to next 10 restaurants
        i= i + 10

    rest_df = pd.DataFrame(restaurant_list)
    rest_df.to_csv("./static/yelp_ballwin_rest.csv")
    #return render_template('index.html',  tables=[rest_df.to_html(classes='data', header="true")])
    #render template is always looking in tempate folder
    #return "
Web Scraping 50 restaurants near me from yelp and storing them in CSV file!
"
    #return redirect(url_for("show_data"))

@app.route("/all")
def show_data():
    rest_df = pd.read_csv("./static/yelp_ballwin_rest.csv")
    #render template is always looking in tempate folder
    return render_template('index.html',  tables=[rest_df.to_html(classes='data', header="true")])

if __name__ == "__main__":
    app.run(debug=True)


import tkinter as tk
from kotlin_sintactico import *
from kotlin_lexico import *

WIN_WIDTH = 430
WIN_HEIGHT = 575

window = tk.Tk()
window.title("Proyecto LP")  # to define the title
#window.config(cursor= 'heart')
canvas = tk.Canvas(window, width=WIN_WIDTH, height=WIN_HEIGHT)  # define the size
canvas.pack()
frame = tk.Frame(window)

#set window at the center of the screen
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x_win_coord = int((screen_width/2) - (WIN_WIDTH/2))
y_win_coord = int((screen_height/2) - (WIN_HEIGHT/2))
window.geometry("{}x{}+{}+{}".format(WIN_WIDTH, WIN_HEIGHT, x_win_coord, y_win_coord))

frame.place(relx=0.05, rely=0, relwidth=0.9, relheight=0.9)
menu = tk.Menu(window)
lexico = tk.IntVar()
Sintactico = tk.IntVar()
Semantico = tk.IntVar()
window.config(menu=menu)

logo = tk.PhotoImage(file='kotlin_logo.png')
logo = logo.subsample(12)
logo_label = tk.Label(frame, image=logo).grid(sticky='W',row=0,column=0,columnspan=1)
label = tk.Label(frame,text='Analizador del Lenguaje Kotlin', bd='3',fg='black', font='Helvetica 12 bold').grid(row=0,column=0,columnspan=4)  # placing labels

#checks
check_button1 = tk.Checkbutton(frame, text="Léxico", variable= lexico, onvalue=1, offvalue=0)
check_button2= tk.Checkbutton(frame, text="Sintáctico", variable= Sintactico, onvalue=1, offvalue=0)
check_button3 = tk.Checkbutton(frame, text="Semántico", variable= Semantico, onvalue=1, offvalue=0)
check_button1.grid(pady=10,row=1,column=1, columnspan=1)
check_button2.grid(pady=10,row=1,column=2, columnspan=1)
check_button3.grid(pady=10,row=1,column=3, columnspan=1)

#input field
label1 = tk.Label(frame,text='Input', bd='1',fg='black', font='Helvetica 9 bold').grid(sticky = 'W',pady=10,row=1,column=0, columnspan=1)
entry_field1= tk.Text(frame,height = 12, width=47,bd='2')
entry_field1.grid(sticky = 'W', row=2, column=0, columnspan=4)
entry_field1.config(state='normal')
analizar = tk.Button(frame, text="Analizar", command=lambda: getValue(entry_field1.get("1.0", "end-1c"))).grid(sticky = 'W', padx=100, pady=10, row=3, column=1,columnspan=4)
clear_button = tk.Button(frame, text="Limpiar", command=lambda: entry_field1.delete("1.0", "end-1c")).grid(sticky = 'E',pady=10, padx=3, row=3, column=3,columnspan=1)

#output field
label2 = tk.Label(frame,text='Output', bd='1',fg='black', font='Helvetica 9 bold').grid(sticky = 'W',pady=10,row=4, column=0,columnspan=1)
p1 = tk.StringVar(frame, "")
v = tk.Scrollbar(frame, orient='vertical')
t = tk.Text(frame, height = 10, width=48, bd='5', wrap=tk.WORD, yscrollcommand=v.set, borderwidth=2, relief="groove")
t.insert(tk.END, p1.get())
t.grid(sticky='W',row=5, column=0, columnspan=4)
v.config(command=t.yview)

#cadena del input a analizar
def getValue(cadena):
    s=""
    try:
        s = cadena
    except EOFError:
        p1.set("EOFError")
    t.configure(state='normal')
    p1.set("")
    t.delete("1.0", "end")
    if s and lexico.get() and (Sintactico.get() or Semantico.get()):
        analizar_lex_sintax(s)
    elif s and (Sintactico.get() or Semantico.get()):
        analizar_sintactico(s)
    elif s and lexico.get():
       analizar_lexico(s)
    elif s:
        p1.set('Seleccione un tipo de análisis')
    t.insert(tk.END, p1.get())
    t.configure(state='disabled')

def analizar_sintactico(s):
    lexer.lineno = 1
    parser.parse(s, lexer=lexer, tracking=True)
    p1.set(cola[-1])
    cola.clear()
    cola.append("¡Perfecto, es una sintáxis de kotlin limpia!")

def analizar_lexico(s):
    lista_tokens.clear()
    lexer.input(s)
    getTokens(lexer)
    lexer.lineno = 1
    for i in lista_tokens:
        if (i.find('LINEBREAK') != -1):
            lexer.lineno += 1
        elif (i.find('Illegal') != -1):
            p1.set(p1.get() + "[ERROR] Linea " + str(lexer.lineno) + ": " + i + '\n')
        else:
            p1.set(p1.get() + "Linea " + str(lexer.lineno) + ": " + i + '\n')
    lista_tokens.clear()

def analizar_lex_sintax(s):
    lexer.lineno = 1
    parser.parse(s, lexer=lexer)
    p1.set(cola[-1] + '\n')
    analizar_lexico(s)
    cola.clear()
    cola.append("¡Perfecto, es una sintáxis de kotlin limpia!")

window.mainloop()


import time

left = str("left")
no = str("no")
yes = str("yes")

def main():

    print("You are at a path that splits 2 ways, there is a sign with arrows. The arrow pointing left says farm, and the arrow pointing right says town.")

    time.sleep(2)

    print("which way would you like to go?")

    choice1 = str(input())

    if choice1 == left:
        print("You walk to the farm and see lots of cattle and fields full of crop. In the distance you see a barn and an old woman in a rocking chair.")
        time.sleep(1)
        print("Would you like to approch the old woman?")

    choice2 = str(input())

    if choice2 == no:
        print("Ok, there is also lots of cattle.")
        time.sleep(1)
        print("Would you like to go look at the animals?")

    if choice2 == yes:
        print("You walk up the old woman, on closer inspection you see her eyes are closed and it looks like she is asleep.")
        time.sleep(1)
        print("Would you like to wake her up?")

    choice6 = str(input())

    if choice6 == yes:
        print("You shake her and she doesn't move, you feel her pulse and she has none. Freaked out, you run back to where you were.")
        time.sleep(2)
        print("There are also lots of cattle. Would you like to go look at the cattle?")

    choice5 = str(input())

    if choice5 == yes:
        print("There are lots of Cows, Pigs, and Chickens.")
        time.sleep(1)
        print("You see a pig with a ribbon on its head oinking at a spider, it's almost like they are communicating.")
        time.sleep(2)
        print("There is nothing else here, so you walk back to the splitting paths.")
        main()

    if choice5 == no:
        print("There is nothing else to look at, so you walk back to the splitting paths.")
        main()

    choice4 = str(input())

    if choice4 == yes:
        print("There are lots of Cows, Pigs, and Chickens.")
        time.sleep(1)
        print("you see a pig with a ribbon on its head oinking at a spider, it's almost like they are communicating.")
        time.sleep(1)
        print("There is nothing else here to see, so you walk back to the splitting paths.")
        main()


import cv2
from HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)
detector = HandDetector()

to_draw = []
colors = [
    (255, 0, 255),
    (0, 0, 255),
    (255, 0, 0)
]

counter = 0
flag = True
current_color = colors[counter]

while True:
    success, img = cap.read()
    img = detector.findHands(img)
    lmList = detector.findPosition(img)

    if len(lmList) != 0:

        # use your fist to clear image
        if lmList[8][2] > lmList[6][2]:
            to_draw = []
        else:
            to_draw.append([lmList[8][1], lmList[8][2]])

            for point in to_draw:
                cv2.circle(img, (point[0], point[1]), 5, current_color, cv2.FILLED)

        # change color with second finger
        if lmList[12][2] < lmList[10][2]:
            if flag:
                counter += 1

                if counter >= 3:
                    counter = 0

                current_color = colors[counter]
                flag = False

        if lmList[12][2] > lmList[10][2]:
            flag = True

    cv2.imshow("Image", img)
    cv2.waitKey(1)


from joblib import load
from sklearn import metrics
import src.main as main
import warnings
warnings.filterwarnings('ignore')

# ATENCIÓ: descomentar les següents 5 línies si es vol executar des del projecte amb un IDE (PyCharm o altres).
"""
demo_dataset = main.load_dataset_from_csv('../data/demo_data.csv')  # Per executar des del projecte
lr = load('../models/logistic_regressor.joblib')  # Per executar des del projecte
svc = load('../models/support_vectors_classifier.joblib')  # Per executar des del projecte
knn = load('../models/k_nearest_neighbors_classifier.joblib')  # Per executar des del projecte
rfc = load('../models/random_forest_classifier.joblib')  # Per executar des del projecte
"""

# ATENCIÓ: comentar les següents 5 línies si es vol executar des del projecte amb un IDE (PyCharm o altres).
demo_dataset = main.load_dataset_from_csv('data/demo_data.csv')  # Per executar des del terminal
lr = load('models/logistic_regressor.joblib')  # Per executar des del terminal
svc = load('models/support_vectors_classifier.joblib')  # Per executar des del terminal
knn = load('models/k_nearest_neighbors_classifier.joblib')  # Per executar des del terminal
rfc = load('models/random_forest_classifier.joblib')  # Per executar des del terminal

demo_dataset = main.remove_spaces(demo_dataset)
demo_dataset = main.remove_columns(demo_dataset)
demo_dataset = main.nan_treatment(demo_dataset)
X = demo_dataset.values[:, 1:]  # Característiques
Y = demo_dataset.values[:, 0]  # TargeT

lr_preds = lr.predict(X)
print("LR prediction metrics: {}".format(metrics.classification_report(y_true=Y, y_pred=lr_preds)))

svc_preds = svc.predict(X)
print("SVC prediction metrics: {}".format(metrics.classification_report(y_true=Y, y_pred=svc_preds)))

knn_preds = knn.predict(X)
print("KNN prediction metrics: {}".format(metrics.classification_report(y_true=Y, y_pred=knn_preds)))

rfc_preds = rfc.predict(X)
print("RFC prediction metrics: {}".format(metrics.classification_report(y_true=Y, y_pred=rfc_preds)))

# ATENCIÓ: DESCOMENTAR EL SEGÜENT BLOC SI ES VOL ENTRENAR ELS MODELS AMB LES DADES ORIGINALS DEL DATASET
"""
bkpcy_full_dataset = main.load_dataset_from_csv('../data/archive/data.csv')
main.print_head(bkpcy_full_dataset)
main.print_data_types(bkpcy_full_dataset)
main.print_data_statistics(bkpcy_full_dataset)
main.df_dimensionality(bkpcy_full_dataset)
main.y_balance(bkpcy_full_dataset)
main.pearson_correlation(bkpcy_full_dataset)

bkpcy_dt = main.remove_spaces(bkpcy_full_dataset)
bkpcy_dt = main.remove_columns(bkpcy_dt)
bkpcy_dt = main.nan_treatment(bkpcy_dt)

# Entrenament i exportació dels models
x_t, x_v, y_t, y_v = main.split_data(bkpcy_dt.values)
x_t_norm, x_v_norm = main.standardize_data(x_t, x_v)
main.logistic_regression(x_t_norm, y_t, x_v_norm, y_v)
main.svm_classifier(x_t_norm, y_t, x_v_norm, y_v)
main.knn_classifier(x_t_norm, y_t, x_v_norm, y_v)
main.random_forest_classifier(x_t_norm, y_t, x_v_norm, y_v)
"""


# This problem was asked by Facebook.

# Implement regular expression matching with the following
# special characters:

# . (period) which matches any single character
# * (asterisk) which matches zero or more of the preceding element
# That is, implement a function that takes in a string and a valid
# regular expression and returns whether or not the string matches
# the regular expression.

# For example, given the regular expression "ra." and the string
# "ray", your function should return true. The same regular
# expression on the string "raymond" should return false.

# Given the regular expression ".*at" and the string "chat", your
# function should return true. The same regular expression on the
# string "chats" should return false.

def recursive_ast(G, n_ast, n_char, parent):
    if not n_ast: return
    for i in range(n_char+1):
        variant=(i, parent)
        if n_ast==1:
            G.append(variant)
        else:
            recursive_ast(G, n_ast-1, n_char-i, variant)

def get_n_ast(reg_exp):
    n_ast = 0
    c_index = 0
    while True:
        try:
            ast_index = reg_exp.index('*', c_index)
            c_index = ast_index + 1
            n_ast = n_ast + 1
        except ValueError:
            break
    return n_ast

def extract_valid_variants(G_variants, G, ast_chars):
    for i in G:
        variant = []
        while True:
            variant.append(i[0])
            i = i[1]
            if not i: break
        total = 0
        for j in variant:
            total = total + j
        if total == ast_chars:
            # print("valid variant", variant)
            G_variants.append(variant)
    return G_variants

def replace_ast_with_dots(reg_exp_ext, n_dots):
    for k in range(n_dots):
        reg_exp_ext = reg_exp_ext + '.'
    return reg_exp_ext

def extend_reg_exp(G_reg_exp, G_variants, reg_exp):
    for variant in G_variants:
        index = 0
        reg_exp_ext = ''
        for char in reg_exp:
            if char == '*':
                reg_exp_ext = replace_ast_with_dots(reg_exp_ext, variant[index])
                index = index +1
            else:
                reg_exp_ext = reg_exp_ext + char
        G_reg_exp.append(reg_exp_ext)
    # for reg_exp_var in G_reg_exp:
    #     print(reg_exp_var)
    return G_reg_exp

def final_match(G_reg_exp, input_string):
    str_len = len(input_string)
    match = False
    for reg_exp_var in G_reg_exp:
        # print(reg_exp_var)
        match = True
        for i in range(str_len):
            if reg_exp_var[i] == '.':
                continue
            elif reg_exp_var[i] != input_string[i]:
                match = False
                break
        if match: break
    return match

def match_expr(input_string, reg_exp):
    n_ast = get_n_ast(reg_exp)
    # print("n_ast",n_ast)
    G_reg_exp=[]
    G_variants=[]
    G=[]
    if n_ast:
        ast_chars = len(input_string) - (len(reg_exp)-n_ast)
        # print("ast_chars",ast_chars)
        recursive_ast(G, n_ast, ast_chars, None)
        # if len(G):
        #     for i in G:
        #         print(i)
        G_variants = extract_valid_variants(G_variants, G, ast_chars)
        G_reg_exp = extend_reg_exp(G_reg_exp, G_variants, reg_exp)
    else:
        if len(reg_exp) == len(input_string):
            G_reg_exp.append(reg_exp)

    match = final_match(G_reg_exp, input_string)
    # print("match", match)
    return match

print(not match_expr("sdf0hello wo", "*.he*llllllllllllll**"))
print(match_expr("sdf0hello wo", "*.he*ll**"))
print(not match_expr("sdf0hello wo", ".he*ll*"))
print(match_expr("sdf0hello wo", "*.hell*"))
print(not match_expr("sdf0hello wo", "*.he*ll"))
print(not match_expr("sdf0hello wo", "*.hi*ll*"))
print(match_expr("ray", "ra."))
print(not match_expr("raymond", "ra."))
print(match_expr("chat", ".*at"))
print(not match_expr("chats", ".*at"))


import maps
from mock import patch

from tendrl.commons import objects
from tendrl.commons.objects.job import Job

def load(*args):
    parent = Job(job_id="Test Parent Job Id", status="Active",
                 payload=maps.NamedDict())
    if args[0]:
        parent.errors = "Error Message"
        parent.children = ["Test_child"]
    return parent

# Testing __init__
def test_constructor():
    '''Testing for constructor involves checking if all needed

    variables are declared initialized
    '''
    job = Job()
    assert job.job_id is None
    # Passing Dummy Values
    job = Job(job_id="Test job id", payload="Test Payload",
              status=True, errors=None, children=None,
              locked_by=None, output="Job Done")
    assert job.output == "Job Done"

# Testing save
@patch.object(objects.BaseObject, "save", return_value=None)
def test_save(mock_save):
    job = Job()
    payload = maps.NamedDict()
    payload['parent'] = "Test Parent Job Id"
    job.payload = payload
    with patch.object(objects.BaseObject, 'load') as mock_load:
        mock_load.return_value = load(False)
        job.status = "true"
        job.save()
    with patch.object(objects.BaseObject, 'load') as mock_load:
        mock_load.return_value = load(False)
        job.status = "failed"
        job.save()
    with patch.object(objects.BaseObject, 'load') as mock_load:
        mock_load.return_value = load(True)
        job.status = "failed"
        job.save()

# Testing render
def test_render():
    job = Job()
    assert job.render() is not None


from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.views.decorators.http import require_POST
from shop.models import Product
from .cart import Cart
from .forms import CartAddProductForm
from coupons.forms import CouponApplyForm
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Cart as CartModel, CartItem

from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver

@receiver(user_logged_in)
def on_login(sender, user, request, **kwargs):
    try:
        session_cart = request.session['cart']
        cart = get_object_or_404(CartModel, user=user)

        for key in session_cart:    # key is product id
            product = get_object_or_404(Product, id=key)
            if CartItem.objects.filter(product=product, cart=cart).exists():
                item = CartItem.objects.get(product=product, cart=cart)
                item.quantity = session_cart[str(key)]['quantity']
                item.save(update_fields=['quantity'])

            else:
                CartItem.objects.create(cart=cart, product=product, price=product.price, quantity=session_cart[str(key)]['quantity'])
    except:
        print('Error when adding products to cart.')

def cart_detail(request):

    if request.user.is_authenticated:
        coupon_apply_form = CouponApplyForm()
        cart = get_object_or_404(CartModel, user=request.user)
        return render(request, 'cart/detail_for_users.html', {'cart': cart, 'coupon_apply_form': coupon_apply_form})
    else:
        cart = Cart(request)
        return render(request, 'cart/detail.html', {'cart': cart})

@require_POST
def cart_add(request, product_id):
    product = get_object_or_404(Product, id = product_id)
    form = CartAddProductForm(request.POST)
    if request.user.is_authenticated:
        cart = get_object_or_404(CartModel, user=request.user)
    else:
        cart = Cart(request)

    if form.is_valid():
        cd = form.cleaned_data
        item = cart.get_item(product_id)
        if item:
            quantity = item.quantity if (request.user.is_authenticated) else item['quantity']

        if ((not item or cd['update']) and (product.quantity >=cd['quantity'])) or (item and product.quantity >= cd['quantity']+quantity):
            cart.add(product = product, quantity = cd['quantity'], update_quantity = cd['update'])
            return redirect('cart:cart_detail')

        messages.error(request, 'Add error. There is no so much {} in the store. There is only left {} item.'.format(product.name, product.quantity))
        return redirect(product.get_absolute_url())
    else:
        return HttpResponse('Bad request', status=400)

def cart_remove(request, product_id):
    if request.user.is_authenticated:
        cart = get_object_or_404(CartModel, user=request.user)
    else:
        cart = Cart(request)
    cart.remove(product_id)
    return redirect('cart:cart_detail')


from django.urls import path
from .views import BookingListView, RoomDetailView, CancelBookingView, CheckoutView, success_view, cancel_view, BookingFormView, contact_us

app_name = 'hotel'

urlpatterns = [
    path('', BookingFormView.as_view(), name='BookingFormView'),
    path('booking_list/', BookingListView.as_view(), name='BookingListView'),
    path('room/<category>', RoomDetailView.as_view(), name='RoomDetailView'),
    path('booking/cancel/<pk>', CancelBookingView.as_view(),
         name='CancelBookingView'),
    path('checkout/', CheckoutView.as_view(), name='CheckoutView'),
    path('success/', success_view, name='success_view'),
    path('cancel/', cancel_view, name='cancel_view'),
    path('contact-us/', contact_us, name="contact_us")

]


import io
import json
from itertools import starmap, chain
from typing import List, Union

from .elements import *

def load(file, context=default_context(), opts=None):
    if opts is None:
        opts = {}

    data = json.load(file)
    data['places'] = {int(k): v for k, v in data['places'].items()}
    data['transitions'] = {int(k): v for k, v in data['transitions'].items()}
    data['arcs'] = {int(k): v for k, v in data['arcs'].items()}
    graphics = data.get('graphics', None)
    names: List[str] = data['names']

    obj_lookup = {}

    if graphics is not None:
        graphics = {int(k): v for k, v in graphics.items()}

    def make_place(name_idx: int, p: dict):
        name = names[name_idx]
        capacity = p.get('capacity', 'infinity')
        capacity = Place.INF_CAPACITY if capacity == 'infinity' else capacity
        place = Place(name, p.get('init_tokens', 0), capacity, context=context)
        obj_lookup[name_idx] = place
        return place

    places = list(starmap(make_place, data['places'].items()))

    def make_transition(name_idx: int, t: dict):
        name = names[name_idx]
        t_type = t.get('T', 'N')
        if t_type == 'T':
            dist = t.get('dist', 'constant')
            if dist == 'constant':
                dist_func = constant_distribution
                t_min = t['t']
                t_max = 1  # unused value
            elif dist == 'uniform':
                dist_func = uniform_distribution
                t_min = t['t_min']
                t_max = t['t_max']
            elif dist == 'custom':
                dfs = opts.get('dist_functions', {})
                dfn = t['dist_func_name']
                dfuncs = [func for func, fname in dfs.items() if fname == dfn]
                t_min = t['t_min']
                t_max = t['t_max']
                if len(dfuncs) == 1:
                    dist_func = dfuncs[0]
                else:
                    raise RuntimeError('error in opts dist_functions for function: '+dfn)
            else:
                raise RuntimeError('unknown distribution: '+dist)
            transition = TransitionTimed(name, t_min, t_max, dist_func, context=context)
            obj_lookup[name_idx] = transition
            return transition
        elif t_type == 'P':
            transition = TransitionPriority(name, t['p'], context=context)
            obj_lookup[name_idx] = transition
            return transition
        elif t_type == 'S':
            transition = TransitionStochastic(name, t['p'], context=context)
            obj_lookup[name_idx] = transition
            return transition
        elif t_type == 'N':
            transition = Transition(name, context=context)
            obj_lookup[name_idx] = transition
            return transition
        else:
            raise RuntimeError('unknown transition type: '+str(t_type))

    transitions = list(starmap(make_transition, data['transitions'].items()))

    def make_arc(name_idx: int, arc: list):
        name = names[name_idx]
        offset = 0
        cls = Arc
        if isinstance(arc[0], str):
            if arc[0] == 'I':
                offset = 1
                cls = Inhibitor
            else:
                raise RuntimeError('unknown first string for arc:', arc[0])
        source = names[arc[offset]]
        target = names[arc[offset+1]]
        try:
            n_tokens = arc[offset+2]
        except IndexError:
            n_tokens = 1
        arc = cls(source, target, n_tokens, name, context=context)
        obj_lookup[name_idx] = arc
        return arc

    arcs = list(starmap(make_arc, data['arcs'].items()))

    if graphics is not None:
        graphics = {obj_lookup[name_idx]: g for name_idx, g in graphics.items()}

    return places, transitions, arcs, graphics

def dump(file, places, transitions, arcs, graphics, opts=None):
    opts = {} if opts is None else opts

    obj_idx_lookup = {x: i for i, x in enumerate(chain(places, transitions, arcs))}
    names = [x.name for x in obj_idx_lookup.keys()]

    def dump_place(p: Place):
        pd = {}
        if p.init_tokens > 0:
            pd['init_tokens'] = p.init_tokens
        if p.capacity != Place.INF_CAPACITY:
            pd['capacity'] = p.capacity
        return pd

    def dump_transition(t: Union[Transition, TransitionTimed, TransitionStochastic, TransitionPriority]):
        # matching for exact type
        if type(t) == TransitionTimed:
            td = {'T': 'T'}
            if t.p_distribution_func == constant_distribution:
                td.update({'t': t.t_min})
            elif t.p_distribution_func == uniform_distribution:
                td.update({'dist': 'uniform', 't_min': t.t_min, 't_max': t.t_max})
            # TODO: add exponential and normal distributions at least
            else:
                if 'dist_functions' in opts:
                    dist_func_name = opts['dist_functions'].get(t.p_distribution_func, t.p_distribution_func.__name__)
                else:
                    dist_func_name = t.p_distribution_func.__name__
                td.update({'dist': 'custom',
                           'dist_func_name': dist_func_name,
                           't_min': t.t_min, 't_max': t.t_max})

            return td
        elif type(t) == TransitionPriority:
            return {'T': 'P', 'p': t.priority}
        elif type(t) == TransitionStochastic:
            return {'T': 'S', 'p': t.probability}
        elif type(t) == Transition:
            return {}
        else:
            raise RuntimeError('unknown transition type: ', str(type(t)))

    def dump_arc(a: Union[Arc, Inhibitor]):
        v = [obj_idx_lookup[a.source], obj_idx_lookup[a.target]]
        if a.n_tokens > 1:
            v += [a.n_tokens]

        if type(a) == Arc:
            return v
        elif type(a) == Inhibitor:
            return ['I'] + v
        else:
            raise RuntimeError('unknown arc type: ', str(type(a)))

    places_dump = {obj_idx_lookup[p]: dump_place(p) for p in places}
    transitions_dump = {obj_idx_lookup[t]: dump_transition(t) for t in transitions}
    arcs_dump = {obj_idx_lookup[a]: dump_arc(a) for a in arcs}

    data = {'names': names,
            'places': places_dump,
            'transitions': transitions_dump,
            'arcs': arcs_dump}

    if graphics is not None:
        data['graphics'] = {obj_idx_lookup[obj]: g for obj, g in graphics.items()}

    json.dump(data, file, indent=2)

def loads(s, context=default_context(), opts=None):
    sio = io.StringIO(s)
    return load(sio, context, opts)

def dumps(places, transitions, arcs, graphics=None, opts=None):
    sio = io.StringIO()
    dump(sio, places, transitions, arcs, graphics, opts)
    return sio.getvalue()


from Heap import Heap

def heapSort(lst):
    heap = Heap() # Create a Heap

    # Add elements to the heap
    for v in lst:
        heap.add(v)

    # Remove elements from the heap
    for i in range(len(lst)):
        lst[len(lst) - 1 - i] = heap.remove()

def main():
    lst = [-44, -5, -3, 3, 3, 1, -4, 0, 1, 2, 4, 5, 53]
    heapSort(lst)
    for v in lst:
        print(str(v) + " ", end = " ")

main()


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 11 18:37:16 2021
@author: guemesturb
"""

import argparse
from libs import *

def main():

    """
        Main execution logic
    """

    """
        Import case chracteristics
    """

    nx, ny, res, channels, n_samples_test, n_samples_train, max_samples_per_tf = get_conf(args.case)

    """
        Generate training tfrecords
    """

    # generate_tfrecords_training(root_folder, us, n_samples_train, max_samples_per_tf, channels, noise)

    """
        Generate testing tfrecords
    """

    generate_tfrecords_testing(root_folder, us, n_samples_train, n_samples_test, max_samples_per_tf, channels, noise, subversion)

    """
        Generate scaling data
    """

    # generate_scaling_data(root_folder, nx, ny, us, n_samples_train, channels, noise)

    return

if __name__ == '__main__':

    """
        Parsing arguments
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("-c", "--case", type=str, required=True)
    parser.add_argument("-u", "--upsampling", type=int, required=True)
    parser.add_argument("-n", "--noise", type=int, required=True)
    parser.add_argument("-s", "--subversion", type=str, default="")
    args = parser.parse_args()

    """
        Define case options
    """

    us = args.upsampling                                               # Subsampling case
    root_folder = f'data/{args.case}/'           # Folder containing the data for the selected case
    noise = f"{args.noise:03d}"
    subversion = args.subversion

    """
        Run execution logic
    """

    main()


#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:same.py
@TIME:2020/4/29 21:13
@DES: 获取两个字典中相同键值对的过程
'''

a = {
     'x':1,
     'y':2,
     'z':3
}
b = {
     'x':11,
     'y':2,
     'w':10
}
print(a.keys() & b.keys())  # 输出a和b中都有的key
print(a.keys() - b.keys()) # 输出a中有，但b中没有的key
print(a.items() & b.items())  # item 表示的是 key和value
c = {key:a[key] for key in a.keys() - {'z','w'}}
print(c)


arr = []
while len(arr) < 10:
    arr.append(int(input()))
is_even = False
for i in arr :
    if i % 2 == 0:
        is_even = True
        break
if is_even:
    print("have")
else:
    print("don't have")


import collections

import advent_tools

def main():
    # advent_tools.TESTING = True
    data = advent_tools.read_input_line_groups()
    print('Part 1:', run_part_1(data[0], data[1]))
    print('Part 2:', run_part_2(data[0], data[1]))

def process_rules(data):
    rules = collections.defaultdict(list)
    for line in data:
        left, right = line.split(':')
        for sp in right.split('|'):
            try:
                rule = [int(num) for num in sp.split()]
            except ValueError:
                rule = sp.replace('"', '').strip()
            rules[int(left)].append(rule)
    return dict(rules)

def run_part_1(rules, messages):
    rules = process_rules(rules)
    return sum(check_rule(message, rules) for message in messages)

def run_part_2(rules, messages):
    rules = rules + ['8: 42 | 42 8', '11: 42 31 | 42 11 31']
    rules = process_rules(rules)
    return sum(check_rule(message, rules) for message in messages)

def check_rule(message, rules):
    return '' in calc_remainders(message, 0, rules)

def calc_remainders(message, rule_num, rules):
    cur_rule = rules[rule_num]
    if len(cur_rule) == 1 and isinstance(cur_rule[0], str):
        if message.startswith(cur_rule[0]):
            yield message[1:]
    else:
        for option in cur_rule:
            rems = [message]
            for num in option:
                next_rems = [r for rem in rems
                             for r in calc_remainders(rem, num, rules)]
                rems = next_rems
            for rem in rems:
                yield rem

if __name__ == '__main__':
    main()


import socket

def listen_broadcast(port=12345):
    # 创建一个UDP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # 设置套接字选项以便在同一地址上重新使用
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 绑定套接字到指定端口
    sock.bind(("", port))

    # 开始监听
    while True:
        data, addr = sock.recvfrom(1024)
        print(f"Received message '{data.decode()}' from {addr}")

if __name__ == "__main__":
    listen_broadcast()


from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Input, concatenate, Bidirectional, LSTM, Reshape, Layer, \
    ReLU, Lambda, Conv1D, add, AveragePooling2D, BatchNormalization
from keras.models import Model, load_model
from keras.optimizers import Adam
from keras.callbacks import TensorBoard, LambdaCallback, EarlyStopping, ReduceLROnPlateau
import keras.backend as K
from config import configurations
from data_utilities.generator import Native_DataGenerator_for_SemanticSimilarityNetwork_TM, \
    Native_ValidationDataGenerator_for_SemanticSimilarityNetwork_TM

import numpy as np
from texttovector import get_ready_vector, get_ready_vector_on_batch
import time
from data_utilities.datareader import read_sts_data, read_sick_data
from sklearn.preprocessing import minmax_scale
import tensorflow as tf
import os

DIM = 9
MAX_TEXT_WORD_LENGTH = configurations.MAX_TEXT_WORD_LENGTH #10
MAX_WORD_CHARACTER_LENGTH = configurations.MAX_WORD_CHARACTER_LENGTH #60
EMBEDDING_LENGTH = configurations.EMBEDDING_LENGTH #300
ALPHABET_LENGTH = configurations.ALPHABET_LENGTH #54
WORD_TO_WORD_COMBINATIONS = int(MAX_TEXT_WORD_LENGTH * MAX_TEXT_WORD_LENGTH) #10*10
WORD_TENSOR_DEPTH = int((ALPHABET_LENGTH * MAX_WORD_CHARACTER_LENGTH) / DIM) #(54*60/9 = 360)
BATCH_SIZE = configurations.BATCH_SIZE

selected_activation='relu'

def triplet_loss(y_true, y_pred, beta = 300, N = 300, epsilon = configurations.EPSILON):
    anchor = Lambda(lambda x: x[0:BATCH_SIZE,:], output_shape=(BATCH_SIZE,1))(y_pred)
    positive = Lambda(lambda x: x[BATCH_SIZE:BATCH_SIZE*2,:], output_shape=(BATCH_SIZE,1))(y_pred)
    negative = Lambda(lambda x: x[BATCH_SIZE*2:BATCH_SIZE*3,:], output_shape=(BATCH_SIZE,1))(y_pred)

    pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), 1)
    neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)), 1)

    pos_dist = -tf.log(-tf.divide((pos_dist), beta) + 1 + epsilon)
    neg_dist = -tf.log(-tf.divide((N - neg_dist), beta) + 1 + epsilon)

    loss = neg_dist + pos_dist

    return loss

def tf_pearson(y_true, y_pred):
    return tf.contrib.metrics.streaming_pearson_correlation(y_pred, y_true)[1]

TRAIN = True

class MLPProject(Layer):
    def __init__(self, num_outputs):
        super(MLPProject, self).__init__()
        self.num_outputs = num_outputs

    def build(self, input_shape):
        super(MLPProject, self).build(input_shape)
        self.dense_1 = Dense(900, activation=selected_activation, kernel_initializer='glorot_uniform', use_bias=True)
        self.dense_2 = Dense(600, activation=selected_activation, kernel_initializer='glorot_uniform', use_bias=True)
        self.dense_3 = Dense(300, activation='sigmoid', kernel_initializer='glorot_uniform', use_bias=True)

    def call(self, input):
        x = self.dense_1(input)
        x = self.dense_2(x)
        x = self.dense_3(x)
        return x

    def compute_output_shape(self, input_shape):
        return (input_shape[0], 300)

embedded_sentence = Input(shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH))

conv1D_2n = Conv1D(filters=40, kernel_size=2, kernel_initializer='glorot_uniform',
                   bias_initializer='glorot_uniform',input_shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH),
                   use_bias=True, activation=selected_activation, padding='same', name='conv1D_2n')
conv1D_3n = Conv1D(filters=40, kernel_size=3, kernel_initializer='glorot_uniform',
                   bias_initializer='glorot_uniform',input_shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH),
                   use_bias=True, activation=selected_activation,padding='same', name='conv1D_3n')
conv2D_2x2 = Conv2D(filters=40, kernel_size=(2, 2), kernel_initializer='glorot_uniform',
                    bias_initializer='glorot_uniform', input_shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH),
                    use_bias=True, activation=selected_activation,
                    padding='same', name='conv2D_2x2')
conv2D_3x3 = Conv2D(filters=40, kernel_size=(3,3), kernel_initializer='glorot_uniform',
                    bias_initializer='glorot_uniform', input_shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH),
                    use_bias=True, activation=selected_activation, padding='same', name='conv2D_3x3')
maxPool2D_2x2 = MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format='channels_first',
                             name='maxPool2D_2x2')
averagePool2D_2x2 = AveragePooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format='channels_first',
                                     name='averagePool2D_2x2')
expand_dims = Lambda(lambda x: K.expand_dims(x, axis=1))
MLP_projector = MLPProject(num_outputs=(300,))

def bi_lstms_network():
    layers = [Bidirectional(LSTM(units=50, activation='tanh', return_sequences=True,
                                 kernel_initializer='glorot_uniform', bias_initializer='glorot_uniform',
                                 input_shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH)), merge_mode='concat'),
              Bidirectional(LSTM(units=100, activation='tanh', return_sequences=True,
                                 kernel_initializer='glorot_uniform', bias_initializer='glorot_uniform',
                                 input_shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH)), merge_mode='concat')
             ]

    def shared_layers(x):
        for layer in layers:
            x = layer(x)
        return x
    return shared_layers

bi_lstms = bi_lstms_network()

conv1D_2n_out_A = conv1D_2n(embedded_sentence)
conv1D_3n_out_A = conv1D_3n(embedded_sentence)
conv2D_2x2_out_A = conv2D_2x2(expand_dims(embedded_sentence))
conv2D_3x3_out_A = conv2D_3x3(expand_dims(embedded_sentence))
bi_lstms_out_A = bi_lstms(embedded_sentence)

pooled_1D_2n = Flatten()(maxPool2D_2x2(expand_dims(conv1D_2n_out_A)))
pooled_1D_3n = Flatten()(maxPool2D_2x2(expand_dims(conv1D_3n_out_A)))
pooled_2D_2x2 = Flatten()(maxPool2D_2x2(conv2D_2x2_out_A))
pooled_2D_3x3 = Flatten()(maxPool2D_2x2(conv2D_3x3_out_A))
pooled_lstms = Flatten()(averagePool2D_2x2(expand_dims(bi_lstms_out_A)))

out =  Lambda(lambda x: K.concatenate(x, axis=-1))([pooled_1D_2n, pooled_1D_3n, pooled_2D_2x2, pooled_2D_3x3,
                                               pooled_lstms])

out = MLP_projector(out)

embedder = Model(inputs=[embedded_sentence], outputs=out)

anchor_in = Input(shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH))
pos_in = Input(shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH))
neg_in = Input(shape=(MAX_TEXT_WORD_LENGTH, EMBEDDING_LENGTH))

anchor_out = embedder(anchor_in)
pos_out = embedder(pos_in)
neg_out = embedder(neg_in)

net_out = concatenate([anchor_out, pos_out, neg_out], axis=0)

combiner_model = Model(inputs=[anchor_in, pos_in, neg_in], outputs=net_out)

network = combiner_model
network.compile(optimizer=Adam(lr=0.01), loss=triplet_loss)
network.summary()
model_head = 'model_semanticsimilarity_TM'
time = time.strftime("%Y%m%d%H%M%S")
dset = 'tarent'
dataset_size = 48000
test_size = 1000
epochs = 500
model_name = model_head + '/' + configurations.EMBEDDER+str(EMBEDDING_LENGTH) + '_dset=' + dset + '_bsize=' + str(BATCH_SIZE) +'_ep=' + str(epochs)+  '_act=' + selected_activation + '_slen=' + str(configurations.MAX_TEXT_WORD_LENGTH) \
             + '_dsize=' + str(dataset_size)+ '_tsize=' + str(test_size)+ '_' + time + '.h5'

if TRAIN:

    reduce_lr = ReduceLROnPlateau(monitor='loss', patience=5, factor=0.1, verbose=1, min_lr=0.0001)

    if not os.path.exists('./logs/'+  model_head):
        os.mkdir('./logs/'+  model_head)
    tensorboard = TensorBoard(log_dir='./logs/' + model_name,
                              histogram_freq=0,
                              batch_size=BATCH_SIZE,
                              write_graph=True, write_grads=False, write_images=False, embeddings_freq=0,
                              embeddings_layer_names=None, embeddings_metadata=None, embeddings_data=None,
                              update_freq='epoch')
    data_generator = Native_DataGenerator_for_SemanticSimilarityNetwork_TM(batch_size=BATCH_SIZE)
    validation_generator = Native_ValidationDataGenerator_for_SemanticSimilarityNetwork_TM(batch_size=BATCH_SIZE)
    K.get_session().run(tf.local_variables_initializer())
    network.fit_generator(generator=data_generator,shuffle=True, validation_data=validation_generator,
                          epochs=epochs, workers=2, use_multiprocessing=False,
                        callbacks=[reduce_lr, tensorboard])
    if not os.path.exists('./trained_models/' + model_head):
        os.mkdir('./trained_models/' + model_head)
    embedder.save('./trained_models/' + 'tm_ebedder' + '.h5')
    network.save('./trained_models/' + model_name + '.h5')
else:
    #network = load_model('trained_models\model_independent_2_02_RegularRNN_Fasttext_mixedmargin.h5')
    network.summary()


import os
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"]="false"
os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"]="platform"
import jax
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import numpy as np
from jax.scipy.special import digamma, gammaln
from .utils import get_s_cp, get_s_cp_missing, get_s_cp_notmissing, lbeta_matrix, lbeta_scalar, rmse, mape

def vb(X: jnp.ndarray,
           R: int,
           a: jnp.ndarray,
           b: jnp.ndarray = jnp.nan,
           num_epochs: int = 1,
           seed: int = 0,
           dir_smooth: jnp.ndarray = 0.1,
           print_freq=0
           ):
   if jnp.isnan(b):
      b = a / jnp.nansum(X)
   I = X.shape
   d = len(I)
   alpha_I = jnp.array([a/(R*I_n) for I_n in I])
   alpha_R = a / R

   S_sum = jnp.nansum(X)

   keys = jax.random.split(jax.random.PRNGKey(seed), d + 2)
   lkeys, key, rkey = keys[:-2], keys[-2], keys[-1]

   log_lam = digamma(S_sum + a) - jnp.log(b + 1)
   log_theta_R = jnp.log(jax.random.dirichlet(rkey, jnp.ones(R) * alpha_R + dir_smooth))
   log_theta_I = [jnp.log(jax.random.dirichlet(lkeys[n], jnp.ones(I_n) * alpha_I[n] + dir_smooth, [R])).T for n, I_n in enumerate(I)]
   log_C = a*jnp.log(b) - (a + S_sum)*jnp.log(b + 1) + gammaln(a + S_sum) - gammaln(a) - gammaln(X + 1).sum()
   ELBO = (jnp.ones(num_epochs) * log_C).tolist()

   all_idx = jnp.array(jnp.where(X!=0)).T
   for i in range(num_epochs):
      s_all, sp_all = get_s_cp(all_idx, log_theta_R, log_theta_I, X)
      S_I = [jax.ops.segment_sum(s_all, all_idx[:, n]).T for n in range(d)]
      S_R = s_all.sum(0)
      ELBO[i] -= sp_all.sum()

      for n, I_n in enumerate(I):
         log_theta_I[n] = digamma(S_I[n] + alpha_I[n]).T - digamma(S_R + alpha_R).T
         ELBO[i] += jnp.apply_along_axis(lbeta_matrix, -1, alpha_I[n] + S_I[n]).sum() - R * lbeta_scalar(alpha_I[n],I_n)
      log_theta_R = digamma(S_R + alpha_R) - digamma(S_sum + R * alpha_R)
      ELBO[i] += lbeta_matrix(alpha_R + S_R) - lbeta_scalar(alpha_R,R)
      if i and print_freq:
         if (i+1) % print_freq == 0:
            print(f"Epoch: {i+1}, ELBO: {ELBO[i]: .0f}")
   return jnp.array(ELBO), [log_lam, log_theta_R, *log_theta_I]

def vb_batch(X: jnp.ndarray,
           R: int,
           a: jnp.ndarray,
           b: jnp.ndarray = jnp.nan,
           num_epochs: int = 1,
           seed: int = 0,
           dir_smooth: jnp.ndarray = 0.1,
           num_batches=0,
           print_freq=0):
   if jnp.isnan(b):
      b = a / jnp.nansum(X)
   I = X.shape
   d = len(I)
   alpha_I = jnp.array([a/(R*I_n) for I_n in I])
   alpha_R = a / R

   S_sum = jnp.nansum(X)

   keys = jax.random.split(jax.random.PRNGKey(seed), d + 2)
   lkeys, key, rkey = keys[:-2], keys[-2], keys[-1]

   log_lam = digamma(S_sum + a) - jnp.log(b + 1)
   log_theta_R = jnp.log(jax.random.dirichlet(rkey, jnp.ones(R) * alpha_R + dir_smooth))
   log_theta_I = [jnp.log(jax.random.dirichlet(lkeys[n], jnp.ones(I_n) * alpha_I[n] + dir_smooth, [R])).T for n, I_n in enumerate(I)]
   log_C = a*jnp.log(b) - (a + S_sum)*jnp.log(b + 1) + gammaln(a + S_sum) - gammaln(a) - gammaln(X + 1).sum()
   ELBO = (jnp.ones(num_epochs) * log_C).tolist()

   all_idx = jnp.array(jnp.where(X!=0)).T
   for i in range(num_epochs):
      if num_batches:
         S_R = jnp.zeros(R)
         S_I = [jnp.zeros_like(log_theta_I_n).T for log_theta_I_n in log_theta_I]
         sp_all = 0
         b = int((len(all_idx) / num_batches)+1)
         for j in range(num_batches):
            s_all, sp_all_  = get_s_cp(all_idx[j*b:(j+1)*b], log_theta_R, log_theta_I, X)
            S_R += s_all.sum(0)
            sp_all += sp_all_.sum()
            S_I = [S_I[n] + jax.ops.segment_sum(s_all, all_idx[j*b:(j+1)*b, n], num_segments=I[n]).T for n in range(d)]
      else:
         s_all, sp_all = get_s_cp(all_idx, log_theta_R, log_theta_I, X)
         S_I = [jax.ops.segment_sum(s_all, all_idx[:, n]).T for n in range(d)]
         S_R = s_all.sum(0)

      ELBO[i] -= sp_all.sum()

      for n, I_n in enumerate(I):
         log_theta_I[n] = digamma(S_I[n] + alpha_I[n]).T - digamma(S_R + alpha_R).T
         ELBO[i] += jnp.apply_along_axis(lbeta_matrix, -1, alpha_I[n] + S_I[n]).sum() - R * lbeta_scalar(alpha_I[n],I_n)
      log_theta_R = digamma(S_R + alpha_R) - digamma(S_sum + R * alpha_R)
      ELBO[i] += lbeta_matrix(alpha_R + S_R) - lbeta_scalar(alpha_R,R),
      if i and print_freq:
         if (i+1) % print_freq == 0:
            print(f"Epoch: {i+1}, ELBO: {ELBO[i]: .0f}")
   return jnp.array(ELBO), [log_lam, log_theta_R, *log_theta_I]

def vb_missing(X: jnp.ndarray,
           R: int,
           a: jnp.ndarray,
           b: jnp.ndarray = jnp.nan,
           num_epochs: int = 1,
           seed: int = 0,
           print_freq=0,
           es_freq=100,
           es_epochs=500,
           X_gt=None,
           trend=None,
           es_idx=None,
           einsum=None,
           b_correction=False,
           dir_smooth: jnp.ndarray = 0.1,
           ):
   jax.config.update("jax_enable_x64", False)
   if jnp.isnan(b):
      b = a / (jnp.nansum(X)/(1-jnp.isnan(X).mean())) if b_correction else a / jnp.nansum(X)
   I = X.shape
   d = len(I)

   alpha_R = a / jnp.prod(R)
   alpha_I = jnp.array([(a/(R*I_n)) for n, I_n in enumerate(I)])
   Alpha_R = jnp.ones(R) * alpha_R
   Alpha_I = [jnp.ones((R, I[n])) * alpha_I_n for n, alpha_I_n in enumerate(alpha_I)]

   keys = jax.random.split(jax.random.PRNGKey(seed), d + 3)
   lkeys, key, rkey, rrkey = keys[:-3], keys[-3], keys[-2], keys[-1]
   S_sum = jnp.nansum(X)

   log_lam = jnp.log(jax.random.gamma(rrkey, a)/b) #digamma(S_sum + a) - jnp.log(b + 1)
   log_theta_R = jnp.log(jax.random.dirichlet(rkey, jnp.ones(R) * alpha_R + dir_smooth))
   log_theta_I = [jnp.log(jax.random.dirichlet(lkeys[n], jnp.ones(I_n) * alpha_I[n] + dir_smooth, [R])).T for n, I_n in enumerate(I)]

   ELBO = jnp.zeros(num_epochs).tolist()
   all_idx_missing = jnp.array(jnp.where(jnp.isnan(X))).T
   all_idx_nonmissing = jnp.array(jnp.where(~jnp.isnan(X))).T
   all_idx = jnp.vstack((all_idx_missing, all_idx_nonmissing))
   best_mape, best_rmse, best_epoch, best_params, es_evals = 1e6, 1e6, 0, [], []

   for i in range(num_epochs):

      X_idx_m, s_all_m = get_s_cp_missing(all_idx_missing, log_lam, log_theta_R, log_theta_I, X)
      s_all, X_idx_elbo_nm = get_s_cp_notmissing(all_idx_nonmissing, log_lam, log_theta_R, log_theta_I, X)
      s_all = jnp.vstack((s_all_m, s_all))
      del s_all_m
      S_I = [jax.ops.segment_sum(s_all, all_idx[:, n]).T for n in range(d)]
      S_R = s_all.sum(0)
      S_sum = jnp.nansum(X) + X_idx_m.sum()
      ELBO[i] += X_idx_m.sum() + X_idx_elbo_nm.sum()
      ELBO[i] += a * jnp.log(b) - (S_sum + a) * jnp.log(b+1)
      for n in range(d):
         ELBO[i] +=  gammaln(Alpha_I[n] + S_I[n]).sum() - gammaln(Alpha_I[n]).sum()
      ELBO[i] += 2*gammaln(Alpha_R).sum() - 2*gammaln(Alpha_R + S_R).sum()
      ELBO[i] -= S_sum * log_lam + (S_R * log_theta_R).sum()
      for n in range(d):
         ELBO[i] -= (S_I[n] * log_theta_I[n].T).sum()

      log_lam = digamma(S_sum+a) - jnp.log(b+1.0)
      log_theta_R = digamma(S_R+Alpha_R) - digamma(S_sum+a)
      for n in range(d):
         log_theta_I[n] = digamma(S_I[n] + Alpha_I[n]).T - digamma(S_R + Alpha_R).T

      if i and es_freq and (i%es_freq==0):
         X_hat = np.einsum(einsum, *[jnp.exp(par) for par in [log_theta_R, *log_theta_I]])  * jnp.exp(log_lam)
         cur_rmse = rmse((X_hat + trend)[es_idx], X_gt[es_idx])
         cur_mape = mape((X_hat + trend)[es_idx], X_gt[es_idx])
         es_evals.append((i, cur_mape, cur_rmse, ELBO[i-1]))
         if i % print_freq == 0:
            print(f"Epoch: {i}, ELBO: {ELBO[i]: .0f}, Val MAPE: {es_evals[-1][1]: .6f}, Val RMSE: {es_evals[-1][2]: .6f}")
         if (cur_rmse < best_rmse) and (cur_mape < best_mape):
            best_rmse = cur_rmse
            best_mape = cur_mape
            best_epoch = i
            best_params = [arr.copy() for arr in [log_lam, log_theta_R, *log_theta_I]]
         else:
            if i - best_epoch >= es_epochs:
               print(f"Early stopping at epoch {i}, reverting to the best parameters obtained at epoch {best_epoch}.")
               log_lam, log_theta_R, *log_theta_I = best_params
               ELBO = ELBO[:best_epoch+1]
               break
   return jnp.array(ELBO), es_evals, [log_lam, log_theta_R, *log_theta_I]


def DFS(src):
	global node, max_dist
	dist = [-1] * (V + 1)
	s = [src]
	dist[src] = 0

	while len(s):
		u = s.pop()

		for v, w in graph[u]:
			if dist[v] == -1:
				dist[v] = dist[u] + w
				max_dist = max(max_dist, dist[v])
				s.append(v)

	node = dist.index(max_dist)

t = int(input())

for _ in range(t):
	V = int(input())
	E = V - 1
	graph = [[] for _ in range(V + 1)]

	for i in range(E):
		u, v, w = map(int, input().split())
		graph[u].append((v, w))
		graph[v].append((u, w))

	node = 0
	max_dist = 0

	DFS(1)
	DFS(node)

	print(max_dist)

6. Depth-first Search (DFS)/The Benefactor (Spoj).py


# -*- coding: utf-8 -*-

"""
使用os.listdir，os.walk,通过遍历生成目录树，
create path-files tree through traverse path with os.listdir or os.walk
Author: Wang Xichang
Date: 2015-09-18
"""

from sys import argv

import os

def traverse_dir(path):
    """
    遍历一个目录，打印目录内的所有文件和目录名
    travers a path to print all files and path name

    :param path: path to traverse
    :return:
    """
    print('[{}]'.format(path))          # 打印当前目录及目录中的文件及子目录名
    pathfiles = os.listdir(path)
    for pf in pathfiles:
        print('\t{}'.format(pf))
    for d in pathfiles:                 # 递归遍历子目录
        if os.path.isdir(path+'/'+d):
            traverse_dir(path+'/'+d)

def dirtree_by_listdir(pathname, include_dir=None, include_files=None, sort=False, indent_level=0):
    """
    使用os.listdir方法生成目录结构树形。
    根据节点层级生成'| '间隔符，节点项前为 '|--'
    ：pathname 开始遍历的根目录
    ：sort 是否对目录内容项进行排序
    返回目录树文本行
    """
    dir_tree = ''
    cur_files = os.listdir(pathname)
    if include_files:
        cur_files = [f for f in cur_files if f in include_files or f in include_dir]
    if sort:
        cur_files = sorted(cur_files)
    files = [f for f in cur_files if not os.path.isdir(pathname+'/'+f)]
    dirs = [d for d in cur_files if os.path.isdir(pathname+'/'+d)]
    indent = '| ' * indent_level + '|--'
    ps = '{}{} [path] [files:{} dirs:{}]'.format(indent, os.path.split(pathname)[1], len(files), len(dirs))
    dir_tree += ps + '\n'
    indent = '| ' * (indent_level + 1) + '|--'
    for file in files:
        dir_tree += '{}{}\n'.format(indent, file)
    for dr in dirs:
        if include_dir:
            if dr not in include_dir:
                continue
        dir_tree += dirtree_by_listdir(pathname + '/' + dr,
                                       include_dir=include_dir,
                                       include_files=include_files,
                                       sort=sort,
                                       indent_level=indent_level + 1)
    return dir_tree

def dirtree_by_walk(pathname, sort=False):
    """
    使用os.walk方法生成目录结构树形。
    根据节点层级生成'| '间隔符，节点项前为 '|--'
    ：pathname 开始遍历的根目录
    ：sort 是否对目录内容项进行排序
    返回目录树文本行
    """
    dir_tree = ''
    for root, dirs, files in os.walk(pathname):
        if sort:
            dirs = sorted(dirs)
            files = sorted(files)
        level_num = root.replace(pathname, '').count(os.sep)
        indent = '| ' * level_num + '|--'
        ps = '{}{} [path] [files:{} dirs:{}]'.format(indent, os.path.split(root)[1], len(files), len(dirs))
        dir_tree += ps + '\n'
        for file in files:
            indent = '| ' * (level_num + 1) + '|--'
            dir_tree += '{}{}\n'.format(indent, file)
    return dir_tree

def dirtree_graph(pathname='.', sort=False, include_dir=None, include_files=None):
    """
    使用中文制表符生成目录树 use china table char
    \u2500:─, \u2514:└, \u251c:├, \u2502:│
    \u25cf:●, \u25ce:◎
    :param pathname: path name
    :param sort: sort pathname
    :param include_dir: list of str,  set paths that is included in pathname
    :param include_files: list of str,  set files that is included in pathname
    :return:
    """
    # include = [] if not include_dir else include_dir
    dir_text = dirtree_by_listdir(pathname, include_dir=include_dir, include_files=include_files, sort=sort)
    # print(dir_text)

    # remove left char and replace to China tab char
    dir_text_new = ''
    for line in dir_text.split('\n'):
        if len(line) == 0: # or all([ix not in line for ix in include]):
            continue
        line_new = line
        for i in range(0, len(line), 2):
            if line[i:i+2] == '| ' and line[i+2:i+5] == '|--':
                line_new = ' '*(int(i/2)+1)*2 + '\u2514' + '\u2500' + line[i+2+3:]
                break
        dir_text_new += line_new + '\n'
    # print(dir_text_new)

    # set table char
    dir_text_new2 = ''
    lines = [line for line in dir_text_new.split('\n') if len(line) > 0]
    for line_num, line in enumerate(lines):
        if line_num == 0:
            # set char: ●─◎─ for root node
            line_new = '\u25cf\u2500\u25ce\u2500' + line[3:] + '\n'
        elif ('\u2514' in line) and ('[path]' not in line) and (line_num < len(lines)-1):
            # set start char to '├' for ch3file item
            line_new = line.replace('\u2514', '\u251c') + '\n'
        else:
            if '[path]' in line:
                # set start char to '└─◎' for path
                line_new = line.replace('\u2514', '\u2514\u2500\u25ce') + '\n'
            else:
                line_new = line + '\n'
        dir_text_new2 += line_new

    # set ├ to └ for last ch3file in subdir
    dir_text = ''
    lines = [line for line in dir_text_new2.split('\n') if len(line) > 0]
    for li, line in enumerate(lines):
        line_new = line + '\n'
        if li < len(lines)-1:
            if line.lstrip()[0] == '\u251c':                # ├
                if lines[li+1].lstrip()[0] == '\u2514':     # └
                    if line.find('\u251c') != lines[li+1].find('\u2514'):
                        line_new = line.replace('\u251c', '\u2514') + '\n'
        dir_text += line_new

    # add vertical char
    lines = [line for line in dir_text.split('\n') if len(line) > 0]
    for li in range(len(lines)-1, 0, -1):
        dirpos = findn(lines[li], '\u2514')
        if len(dirpos) > 0:
            for j in range(li-1, 0, -1):
                for p in dirpos:
                    if p > len(lines[j]) - 1:
                        continue
                    if lines[j][p] == ' ':
                        lines[j] = lines[j][0:p] + '\u2502' + lines[j][p + 1:]
                    else:
                        dirpos.remove(p)
                        break
    dir_text = '\n'.join(lines)

    return dir_text

def findn(string, sub):
    """
    定位当前行目录标识符的开始位置
    :param string:
    :param sub:
    :return:
    """
    result = []
    _str = string
    _pos = 0
    while True:
        if sub in _str:
            pos = _str.find(sub)
            result += [pos+_pos]
            _pos += pos + 1
            _str = _str[pos+1:]
        else:
            return result

def get_dir_files(pathname, suff_list=None):
    """
    遍历一个目录，打印目录内的所有文件和目录名
    :param pathname: 路径名称
    :param suff_list: 后缀名称
    """
    suff_list = [] if not suff_list else suff_list
    # print('[{}]'.format(pathname))
    pathfiles = os.listdir(pathname)
    for pf in [f for f in pathfiles if f[f.find('.'):] in suff_list]:
        print('\t{}'.format(pathname + '/' + pf))
    for d in pathfiles:
        if os.path.isdir(pathname+'/'+d):
            get_dir_files(pathname + '/' + d, suff_list)    # 递归子目录

if __name__ == '__main__':
    # get path-tree for command line: python argv[1]
    path = os.path.abspath('./work')
    if len(argv) > 1:
        path = argv[1]
    print(path)

    print('get path-tree by os.listdir:')
    print(dirtree_by_listdir(path))

    print('get path-tree by os.walk:')
    print(dirtree_by_walk(path))

    print('get path-tree-graph:\n{}'.format(path))
    print(dirtree_graph(path))


import pyttsx3
import os

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
#print(voices[1].id)
engine.setProperty('voice',voices[0].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

remember = open('input.txt','r')

# print(remember.read())
speak(remember.read())


from pyschism.mesh.hgrid import Hgrid
from pyschism.mesh.fgrid import DragCoefficient

hgrid=Hgrid.open('./hgrid.gr3', crs='epsg:4326')
depth1=-1.0
depth2=-3.0
bfric_river=0.0025
bfric_land=0.025
fgrid=DragCoefficient.linear_with_depth(hgrid, depth1, depth2, bfric_river, bfric_land)

#modify values in regions
regions=['GoME+0.001.reg', 'Lake_Charles_0.reg']
values=[0.001, 0.0]
flags=[1, 0] # 0: reset to given value, 1: add given value to the current value
for reg, value, flag in zip(regions, values, flags):
    fgrid.modify_by_region(hgrid, f'./{reg}', value, depth1, flag)

fgrid.write('drag.gr3', overwrite=True)


import argparse
import os

COMP = "g++"
SRC_FILES = ["main.cpp", "structures.cpp",
             "utils.cpp", "algorithms.cpp"]
INC_FILES = ["structures.hpp", "utils.hpp", "algorithms.hpp"]
FLAGS = "-Wall -Wextra -pedantic -O3 -std=c++20"
OUTPUT = "./bin/tp3"
DEFS = ""
LIBS = ""

def build():
    #os.system("mkdir -p bin")
    cmd = f"""{COMP}\
    {" ".join(["src/" + f for f in SRC_FILES])}\
    -I"{" ".join(["str/" + f for f in INC_FILES])}"\
    {FLAGS}\
    {DEFS}\
    {LIBS}\
    -o {OUTPUT}"""
    print(cmd.replace("    ", "\n"))
    os.system(cmd)

def run():
    os.system("cd bin && ./tp3")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-n", "--no-build",
        help="Disable build",
        action="store_true",
        required=False,
        dest="no_build"
    )
    parser.add_argument(
        "-r", "--run",
        help="Runs or not after build",
        action="store_true",
        required=False,
        dest="run"
    )
    parser.add_argument(
        "-d", "--display",
        help="Compiles the renderer",
        action="store_true",
        required=False,
        dest="display"
    )

    args = parser.parse_args()
    print(args)
    if (args.display):
        SRC_FILES += ["renderer.cpp"]
        INC_FILES += ["renderer.hpp"]
        DEFS += "-DRENDER"
        LIBS += "-lSDL2"
    if (not args.no_build):
        build()
    if (args.run):
        run()


import cv2
import numpy as np

cap = cv2.VideoCapture(0)

hsv_min = np.array((0, 77, 17), np.uint8)
hsv_max = np.array((208, 255, 255), np.uint8)

while(1):
   #_, frame = cap.read()

   frame = cv2.imread("Best/Picture 165.jpg", 0)

   cv2.imshow('Original',frame)
   edges = cv2.Canny(frame,120,110)
   cv2.imshow('Canny',edges)
   k = cv2.waitKey(5) & 0xFF
   if k == 27:
      break
   # contours0, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
   # for cnt in contours0:
   #     if len(cnt)>4:
   #         ellipse = cv.fitEllipse(cnt)
   #         cv.ellipse(img,ellipse,(0,0,255),2)

   # cv.imshow('contours', img)
   # cv2.drawContours( edges, contours0, -1, (255,255,0), 1, cv2.LINE_AA, hierarchy, 1 )
   # cv2.imshow('contours', edges) # выводим итоговое изображение в окно

   #    img = cv2.imread('1.jpg', 1)
   # path = 'D:/OpenCV/Scripts/Images'
   # cv2.imwrite(os.path.join(path , 'waka.jpg'), img)

cv2.destroyAllWindows()
cap.release()


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

def sendP(sock, data):
    prefix = str(len(data)).zfill(10)
    sock.send((prefix + data).encode())

def sendAll(users, client, data):
    for user in users:
        if user.is_alive() and user.conn != client.conn:
            sendP(user.conn, '['+client.name+']: '+data)

def getP(sock):
    try:
        prefix = sock.recv(10)
        msg_length = int(prefix.decode())
        data = sock.recv(msg_length)
        return data.decode()
    except Exception:
        return None

def createSock(host='localhost'):
    sock = socket.socket()
    for i in range(1, 2 ** 16 - 1):
        try:
            sock.bind((host, i))
            print(f"Server host -> {host} \nPort -> {i}")
            return sock
        except socket.error:
            pass


import Foundation
from PyObjCTools.TestSupport import TestCase, min_os_level

class UserNotificationHelper(Foundation.NSObject):
    def userNotificationCenter_shouldPresentNotification_(self, a, b):
        pass

class TestNSUserNotification(TestCase):
    def test_enum_types(self):
        self.assertIsEnumType(Foundation.NSUserNotificationActivationType)

    @min_os_level("10.8")
    def testConstants10_8(self):
        self.assertEqual(Foundation.NSUserNotificationActivationTypeNone, 0)
        self.assertEqual(Foundation.NSUserNotificationActivationTypeContentsClicked, 1)
        self.assertEqual(
            Foundation.NSUserNotificationActivationTypeActionButtonClicked, 2
        )
        self.assertEqual(Foundation.NSUserNotificationActivationTypeReplied, 3)
        self.assertEqual(
            Foundation.NSUserNotificationActivationTypeAdditionalActionClicked, 4
        )

        self.assertIsInstance(Foundation.NSUserNotificationDefaultSoundName, str)

    @min_os_level("10.8")
    def testMethods10_8(self):
        obj = Foundation.NSUserNotification.alloc().init()
        self.assertResultIsBOOL(obj.isPresented)
        self.assertResultIsBOOL(obj.isRemote)
        self.assertResultIsBOOL(obj.hasActionButton)
        self.assertArgIsBOOL(obj.setHasActionButton_, 0)

    @min_os_level("10.9")
    def testMethods10_9(self):
        obj = Foundation.NSUserNotification.alloc().init()
        self.assertResultIsBOOL(obj.hasReplyButton)
        self.assertArgIsBOOL(obj.setHasReplyButton_, 0)

    @min_os_level("10.8")
    def testProtocol10_8(self):
        self.assertResultIsBOOL(
            UserNotificationHelper.userNotificationCenter_shouldPresentNotification_
        )

    @min_os_level("10.10")
    def testProtocolsObjects(self):
        self.assertProtocolExists("NSUserNotificationCenterDelegate")


import re
import xml.etree.ElementTree as ET

class LWP:

    ''' Variable définissant l'extension des fichiers décrivant un objet '''

    ext: str = ".flexipage-meta.xml"
    flexpath: str = "/flexipages"

    def __init__(self,path: str, nom: str) -> None:

        ''' Définition des caractéristiques d'un objet '''

        self.nom: str = nom
        self.path: str = path + LWP.flexpath
        self.file:str = nom + LWP.ext

        xml_file = open(self.path + "/" + self.file, "r").read()
        self.src = re.sub(' xmlns="[^"]+"', '', xml_file, count=1)
        self.tree = ET.fromstring(self.src)

        self.label = self.tree.find("masterLabel").text
        if self.tree.find("description") != None:
            self.descr = self.tree.find("description").text
        else:
            self.descr = ""

        self.type = self.tree.find("type").text

    #Si page d'enregistrement, à quel object elle est associée
    def object(self) -> str:
        if self.type() == "RecordPage":
            return self.tree.find("sobjectType").text
        else:
            return "Aucun objet associé"

    #liste des actions visibles sur la page
    def action(self) -> list:
        l_action = []
        hasactions = self.tree.findall(".//*componentInstanceProperties/[name='actionNames']")
        if hasactions != None:
            for actions in hasactions:
                action = actions.iter("/valueList/ValueListItems/value")
                for u_action in action:
                    if u_action.find("value") != None:
                        l_action.append(u_action.find("value").text)

        '''
        regions = self.tree.iter("flexiPageRegions")
        for region in regions:
            if region.find("name").text == "header":
                items = region.iter("itemInstances")
                for item in items:
                    if item.find("componentInstance").find("componentInstanceProperties").find("name").text == "actionNames":
                        actions = item.find("componentInstance").find("componentInstanceProperties").iter("valueListItems")
                        for action in actions:
                            l_action.append(action.find("value").text)
        '''
        return l_action

    #liste des flows directement ajouté à la page
    def flow(self) -> list:
        l_flow = []
        flows = self.tree.findall(".//*componentInstanceProperties/[name='flowName']")
        if flows != None:
            for flow in flows:
                l_flow.append(flow.find("value").text)

        return l_flow


from xml.dom import minidom
import os
from STBWork import *

s = STBWork()
root_dir_xml = input("Enter xml input dir: ")
root_dir_stb = input("Enter stb output dir: ")
end_of_filenames = os.listdir(root_dir_xml)
#end_of_filenames = ["qst.xml", "tutorials.xml", "titles.xml"]
#end_of_filenames = ["npc.xml"]
print(end_of_filenames)
npc_mod = False
for end_of_filename in end_of_filenames:
    filename_xml = root_dir_xml + end_of_filename
    filename_stb = root_dir_stb + end_of_filename.replace(".xml", ".stb")

    xmldoc = minidom.parse(filename_xml)
    text_list = xmldoc.getElementsByTagName('text')
    stb_strings = []

    for text_el in text_list:
        text = text_el.firstChild.nodeValue.strip()
        if npc_mod:
            text = text.replace("?", "").replace("!", "").strip()
        id = int(text_el.attributes["id1"].value)
        id2 = int(text_el.attributes["id2"].value)
        bitflag = int(text_el.attributes["bitflag"].value)
        version = int(text_el.attributes["version"].value)
        stb_string = STBString(id, id2, bitflag, version, None, None, None, text)
        stb_strings.append(stb_string)

    stb_cont = s.write_stb(stb_strings)
    with open(filename_stb, "wb") as stb:
        stb.write(stb_cont)


'function tools'
from itertools import chain, zip_longest
from random import choices

def weighted_sample_without_replacement(population, weights, k=1):
    weights = list(weights)
    positions = range(len(population))
    indices = []

    while True:
        needed = k - len(indices)
        if not needed:
            break
        for i in choices(positions, weights, k=needed):
            if weights[i]:
                weights[i] = 0.0
                indices.append(i)

    return [population[i] for i in indices]

def preprend(value, itr):
    return chain([value], itr)

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


from typing import Optional, List, Union

from fastapi import Depends, HTTPException
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from fastapi.security import OAuth2
from fastapi.security import SecurityScopes
from fastapi.security.utils import get_authorization_scheme_param
from jwt.exceptions import InvalidTokenError
from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED

from api.adapter.s3_adapter import S3Adapter
from api.application.services.authorisation.token_utils import parse_token
from api.application.services.authorisation.dataset_access_evaluator import (
    DatasetAccessEvaluator,
)
from api.application.services.permissions_service import PermissionsService
from api.common.config.auth import (
    IDENTITY_PROVIDER_TOKEN_URL,
    RAPID_ACCESS_TOKEN,
    Action,
)
from api.common.config.layers import Layer
from api.common.custom_exceptions import (
    AuthorisationError,
    UserCredentialsUnavailableError,
    NotAuthorisedToViewPageError,
    AuthenticationError,
)
from api.common.logger import AppLogger
from api.domain.token import Token
from api.domain.dataset_metadata import DatasetMetadata

class OAuth2ClientCredentials(OAuth2):
    def __init__(
        self,
        token_url: str,
        scheme_name: str = None,
        allowed_scopes: dict = None,
        auto_error: bool = True,
    ):
        if not allowed_scopes:
            allowed_scopes = {}
        flows = OAuthFlowsModel(
            clientCredentials={"tokenUrl": token_url, "scopes": allowed_scopes}
        )
        super().__init__(flows=flows, scheme_name=scheme_name, auto_error=auto_error)

    async def __call__(self, request: Request) -> Optional[str]:
        return get_client_token(request)

class OAuth2UserCredentials:
    async def __call__(self, request: Request) -> Optional[str]:
        return get_user_token(request)

oauth2_scheme = OAuth2ClientCredentials(token_url=IDENTITY_PROVIDER_TOKEN_URL)
oauth2_user_scheme = OAuth2UserCredentials()
s3_adapter = S3Adapter()
permission_service = PermissionsService()
dataset_access_evaluator = DatasetAccessEvaluator()

def is_browser_request(request: Request) -> bool:
    accept_type = request.headers.get("Accept")
    return accept_type.startswith("text/html")

def user_logged_in(request: Request) -> bool:
    token = request.cookies.get(RAPID_ACCESS_TOKEN, None)
    return token is not None

def validate_token(
    browser_request: bool = Depends(is_browser_request),
    client_token: Optional[str] = Depends(oauth2_scheme),
    user_token: Optional[str] = Depends(oauth2_user_scheme),
) -> Token:
    check_credentials_availability(browser_request, client_token, user_token)
    token = client_token if client_token else user_token
    return parse_token(token)

def handle_authorisation_error(
    user_token: Optional[str], error: Union[AuthorisationError, InvalidTokenError]
):
    if isinstance(error, InvalidTokenError):
        raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail=str(error))
    else:
        if user_token:
            raise NotAuthorisedToViewPageError()
        else:
            raise error

def secure_endpoint(
    security_scopes: SecurityScopes,
    browser_request: bool = Depends(is_browser_request),
    client_token: Optional[str] = Depends(oauth2_scheme),
    user_token: Optional[str] = Depends(oauth2_user_scheme),
):
    try:
        token = validate_token(browser_request, client_token, user_token)
        check_permissions(token.subject, security_scopes.scopes)
    except (InvalidTokenError, AuthorisationError) as error:
        handle_authorisation_error(user_token, error)

def secure_dataset_endpoint(
    security_scopes: SecurityScopes,
    browser_request: bool = Depends(is_browser_request),
    client_token: Optional[str] = Depends(oauth2_scheme),
    user_token: Optional[str] = Depends(oauth2_user_scheme),
    layer: Optional[Layer] = None,
    domain: Optional[str] = None,
    dataset: Optional[str] = None,
):
    try:
        token = validate_token(browser_request, client_token, user_token)
        metadata = process_dataset_metadata(layer, domain, dataset)
        dataset_access_evaluator.can_access_dataset(
            metadata, token.subject, security_scopes.scopes
        )
    except (InvalidTokenError, AuthorisationError) as error:
        handle_authorisation_error(user_token, error)

def process_dataset_metadata(layer, domain, dataset) -> DatasetMetadata:
    if all([layer, domain, dataset]):
        return DatasetMetadata(layer, domain, dataset)
    else:
        AppLogger.info(
            "Cannot retrieve dataset metadata if all values are not provided"
        )
        raise AuthenticationError("You are not authorised to perform this action")

def get_subject_id(request: Request):
    client_token = get_client_token(request)
    user_token = get_user_token(request)
    token = client_token if client_token else user_token
    token = parse_token(token)
    return token.subject

def get_client_token(request: Request) -> Optional[str]:
    authorization: str = request.headers.get("Authorization")
    scheme, jwt_token = get_authorization_scheme_param(authorization)
    if not authorization or scheme.lower() != "bearer":
        return None
    return jwt_token

def get_user_token(request: Request) -> Optional[str]:
    return request.cookies.get(RAPID_ACCESS_TOKEN, None)

def check_credentials_availability(
    browser_request: bool,
    client_token: Optional[str],
    user_token: Optional[str],
) -> None:
    if not have_credentials(client_token, user_token):
        if browser_request:
            AppLogger.info("Cannot retrieve user credentials if no user token provided")
            raise UserCredentialsUnavailableError()
        else:
            AppLogger.info(
                "Cannot retrieve client credentials if no client token provided"
            )
            raise AuthenticationError(
                message="You are not authorised to perform this action"
            )

def have_credentials(client_token: str, user_token: str) -> bool:
    return bool(user_token or client_token)

def check_permissions(subject_id: str, endpoint_scopes: List[Action]):
    """
    Ensure that at least one of the endpoint_scopes exists in the users permissions.
    Raising an AuthorisationError if not.
    """
    if not endpoint_scopes:
        return True

    permissions = permission_service.get_subject_permissions(subject_id)
    if any([permission.type in endpoint_scopes for permission in permissions]):
        return True

    raise AuthorisationError(
        f"User {subject_id} does not have permissions that grant access to the endpoint scopes {endpoint_scopes}"
    )


import os
from flask import Flask
from flask.ext.socketio import SocketIO
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager

# Flask app
app = Flask(__name__)

# SocketIO
socketio = SocketIO()

# SQLAlchemy
db = SQLAlchemy()

# flask-login
login_manager = LoginManager()

def create_app(sqlalchemy_database_uri, debug=False):
    """Create an application."""
    # Set debug state
    app.debug = debug

    # Load secret key
    try:
        with open('secret', 'rb') as f:
            app.secret_key = f.read()
    except IOError:
        with open('secret', 'wb') as f:
            app.secret_key = os.urandom(32)
            f.write(app.secret_key)

    # Initialize flask-sqlalchemy
    app.config['SQLALCHEMY_DATABASE_URI'] = sqlalchemy_database_uri
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    db.init_app(app)

    # Set login manager
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    # Initialize SocketIO
    socketio.init_app(app)

    # Import routes and events
    from app import routes, events

    # Create database tables
    with app.app_context():
        db.create_all()

    return app


# Databricks notebook source
# MAGIC %md
# MAGIC ## Load parameters form MLFlow Registry

# COMMAND ----------

import mlflow
from mlflow.tracking import MlflowClient

# set model & registry params
model_name = 'Airbnb_Model'
cmr_uri = 'databricks://mlops_webinar:CMR'
dev_uri = 'databricks://mlops_webinar:dev'

# fetch model from registry
client = MlflowClient(tracking_uri=dev_uri, registry_uri=cmr_uri)
reg_mdl = client.get_registered_model(model_name)

# COMMAND ----------

# find latest production model
prod_mdl = None
for mdl in reg_mdl.latest_versions:
  print(f"{mdl.name} (v. {mdl.version}) in {mdl.current_stage} is {mdl.status}")
  if mdl.current_stage == "Production":
    prod_mdl = mdl

if prod_mdl is None:
  raise RuntimeError("No Production Model Found")

# COMMAND ----------

# get parameters for last production model
run = client.get_run(prod_mdl.run_id)

# extract logged parameters
current_params = run.data.params

print("Current Parameters:")
for param in current_params:
  print(f"{param} = {current_params[param]}")

# COMMAND ----------

# MAGIC %md
# MAGIC ## Load Data

# COMMAND ----------

from sklearn.model_selection import train_test_split

target_col = "price"
all_data_df = spark.table("airbnb.features").drop("id").toPandas()
split_X = all_data_df.drop([target_col], axis=1)
split_y = all_data_df[target_col]

# Split out train data
X_train, split_X_rem, y_train, split_y_rem = train_test_split(split_X, split_y, train_size=0.6, random_state=600418151)

# Split remaining data equally for validation and test
X_val, X_test, y_val, y_test = train_test_split(split_X_rem, split_y_rem, test_size=0.5, random_state=600418151)

# COMMAND ----------

# MAGIC %md
# MAGIC ## Set up Model

# COMMAND ----------

import json
from databricks.automl_runtime.sklearn.column_selector import ColumnSelector

select_cols = json.loads(current_params['column_selector__cols'].replace("'", '"'))
col_selector = ColumnSelector(select_cols)

# COMMAND ----------

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder

numerical_pipeline = Pipeline(steps=[
    ("converter", FunctionTransformer(lambda df: df.apply(pd.to_numeric, errors="coerce"))),
    ("imputer", SimpleImputer(strategy=current_params['preprocessor__numerical__imputer__strategy']))
])
one_hot_encoder = OneHotEncoder(handle_unknown=current_params['preprocessor__onehot__handle_unknown'])

transformers = []
transformers.append(("numerical", numerical_pipeline, ["availability_365", "calculated_host_listings_count", "minimum_nights", "neighbourhood_idx", "number_of_reviews", "reviews_per_month"]))
transformers.append(("onehot", one_hot_encoder, ["room_type_idx"]))

preprocessor = ColumnTransformer(transformers,
                                 remainder=current_params['preprocessor__remainder'],
                                 sparse_threshold=int(current_params['preprocessor__sparse_threshold']))

# COMMAND ----------

from sklearn.preprocessing import StandardScaler

standardizer = StandardScaler()

# COMMAND ----------

import mlflow
import sklearn
from sklearn import set_config
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestRegressor

set_config(display='diagram')

skrf_regressor = RandomForestRegressor(
  bootstrap=bool(current_params['regressor__bootstrap']),
  criterion=current_params['regressor__criterion'],
  max_depth=int(current_params['regressor__max_depth']),
  max_features=float(current_params['regressor__max_features']),
  min_samples_leaf=float(current_params['regressor__min_samples_leaf']),
  min_samples_split=float(current_params['regressor__min_samples_split']),
  n_estimators=int(current_params['regressor__n_estimators']),
  random_state=int(current_params['regressor__random_state']),
)

model = Pipeline([
    ("column_selector", col_selector),
    ("preprocessor", preprocessor),
    ("standardizer", standardizer),
    ("regressor", skrf_regressor),
])

model

# COMMAND ----------

# MAGIC %md
# MAGIC ## Train with discovered parameters

# COMMAND ----------

import pandas as pd
import mlflow.sklearn

# Enable automatic logging of input samples, metrics, parameters, and models
mlflow.sklearn.autolog(log_input_examples=True, silent=True)

with mlflow.start_run(run_name="random_forest_regressor") as mlflow_run:
    model.fit(X_train, y_train)

    # Training metrics are logged by MLflow autologging
    # Log metrics for the validation set
    skrf_val_metrics = mlflow.sklearn.eval_and_log_metrics(model, X_val, y_val, prefix="val_")

    # Log metrics for the test set
    skrf_test_metrics = mlflow.sklearn.eval_and_log_metrics(model, X_test, y_test, prefix="test_")

    # Display the logged metrics
    skrf_val_metrics = {k.replace("val_", ""): v for k, v in skrf_val_metrics.items()}
    skrf_test_metrics = {k.replace("test_", ""): v for k, v in skrf_test_metrics.items()}
    display(pd.DataFrame([skrf_val_metrics, skrf_test_metrics], index=["validation", "test"]))

# COMMAND ----------

# MAGIC %md
# MAGIC ## Automatically push model to registry

# COMMAND ----------

import time
from mlflow.entities.model_registry.model_version_status import ModelVersionStatus

artifact_name = "model"
artifact_uri = f"runs:/{mlflow_run.info.run_id}/{artifact_name}"
mlflow.set_registry_uri(cmr_uri)
registered_mdl = mlflow.register_model(artifact_uri, model_name)

# Wait until the model is ready
def wait_until_ready(model_name, model_version):
  client = MlflowClient(registry_uri=cmr_uri)
  for _ in range(20):
    model_version_details = client.get_model_version(
      name=model_name,
      version=model_version,
    )
    status = ModelVersionStatus.from_string(model_version_details.status)
    print("Model status: %s" % ModelVersionStatus.to_string(status))
    if status == ModelVersionStatus.READY:
      break
    time.sleep(5)

wait_until_ready(registered_mdl.name, registered_mdl.version)

# COMMAND ----------

Live Webinars/MLOps Virtual Event - Standardizing MLOps at Scale/Python/09. Automatic Model Retraining.py


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

from targets.firefox.fx_testcase import *

class Test(FirefoxTest):

    @pytest.mark.details(
        description='Users can enable/disable language spelling checks',
        test_case_id='143564',
        test_suite_id='2241',
        locale=['en-US'],
    )
    def run(self, firefox):
        text_editor_title_pattern = Pattern('text_editor_title.png')
        check_your_spelling_unchecked_pattern = Pattern('check_your_spelling_unchecked.png').similar(0.65)
        check_your_spelling_checked_pattern = Pattern('check_your_spelling_checked.png')
        word_underlined_red_pattern = Pattern('word_underlined_red.png')
        text_editor_page = self.get_asset_path('editor.html')

        navigate('about:preferences#general')

        page_loaded = exists(AboutPreferences.PRIVACY_AND_SECURITY_BUTTON_NOT_SELECTED,
                             FirefoxSettings.SITE_LOAD_TIMEOUT)
        assert page_loaded, 'about:preferences page loaded'

        navigate(text_editor_page)

        text_editor_loaded = exists(text_editor_title_pattern)
        assert text_editor_loaded, 'Text editor page loaded.'

        screen_center_location = Location(Screen.SCREEN_WIDTH//2, Screen.SCREEN_HEIGHT//2)

        click(screen_center_location)

        # The word that was spelled wrong is underlined with a red squiggly line.

        paste('test   ttteeesssttt ')

        wrong_spelled_word_underlined_red = exists(word_underlined_red_pattern)
        assert wrong_spelled_word_underlined_red, 'The word that was spelled wrong is underlined with a red ' \
                                                  'squiggly line.'

        # From "Language and Appearance", underneath the "Language", uncheck the box "Check your spelling as you type".

        new_tab()

        navigate('about:preferences#general')

        page_loaded = exists(AboutPreferences.PRIVACY_AND_SECURITY_BUTTON_NOT_SELECTED, FirefoxSettings.FIREFOX_TIMEOUT)
        assert page_loaded, 'about:preferences#general page loaded.'

        type('language')

        check_your_spelling_checked = find_in_region_from_pattern(check_your_spelling_checked_pattern,
                                                                  AboutPreferences.CHECKED_BOX)
        if check_your_spelling_checked:
            assert check_your_spelling_checked, '"Check you spelling..." is unchecked.'

            click(check_your_spelling_checked_pattern)

        check_your_spelling_unchecked = find_in_region_from_pattern(check_your_spelling_unchecked_pattern,
                                                                    AboutPreferences.UNCHECKED_BOX)
        assert check_your_spelling_unchecked, '"Check you spelling..." is unchecked.'

        new_tab()

        navigate(text_editor_page)

        text_editor_loaded = exists(text_editor_title_pattern)
        assert text_editor_loaded, 'Text editor page loaded.'

        click(screen_center_location)

        paste('test   ttteeesssttt ')

        wrong_spelled_word_underlined_red = exists(word_underlined_red_pattern.similar(0.9),
                                                   FirefoxSettings.TINY_FIREFOX_TIMEOUT)
        assert wrong_spelled_word_underlined_red is False, 'The word that was spelled wrong is underlined with a red ' \
                                                           'squiggly line.'


"""
Diffie Hellman Algorithm

Step1:  Assume prime q, select alpha where alpha is a primitive root of q (alpha<q)
        *alpha is a primitive root of q if the following series is followed:
        alpha mod(q), alpha^2 mod(q), ... , alpha^(q-1) mod(q)
        = 1, 2, 3, ..., q-1

Step2:  Assume x_a (private key of user a) where x_a<q.
        Calculate public key y_a = alpha^(x_a) mod(q)

        Assume x_b (private key of user b) where x_b<q.
        Calculate public key y_b = alpha^(x_b) mod(q)

Step3:  Generate secret keys.
        User a has {x_a, y_b, q}
        User b has {x_b, y_a, q}

        User a: key k = (y_b)^(x_a) mod(q)
        User b: key k = (y_a)^(x_b) mod(q)

"""
import random
from Crypto.Util import number

def choose_alpha():
    chosen_alpha = random.randint(2, q - 1)
    # print("Choose alpha = " + str(chosen_alpha))
    # array of values to hold (alpha ** i) % q
    array = []
    for i in range(1, q):
        roottest = (chosen_alpha ** i) % q
        if roottest in array:
            # print(str(chosen_alpha) + " is not a primitive root of " + str(q))
            return -1
        array.append(roottest)

    # if loop is not broken, choose alpha
    return chosen_alpha

q = number.getPrime(13)
print("Prime q = " + str(q))

# finding alpha with alpha^(i) mod(11).
# all alpha^(i) mod(11) in the set from i=1...q-1 must be less than 11
# e.g. 2 satisfies the condition because:
# if alpha = 2; alpha^(i) mod(11) for 0 < i < 11 =
# 2, 4, 8, 5, 10, 9, 7, 3, 6, 1 (all values from 1...q-1 appear)

# primitive root (currently works in reasonable time for q of 4 digits or less
alpha = choose_alpha()
while alpha == -1:
    alpha = choose_alpha()
print("Primitive root alpha = " + str(alpha))

# assume secret key of user a
x_a = random.randint(1, q - 1)
print("Secret key of User a, x_a = " + str(x_a))

# then public key of user a :
y_a = (alpha ** x_a) % q
print("Public key of User a, y_a = " + str(y_a))

# assume secret key of user b
x_b = random.randint(1, q - 1)
print("Secret key of User b, x_b = " + str(x_b))

# then public key of user a :
y_b = (alpha ** x_b) % q
print("Public key of User b, y_b = " + str(y_b))

# User a key:
k_a = (y_b ** x_a) % q
print("User a generated key, k_a = " + str(k_a))

# User b key:
k_b = (y_a ** x_b) % q
print("User b generated key, k_b = " + str(k_b))

if (k_a == k_b):
    print("Matching keys, Success!")
else:
    print("Error: Keys do not match!")