import aiohttp
import asyncio
import pathlib

BACKEND_URL = "http://localhost:8000"
API_URL = f"{BACKEND_URL}/api"
AUTH_URL = f"{BACKEND_URL}/auth"

NUM_REQUESTS = 20
NUM_QUESTIONS = 5
CONTENT_FILE = pathlib.Path(__file__).parent.resolve().parent.joinpath("plai/smol-reactivity.md")

# POST data for new quiz
with open(CONTENT_FILE) as f:
    content = f.read()

data = {
    "title": "Test quiz",
    "content": content,
    "count": NUM_QUESTIONS,
    "is_markdown": True,
}

# call /upload route
async def make_gpt_request(session: aiohttp.ClientSession):
    response = await session.post(f"{API_URL}/upload", json=data)
    result = await response.json()
    return result

async def main():
    async with aiohttp.ClientSession() as session:
        # authenticate
        await session.post(f"{AUTH_URL}/authenticate")

        tasks = []

        for _ in range(NUM_REQUESTS):
            tasks.append(make_gpt_request(session))

        results = await asyncio.gather(*tasks, return_exceptions=True)

    return results

if __name__ == "__main__":
    data = asyncio.run(main())

    for result in data:
        print(result)


# coding: utf-8

# In[1]:

from PIL import Image
import glob
from flask import Blueprint, request, render_template, flash, redirect, url_for
from flask import current_app as current_app

class MatchHair():
    def __inti__(self):

        print("")
        #print("init")

    def recoHairShape(self,shape,gender):

        root_path='static/img/hairShape'

        ownshape=shape["shape"]
        owngen=gender["gender"]

        if ownshape=='ang':
            images = glob.glob(root_path+'/' + owngen +'/' + ownshape + '/'+'*')
#             print(images)
#             for image_path in images:
#                 im = Image.open(image_path) # 이미지 불러오기
#                 #im.save('rename.jpeg') # 이미지 다른 이름으로 저장
#                 im.show()

            return images

        elif ownshape=='egg':
            images = glob.glob(root_path+'/' + owngen +'/' + ownshape + '/'+'*')

            return images

        elif ownshape=='long':
            images = glob.glob(root_path+'/' + owngen +'/' + ownshape + '/'+'*')

            return images

        elif ownshape=='round':
            images = glob.glob(root_path+'/' + owngen +'/' + ownshape + '/'+'*')

            return images

    #@app.route("/", methods=['POST'])
    def send_recohair_to_html(self,shape,gender):
        hairpath=self.recoHairShape(shape,gender)

        recoHairPath={}

        for i in range(0,len(hairpath)):

            recoHairPath['reco_Hair_Path'+str(i+1)]=hairpath[i]

        print(recoHairPath)

        return render_template('/index.html', hairPathHtml=recoHairPath)

#아래와같은 모양과 성별을 받은뒤 머리모양 파일의 위치를 dict으로 알려준다.
shape={'shape' : "egg"}
gen={'gender' : "Man"}
go=MatchHair()
#go.recoHairShape(shape,gen)
go.send_recohair_to_html(shape,gen)


"""
https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

    Input: "babad"
    Output: "bab"
    Note: "aba" is also a valid answer.
Example 2:

    Input: "cbbd"
    Output: "bb"
"""
"""
Thanks to Chomohlungma at
https://leetcode.com/problems/longest-palindromic-substring/discuss/2925/Python-O(n2)-method-with-some-optimization-88ms.
"""
class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s)==0:
        	return s
        maxLen=1
        start=0
        for i in range(1, len(s)):
            #if add a character at the end, the length of longest Palindrome substring may add two

        	if i-maxLen >=1 and s[i-maxLen-1:i+1]==s[i-maxLen-1:i+1][::-1]:
        		start=i-maxLen-1
        		maxLen+=2
        		continue

            #if add a character at the end, the length of longest Palindrome substring may add one

        	if i-maxLen >=0 and s[i-maxLen:i+1]==s[i-maxLen:i+1][::-1]:
        		start=i-maxLen
        		maxLen+=1
        return s[start:start+maxLen]

x = Solution()
print(x.longestPalindrome('abccda'))


import torch
import torch.nn as nn

class FeedForward(nn.Module):
    def __init__(self, d_model, d_ffn, dropout=0.1):
        super(FeedForward, self).__init__()
        self.linear1 = nn.Linear(d_model, d_ffn)
        self.relu = nn.ReLU()
        self.dropout = nn.Dropout(dropout)
        self.linear2 = nn.Linear(d_ffn, d_model)

    def forward(self, x):
        x = self.linear1(x)
        x = self.relu(x)
        x = self.dropout(x)
        x = self.linear2(x)
        return x


word = ['r', 'i', 'g', 'h', 't']
word_validate = "right"
game = True
while game== True:

    userinput = input("enter a character: ").lower()
    if len(userinput) >= 2:
        print('invald character, please enter only one character')
        continue
    else:
        if not userinput.isalpha():
                print("invalid aplphabet, please enter a valid aplhabet")
                continue
        else:
            if userinput not in word:
                print("alphabet not in word, please enter another alphabet")
                continue
            else:
                #accepting multiple values from user and adding to a list
                guessword = []
                guessword.append(userinput)
                print(guessword)

                #print("Right!")
                #print(userinput)
                #break


''' NeuralNetPurePython.py '''

import numpy as np
import matplotlib.pyplot as plt

def initialize(p, w_sig = 1):
    W, b = [[]]*len(p), [[]]*len(p)

    for l in range(1,len(p)):
       W[l]= w_sig * np.random.randn(p[l], p[l-1])
       b[l]= w_sig * np.random.randn(p[l], 1)
    return W,b

def list2vec(W,b):
    # converts list of weight matrices and bias vectors into one column vector
    b_stack = np.vstack([b[i] for i in range(1,len(b))] )
    W_stack = np.vstack(W[i].flatten().reshape(-1,1) for i in range(1,len(W)))
    vec = np.vstack([b_stack, W_stack])
    return vec
#%%
def vec2list(vec, p):
    # converts vector to weight matrices and bias vectors
    W, b = [[]]*len(p),[[]]*len(p)
    p_count = 0

    for l in range(1,len(p)): # construct bias vectors
        b[l] = vec[p_count:(p_count+p[l])].reshape(-1,1)
        p_count = p_count + p[l]

    for l in range(1,len(p)): # construct weight matrices
        W[l] = vec[p_count:(p_count + p[l]*p[l-1])].reshape((p[l], p[l-1]))
        p_count = p_count + (p[l]*p[l-1])

    return W, b
#%%
def RELU(z,l):
    # RELU activation function: value and derivative
    if l == L: return z, np.ones_like(z) # if last layer return identity
    else:
        val = np.maximum(0,z) # RELU function element-wise
        J = np.array(z>0, dtype = float) # derivative of RELU element-wise
        return val, J

#%%
def loss_fn(y,g):
    return (g - y)**2, 2 * (g - y)

#%%
def feedforward(x,W,b):
    a, z, gr_S = [0]*(L+1), [0]*(L+1), [0]*(L+1)

    a[0] = x.reshape(-1,1)
    for l in range(1,L+1):
        z[l] = W[l] @ a[l-1] + b[l] # affine transformation
        a[l], gr_S[l] = S(z[l],l) # activation function
    return a, z, gr_S

#%%
def backward(W,b,X,y):
    n =len(y)
    delta = [0]*(L+1)
    dC_db, dC_dW = [0]*(L+1), [0]*(L+1)
    loss=0

    for i in range(n): # loop over training examples
        a, z, gr_S = feedforward(X[i,:].T, W, b)
        cost, gr_C = loss_fn(y[i], a[L]) # cost i and gradient wrt g
        loss += cost/n

        delta[L] = gr_S[L] @ gr_C

        for l in range(L,0,-1): # l = L,...,1
            dCi_dbl = delta[l]
            dCi_dWl = delta[l] @  a[l-1].T

            # ---- sum up over samples ----
            dC_db[l] = dC_db[l] + dCi_dbl/n
            dC_dW[l] = dC_dW[l] + dCi_dWl/n
            # -----------------------------

            delta[l-1] =  gr_S[l-1] * W[l].T @ delta[l]

    return dC_dW, dC_db, loss

#%%
# import data
data = np.genfromtxt('polyreg.csv',delimiter=',')
X = data[:,0].reshape(-1,1)
y = data[:,1].reshape(-1,1)

    # Network setup
p = [X.shape[1],20,20,1] # size of layers
L = len(p)-1             # number of layers
W,b = initialize(p) # initialize weight matrices and bias vectors
S = RELU

batch_size = 20
lr = 0.005
beta = list2vec(W,b)
loss_arr = []
n = len(X)
num_epochs = 10000
print("epoch | batch loss")
print("----------------------------")
for epoch in range(1,num_epochs+1):
    batch_idx = np.random.choice(n,batch_size)
    batch_X = X[batch_idx].reshape(-1,1)
    batch_y=y[batch_idx].reshape(-1,1)
    dC_dW, dC_db, loss = backward(W,b,batch_X,batch_y)
    d_beta = list2vec(dC_dW,dC_db)
    loss_arr.append(loss.flatten()[0])
    if(epoch==1 or np.mod(epoch,1000)==0):
        print(epoch,": ",loss.flatten()[0])
    beta = beta - lr*d_beta
    W,b = vec2list(beta,p)

    # calculate the loss of the entire training set
dC_dW, dC_db, loss = backward(W,b,X,y)
print("entire training set loss = ",loss.flatten()[0])

#%%
xx = np.arange(0,1,0.01)
y_preds = np.zeros_like(xx)

for i in range(len(xx)):
    a, _, _ = feedforward(xx[i],W,b)
    y_preds[i],  = a[L]

plt.plot(np.array(xx), y_preds, 'b',label = 'fit')
plt.plot(X,y, 'r.', markersize = 4,label = 'y')

plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()

plt.plot(np.array(loss_arr), 'b')
plt.xlabel('iteration')
plt.ylabel('Training Loss')
plt.show()

#%% latex plots
plt.rc('text', usetex=True)
plt.rc('font', family='serif',size=20)
plt.tight_layout()
plt.clf()
xx = np.arange(0,1,0.01)
y_preds = np.zeros_like(xx)

for i in range(len(xx)):
    a, _, _ = feedforward(xx[i],W,b)
    y_preds[i],  = a[L]

plt.plot(np.array(xx), y_preds, 'b',label = 'fit')
plt.plot(X,y, 'r.', markersize = 4, label='$y$')

    #beta = np.array([[10, -140, 400, -250]]).T
    #yy = np.polyval(np.flip(beta), xx)
    #plt.plot(xx, yy, 'k',  alpha = 0.4, label = 'Ground truth')

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

plt.legend()
#plt.xlabel('$x$',fontsize=30)
#plt.ylabel('$y$',fontsize=30)
plt.xlabel('input $u$',fontsize=20)
plt.ylabel('output $y$',fontsize=20)
plt.savefig("nnpolyreg1.pdf",bbox_inches = "tight")
plt.show()

plt.plot(np.array(loss_arr), 'b', label = 'Batch Loss')
plt.xlabel(r'{iteration}')
plt.ylabel(r'{Batch Loss}')

plt.savefig("nnpolyreg2.pdf",bbox_inches = "tight")

plt.show()


import sys

required = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
values = dict()
valid = 0

for line in sys.stdin:
    line = line.strip()
    if not line:
        keys = values.keys()
        if all(r in keys for r in required):
            valid += 1
        values.clear()

    for pair in line.split():
        k, v = pair.split(':')
        values[k] = v

if all(r in keys for r in required):
            valid += 1

print(valid)


# name of student: Bilal Achrifi
# number of student: 99066318
# purpose of program: wisselgeld uitrekenen
# function of program:
# structure of program: inputs, if en elif en while loops

toPay = int(float(input('Amount to pay: '))* 100) # Hier wordt gevraagd hoeveel je moet betalen
paid = int(float(input('Paid amount: ')) * 100) # Hier wordt gevraagd hoeveel je al hebt betaald
change = paid - toPay # Hier wordt de betaalde bedrag en het bedrag dat nog betaald moet worden van elkaar afgetrokken om 'change' een waarde te geven

if change > 0: # Als de wisselgeld groter is dan 0, dan wordt deze if command geactiveerd
  coinValue = 500 # De muntstuk heeft een waarde van 500 cent

  while change > 0 and coinValue > 0: # Deze while loopt wordt geactiveerd als de coinvalue en change groter zijn dan 0
    nrCoins = change // coinValue # Hier wordt change en coinvalue door elkaar gedeeld

    if nrCoins > 0: # Als de amount gelijk is aan 0, dan wordt deze if geact
      print('return maximal ', nrCoins, ' coins of ', coinValue, ' cents!' ) # Hier wordt weergegeven hoeveel je moet geven
      nrCoinsReturned = int(input('How many coins of ' + str(coinValue) +  ' cents did you return? ')) # Hier wordt gevraagd hoeveel je bepaalde muntstukken hebt gegeven
      change -= nrCoinsReturned * coinValue # Hier wordt de wisselgeld berekend

# comment on code below:
    if coinValue == 500:
      coinValue = 50
    elif coinValue == 300:
      coinValue = 20
    elif coinValue == 200:
      coinValue = 10
    elif coinValue == 10:
      coinValue = 5
    elif coinValue == 5:
      coinValue = 2
    elif coinValue == 2:
      coinValue = 1
    else:
      coinValue = 0

if change > 0: # Als je geen muntstukken hebt om te geven, word je hier naartoe geleidt
  print('Change not returned: ', str(change) + ' cents')
else:
  print('Done')


# -*- coding: utf-8 -*-
"""
Created on Fri Aug 19 12:18:38 2022

@author: lab53"""

funcionario = "felipe"
idade = 23
endereco ="santos"
salario = 10000
funcao = "programador"

a = funcionario
b = idade
c = endereco
d = salario
e = funcao

print ("a = ",a)
print ("b = ",b)
print ("c = ",c)
print ("d = ",d)
print ("e = ",e)


############# EJERCICIO 3 ##############
#OBTENER EL AREA Y LONGITUD DE UN CIRCULO
#FORMULA DEL AREA: PI*R2; FORMULA DEL DIAMETRO: 2*IP*R

import math #PEDIMOS LA FUNCION MATEMATICA CONO IMPORT
r=float(input("radio(u): "))
area=math.pi*(r**2)  #fORMULA DEL AREA CON LA FUNCION MATH, PARA RESULTADOS MAS EXACTOS
longitud=2*math.pi*r #LONGIRUD CON EL VALOR DE PI EXACTO

print(f"El area del circulo es: {area:.2f} u2") #:.nf es igual al numero de decimales que queramos imprimir
print(f"La longitud del circulo es {longitud:.2f} u")


"""
https://leetcode.com/problems/remove-nth-node-from-end-of-list/

Given a linked list, remove the n-th node from the end of list and return its head.

Example:
    Given linked list: 1->2->3->4->5, and n = 2.
    After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.

Follow up:
Could you do this in one pass?
"""

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def removeNthFromEnd(self, head: 'ListNode', n: 'int') -> 'ListNode':
        index = 0
        t = head
        #先判断链表长度
        while t!=None:
            t = t.next
            index+=1
        #找到并链接
        if n == index:
            head = head.next
        else:
            h = head
            for i in range(index):
                if i == index-n-1:
                    break
                h = h.next
            h.next = h.next.next
        return head


# https://www.acmicpc.net/problem/2846

N = int(input())
nums = list(map(int, input().split()))
answer, start = 0, nums[0]

for i in range(1, N) :
    if nums[i-1] < nums[i]:
        answer = max(answer, nums[i] - start)
    else :
        start = nums[i]
print(answer)


class User:
    """Class usuario"""

    def __init__(self, nome, sobrenome, endereco, email, telefone):
        self.id = None
        self.nome = nome
        self.sobrenome = sobrenome
        self.endereco = endereco
        self.email = email
        self.telefone = telefone


"""
Transaction file handles everything related to transaction.

# Name1: Nash Baek (nash4comp@gmail.com)
# Student number1: A01243888

# Name2: Taylor Ji (taylor.ji719@gmail.com)
# Student number2: A01304056

UML diagram: https://app.diagrams.net/#G1DUxHF4SH4QveN8GbqGaHewuu07bC5lDG
"""

import datetime
from budget import BudgetTypeEnum

class Transaction:
    """
    Transaction class creates transactions,
    """
    transactions = []

    def __init__(self, dollar_amount, shop_name, budget_type):
        """
        initialize transaction with dollar amount you spent, and the store name
        :param dollar_amount: positive float
        :param shop_name: string
        :param budget_type: string
        """
        self._raw_temp_time = (datetime.datetime.now())
        self._time_stamp = self._raw_temp_time.strftime("%c")
        self._dollar_amount = dollar_amount
        self._shop_name = shop_name
        self._budget_type = budget_type

    def add_transaction(self):
        """
        This method returns a transaction that will be saved under user class.
        For lab 4, I create a transaction list that stores transactions.
        :return: Transaction
        """
        user_input_store_name = input("Enter the place you went: ")
        self.set_shop_name(user_input_store_name)
        user_input_dollar_amount = float(input("Enter the amount you spent: "))
        self.set_dollar_amount(user_input_dollar_amount)
        print("Please select one budget type")
        print("1. Game and Entertainment")
        print("2. Clothing and Accessories")
        print("3. Eating Out")
        print("4. Miscellaneous")
        user_budget_type = int(input("Enter the budget type number: "))
        if user_budget_type == 1:
            self.set_budget_type("Game and Entertainment")
        elif user_budget_type == 2:
            self.set_budget_type("Clothing and Accessories")
        elif user_budget_type == 3:
            self.set_budget_type("Eat out")
        elif user_budget_type == 4:
            self.set_budget_type("Miscellaneous")
        transaction_to_add = Transaction(self.get_dollar_amount(), self.get_shop_name(), self.get_budget_type())
        Transaction.add_transactions_to_list(transaction_to_add)
        return transaction_to_add

    @classmethod
    def add_transactions_to_list(cls, transaction):
        """
        Save transactions to the transaction list.
        Used for lab4, transactions will be stored into user's transaction list.
        :param transaction
        """
        cls.transactions.append(transaction)

    def get_time(self):
        """
        Getter for dollar amount.
        :return: self._dollar_amount
        """
        return self._time_stamp

    def get_dollar_amount(self):
        """
        Getter for dollar amount.
        :return: self._dollar_amount
        """
        return self._dollar_amount

    def set_dollar_amount(self, user_input_dollar_amount):
        """
        Setter for dollar_amount.
        :param user_input_dollar_amount
        """
        self._dollar_amount = user_input_dollar_amount

    def get_shop_name(self):
        """
        Getter for shop_name.
        :return: self._shop_name
        """
        return self._shop_name

    def get_budget_type(self):
        """
        Getter for dollar amount.
        :return: self._dollar_amount
        """
        return self._budget_type

    def get_budget_type_for_key(self):
        """
        Convert budget type string value to Enum class name
        Return String
        """
        type_to_change = self.get_budget_type()
        key = None
        if type_to_change == BudgetTypeEnum.GE.value:
            key = BudgetTypeEnum.GE.name
        elif type_to_change == BudgetTypeEnum.CA.value:
            key = BudgetTypeEnum.CA.name
        elif type_to_change == BudgetTypeEnum.EO.value:
            key = BudgetTypeEnum.EO.name
        elif type_to_change == BudgetTypeEnum.MIS.value:
            key = BudgetTypeEnum.MIS.name
        return key

    def set_shop_name(self, user_input_shop_name):
        """
        Setter for shop_name
        :param user_input_shop_name
        """
        self._shop_name = user_input_shop_name

    def set_budget_type(self, user_input_budget_type):
        """
        Setter for shop_name
        :param user_input_budget_type
        """
        self._budget_type = user_input_budget_type

    def __str__(self):
        """
        String representation of Transaction class
        :return: string to print
        """
        to_str = f"Budget type is {self.get_budget_type()}, Date is {self.get_time()}, " \
                 f"Amount spent is ${self.get_dollar_amount()}, " \
                 f"Store name is {self.get_shop_name()}"
        return to_str


def solution(number, k):
    answer = []

    for i in number:
        if len(answer) == 0:
            answer.append(i)
            continue
        if k > 0:
            while answer[-1] < i:
                answer.pop()
                k -= 1
                if len(answer) == 0 or k <= 0:
                    break
        answer.append(i)

    answer = answer[:-k] if k > 0 else answer
    return ''.join(answer)


from PyQt5.QtWidgets import QMessageBox, QFileDialog, QErrorMessage

from org.sortition.groupselect.gui.mainwin.TAImportOptionsDialog import TAImportOptionsDialog
from org.sortition.groupselect.gui.mainwin.TAInsertRowsColsDialog import TAInsertRowsColsDialog

class TAMainWindowDataActionHandler:
    def __init__(self, ctx, window):
        self.ctx = ctx
        self.win = window

    def confirm_discard(self):
        if not self.ctx.app_data_manager.peopledata_is_empty():
            reply = QMessageBox.question(self.win, 'Overwrite Content', "The data import will overwrite all the raw data. Proceed?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes: return True
            else: return False
        else: return True

    def confirm_discard_results(self):
        if self.ctx.app_data.results:
            reply = QMessageBox.question(self.win, 'Discard Results', "Please be aware that this action will discard your current results. Proceed?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes: return True
            else: return False
        else: return True

    def import_raw(self):
        if not self.ctx.get_status(): return
        if self.confirm_discard():
            fname, scheme = QFileDialog.getOpenFileName(self.win, 'Import People Data to CSV', None, "Comma-separated Values Files (*.csv)")
            if not fname: return
            ok, csv_format = TAImportOptionsDialog.get_input(self.win)
            if not ok: return
            try:
                with open(fname, 'r') as handle:
                    self.ctx.app_data_manager.import_raw_from_csv(handle, csv_format)
            except Exception as e:
                error_dialog = QErrorMessage()
                error_dialog.showMessage(str(e))
                return
            self.ctx.set_unsaved()
            self.win.tabs.tab_peopledata.update_table_from_data()
            self.win.tabs.peopledata_updated()

    def export_raw(self):
        if not self.ctx.get_status(): return
        fname, scheme = QFileDialog.getSaveFileName(self.win, 'Export People Data to CSV', None, "Comma-separated Values Files (*.csv)")
        if not fname: return
        if not fname.endswith('.csv'):
            fname += '.csv'
        try:
            with open(fname, 'w') as handle:
                self.ctx.app_data_manager.export_raw_to_csv(handle)
                handle.close()
        except Exception as e:
            error_dialog = QErrorMessage()
            error_dialog.showMessage(str(e))

    def insert_rows(self):
        if not self.ctx.get_status(): return
        if not self.confirm_discard_results(): return
        options = [(i, i+1) for i in range(self.ctx.app_data.m_data)]
        options.append((self.ctx.app_data.m_data, 'end'))
        ok, beforeRow, number = TAInsertRowsColsDialog.get_input(self.win, 'rows', options)
        if not ok: return
        self.ctx.app_data_manager.insert_rows(beforeRow, number)
        self.ctx.set_unsaved()
        self.win.tabs.tab_peopledata.update_table_from_data()
        self.win.tabs.peopledata_updated()
        self.win.tabs.tab_results.display_empty()
        self.win.tabs.results_updated()
        self.win.results_menu.setEnabled(False)

    def insert_cols(self):
        if not self.ctx.get_status(): return
        options = [(j, self.ctx.app_data.peopledata_keys[j]) for j in range(self.ctx.app_data.n_data)]
        options.append((self.ctx.app_data.n_data, 'end'))
        ok, beforeCol, number = TAInsertRowsColsDialog.get_input(self.win, 'cols', options)
        if not ok: return
        self.ctx.app_data_manager.insert_cols(beforeCol, number)
        self.ctx.set_unsaved()
        self.win.tabs.tab_peopledata.update_table_from_data()
        self.win.tabs.peopledata_updated()
        self.win.tabs.tab_results.display_empty()
        self.win.tabs.results_updated()
        self.win.results_menu.setEnabled(False)

    def delete_rows(self):
        if not self.ctx.get_status(): return
        if not self.confirm_discard_results(): return
        selection = self.win.tabs.tab_peopledata.table_widget.selectionModel()
        rows = [index.row() for index in selection.selectedRows()]
        if not rows: return
        self.ctx.app_data_manager.delete_rows(rows)
        self.ctx.set_unsaved()
        self.win.tabs.tab_peopledata.update_table_from_data()
        self.win.tabs.peopledata_updated()
        self.win.tabs.tab_results.display_empty()
        self.win.tabs.results_updated()
        self.win.results_menu.setEnabled(False)

    def delete_cols(self):
        if not self.ctx.get_status(): return
        selection = self.win.tabs.tab_peopledata.table_widget.selectionModel()
        cols = [index.column() for index in selection.selectedColumns()]
        if not cols: return
        must_discard_results = self.ctx.app_data_manager.cols_not_ignored(cols)
        if must_discard_results:
            if not self.confirm_discard_results(): return
        self.ctx.app_data_manager.delete_cols(cols, must_discard_results)
        self.ctx.set_unsaved()
        self.win.tabs.tab_peopledata.update_table_from_data()
        self.win.tabs.peopledata_updated()
        if must_discard_results: self.win.tabs.tab_results.display_empty()
        self.win.tabs.results_updated()
        self.win.results_menu.setEnabled(False)


import argparse
import json
import logging
from typing import List

import requests
from bs4 import BeautifulSoup

logger = logging.getLogger('Team Stats')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)

parser = argparse.ArgumentParser()
parser.add_argument(
    '-send',
    '--send',
    type=int,
    default=1,
    choices = [0, 1],
    help='1 send email, 0 not send email')
parser.add_argument(
    '-display',
    '--display',
    type=int,
    default=0,
    choices = [0, 1],
    help='1 display in terminal, 0 not display')
args_list = parser.parse_args()

def get_arguments(filename: str):
    with open(filename, 'r') as f:
            arguments = json.load(f)

    return arguments

def get_first_link(team: str):
    url = 'https://www.google.com/search'
    headers = {
        'Accept' : '*/*',
        'Accept-Language': 'en-US,en;q=0.5',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82',
    }
    parameters = {'q': team + " footystats"}
    content = requests.get(url, headers = headers, params = parameters).text
    soup = BeautifulSoup(content, 'html.parser')

    search = soup.find(id = 'search')
    first_link = search.find('a')
    url = first_link['href']

    if '/es/' in url:
        url = url.replace('/es/','/')
    return url

def create_all_disabled_config_file(all_stats_list: List[list]):
    stats_dict = {}
    for item in all_stats_list[1:]:
        stats_dict.update({item[0]:"Disabled"})

    with open("stats.json", "w") as f:
        json.dump(stats_dict, f)

# Implement setup logging() right here


'''
You are given an array and you need to find number of tripets of indices (i,j,k) such that the elements at those indices are in geometric progression for a given common ratio r and i<j<k.
For example,arr=[1,4,16,64] . If r=4, we have [1,4,16] and [4,16,64] at indices (0,1,2) and (1,2,3).
'''

from collections import defaultdict
n, r = map(int, input().split())
arr = list(map(int, input().split()))
m1, m2 = defaultdict(int), defaultdict(int)
triplets = 0
for i in reversed(arr):
    if (i * r) in m2:
        triplets += m2[i * r]
    if (i * r) in m1:
        m2[i] += m1[i * r]
    m1[i] += 1
print(triplets)


#filename: q8_find_uppercase.py
#author: Yuan Siang
#created: 27/2/13
#modified: 1/3/13
#description: Find the number of uppercase letters in a string
#Practical 04 Q8

#define function find_num_uppercase(str)
def find_num_uppercase(string):
    if len(string)==1:
        if(65<=ord(string[0])<=90): #using the unicode values of the uppercase letters, check letter
            return 1 #case for when there is only 1 letter in string
        else:
            return 0
    else:
        if(65<=ord(string[0])<=90):
            return 1+find_num_uppercase(string[1:]) #use recursion to find no. of uppercaes letters in a large string
        else:
            return find_num_uppercase(string[1:])

#main
string = str(input("Enter a string: "))
print (find_num_uppercase(string))

## Enter a string: THERE are EXACTLY 13 uppercase letterS in this sentence
## 13


# asd

from vmtool.config import Config

def _up(val, sect, opt):
    return val.upper()

_FUNCS = {
    'UP': _up,
}

def load(data, main_section='test', filename=None, user_defs=None, override=None, ignore_defs=False, func_map=None):
    cf = Config(main_section=main_section, filename=filename, user_defs=user_defs,
                override=override, ignore_defs=ignore_defs, func_map=func_map)
    cf.cf.read_string(data)
    return cf

_sample_cf = '''
[test]
foo = 1
foo0 = zero
foo1 = one
bar = 0
gaz = ${foo${bar}}
goz = ${foo${foo}}
xone = ${UP ! ${foo1}}

yfoo = ${other:foo}

[other]
foo = zab
'''

def test_config():
    cf = load(_sample_cf, func_map=_FUNCS)
    assert cf.get('foo') == '1'
    assert cf.getint('foo') == 1
    assert cf.get('gaz') == 'zero'
    assert cf.get('goz') == 'one'
    assert cf.get('xone') == 'ONE'
    assert cf.get('yfoo') == 'zab'


import argparse
import numpy as np
import pandas as pd
from utilities import *

def clean(args):
    """Load and clean user-supplied data."""

    print('CLEANING DATA....')
    # load data as a pandas data frame
    df = pd.read_csv(args.filePath, low_memory=False)

    # interpolate missing data values
    if args.interpolate or args.all:
        print('\tDetecting missing values...')
        df = fill_empty_with_nan(df)
        print('\tImputing missing values...')
        df = replace_missing_data(df)
        df = drop_missing_data(df)

    # detect and remove outliers
    if args.outliers or args.all:
        print('\tRemoving outliers...')
        df = remove_outliers(df)
        df = normalize(df)

    # one-hot encode the categorical variables

    # delete useless columns
    if args.all:
        print('\tDeleting useless columns...')
        df = combine_first_last_name(df)
        df = drop_useless_columns(df)
        df, date = check_if_dateTime(df)
    # save cleaned data file to same directory as uncleaned version

    if args.categorical or args.all:
        print('\tTransforming categorical data using one-hot encoding...')
        df = one_hot_encode(df)
    df.to_csv(args.filePath[:-4] + '_CLEANED.csv')
    print('DONE.')
    return df

def add_args(parser):
    """Add command line options for customized data preprocessing."""
    parser.add_argument('filePath', metavar='filePath', type=str, help='Path to uncleaned data file')
    parser.add_argument('-a', '--all', action='store_const', const='a')
    parser.add_argument('-c', '--categorical', action='store_const', const='c')
    parser.add_argument('-i', '--interpolate', action='store_const', const='i')
    parser.add_argument('-m', '--missing', action='store_const', const='m')
    parser.add_argument('-o', '--outliers', action='store_const', const='o')
    parser.add_argument('-v', '--version', action='version', version='v1.0.0')

def main():
    """Create command line argument parser and call clean for preprocessing."""
    parser = argparse.ArgumentParser()
    add_args(parser)
    args = parser.parse_args()
    print(args)
    df = clean(args) # clean data according to user-supplied options
    # CorrelationMatrixPlot(df)
if __name__ == '__main__':
    main()


# Создайте программу для игры в ""Крестики-нолики"".

'''
нужна структура более высокого уровня (над функциями). это классы скорее всего, но про них я пока знаю только то,
что они существуют.
'''

from tkinter import *
import tkinter.font as font
import tkinter.messagebox as mb

def buttons_generator():  # генератор списка кнопок из которых будет собираться игровое поле
    my_font = font.Font(size=30)
    buttons = [Button(window, text='', width=15, height=6) for i in range(9)]
    # скорее всего, можно прикрутить обработчик событий в генератор кнопок, но я не шмог.
    for i in range(len(buttons)):
        buttons[i].bind('<Button-1>', on_click)
        buttons[i]['font'] = my_font
    return buttons

def field_filler(array_of_buttons):  # заполняет поле кнопками из buttons_generator'а
    index = 0
    for row_numbers in range(3):
        for column_number in range(3):
            array_of_buttons[index].grid(column=column_number, row=row_numbers)
            index += 1

'''
задача функции on_click - выдавать разные результаты в зависимости от того, четное или нечетное количество раз она
была вызвана. значит, где-то вне этой функции об этом должна храниться информация.
и хотя использование глобальных переменных не есть хорошая практика, по-другому я сделать пока не смог.
вроде как тут меня могло выручить замыкание, но мне пока нехватает навыков, что бы его сюда вкорячить.
'''

def on_click(event):  # рисует крестик или нолик в нажатой кнопке, вызывает проверку условия победы
    global counter  # сюда будем складывать количество вызовов функции
    if counter % 2 != 0:
        event.widget["text"] = f'X'
    else:
        event.widget["text"] = f'0'
    counter += 1
    win_conditions()

'''
# функцию win_conditions можно оптимизировать. достаточно проверять только те строки/столбы/диагонали,
# в которые был поставлен последний крестик/нолик. но я не буду.
'''

def win_conditions():  # проверяет не закончилась ли у нас игра, вызывает всплывающие окно в случае победы
    conditions_pos = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
    for i in conditions_pos:
        a, b, c = i
        if (l_buttons[a]['text'] == l_buttons[b]['text'] == l_buttons[c]['text']) and l_buttons[a]['text'] != '':
            for j in i:
                l_buttons[j].configure(bg='green')
            winner = 'Крестики' if l_buttons[a]['text'] == 'X' else 'Нолики'
            win_message(winner)

def win_message(winner):  # рисует всплывающее окно если сработал винкондишин
    global l_buttons  # а вот тут я не вижу ничего плохого в глобале
    answer = mb.askyesno(
        title='Игра окончена',
        message=f'Победили {winner}. Новая игра?')
    if answer:  # чистим кнопки и перезаполняем поле для новой игры
        l_buttons = buttons_generator()
        field_filler(l_buttons)
    else:  # закрываем окно игры, берем портвейн, идем домой.
        window.destroy()

counter = 1  # вспомогательная переменная для функции on_click, хранит количество вызовов функции

window = Tk()
window.title('Крестики-нолики')
window.geometry('1100x990')

l_buttons = buttons_generator()
field_filler(l_buttons)

window.mainloop()  # по сути, это такой местный while true


import os
import glob
import numpy as np
import cv2
from sklearn.utils import shuffle

def read_set(path, image_size):
    images = []
    labels = []
    ids = []
    cls = []

    classes = get_classes(path)

    print('Reading images')
    for fld in classes:  # assuming data directory has a separate folder for each class, and that each folder is named after the class
        index = classes.index(fld)
        print('Loading {} files (Index: {})'.format(fld, index))
        path = os.path.join(path, fld, '*g')
        files = glob.glob(path)
        for fl in files:
            image = cv2.imread(fl)
            image = cv2.resize(image, (image_size, image_size), cv2.INTER_LINEAR)
            images.append(image)
            label = np.zeros(len(classes))
            label[index] = 1.0
            labels.append(label)
            flbase = os.path.basename(fl)
            ids.append(flbase)
            cls.append(fld)
    images = np.array(images)
    labels = np.array(labels)
    ids = np.array(ids)
    cls = np.array(cls)

    return images, labels, ids, cls

def get_classes(path):
    return os.listdir(path)


import lsst.pex.config as pexConfig

__all__ = ["BaseSequence"]

class BaseSequence(pexConfig.Config):
    """Part of the configuration for sub-sequences.
    """

    num_events = pexConfig.Field('The number of required events for the sub-sequence.', int)
    num_max_missed = pexConfig.Field('The maximum number of events the sub-sequence is allowed to miss.', int)
    time_interval = pexConfig.Field('Time (units=seconds) between subsequent visits for a field/filter '
                                    'combination. Must be non-zero if number of grouped visits is greater '
                                    'than one.', float)
    time_window_start = pexConfig.Field('Relative time when the window opens for subsequent grouped visits.',
                                        float)
    time_window_max = pexConfig.Field('Relative time when the window reaches maximum rank for subsequent '
                                      'grouped visits.', float)
    time_window_end = pexConfig.Field('Relative time when the window ends for subsequent grouped visits.',
                                      float)
    time_weight = pexConfig.Field('Weighting factor for scaling the shape of the time window.', float)

    def setDefaults(self):
        """Default specification for BaseSequence information.
        """
        self.num_events = 0
        self.num_max_missed = 0
        self.time_interval = 0.0
        self.time_window_start = 0.0
        self.time_window_max = 0.0
        self.time_window_end = 0.0
        self.time_weight = 0.0


import time

import cv2
import numpy as np
from mediapipe import solutions
from socket import *
import re

pattern = re.compile(r"x:\s+([\d\\.\-e]*)\s+y:\s+([\d\\.\-e]*)\s+z:\s+([\d\\.\-e]*)")

def bytes_to_image(width, height, bs):
    return np.frombuffer(bs, dtype=np.uint8).reshape((height, width, 3))

def process_result(results):
    if results.multi_hand_landmarks is None:
        return "[]"
    res_list = []
    hands_num = len(results.multi_hand_landmarks)
    for i in range(hands_num):
        hand = results.multi_hand_landmarks[i]
        res = pattern.findall(str(hand))
        tmp = []
        for tup in res:
            tmpmp = list(tup)
            for index in range(3):
                tmpmp[index] = float(tmpmp[index])

            tmp.append(tmpmp)
        res_list.append(tmp)

    return str(res_list)

class Processor(object):
    def __init__(self):
        self.hands = solutions.hands.Hands(static_image_mode=False,
                                           max_num_hands=2,
                                           min_detection_confidence=0.8)

    def image_process(self, img):
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        results = self.hands.process(img)
        return process_result(results)

class Communicator(object):
    def __init__(self):
        self.socket = socket(AF_INET, SOCK_STREAM)
        while True:
            try:
                self.socket.connect(("127.0.0.1", 1234))
                break
            except ConnectionRefusedError:
                time.sleep(1)  # spin

    def send(self, message: str):
        self.socket.send(message.encode())

    def receive_int(self):
        bb = self.socket.recv(10)
        return int(bb)

    def receive_img(self, width, height):
        bb = self.socket.recv(width * height * 3)
        return bytes_to_image(width, height, bb)

    def close(self):
        self.socket.close()

def main():
    processor = Processor()
    communicator = Communicator()

    width = communicator.receive_int()
    height = communicator.receive_int()

    res = "begin"
    communicator.send(res)

    try:
        while True:
            img = communicator.receive_img(width, height)
            res = processor.image_process(img)
            communicator.send(res)
    except ConnectionResetError:
        pass

    communicator.close()

if __name__ == '__main__':
    main()


class Solution:
    # 超出时间，其实只要比较一半就可以了，所以会慢
    def isPalindrome(self, s: str) -> bool:
        # 先把字符串把正向和反向列表存下来
        forwardlist = list(s)
        reverselist = list(s[::-1])
        while len(forwardlist)!=0 and len(reverselist)!=0:
            # 去除掉正向列表中的非数字和字母，后面那一串判断是否为数字或者字母
            while len(forwardlist) != 0 and not (65<= ord(forwardlist[0]) <=90 or 97<= ord(forwardlist[0]) <=122 or 48<= ord(forwardlist[0]) <=57) :
                forwardlist.pop(0)
            item1 = forwardlist.pop(0) if len(forwardlist) != 0 else ""
            # 去除掉反向列表中的非数字和字母
            while len(reverselist) != 0 and not (65<= ord(reverselist[0]) <=90 or 97<= ord(reverselist[0]) <=122 or 48<= ord(reverselist[0]) <=57) :
                reverselist.pop(0)
            item2 = reverselist.pop(0) if len(reverselist) != 0 else ""
            # print(item1,item2)
            # 比较两个字符，是否相等
            if item1.lower() != item2.lower():
                return False
        # print(forwardlist,reverselist)
        # 去除掉剩下的非数字和字母
        while len(forwardlist) != 0 and not (65<= ord(forwardlist[0]) <=90 or 97<= ord(forwardlist[0]) <=122 or 48<= ord(forwardlist[0]) <=57) :
            forwardlist.pop(0)
        while len(reverselist) != 0 and not (65<= ord(reverselist[0]) <=90 or 97<= ord(reverselist[0]) <=122 or 48<= ord(reverselist[0]) <=57) :
            reverselist.pop(0)
        # 去除完以后长度不等，则为否
        if len(forwardlist) != len(reverselist):
            return False
        return True


def delsame(text):

    beftxt = open(text,"r")
    aftext = open("del-same.txt","w")

    count = 1
    cnt = 0

    bftxt = beftxt.readlines()
    length = len(bftxt)

    for i in range(length):
        line = bftxt[cnt]
        aftext.writelines(line)
        if cnt == length-1:
            break
        else:
            for j in range(count,length):
                if line == bftxt[j]:
                    count=count+1
                else:
                    cnt = count
                    break

    beftxt.close()
    aftext.close()


from __future__ import print_function  # print('me') instead of print 'me'
from __future__ import division  # 1/2 == 0.5, not 0

import_list = ['os','os.path','shutil','scipy','scipy.io','string','glob','time','sys','datetime','random','re',
    'subprocess','threading','serial','inspect','fnmatch','h5py','socket','getpass','numbers','math']#,'importlib']
import_from_list = [['FROM','pprint','pprint'],['FROM','termcolor','cprint']]
import_as_list = [['AS','numpy','np'],['AS','cPickle','pickle']]

def opj(*args):
    if len(args) == 0:
        args = ['']
    str_args = []
    for a in args:
        str_args.append(str(a))
    return os.path.join(*str_args)
def opjh(*args):
    return opj(home_path,opj(*args))
def opjD(*args):
    return opjh('Desktop',opj(*args))
def opjk(*args):
    return opjh('kzpy3',opj(*args))
def opjm(*args):
    if not using_osx():
        media_path = opj('/media',username)
        return opj(media_path,opj(*args))
    else:
        media_path = '/Volumes'
        return opj(media_path,opj(*args))

for im in import_list + import_from_list + import_as_list:
    if type(im) == str:
        try:
            exec('import '+im)
            #print("imported "+im)
        except:
            pass
            print('Failed to import '+im)
    else:
        assert(type(im)) == list
        if im[0] == 'FROM':
            try:
                exec('from '+im[1]+' import '+im[2])
                # print("from "+im[1]+" imported "+im[2])
            except:
                pass
                print('Failed to from '+im[1]+' import '+im[2])
        else:
            assert(im[0] == 'AS')
            try:
                exec('import '+im[1]+' as '+im[2])
                #print("imported "+im[1]+" as "+im[2])
            except:
                pass
                print('Failed to import '+im[1]+' as '+im[2])

rnd = np.random.random
rndint = np.random.randint
rndn = np.random.randn
rndchoice = np.random.choice
na = np.array
host_name = socket.gethostname()
home_path = os.path.expanduser("~")
username = getpass.getuser()
try:
    imread = scipy.misc.imread
    imsave = scipy.misc.imsave
    imresize = scipy.misc.imresize
except:
    print("failed: imread = scipy.misc.imread, imsave = scipy.misc.imsave")
degrees = np.degrees
arange = np.arange
shape = np.shape
randint = np.random.randint
randn = np.random.randn
zeros = np.zeros
ones = np.ones
reshape = np.reshape
mod = np.mod
array = np.array

from utils.printing import *
from utils.have_using import *

def fname(path):
    return path.split('/')[-1]

def fnamene(path):
    """
    filename, no extension
    """
    return fname(path).split('.')[0]

def fnames(list_of_paths):
    l = []
    for p in list_of_paths:
        l.append(fname(p))
    return l

def fnamenes(list_of_paths):
    l = []
    for p in list_of_paths:
        l.append(fnamene(p))
    return l

def pname(path):
    p = path.split('/')[:-1]
    pstr = ""
    for s in p:
        if len(s)>0:
            pstr += '/' + s
    return pstr

def raw_enter(optional_str=''):
    return raw_input(optional_str+'   Hit enter to continue > ')

def is_even(q):
    if np.mod(q,2) == 0:
        return True
    return False

def str_is_int(s):
    try:
        int(s)
        return True
    except:
        return False

def str_is_float(s):
    try:
        float(s)
        return True
    except:
        return False

def rlen(a):
    return range(len(a))

def dic_is_type(Dic,type_str):
    assert type(Dic) == dict
    assert type(type_str) == str
    if 'type' in Dic.keys():
        if Dic['type'] == type_str:
            return True
    return False

def dic_of_(list_or_dic,keys):

    D = {}
    for k in keys:
        if list_or_dic == 'lists':
            D[k] = []
        elif list_or_dic == 'dics':
            D[k] = {}
        else:
            cr("***** Error, expected 'lists' or 'dics' as first argument *****")
            assert False
    return D

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    '''
    alist.sort(key=natural_keys) sorts in human order
    http://nedbatchelder.com/blog/200712/human_sorting.html
    (See Toothy's implementation in the comments)
    '''
    return [ atoi(c) for c in re.split('(\d+)', text) ]

def dict_to_sorted_list(d):
    l = []
    ks = sorted(d.keys(),key=natural_keys)
    for k in ks:
        l.append(d[k])
    return l

def advance(lst,e,min_len=1):
    len_lst = len(lst)
    if len_lst < min_len:
        pass
    elif len_lst > 1.2*min_len:
        lst = lst[-min_len:]
    else:
        lst.pop(0)
    lst.append(e)

def a_key(dic):
    keys = dic.keys()
    k = np.random.randint(len(keys))
    return keys[k]

def an_element(dic):
    return dic[a_key(dic)]

def get_key_sorted_elements_of_dic(d,specific=None):
    ks = sorted(d.keys())
    els = []
    for k in ks:
        if specific == None:
            els.append(d[k])
        else:
            els.append(d[k][specific])
    return ks,els

def even_len(d):
    l = d['l']
    return np.mod(len(l),2) == 0

def unix(command_line_str, print_stdout=False, print_stderr=False,print_cmd=False):
    command_line_str = command_line_str.replace('~',home_path)
    p = subprocess.Popen(command_line_str.split(), stdout=subprocess.PIPE)
    stdout,stderr = p.communicate()
    if print_cmd:
        print(command_line_str)
    if print_stdout:
        print(stdout)
    if print_stderr:
        print(stderr)
#    return stdout,stderr
    return stdout.split('\n')

def kill_ps(process_name_to_kill):
    ax_ps_lst = unix('ps ax',False)
    ps_lst = []
    for p in ax_ps_lst:
        if process_name_to_kill in p:
            ps_lst.append(p)
    pid_lst = []
    for i in range(len(ps_lst)):
        pid = int(ps_lst[i].split(' ')[1])
        pid_lst.append(pid)
    #print pid_lst
    for p in pid_lst:
        unix(d2s('kill',p))

def nvidia_smi_continuous(t=0.1):
    while True:
        unix('nvidia-smi',print_stdout=True)
        time.sleep(t)

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

def args_to_dictionary(*args):
    if not is_even(len(args[0])):
        print("args_to_dictionary(*args)")
        print("args are:")
        print(args)
        #raise ValueError('ERROR because: not is_even(len(args[0]))')
        spd2s('def args_to_dictionary(*args): Warning, not is_even(len(args[0]))')
        return
    ctr = 0
    keys = []
    values = []
    for e in args[0]:
        if is_even(ctr):
            keys.append(e)
        else:
            values.append(e)
        ctr += 1
    d = {}
    if len(keys) != len(values):
        print("args_to_dictionary(*args)")
        print("given keys are:")
        print(keys)
        print("given values are:")
        print(values)
        raise ValueError('ERROR because: len(keys) != len(values)')
    for k,v in zip(keys,values):
        d[k] = v
    return d

temp = args_to_dictionary(sys.argv[1:])
if temp != None:
    Args = {}
    for k in temp.keys():
        if '/' in temp[k]:
            print('Treating '+temp[k]+' as filename')
            exec("Args[\'"+k+"\'] = '"+temp[k]+"'")
        elif type(temp[k]) == str:
            exec("Args[\'"+k+"\'] = '"+temp[k]+"'")
        else:
            exec('Args[\''+k+'\'] = '+temp[k])
    del temp
    Arguments = {}
    for a in Args.keys():
        ar = Args[a]
        if a[0] == '-':
            assert a[0] == '-'
            assert a[1] == '-'
            a = a[2:]
        else:
            print(Args)
            pd2s('\x1b[1m\x1b[41m\x1b[37m',
                '*** Warning, argument',
                "'"+k+"'",
                'not proceeded by -- on command line ***',
                '\x1b[0m'
            )
            time.sleep(4)
            #raw_enter()
        if str_is_int(ar):
            Arguments[a] = int(ar)
        elif ',' in ar:
            Arguments[a] = ar.split(',')
        elif ar == 'True':
            Arguments[a] = True
        elif ar == 'False':
            Arguments[a] = False
        else:
            Arguments[a] = ar

def parse_to_Arguments(sys_str):
    a = sys_str.split(' ')
    b = []
    for c in a:
        if c != '':
            b.append(c)
    if len(b) > 1:
        b = b[1:]

    temp = args_to_dictionary(b)
    if type(temp) != dict:
        return {}
    kprint(temp,'temp')
    if temp != None:
        Args = {}
        for k in temp.keys():
            if '/' in temp[k]:
                print('Treating '+temp[k]+' as filename')
                exec("Args[\'"+k+"\'] = '"+temp[k]+"'")
            elif type(temp[k]) == str:
                exec("Args[\'"+k+"\'] = '"+temp[k]+"'")
            else:
                exec('Args[\''+k+'\'] = '+temp[k])
        del temp
        Arguments_ = {}
        for a in Args.keys():
            ar = Args[a]
            if a[0] == '-':
                assert a[0] == '-'
                assert a[1] == '-'
                a = a[2:]
            else:
                print(Args)
                pd2s('\x1b[1m\x1b[41m\x1b[37m',
                    '*** Warning, argument',
                    "'"+k+"'",
                    'not proceeded by -- on command line ***',
                    '\x1b[0m'
                )
                time.sleep(4)
                #raw_enter()
            if str_is_int(ar):
                Arguments_[a] = int(ar)
            elif str_is_float(ar):
                Arguments_[a] = float(ar)
            elif ',' in ar:
                Arguments_[a] = ar.split(',')
            elif ar == 'True':
                Arguments_[a] = True
            elif ar == 'False':
                Arguments_[a] = False
            else:
                Arguments_[a] = ar
    return Arguments_

def setup_Default_Arguments(Defaults):
    for k in Arguments:
        if k not in Defaults:
            cr("*** Warning, unexpected argument","'"+k+"'",'***')
    for k in Defaults:
        if k not in Arguments:
            Arguments[k] = Defaults[k]
    if 'help' in Arguments:
        if Arguments['help']:
            print("\nDefault Arguments")
            for k in sorted(Defaults):
                print(d2n('\t',k,':\t',Arguments[k]),' (',type(Arguments[k]),')')
            print("")
            sys.exit()

def set_Defaults(Defaults,Dst):
    for k in Dst.keys():
        if k not in Defaults.keys():
            cr("*** Warning, argument '"+k+"' not in expected Dst:\n\t",Defaults.keys())
    for k in Defaults.keys():
        if k not in Dst.keys():
            Dst[k] = Defaults[k]

def print_Arguments():
    if len(Arguments) > 0:
        cg("\nArguments",sf=0)
        for k in Arguments:
            cy(d2n('\t',k,':',Arguments[k],' (',type(Arguments[k]),')'),sf=0)
    else:
        cb('No Arguments')

def set_Argument_defaults(Arguments,Defaults):
    for k in Defaults:
        if k not in Arguments:
            Arguments[k] = Defaults[k]

def require_Arguments(arglst):
    fail = False
    for a in arglst:
        if a not in Arguments:
            cr("***",__file__,"lacking command line argument ","'"+a+"'")
            fail = True
    if fail:
        cr("Required arguments are:",arglst)
        sys.exit(-1)

#

if True:
    def memory():
        """
        Get node total memory and memory usage
        http://stackoverflow.com/questions/17718449/determine-free-ram-in-python
        """
        if using_osx():
            import psutil
            m = psutil.virtual_memory()
            return m.percent
        else:
            with open('/proc/meminfo', 'r') as mem:
                ret = {}
                tmp = 0
                for i in mem:
                    sline = i.split()
                    if str(sline[0]) == 'MemTotal:':
                        ret['total'] = int(sline[1])
                    elif str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
                        tmp += int(sline[1])
                ret['free'] = tmp
                ret['used'] = int(ret['total']) - int(ret['free'])
            return ret

def get_terminal_size():
    rows, columns = os.popen('stty size', 'r').read().split()
    return int(rows),int(columns)

def getch():
    import sys, termios, tty, os, time
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch

####################################
# exception format:
def et():
    print(
        """
except KeyboardInterrupt:
    cr('\n\n*** KeyboardInterrupt ***\n')
    sys.exit()
except Exception as e:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    file_name = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
    CS_('Exception!',emphasis=True)
    CS_(d2s(exc_type,file_name,exc_tb.tb_lineno),emphasis=False)

        """
        )
EXCEPT_STR = """
exc_type, exc_obj, exc_tb = sys.exc_info()
file_name = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
CS_('Exception!',exception=True,newline=False)
CS_(d2s(exc_type,file_name,exc_tb.tb_lineno),emphasis=False)
"""
#
####################################

identify_file_str = """
if '__file__' not in locals():
    __file__ = 'INTERPRETER'
#cprint('using '+__file__,'yellow')
CVerbose = {}
CShowFile = {}
cfile = fname(__file__)#.replace(opjk(),'').replace(opjh(),'')
cstr = "CVerbose['COLOR'] = True\\n"+\
    "CShowFile['COLOR'] = True\\n"+\
    "def cQ(*args,**kwargs):\\n"+\
    "\tif not CVerbose['COLOR']:\\n"+\
    "\t\treturn\\n"+\
    "\tif CShowFile['COLOR']:\\n"+\
    "\t\tccfile = '('+cfile+')'\\n"+\
    "\telse:\\n"+\
    "\t\tccfile = ''\\n"+\
    "\tif 'sf' in kwargs and not kwargs['sf']:\\n"+\
    "\t\tscf = ''\\n"+\
    "\telse:\\n"+\
    "\t\tscf = \tccfile\\n"+\
    "#\tcprint(d2s_spacer(tuple(list(args)+['\t'+scf]),spacer=' '),'COLOR')\\n"+\
    "\tcprint(d2s_spacer(tuple(list(args)),spacer=' '),'COLOR')\\n"+\
    "\tif 'ra' in kwargs:\\n"+\
    "\t\tif kwargs['ra'] == 1:\\n"+\
    "\t\t\tcprint('\b  (hit Enter to continue)','COLOR')\\n"+\
    "\t\t\traw_input()\\n"+\
    "\tif 'r' in kwargs:\\n"+\
    "\t\tif kwargs['r'] == 1:\\n"+\
    "\t\t\tcprint('\b  (hit Enter to continue)','COLOR')\\n"+\
    "\t\t\traw_input()\\n"+\
    "\tif 't' in kwargs:\\n"+\
    "\t\tif kwargs['t'] > 0:\\n"+\
    "\t\t\ttime.sleep(kwargs['t'])\\n"
for color in ['red','yellow','green','blue','magenta','cyan','white','Grey']:
    an_exec_string = cstr.replace('Q',color[0]).replace('COLOR',color).replace('Grey','grey')
    exec(an_exec_string)
    """

def in_True(a,B):
    if a in B and B[a]:
        return True
    else:
        return False

def k_in_D(k,D):
    if k not in D:
        return False
    else:
        return D[k]

from kzpy3.utils.printing2 import *

exec(identify_file_str)

#EOF


from __future__ import annotations
from abc import ABC, abstractmethod

import datetime
from chrome import ChromeDriver
from html_parser import HTMLParser, Element
from typing import List

PCF_TEMPLATE = 'https://investor.vanguard.com/etf/profile/portfolio/%s/pcf'
OVERVIEW_TEMPLATE = 'https://investor.vanguard.com/etf/profile/overview/%s'

class ETFFetcher(ABC):
    @abstractmethod
    def holdings(self) -> Holdings:
        pass

    @abstractmethod
    def nav(self) -> float:
        pass

    @abstractmethod
    def quit(self) -> None:
        pass

class VanguardETFFetcher(ETFFetcher):
    def __init__(self, driver: ChromeDriver, html_parser: HTMLParser):
        self._driver = driver
        self._html_parser = html_parser

    def holdings(self, ticker: str) -> Holdings:
        url = PCF_TEMPLATE % ticker
        self._driver.load(url)
        self._expand_page()
        self._parse_source()

        raw_date = self._html_parser.find_first(
            'span', {'class': 'displayBlock ng-binding'}).content()
        date = datetime.datetime.strptime(raw_date, 'as of %m/%d/%Y')

        raw_elements = self._retrieve_holding_elements()
        holding_elements = self._parse_holding_elements(raw_elements)

        return Holdings(date, holding_elements)

    def _expand_page(self) -> None:
        selector = "a[data-ng-click='goToNextPage()'"
        next_page = self._driver.clickable_element(selector)
        next_page.click_until_stale()

    def _parse_source(self) -> None:
        html = self._driver.source()
        self._html_parser.parse(html)

    def _retrieve_holding_elements(self) -> List[Element]:
        elements = self._html_parser.find_all('tr', {
            'data-ng-repeat': 'curRow in dynamicData.pcfData.items ' +
            '| startFrom : pagination.startLoopFrom | limitTo : pagination.showUpto ' +
            '| orderBy : shareQuantity'}
        )
        elements = elements[:len(elements) // 2]
        return elements

    @staticmethod
    def _parse_holding_elements(holding_elements: List[Element]) -> List[Holdings.Entry]:
        holdings = []
        for holding_element in holding_elements:
            elements = holding_element.find_all('td', {'class': 'ng-binding'})
            ticker = elements[0].content().replace('.', '-')
            sharesText = elements[2].content().replace(',', '')
            shares = int(sharesText)
            holdings.append(Holdings.Entry(ticker, shares))
        return holdings

    def nav(self, ticker: str) -> float:
        url = OVERVIEW_TEMPLATE % ticker
        self._driver.load(url)
        selector = 'span[class="ng-scope ng-binding sceIsLayer arrange arrangeSec"'
        self._driver.wait(selector, count=5)
        self._parse_source()

        return self._parse_nav()

    def _parse_nav(self) -> float:
        elements = self._html_parser.find_all(
            'span', {'class': 'ng-scope ng-binding sceIsLayer arrange arrangeSec'})
        nav = elements[4].content()[1:]
        return float(nav)

    def quit(self) -> None:
        self._driver.quit()

class Holdings(object):
    class Entry(object):
        def __init__(self, ticker: str, shares: int):
            self.ticker = ticker
            self.shares = shares

        def __repr__(self):
            return f'(Ticker: {self.ticker}, Shares: {self.shares})'

    def __init__(self, date: datetime.datetime, entries: List[Entry]):
        self.date = date
        self.entries = entries

    def __repr__(self):
        repr = f'As of {self.date}:\n'
        repr += '\n'.join(f'{idx+1} - {h}' for idx,
                          h in enumerate(self.entries))
        return repr


#!/bin/sh python
import math
import numpy as np
import torch as tc

import argparse

import syft as sf
import grid as gr

from torch import nn
from GRU_RNN import GRU

parser = argparse.ArgumentParser(
    description="Perform training and bechmark of spam dataset.")

parser.add_argument(
    "-gw",
    "--gateway",
    type=str,
    required=True,
    help="Address of the grid gateway",
)

def main(args):
    hook = sf.TorchHook(tc)

    tr_grid = gr.GridNetwork("http://" + args.gateway)
    texts = tr_grid.search("#X", "#spam", "#dataset")
    types = tr_grid.search("#Y", "#spam", "#dataset")
    print("Found datasets:")
    print(texts)
    print(types)

    # Model parameters
    HIDDEN_DIM = 10
    EMBEDDING_DIM = 50
    DROPOUT = 0.2
    EPOCHS = 15
    BATCH_SIZE = 32
    HIDDEN_DIM = 10
    LR = 0.1
    VOCAB_SIZE = 0
    for texts_comp in texts:
        VOCAB_SIZE = max(VOCAB_SIZE, int(texts_comp[0].max().get()))
    VOCAB_SIZE += 1

    # Initiating the model
    model = GRU(vocab_size=VOCAB_SIZE, hidden_dim=HIDDEN_DIM,
                embedding_dim=EMBEDDING_DIM, dropout=DROPOUT)

    # Defining the loss and optimizer
    criterion = nn.BCELoss()
    optimizer = tc.optim.SGD(model.parameters(), lr=LR)

    for epoch in range(EPOCHS):
        dataset_size = sum([len(texts[i][0]) for i in range(len(texts))])
        print("Beginning training ...")
        model.train()

        for i in range(len(texts)):
            loss_acc = 0
            nr_batches = math.ceil(len(texts[i][0]) / BATCH_SIZE)
            for batch_idx in range(nr_batches):
                # Extract the batch for training and target
                texts_batch = texts[i][0][BATCH_SIZE *
                                          batch_idx: BATCH_SIZE * (batch_idx + 1), :]
                types_batch = types[i][0][BATCH_SIZE *
                                          batch_idx: BATCH_SIZE * (batch_idx + 1)]

                # Send the model to the worker
                worker = texts_batch.location
                model.send(worker)
                h = tc.Tensor(tc.zeros((BATCH_SIZE, HIDDEN_DIM))).send(worker)

                optimizer.zero_grad()
                pred, _ = model(texts_batch, h)
                loss = criterion(pred.squeeze(), types_batch.float())
                loss.backward()
                optimizer.step()
                model.get()

                # Accumulate the loss
                loss_acc += loss.get().item()

            print('Epoch: {} [{}/{} ({:.0f}%)]\tTraining loss: {:.6f}'.format(
                epoch, i * texts[i][0].shape[0], dataset_size,
                100. * (i*texts[i][0].shape[0]) / dataset_size, loss_acc))

if __name__ == '__main__':
    main(parser.parse_args())


from . import main
from flask import render_template, redirect, url_for, request, jsonify
from flask_login import login_required
import requests

FLOWER_URL = 'http://127.0.0.1:5555'

@main.route('/')
def index():
    return render_template('cover.html')
    #return redirect(url_for('data.samples'))

@main.route('/task/result/<task_id>/', methods=['GET'])
def show_result(task_id):
    return render_template('celery_task.html', task_id=task_id, state='pending')

@main.route('/task/result/', methods=['POST'])
def celery_task():
    if request.method == 'POST':
        task_id = request.form['task_id']
        url = '{root_url}/api/task/result/{id}'.format(root_url=FLOWER_URL, id=task_id)
        reply = requests.get(url).json()
        if reply['state'] == 'SUCCESS':
            task = reply['result']['task']
            result = reply['result']['result']
            return jsonify({'msg': 'ok', 'task': task, 'result': result})
        elif reply['state'] == 'PENDING':
            return jsonify({'msg': 'pending'})
        else:
            return jsonify({'msg': 'error'})


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  6 11:38:16 2019

@author: janiceteo
"""

import requests
import json
import pandas as pd
from pprint import pprint
from openpyxl import load_workbook
import numpy as np

path = '/Users/janiceteo/Documents/YoRipe/Recipes/Simpliigood/SimpliiGood Recipes 24012020.xlsx'
worksheet = 'Sheet1'
df = pd.read_excel(path, worksheet)
equip = pd.read_excel('/Users/janiceteo/Documents/YoRipe/Recipes Masterfile_Dec 2019.xlsx', 'Kitchen Equipment')
method = pd.read_excel('/Users/janiceteo/Documents/YoRipe/Recipes Masterfile_Dec 2019.xlsx', 'Method')
allergies = pd.read_excel('/Users/janiceteo/Documents/YoRipe/Allergy-ingredients list.xlsx', 'Allergy-Ingredients')
foodList = list(allergies['Ingredient'])
foodList = [j.split(", ") if ", " in j else j.split(", ") if "," in j else j for j in foodList]
exceptions = pd.read_excel('/Users/janiceteo/Documents/YoRipe/Allergy-ingredients list.xlsx', 'Exceptions')
exceptionList = list(exceptions['Exception'])
exceptionList = [j.split(", ") if ", " in j else j.split(", ") if "," in j else j for j in exceptionList]

#equipment
equiplist = []
for d in range(len(df)):
    equipmentList = []
    for e in range(len(equip)):
        if type(df.instructions[d]) != float:
            if equip['Kitchen Equipment'][e].lower() in df['instructions'][d].lower():
                if int(equip['ID'][e]) not in equipmentList:
                    equipmentList.append(int(equip['ID'][e]))
    equipmentList = sorted(equipmentList)
    equipmentList = [str(x) for x in equipmentList]
    equiplist.append(','.join(equipmentList))
df['Kitchen Equipment'] = equiplist

#cooking method
methodlist = []
for d in range(len(df)):
    meanslist = []
    if not(np.isnan(df['Method'][d])):
        meanslist.append(int(df['Method'][d]))
    for m in range(len(method)):
        if type(df.instructions[d]) != float:
            if method['Method'][m].lower() in df['instructions'][d].lower():
                if int(method['ID'][m]) not in meanslist:
                    meanslist.append(int(method['ID'][m]))
    meanslist = sorted(meanslist)
    meanslist = [str(x) for x in meanslist]
    methodlist.append(','.join(meanslist))
df['Method'] = methodlist

#allergies
allergyList = []
for i in range(len(df)):
    allergiesList = []
    for j in range(len(foodList)):
        if type(foodList[j]) is list:
            for k in foodList[j]:
                if k in df['ingredients'][i]:
                    if int(allergies['Allergy_ID'][j]) not in allergiesList:
                        allergiesList.append(int(allergies['Allergy_ID'][j]))
        else:
            if foodList[j] in df['ingredients'][i]:
                if int(allergies['Allergy_ID'][j]) not in allergiesList:
                    allergiesList.append(int(allergies['Allergy_ID'][j]))
    for j in range(len(exceptionList)):
        if type(exceptionList[j]) is list:
            for e in exceptionList[j]:
                if e in df['ingredients'][i]:
                    if int(exceptions['Allergy_ID'][j]) in allergiesList:
                        allergiesList.remove(int(exceptions['Allergy_ID'][j]))
        else:
            if exceptionList[j] in df['ingredients'][i]:
                if int(exceptions['Allergy_ID'][j]) in allergiesList:
                    allergiesList.remove(int(exceptions['Allergy_ID'][j]))
    allergiesList = sorted(allergiesList)
    allergiesList = [str(x) for x in allergiesList]
    allergyList.append(','.join(allergiesList))
df['allergy'] = allergyList

newpath = path[:path.find('.xlsx')] + ' edited.xlsx'
writer = pd.ExcelWriter(newpath, engine='xlsxwriter', options={'strings_to_urls': False})
df.to_excel(writer,'Sheet1', index = False)
writer.save()


'''
Definition of BaseGFSClient
class BaseGFSClient:
    def readChunk(self, filename, chunkIndex):
        # Read a chunk from GFS
    def writeChunk(self, filename, chunkIndex, content):
        # Write a chunk to GFS
'''

class GFSClient(BaseGFSClient):
    """
    @param: chunkSize: An integer
    """

    def __init__(self, chunkSize):
        self.chunkSize = chunkSize
        self.fileChunkCount = {}
        self.chunks = {}

    """
    @param: filename: a file name
    @return: conetent of the file given from GFS
    """

    def read(self, filename):
        if filename not in self.fileChunkCount:
            return None
        chunkCount = self.fileChunkCount[filename]
        contents = []
        for chunkIndex in range(chunkCount):
            contents.append(self.readChunk(filename, chunkIndex))
        return ''.join(contents)

    """
    @param: filename: a file name
    @param: content: a string
    @return: nothing
    """

    def write(self, filename, content):
        count = 0

        chunkSize = self.chunkSize
        while content:
            count += 1
            writeToChunk = content[:chunkSize]
            content = content[chunkSize:]
            self.writeChunk(filename, count - 1, writeToChunk)

        self.fileChunkCount[filename] = count


from functools import reduce
from collections import Counter
from utils import read_file, parse_multiline

def find_group_count(entry):
    entry_set = set(''.join(entry.split()))
    return len(entry_set)

def common_letters(group):
    counts = Counter(''.join(group.split()))
    letters = [letter for letter, cnt in counts.most_common() if cnt == len(group.split())]
    return letters

if __name__ == '__main__':
    data = read_file("day6/data.txt")
    parsed = parse_multiline(data)
    ans = sum([find_group_count(entry) for entry in parsed])
    print(f"Sum of each group count {ans}")

    group_letters = [common_letters(group) for group in parsed]
    ans = sum(map(len, group_letters))
    print(f"Sum where groups all answered yes count {ans}")


# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Initial Owner of the Original Code is European Environment
# Agency (EEA).  Portions created by Eau de Web are
# Copyright (C) European Environment Agency.  All
# Rights Reserved.
#
# Authors:
#
# Cornel Nitu, Eau de Web
# Valentin Dumitru, Eau de Web

import re
from os.path import join
from Globals import InitializeClass
from AccessControl import ClassSecurityInfo
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.PageTemplates.ZopePageTemplate import manage_addPageTemplate
from OFS.Folder import Folder
import time

from Products.NaayaCore.managers import utils as naaya_utils
from Products.NaayaBase.NyContainer import NyContainer
from naaya.i18n.LocalPropertyManager import LocalPropertyManager, LocalProperty
from CHMParticipant import CHMParticipant
from utilities.Slugify import slugify
from utilities.SendMail import send_mail
from utilities.validators import form_validation, registration_validation, str2date
from utilities import tmpfile, checkPermission
import constants

add_chm_registration = PageTemplateFile('zpt/registration/add', globals())
def manage_add_chm_registration(self, id='', title='', conference_details='', administrative_email ='', start_date='', end_date='', lang='', REQUEST=None):
    """ Adds a CHM registration instance"""
    if registration_validation(REQUEST):
        if id:
            id = slugify(id)
        else:
            id = slugify(title)
        if lang is None:
            lang = self.gl_get_selected_language()
        ob = CHMRegistration(id, title, conference_details, administrative_email, start_date, end_date, lang)
        self.gl_add_languages(ob)
        self._setObject(id, ob)
        ob = self._getOb(id)
        ob.loadDefaultContent()
        if REQUEST:
            REQUEST.RESPONSE.redirect(self.absolute_url())
    else:
        return add_chm_registration.__of__(self)(REQUEST)

class CHMRegistration(LocalPropertyManager, Folder, NyContainer):
    """ Main class of the meeting registration"""

    meta_type = 'CHM Registration'
    product_name = 'CHMRegistration'

    security = ClassSecurityInfo()

    title = LocalProperty('title')
    conference_details = LocalProperty('conference_details')

    manage_options = (
        Folder.manage_options[:1]
        +
        (
            {'label': 'Reload registration forms', 'action': 'reloadRegistrationForms'},
        )
        +
        Folder.manage_options[2:]
    )

    security.declareProtected(constants.MANAGE_PERMISSION, 'loadDefaultContent')
    def loadDefaultContent(self):
        """ load default content such as: email templates """
        from TemplatesManager import manage_addTemplatesManager
        manage_addTemplatesManager(self)
        self._loadRegistrationForms()

    def __init__(self, id, title, conference_details, administrative_email, start_date, end_date, lang):
        """ constructor """
        self.id = id
        self.save_properties(title, conference_details, administrative_email, start_date, end_date, lang)

    security.declareProtected(constants.MANAGE_PERMISSION, 'save_properties')
    def save_properties(self, title, conference_details, administrative_email, start_date, end_date, lang):
        """ save properties """
        self._setLocalPropValue('title', lang, title)
        self._setLocalPropValue('conference_details', lang, conference_details)
        self.administrative_email = administrative_email
        self.start_date = str2date(start_date)
        self.end_date = str2date(end_date)

    security.declarePrivate('loadDefaultContent')
    def _loadRegistrationForms(self):
        """ load registration forms """
        registration_form = file(join(constants.PRODUCT_PATH, 'zpt', 'registration', 'registration.zpt')).read()
        manage_addPageTemplate(self, 'registration_form', title='', text=registration_form)
        view_participant = file(join(constants.PRODUCT_PATH, 'zpt', 'participant', 'view_participant.zpt')).read()
        edit_participant = file(join(constants.PRODUCT_PATH, 'zpt', 'participant', 'edit_participant.zpt')).read()
        menu_buttons = file(join(constants.PRODUCT_PATH, 'zpt', 'menu_buttons.zpt')).read()
        manage_addPageTemplate(self, 'menu_buttons', title='', text=menu_buttons)
        manage_addPageTemplate(self, 'view_participant', title='', text=view_participant)
        manage_addPageTemplate(self, 'edit_participant', title='', text=edit_participant)

    def _deleteRegistrationForms(self):
        try:
            self.manage_delObjects(['registration_form', 'menu_buttons', 'view_participant', 'edit_participant'])
        except:
            pass

    security.declareProtected(constants.MANAGE_PERMISSION, 'reloadRegistrationForms')
    def reloadRegistrationForms(self, REQUEST=None):
        """ reload registration forms """
        self._deleteRegistrationForms()
        self._loadRegistrationForms()
        if REQUEST:
            return self.manage_main(self, REQUEST, update_menu=1)

    def registration_html(self, REQUEST):
        """ registration form """
        submit =  REQUEST.form.get('submit', '')
        if submit:
            form_valid = form_validation(constants.PART_MANDATORY_FIELDS,
                                            constants.DATE_FIELDS,
                                            constants.TIME_FIELDS,
                                            REQUEST)
            if form_valid:
                lang = self.gl_get_selected_language()
                registration_no = naaya_utils.genRandomId(10)
                cleaned_data = REQUEST.form
                del cleaned_data['submit']
                if not 'event_1' in cleaned_data: cleaned_data['event_1'] = '0'
                if not 'event_2' in cleaned_data: cleaned_data['event_2'] = '0'
                if not 'event_3' in cleaned_data: cleaned_data['event_3'] = '0'
                ob = CHMParticipant(registration_no, **cleaned_data)
                self._setObject(registration_no, ob)
                participant = self._getOb(registration_no, None)
                if participant:
                    #save the authentication token on session
                    REQUEST.SESSION.set('authentication_id', registration_no)
                    REQUEST.SESSION.set('authentication_name', self.unicode2UTF8(participant.first_last_name))

                    #send notifications
                    values = {'registration_edit_link': participant.absolute_url(),
                                'registration_event': self.unicode2UTF8(self.title),
                                'website_team': self.unicode2UTF8(self.site_title),
                                'registration_number': registration_no,
                                'name': self.unicode2UTF8(participant.first_last_name)}
                    self.send_registration_notification(participant.email,
                        'Event registration',
                        self.getEmailTemplate('user_registration_html', lang) % values,
                        self.getEmailTemplate('user_registration_text', lang) % values)
                    self.send_registration_notification(self.administrative_email,
                        'Event registration',
                        self.getEmailTemplate('admin_registration_html', 'en') % values,
                        self.getEmailTemplate('admin_registration_text', 'en') % values)

                    #redirect to profile page
                    return REQUEST.RESPONSE.redirect(participant.absolute_url())
        return self.registration_form(REQUEST)

    security.declareProtected(constants.VIEW_PERMISSION, 'index_html')
    index_html = PageTemplateFile('zpt/registration/index', globals())

    security.declareProtected(constants.MANAGE_PERMISSION, '_edit_html')
    _edit_html = PageTemplateFile('zpt/registration/edit', globals())

    security.declarePrivate('getEmailTemplate')
    def getEmailTemplate(self, id, lang='en'):
        """ get email template """
        lang_dir = self.email_templates._getOb(lang, None)
        if lang_dir is None:    #maybe arabic?
            lang_dir = self.email_templates._getOb('en', None)
        email_template = lang_dir._getOb(id)
        return self.unicode2UTF8(email_template.document_src())

    def registrationOpened(self):
        """ check if the registration is opend to the public """
        now = time.localtime()
        if now >= self.start_date:
            return True
        return False

    def registrationNotClosed(self):
        """ check if the registration is opend to the public """
        now = time.localtime()
        from datetime import date, timedelta
        end_date = date(*self.end_date[0:3]) + timedelta(days=1)
        end_date = end_date.timetuple()[0:3] + self.end_date[3:]
        if now < end_date:
            return True
        return False

    security.declareProtected(constants.MANAGE_PERMISSION, 'edit_html')
    def edit_html(self, REQUEST):
        """ edit properties """
        submit =  REQUEST.form.get('edit-submit', '')
        if submit:
            if registration_validation(REQUEST):
                cleaned_data = REQUEST.form
                del cleaned_data['edit-submit']
                self.save_properties(**cleaned_data)
        return self._edit_html(REQUEST)

    security.declarePrivate('send_registration_notification')
    def send_registration_notification(self, email, title, email_html, email_txt):
        """ send a notification when a folder is added / edited / commented"""
        send_mail(msg_from=constants.NO_REPLY_MAIL,
                    msg_to=self.utConvertToList(email),
                    msg_subject='%s - Registration added / edited' % title,
                    msg_body=self.unicode2UTF8(email_html),
                    msg_body_text=self.unicode2UTF8(email_txt),
                    smtp_host = constants.SMTP_HOST,
                    smtp_port = constants.SMTP_PORT
                    )

    security.declareProtected(constants.VIEW_EDIT_PERMISSION, 'exportParticipants')
    def exportParticipants(self, REQUEST=None, RESPONSE=None):
        """ exports the participants list in CSV format """
        data = [('Registration date', 'Registration number', 'Name', 'Position', 'Organisation',
                    'Address', 'Postal code', 'eMail', 'eMail type', 'Phone number', 'Event #1', 'Event #2', 'Event #3',
                    'Topic #1', 'Topic #2', 'Topic #3', 'Topic #4', 'Explanation')]
        data_app = data.append
        for part in self.getParticipants(skey='registration_date', rkey=1):
            if part.private_email:
                email_type = 'Private'
            else:
                email_type = 'Public'
            data_app((self.formatDate(part.registration_date), part.id,
                    self.unicode2UTF8(part.first_last_name), self.unicode2UTF8(part.position),
                    self.unicode2UTF8(part.organisation), self.unicode2UTF8(part.address),
                    self.unicode2UTF8(part.zip_code), part.email, email_type, self.unicode2UTF8(part.phone_number),
                    self.unicode2UTF8(part.event_1), self.unicode2UTF8(part.event_2),
                    self.unicode2UTF8(part.event_3), self.unicode2UTF8(part.topic_1),
                     self.unicode2UTF8(part.topic_2), self.unicode2UTF8(part.topic_3),
                     self.unicode2UTF8(part.topic_4),
                     self.unicode2UTF8(part.explanation.replace('\r\n', ' ').replace('\n', ' '))))

        return self.create_csv(data, filename='participants.csv', RESPONSE=REQUEST.RESPONSE)

    security.declarePrivate('create_csv')
    def create_csv(self, data, filename, RESPONSE):
        tmp_name = tmpfile(data)
        content = open(str(tmp_name)).read()
        RESPONSE.setHeader('Content-Type', 'text/csv')
        RESPONSE.setHeader('Content-Disposition', 'attachment; filename=%s' % filename)
        return content

    security.declareProtected(constants.VIEW_EDIT_PERMISSION, 'participants')
    participants = PageTemplateFile('zpt/registration/participants', globals())

    security.declareProtected(constants.VIEW_EDIT_PERMISSION, 'getParticipants')
    def getParticipants(self, skey, rkey):
        """ Returns the list of participants """
        meta_type = 'CHM Participant'
        participants = [ ( self.unicode2UTF8(getattr(p, skey)), p ) for p in self.objectValues(meta_type) ]
        participants.sort()
        if rkey:
            participants.reverse()
        return [p for (key, p) in participants]

    security.declareProtected(constants.VIEW_EDIT_PERMISSION, 'deleteParticipants')
    def deleteParticipants(self, ids=[], REQUEST=None):
        """ Deletes selected participants """
        ids = self.utConvertToList(ids)
        self.manage_delObjects(ids)
        return REQUEST.RESPONSE.redirect(REQUEST.HTTP_REFERER)

    security.declarePublic('canManageParticipants')
    def canManageParticipants(self):
        """ Check the permissions to edit/delete meeting settgins and participants """
        return checkPermission(constants.MANAGE_PERMISSION, self)

    security.declarePublic('canViewParticipants')
    def canViewParticipants(self):
        """ Check the permissions to edit/delete participants """
        return checkPermission(constants.VIEW_EDIT_PERMISSION, self)

    security.declarePublic('getRegistrationTitle')
    def getRegistrationTitle(self):
        """ """
        return self.title

    security.declarePublic('getConferenceDetails')
    def getConferenceDetails(self):
        """ """
        return self.conference_details

    #internal
    def formatDate(self, sdate, format='%d/%m/%Y'):
        if sdate:
            return time.strftime(format, sdate)
        return None

    def unicode2UTF8(self, s):
        if isinstance(s, unicode):
            return s.encode('utf-8')
        return s

    def getPropertyValue(self, id, lang=None):
        """ Returns a property value in the specified language. """
        if lang is None: lang = self.gl_get_selected_language()
        return self.getLocalProperty(id, lang)

    security.declareProtected(constants.VIEW_PERMISSION, 'getCountryList')
    def getCountryList(self):
        """ """
        catalog = self.glossary_coverage.getGlossaryCatalog()
        brains = catalog(meta_type='Naaya Glossary Element', sort_on='id', sort_order='ascending')
        return self.__getObjects(catalog, brains)

    def __getObjects(self, catalog, p_brains):
        """ """
        try:
            return map(catalog.getobject, map(getattr, p_brains, ('data_record_id_',)*len(p_brains)))
        except:
            return []

    def hasVersion(self):
        """ """
        return None

InitializeClass(CHMRegistration)


"""
@author: Cecilia Aponte
Probabilistic Robotics
Final Project
Planar Monocular SLAM -- Associate Landmark IDs
"""

# Import libraries
import numpy as np
import os

# Set working directory
directory = os.getcwd()

# Set directory with dataset
dataset_dir = os.path.join(directory, "dataset")

# This function gets the landmark index
#inputs:
#  observations:
#            a structure containing n observations of landmarks
#            for each observation we have
#            - the appearance of each landmark observed
#outputs:
#  index of landmark
#  [observations]: updated observation info with correct landmark id

def associateLandmarkIDs(world_data, observations):

    # Get how many landmarks have been seen in current step
    M = len(observations)

    # First of all we are interested in REOBSERVED landmark
    for i in range(M):

        # Get the appearance given by known info
        l_appear = world_data[:,4:14]

        # Difference between the known and measured appearances
        delta = l_appear - observations[i][2][:]
        # Get the error of the Euclidean distance of each option
        error = np.linalg.norm(delta, ord=2, axis=1)
        # Get the index of the smallest error
        land_index = np.argmin(error)

        # Test: to compare that the landmark id is correct
        # measurement = observations[i]
        # id = int(measurement[0][1]) # current landmark number
        # if land_index == id:
        #     print('Same landmark!')
        # else: print('NO!')

        # Update the observation info with id info to be used later
        observations[i][0] = np.append(observations[i][0],land_index)
        # print('updated observations \n', observations[i][0])

    return (observations)

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

#                          END ASSOCIATE LANDMARK SETUP

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


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

import sys
import fileinput
import binascii

# Used to find end of the Headers section
EMPTY_LINE = b'\r\n\r\n'

def log(msg):
    """
    Logging to STDERR as STDOUT and STDIN used for data transfer
    @type msg: str or byte string
    @param msg: Message to log to STDERR
    """
    try:
        msg = str(msg) + '\n'
    except:
        pass
    sys.stderr.write(msg)
    sys.stderr.flush()

def find_end_of_headers(byte_data):
    """
    Finds where the header portion ends and the content portion begins.
    @type byte_data: str or byte string
    @param byte_data: Hex decoded req or resp string
    """
    return byte_data.index(EMPTY_LINE) + 4

def process_stdin():
    """
    Process STDIN and output to STDOUT
    """
    for raw_line in fileinput.input():

        line = raw_line.rstrip()

        # Decode base64 encoded line
        decoded = bytes.fromhex(line)

        # Split into metadata and payload, the payload is headers + body
        (raw_metadata, payload) = decoded.split(b'\n', 1)

        # Split into headers and payload
        headers_pos = find_end_of_headers(payload)
        raw_headers = payload[:headers_pos]
        raw_content = payload[headers_pos:]

        log('===================================')
        request_type_id = int(raw_metadata.split(b' ')[0])
        log('Request type: {}'.format({
          1: 'Request',
          2: 'Original Response',
          3: 'Replayed Response'
        }[request_type_id]))
        log('===================================')

        log('Original data:')
        log(line)

        log('Decoded request:')
        log(decoded)

        encoded = binascii.hexlify(raw_metadata + b'\n' + raw_headers + raw_content).decode('ascii')
        log('Encoded data:')
        log(encoded)

        sys.stdout.write(encoded + '\n')

if __name__ == '__main__':
    process_stdin()


import string

numl = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
alphal = string.ascii_lowercase
alphau = string.ascii_uppercase

items = {}

keywords = [
    'define',
    'return',
    'math'
]

class checks:
    def variables(var):
        """
        This function is used to check if the string contains the define word, if it
        does, then it will create a variable and done!
        """
        if "define" in var:
            var = var[7:len(var)+1]
            idx = var.index("=")

            v = var[0:idx-1]
            key = var[idx+2:]

            items[v] = key

            print(items[v])
            return True
        else:
            return False

    def mathematics(uwu):
        """
        Used for performing some mathematical tasks, It just needs one string, and
        it will output you the result within few seconds
        """

        print(eval(uwu))

    def retur_n(uwu):
        if uwu in items:
            print(f"{items[uwu]}")
        else:
            print("UwU! '{}' is not defined, please define it using 'define var_name = value'".format(uwu))

def run(command):
    ans = checks.variables(command)
    if "math" in command:
        command = list(command)
        command.remove("m")
        command.remove("a")
        command.remove("t")
        command.remove("h")
        while " " in command:
            command.remove(" ")
        listToStr = ''.join([str(elem) for elem in command])
        checks.mathematics(listToStr)
    elif "return" in command:
        try:
            command = command.split(" ")
            command.remove("return")
            command.remove("{")
            command.remove("}")
            command = "".join(command)
            checks.retur_n(command)
        except ValueError:
            print("UwU! Please use Curly Brackets, like this, 'return { command goes here }'")
    else:
        pass


#!/usr/bin/python
import math

#
#   Project Euler problem #3
#   Finding largest prime factor of a given number
#   Implemented with function practice
#

def isFactor( arg1 , max ):
    rtrn = 0
    if max % arg1 == 0:
        rtrn = arg1
    return rtrn

def checkPrime( arg1 ):
    i = arg1 / 2
    while i > 1:
        if arg1 % 2 == 0:
            return 0
        if arg1 % i == 0:
            return 0
        i -= 1
    return arg1

result = 3
final = 3
final2 = 0
max = 600851475143
realmax = math.ceil(math.sqrt(max))
while result < realmax:
    final = isFactor( result , max )
    if final != 0:
        final = checkPrime( result )
    if final != 0:
        final2 = final
    result += 1

print(final2)