# Firebase Imports
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import threading

# Selenium Imports
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager

import copy
from urllib.parse import urlparse
import numpy as np
import pandas as pd
import re
from pathlib import Path
import os
import time
from datetime import date
from datetime import timedelta
from datetime import datetime
import dateutil.parser as parser

import time

today = date.today()
cwd = os.getcwd()

project_id = 'tpc-dev-5330f'
# Use the application default credentials
cred = firebase_admin.credentials.Certificate('./secret/tpc-dev-5330f-firebase-adminsdk-2p698-e13719db26.json')

firebase_admin.initialize_app(cred, {
  'projectId': project_id,
})

db = firestore.client()

doc_ref = db.collection(u'clients').document(u'YIJ3bLzUXlubsxnDPnDR').collection(u'projects').document(u'BOuyALnDYmDHSBW7kAZm').collection('wa-queue')

# Create an Event for notifying main thread.
callback_done = threading.Event()
# MAIN VARIABLE : Clean after use
process_queue = []

# Create a callback on_snapshot function to capture changes
def on_snapshot(col_snapshot, changes, read_time):
    for doc in col_snapshot:
#         print(f'{doc.id}')
        process_queue.append(doc.id)
    callback_done.set()

col_query = db.collection(u'clients').document(u'YIJ3bLzUXlubsxnDPnDR').collection(u'projects').document(u'BOuyALnDYmDHSBW7kAZm').collection('wa-queue').where(u'processed', u'==', False)

# Watch the collection query
query_watch = col_query.on_snapshot(on_snapshot)

# RUN WA AUTOMATION HERE --------------

# START WHATSAPP SEND

# Starting the selenium webserver and getting whatsapp
userprofile = 'samarth'
options = webdriver.ChromeOptions()
options.add_argument(f"user-data-dir={cwd}/."+userprofile+"UserProfile")
driver = webdriver.Chrome(ChromeDriverManager().install() , options=options)
driver.get("https://web.whatsapp.com/")

# Default getter functions
def F_SEARCH_2(driverVar,contact_number):

    driverVar.find_element(By.CSS_SELECTOR, "body").send_keys(Keys.CONTROL + Keys.COMMAND + '//')
    time.sleep(1)

    FORM_HEADER_CLASS = '_1Jn3C' # Label Class
    FORM_CLASS = '_13NKt copyable-text selectable-text'

    formHeadingClassList = driverVar.find_elements(By.XPATH,f"//label[@class='{FORM_HEADER_CLASS}']")

    print(len(formHeadingClassList))

    if len(formHeadingClassList)==1:
        formHeadingClass = formHeadingClassList[0]
        formElementsList = formHeadingClass.find_elements(By.XPATH,f".//div[@class='{FORM_CLASS}']")

        print(len(formElementsList))

        if len(formElementsList)>0:
            formElement = formElementsList[0]
            formElement.click();
            formElement.clear();
            formElement.send_keys(f'{contact_number}')
            time.sleep(4)
            formElement.send_keys(Keys.RETURN)

def F_SINGLE_SEND(driverVar,text_message):
    CHAT_HEADER_CLASS = '_1UWac _1LbR4'
    ALT_CHAT_HEADER_CLASS = '_1UWac _1LbR4 focused'
    CHAT_CLASS = '_13NKt copyable-text selectable-text'

    print('Trying Unfocussed')
    chatHeadingClassList = driverVar.find_elements(By.XPATH,f"//div[@class='{CHAT_HEADER_CLASS}']")
    if len(chatHeadingClassList)==0:
        print('Unfocussed failed, trying focussed;')
        chatHeadingClassList = driverVar.find_elements(By.XPATH,f"//div[@class='{ALT_CHAT_HEADER_CLASS}']")
    print(f'Length of Chat Header Div => {len(chatHeadingClassList)}')

    if len(chatHeadingClassList)==1:
        chatHeadingClass = chatHeadingClassList[0]
        chatElementsList = chatHeadingClass.find_elements(By.XPATH,f".//div[@class='{CHAT_CLASS}']")
        print(len(chatElementsList))
        if len(chatElementsList)>0:
            chatElement = chatElementsList[0]
            chatElement.click();
            time.sleep(1)
            chatElement.clear();
            chatElement.send_keys(f'{text_message}')
            time.sleep(2)
            chatElement.send_keys(Keys.RETURN)

while(True):

    print('Status - Sleep---------------')
    time.sleep(10)

    print('STATUS : Checking Queue')
    process_queue_clean = list(set(process_queue))

    if len(process_queue_clean)>0:
        print(f'FOUND {len(process_queue_clean)} jobs')
    #     print(process_queue_clean)
        # -----------------

        print('STATUS : Running Job')
        for TASK_ID in process_queue_clean:
            task_doc_ref = db.collection(u'clients').document(u'YIJ3bLzUXlubsxnDPnDR').collection(u'projects').document(u'BOuyALnDYmDHSBW7kAZm').collection('wa-queue').document(TASK_ID)
            task_doc = task_doc_ref.get()
            TASKDATA = task_doc.to_dict()
#             print(TASKDATA)

            TASK_PHONE = TASKDATA['contactPhone']
            TASK_MESSAGE = TASKDATA['messageContent']
            TASKDATA['processed'] = True
            task_doc_ref = db.collection(u'clients').document(u'YIJ3bLzUXlubsxnDPnDR').collection(u'projects').document(u'BOuyALnDYmDHSBW7kAZm').collection('wa-queue').document(TASK_ID).set(TASKDATA)

            print('SEND TO : ', TASK_PHONE)
            print('MESSAGE : ',TASK_MESSAGE)

            F_SEARCH_2(driver,TASK_PHONE)
            F_SINGLE_SEND(driver,TASK_MESSAGE)
        process_queue = []


# Calculate days in the month according to the years attribute -> is leap or not
# If a year is a leap year, february contains 29 days.
# Doesn't matter to the other months. They always contains the same amount of days.

def is_leap(year):
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False

def days_in_month(year, month):
    month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if month == 2 and is_leap(year=year):
        return 29
    else:
        return month_days[month - 1]

months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

print("Hey, welcome to the days in month calculator!")

year = int(input("Please enter the year: "))
month = int(input("Please enter the month: "))

if month not in months:
    print("\nYou entered an invalid month.")
    print("Month should be in range [0,12]\n")
else:
    days_in_month(year=year, month=month)


# class example

class MyClass:
    number = 0
    name = 'noname'
    age = 'under 40'

def Main():
    me = MyClass()
    me.number = 55
    me.name = 'Martin'
    me.age = 40

    friend = MyClass()
    friend.number = 10
    friend.name = 'Susan'
    friend.age = 25

    default = MyClass()

    print('My name is ' + me.name + ' I am ' + str(me.age) + ' and my number is: ' + str(me.number))
    print('My name is ' + friend.name + ' I am ' + str(friend.age) + ' and my number is: ' + str(friend.number))
    print('My name is ' + default.name + ' I am ' + str(default.age) + ' and my number is: ' + str(default.number))

Main()


"""NovoEd async tasks"""
import logging

from django.contrib.auth import get_user_model

from main.celery import app
from novoed import api

log = logging.getLogger(__name__)
User = get_user_model()

@app.task
def enroll_users_in_novoed_course(*, user_ids, novoed_course_stub):
    """
    Enrolls a group of users in a NovoEd course

    Returns:
        dict: A dict containing information about the number of users created, the number that already existed,
            and the number that failed
    """
    users = User.objects.select_related("profile", "legal_address").filter(
        id__in=user_ids
    )
    results = {"created": 0, "existed": 0, "failed": 0}
    for user in users:
        try:
            created, existed = api.enroll_in_novoed_course(user, novoed_course_stub)
            if created:
                results["created"] += 1
            elif existed:
                results["existed"] += 1
        except:  # pylint: disable=bare-except
            results["failed"] += 1
            log.exception(
                "User enrollment in NovoEd failed (%s, %s)",
                user.email,
                novoed_course_stub,
            )
    return results

@app.task
def unenroll_user_from_novoed_course(*, user_id, novoed_course_stub):
    """
    Unenrolls a user from a NovoEd course

    Returns:
        (string, bool): The user's email paired with a flag indicating whether or not the unenrollment succeeded
    """
    user = User.objects.select_related("profile", "legal_address").get(id=user_id)
    try:
        api.unenroll_from_novoed_course(user, novoed_course_stub)
        return user.email, True
    except:  # pylint: disable=bare-except
        log.exception(
            "User unenrollment from NovoEd failed (%s, %s)",
            user.email,
            novoed_course_stub,
        )
        return user.email, False


import requests
import json
import os

app_id = os.environ.get("OXFORD_ID")
app_key = os.environ.get("OXFORD_API_KEY")

def define_word(word):

    language = 'en'
    word_id = word

    url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + word_id.lower()
    r = requests.get(url, headers = {'app_id': app_id, 'app_key': app_key}).json()

    definition = r['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'][0]
    result = word.capitalize() + ": " + definition
    return result


#!/usr/bin/python3

import sys
sys.path.append("/course/common/utils")
from inginious_container_api import input, feedback, rst
from answer import expected_answers
from feedback_functions import *
from validation_functions import *
from parsing_functions import *
from correction_functions import *

student_answer_q1 = input.get_input("a").strip()
student_answer_q2 = input.get_input("a2").strip()
student_answer_q3 = input.get_input("mailto").strip()
student_answer_q4 = input.get_input("tel").strip()

correct_answers = 0

raw_student_answers = {"a": [student_answer_q1, True], "a2": [student_answer_q2, True], "mailto": [student_answer_q3, True], "tel": [student_answer_q4, True]}

validation_errors_q1 = is_invalid_element(student_answer_q1)
validation_errors_q2 = is_invalid_element(student_answer_q2)
validation_errors_q3 = is_invalid_element(student_answer_q3)
validation_errors_q4 = is_invalid_element(student_answer_q4)

validation_errors = {"a": validation_errors_q1, "a2": validation_errors_q2, "mailto": validation_errors_q3, "tel": validation_errors_q4}
for task in validation_errors:
    if validation_errors[task]:
        raw_student_answers.pop(task) # removes non valid response
        feedback.set_problem_feedback(validation_errors[task], task, True) # append invalid fb msg

parsed_answers = parse_html_as_dict(raw_student_answers)

task_result = check_html_correctness(parsed_answers, expected_answers)

for task in task_result:
    if task_result.get(task):
        correct_answers += 1
        append_raw_html_feedback(input.get_input(task).strip(), task)

if correct_answers == 4:
    feedback.set_global_result("success")
else:
    feedback.set_global_result("failed")

compute_score(4, correct_answers)


import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from sklearn.model_selection import train_test_split
from custom_functions import Mel_spectroize, CustomDataset, VRModel, train_model

if __name__ == "__main__":
    # set number of usable gpus
    num_gpus = 4
    # set batch size
    batch_size = 256
    # set total train epoch
    total_epoch = 100
    # set path of data
    train_feature_path = './train/*.wav'
    train_label_path = 'train_answer.csv'

    # generate mel spectrogram
    mel, y_data = Mel_spectroize(train_feature_path, train_label_path)
    train_data_x, val_data_x, train_data_y, val_data_y = train_test_split(mel.numpy(), y_data,
                                                                            test_size=0.2)
    # load data
    train_dataset = CustomDataset(train_data_x, train_data_y)
    train_loader = DataLoader(dataset=train_dataset, pin_memory=True,
                              batch_size=batch_size,
                              shuffle=True,
                              num_workers=10, drop_last=True)
    val_dataset = CustomDataset(val_data_x, val_data_y)
    val_loader = DataLoader(dataset=val_dataset, pin_memory=True,
                             batch_size=batch_size,
                             shuffle=True,
                             num_workers=10, drop_last=True)
    # define model

    model = nn.DataParallel(VRModel(batch_size, num_gpus))
    # train model
    print(len(train_loader))
    print(len(val_loader))

    train_model(model, total_epoch, train_loader, val_loader)


def prevent(target):
    if target.find('=') != -1 or target.find("'") != -1 or target.find('#') != -1:
        return False  # Illegal character detected
    else:
        return True

def getPayment():
    import sqlite3
    import time
    query = "select order_price from order_ where stat = 'Finished' and time_end like '%" + \
        time.strftime("%Y_%m_%d") + "%'"
    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query)

    ret = 0
    for row in cursor:
        print(str(row[0]))
        ret += int(row[0])
    return ret

def getItemNames():
    import sqlite3
    query = "select distinct itemname from shop"
    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query)

    data = []
    for row in cursor:
        print(str(row[0]))
        data.append(str(row[0]))
    return data

def tryLogin(Acc, pwd):
    import sqlite3
    import hashlib
    m = hashlib.md5()

    data = {'Passed': False, 'Phone': ''}

    if prevent(Acc) == False or prevent(pwd) == False:
        print("Not passed")
        return data

    query = \
        "select username, pwd, phone \
        from user \
        where username = '" + str(Acc) + "'"

    db = sqlite3.connect("data/data.db")
    cursor = db.cursor()
    cursor.execute(query)
    row = cursor.fetchone()

    print(row)

    if row == None:
        print("Not passed")
        db.close()
        return data

    else:
        m.update(pwd.encode('utf-8'))
        h = m.hexdigest()

        if h == row[1]:
            print("Passed")
            db.close()
            data['Passed'] = True
            data['Phone'] = row[2]
            return data
        else:
            print("Not passed")
            db.close()
            return data

def tryRegister(Acc, Pwd, ConPwd, Phone):
    import sqlite3
    import hashlib
    import random
    m = hashlib.md5()

    data = {'0': "", '1': "", '2': "", '3': ""}

    noEx = True

    if Acc == "":
        data['0'] = "Required!"
        noEx = False
    if Pwd == "":
        data['1'] = "Required!"
        noEx = False
    if ConPwd == "":
        data['2'] = "Required!"
        noEx = False
    if Phone == "":
        data['3'] = "Required!"
        noEx = False
    if Pwd != ConPwd:
        data['2'] = "Password_mismatch"
        noEx = False
    if Pwd.isalnum() == False and Pwd != "":
        data['1'] = "Invalid password format"
        noEx = False
    if Phone.isdigit() == False and Phone != "":
        data['3'] = "Invalid phone format"
        noEx = False
    # error here when register
        '''
    if target(Acc) == False:
        data['0'] = "Illegal character detected"
        noEx = False
        '''

    if not noEx:
        return data

    query1 = \
        "select username\
    from user\
    where username = '" + str(Acc) + "'"

    print(query1)

    db = sqlite3.connect("data/data.db")
    print(db)
    cursor = db.cursor()
    print(cursor)
    cursor.execute(query1)
    # error here no such column username

    row = cursor.fetchall()
    print(row)

    if row != []:
        print("repeated")
        data['0'] = "Username is repeated"
        noEx = False

    if noEx:
        data['0'] = "Register success!"
        print("insert")
        m.update(Pwd.encode('utf-8'))
        h = m.hexdigest()

        U_ID = str(random.randint(1000000, 9999999))

        query2 = "insert into user\
        values('" + U_ID + "','" + str(Acc) + "','" + str(h) + "','" + str(Phone) + "')"
        print(query2)

        cursor.execute(query2)
        db.commit()

    db.close()
    return data

def searchGoods(Itemname, LowPrice, HighPrice):
    import sqlite3
    data = {'data': []}
    query = \
        "select itemname, img_url, price, stock from shop where stock > 0 and  "
    if LowPrice != "" and HighPrice != "":
        if int(LowPrice) > int(HighPrice):
            LowPrice, HighPrice = HighPrice, LowPrice

    if Itemname != "" and prevent(Itemname) != False:
        query += "itemname like '%" + str(Itemname) + "%' and  "
    if LowPrice != "" and prevent(LowPrice) != False:
        query += "price >= " + str(LowPrice) + " and  "
    if HighPrice != "" and prevent(HighPrice) != False:
        query += "price <= " + str(HighPrice) + " and  "
    query = query[0:-6]

    print(query)
    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query)
    for row in cursor:
        print(row)
        insert = []
        for r in row:
            insert.append(r)
        data['data'].append(insert)

    return data

def PriceChange(Itemname, Price):
    import sqlite3
    Price.replace(' ', '')
    data = {"data": ""}
    db = sqlite3.connect("data/data.db")

    if Price.isdigit() == False:
        data["data"] = "Invalid format"
        return data
    if int(Price) < 0:
        data["data"] = "Invalid value"
        return data

    query = "update shop\
        set price = " + str(Price) + " where itemname = '" + str(Itemname) + "'"
    cursor = db.execute(query)
    db.commit()
    data["data"] = "Price succesfully changed"
    return data

def AmountChange(Itemname, Amount):
    import sqlite3
    Amount.replace(' ', '')
    data = {"data": ""}
    db = sqlite3.connect("data/data.db")

    if Amount.isdigit() == False:
        data["data"] = "Invalid format"
        return data
    if int(Amount) < 0:
        data["data"] = "Invalid value"
        return data

    query = "update shop\
        set stock = " + str(Amount) + " where itemname = '" + str(Itemname) + "'"
    cursor = db.execute(query)
    db.commit()
    data["data"] = "Amount succesfully changed"
    return data

def searchMyOrderList(Acc, Status):
    import sqlite3
    data = {'data': []}

    query = \
        "select orderID, stat, time_start, time_end, itemname, order_price\
    from order_\
    where orderer = '" + str(Acc) + "'         "

    if Status != "All":
        query += " and stat = '" + str(Status) + "'      "
    query = query[0:-6]

    print(query)

    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query)

    print(cursor)

    for row in cursor:
        insert = []
        for i in row:
            insert.append(i)
        data['data'].append(insert)

    print(data)

    return data

def searchShopOrderList(Itemname, Status):
    import sqlite3
    data = {'data': []}
    query = \
        "select orderID, orderer, stat, time_start, time_end, itemname, order_price\
    from order_\
    where   "
    if Itemname != "":
        query += "itemname like '%" + str(Itemname) + "%' and  "
    if Status != "All":
        query += "stat = '" + str(Status) + "' and  "
    query = query[0:-6]
    print(query)

    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query)

    for row in cursor:
        insert = []
        for i in row:
            insert.append(i)
        data['data'].append(insert)

    print(data)
    return data

def Order(Acc, Itemname, Amount):
    import sqlite3
    import time

    data = {"data": ""}

    if Amount.isdigit() == False or int(Amount) <= 0:
        data["data"] = "Illegal input Amount"
        return data

    query1 = "select stock, price\
    from shop\
    where itemname = '" + str(Itemname) + "'"
    print(query1)

    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query1)
    row = cursor.fetchone()

    inventory = int(row[0])
    price = int(row[1])

    if int(Amount) > inventory:
        data["data"] = "Amount is larger than the inventory of the shop"
        return data

    result = inventory - int(Amount)

    query_ = "update shop\
    set stock = " + str(result) + " where itemname = '" + str(Itemname) + "'"
    cursor = db.execute(query_)
    db.commit()

    query2 = 'select count (distinct orderID)\
    from order_'
    cursor = db.execute(query2)
    row = cursor.fetchone()
    OID = row[0] + 1

    print(OID)

    t = time.localtime()
    time_start = time.strftime("%Y_%m_%d_%H_%M_%S")

    query3 = "insert into order_\
    values(" + str(OID) + ",'Not Finished','" + str(Acc) + "','" + str(Itemname) + "','" + str(time_start) + "','" + "" + "'," + str(Amount) + "," + str(int(Amount) * price) + ")"
    print(query3)

    cursor = db.execute(query3)
    db.commit()

    data["data"] = "Successfully ordered"

    return data

def DelOrder(Acc, OID):
    import sqlite3
    import time
    data = {"data": ""}
    query = "select orderID, stat, order_amount, itemname\
    from order_\
    where orderID = " + str(OID) + ""

    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query)
    row = cursor.fetchone()

    print(row)
    amount = int(row[2])
    shop = str(row[3])

    if row == None:
        data["data"] = "Order doesn't exist"
        return data

    if str(row[1]) == "Cancelled":
        data["data"] = "The order number " + str(OID) + " is already cancelled"
        return data

    if str(row[1]) == "Finished":
        data["data"] = "Finished order can't be cancelled"
        return data

    t = time.localtime()
    time_end = time.strftime("%Y_%m_%d_%H_%M_%S")

    query1 = "update order_\
    set stat = " + "'Cancelled'\
    where orderID = " + str(OID) + ""

    cursor = db.execute(query1)
    db.commit()

    query2 = "update order_\
    set time_end = '" + str(time_end) + "'\
    where orderID = " + str(OID) + ""

    cursor = db.execute(query2)
    db.commit()

    query3 = "select stock\
    from shop\
    where itemname = '" + shop + "'"

    cursor = db.execute(query3)
    row = cursor.fetchone()

    remain = int(row[0])
    result = remain + amount

    query4 = "update shop\
    set stock = " + str(result) + " where itemname = '" + shop + "'"
    cursor = db.execute(query4)
    db.commit()

    data["data"] = "Order successfully cancelled"
    return data

def DoneOrder(Acc, OID):
    import sqlite3
    import time
    data = {"data": ""}
    query1 = "select itemname, order_amount, stat\
    from order_\
    where orderID = " + str(OID) + ""

    db = sqlite3.connect("data/data.db")
    cursor = db.execute(query1)
    row = cursor.fetchone()

    shop = str(row[0])
    amount = int(row[1])
    stat = str(row[2])

    if stat == "Cancelled":
        data["data"] = "The order is already cancelled"
        return data

    if stat == "Finished":
        data["data"] = "Finished order can't be cancelled"
        return data

    t = time.localtime()
    time_end = time.strftime("%Y_%m_%d_%H_%M_%S")

    query4 = "update order_\
    set stat = " + "'Finished'\
    where orderID = " + str(OID) + ""

    cursor = db.execute(query4)
    db.commit()

    query5 = "update order_\
    set time_end = '" + str(time_end) + "'\
    where orderID = " + str(OID) + ""

    cursor = db.execute(query5)
    db.commit()

    query6 = "update order_\
    set seller = '" + str(Acc) + "'\
    where orderID = " + str(OID) + ""

    cursor = db.execute(query6)
    db.commit()

    data["data"] = "Order successfully done"

    return data

def DelAllOrder(Acc, OIDs):
    import sqlite3
    import time

    data = {"data": ""}
    print("DelAllOrder")
    print(OIDs)

    for OID in OIDs:
        d = DelOrder(Acc, OID)
        if(d["data"] != "Order successfully cancelled"):
            data["data"] += d["data"] + "
"

    if data["data"].endswith("
"):
        data["data"] = data["data"][:-6]

    if data["data"] == "":
        data["data"] = "Orders successfully cancelled"

    return data

def DoneAllOrder(Acc, OIDs):
    import sqlite3
    import time
    data = {"data": ""}
    db = sqlite3.connect("data/data.db")

    print("DoneAllOrder")
    print(OIDs)

    for OID in OIDs:
        print(OID)
        query1 = "select stat\
        from order_\
        where orderID = " + str(OID) + ""

        cursor = db.execute(query1)
        row = cursor.fetchone()
        stat = str(row[0])

        if stat == "Cancelled":
            data["data"] = "The order number " + \
                str(OID) + " is already cancelled"
            return data

        if stat == "Not Finished":
            data["data"] = "The order number " + \
                str(OID) + " is not paid"
            return data

        if stat == "Finished":
            data["data"] = "Finished order" + str(OID) + "can't be cancelled"
            return data

        time_end = time.strftime("%Y_%m_%d_%H_%M_%S")

        query1 = "update order_\
        set stat = " + "'Finished'\
        where orderID = " + str(OID) + ""

        print(query1)

        cursor = db.execute(query1)
        db.commit()

        query2 = "update order_\
        set time_end = '" + str(time_end) + "'\
        where orderID = " + str(OID) + ""

        cursor = db.execute(query2)
        db.commit()

    data["data"] = "Orders all succesfully done"

    return data

def PayAllOrder(Acc, OIDs):
    import sqlite3
    import time
    data = {"data": ""}
    db = sqlite3.connect("data/data.db")

    print("PayAllOrder")
    print(OIDs)

    for OID in OIDs:
        print(OID)
        query1 = "select stat\
        from order_\
        where orderID = " + str(OID) + ""

        cursor = db.execute(query1)
        row = cursor.fetchone()
        stat = str(row[0])

        if stat == "Cancelled":
            data["data"] = "The order number " + \
                str(OID) + " is already cancelled"
            return data

        if stat == "Paid" or stat == "Finished":
            data["data"] = "The order number " + \
                str(OID) + " has been paid"
            return data

        time_end = time.strftime("%Y_%m_%d_%H_%M_%S")

        query1 = "update order_\
        set stat = " + "'Paid'\
        where orderID = " + str(OID) + ""

        print(query1)

        cursor = db.execute(query1)
        db.commit()

    data["data"] = "Orders all succesfully paid"

    return data


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 22 10:39:41 2018

@author: simonlbs
"""
preSteatment = ""
if input("Pre-staetment (y/n): ") == "y":
	preSteatment = input("""Write pre-staetment (no ending " "): """)

topInputName = input("Write top input name: ")

topInputVars = []
while True:
    inputVar = input("Wirte {} input term from left to right (q to quit): ".format(topInputName))
    if inputVar == "q":
        break
    topInputVars.append(inputVar)

leftInputName = input("Write left input name: ")
leftInputVars = []
while True:
    inputVar = input("Wirte {} input term from top to buttom (q to quit): ".format(leftInputName))
    if inputVar == "q":
        break
    leftInputVars.append(inputVar)

outputVars = []
while True:
    outputVar = input("Output var (q to quit): ")
    if outputVar == "q":
        break
    outputVars.append(outputVar)

roules = []
for topV in topInputVars:
    for leftV in leftInputVars:
        rule = "rule: "+preSteatment + " {} is {} and {} is {} then ".format(topInputName, topV, leftInputName, leftV)
        print("\n"+rule)
        outputGiven = False
        for i, outVar in enumerate(outputVars):
            ov = input("Write {} output (- to None): ".format(outVar))
            if ov is not "-":
                outputGiven = True
                if i is not len(outputVars)-1:
                    rule += "{} is {} and ".format(outVar, ov)
                else:
                    rule += "{} is {}".format(outVar, ov)
        if outputGiven:
            roules.append(rule+"\n")

outputFile = input("Write outputfile: ")
with open(outputFile, "w") as f:
    f.writelines(roules)


"""
Import a table of contents (ToC) from a CSV file into a PDF document
-------------------------------------------------------------------------------
License: GNU GPL V3
(c) 2023 Jorj X. McKie

Usage
-----
python import.py -d ";" -csv input.csv -pdf input.pdf

Description
-----------
The output.csv file generated in examples/export-toc is renamed as input.csv
to be used as an input file in this example. The input.pdf file behaves as both
an input and an output file.

Please note that all existing outline entries (bookmarks) in the PDF will be
replaced if running this script. The document is updated.

Each CSV line must contain 3 or 4 entries:

lvl     A positive integer indicating the hierarchy level of the entry. The
        first line must contain an lvl value of 1. It can be increased by 1 and
        decrease by any number.

title   A non-empty string containing the entry's title.

page    An integer representing the page number which value must be in the
        document's page range.

height  An optional, positive float value representing the entry position on the
        page and counting from the bottom. If omitted, 36 points (half an inch)
        below the top of the page are taken.

Dependencies
------------
PyMuPDF
"""

import csv
import fitz
import argparse

parser = argparse.ArgumentParser(
    description="Enter CSV delimiter [;], CSV filename and PDF filename"
)
parser.add_argument("-d", help="CSV delimiter [;]", default=";")
parser.add_argument("-csv", help="CSV filename")
parser.add_argument("-pdf", help="PDF filename")

args = parser.parse_args()

assert args.csv, "missing CSV filename"
assert args.pdf, "missing PDF filename"

doc = fitz.open(args.pdf)
toc = []
with open(args.csv) as tocfile:
    tocreader = csv.reader(tocfile, delimiter=args.d)
    for row in tocreader:
        assert len(row) <= 4, "cannot handle more than 4 entries:\n %s" % (str(row),)
        try:
            p4 = float(row[3])
            toc.append([int(row[0]), row[1], int(row[2]), p4])
        except:
            toc.append([int(row[0]), row[1], int(row[2])])
doc.set_toc(toc)
doc.saveIncr()


from reportlab.pdfgen import canvas
from reportlab.graphics.shapes import Rect
from reportlab.lib.colors import HexColor, black
from tools import Tools
import datetime
import os

class MakePDF:
    def __init__(self):
        self.line = 790
        self.c = None

    def make_report(self, input_list, input_header):

        # Check if output-directory exists. If not, create one
        if not os.path.exists("reports"):
            os.makedirs("reports")
        """ A function to make a pdf. Can be inputted eg a list returned from gimme_my_todo_list()"""

        # Define pdf-name with path to save output to.
        pdf_name = "Report_" + datetime.datetime.now().strftime("%d-%m-%Y_%H-%M-%S") + ".pdf"
        save_name = os.path.join("reports/", pdf_name)

        # Create canvas
        self.c = canvas.Canvas(save_name)

        # Write header to canvas
        self.c.setFont("Helvetica-Bold", 17, leading=None)
        self.c.drawString(30, self.line, input_header + " " + datetime.datetime.now().strftime("%d.%m.%Y @ %H:%M"))
        self.line -= 30

        # Roll trough the list and write jobs to canvas with _generate_job_info function.
        for job in input_list:
            self._generate_job_info(job.customer, \
                    job.product, \
                    job.amount, \
                    job.material, \
                    job.printing_sheet_size, \
                    job.status, \
                    job.comment, \
                    job.addedDate, \
                    job.job_id, \
                    job.priority, \
                    )

        # Save the canvas after all jobs have been written
        self.c.save()

    def _generate_job_info(self, customer, \
                    product, \
                    amount, \
                    material, \
                    printing_sheet_size, \
                    status, \
                    comment, \
                    addedDate, \
                    job_id, \
                    priority, \
                    ): #Takes arguments from make_report()

        # Continue on the next page if there is too little space left in the current page.
        if self.line < 130:
            self.c.drawString(30, self.line - 15, "More jobs on the next page >>")
            self.line = 790
            self.c.showPage()

        #Draw a fucking rectangle
        color1 = HexColor("#DDDDCC")
        self.c.setFillColor(color1)
        self.c.rect(25,self.line - 2,550,12, fill=True, stroke=False)

        # Write details of job on canvas in rectangle
        self.c.setFillColor(black)
        self.c.setFont("Helvetica-Bold", 11, leading=None)
        self.c.drawString(30, self.line, customer + " : " + product + " : " + addedDate)
        self.c.drawString(500, self.line, "PR {} : ID {}".format(priority, job_id))
        self.line -= 14

        # Writing rest of the info under rectangle
        self.c.setFont("Helvetica", 11, leading=None)
        self.c.drawString(30, self.line, "Amount: ")
        self.c.drawString(96, self.line, amount)
        self.line -= 12
        self.c.drawString(30, self.line, "Material: ")
        self.c.drawString(96, self.line, material)
        self.line -= 12
        self.c.drawString(30, self.line, "Sheet: ")
        self.c.drawString(96, self.line, printing_sheet_size)
        self.line -= 12
        self.c.drawString(30, self.line, "Status: ")
        self.c.drawString(96, self.line, status)
        self.line -= 12

        # Write Comment of job on separate lines on canvas
        comment_rows = Tools.rivitetty(comment, 70)
        self.c.drawString(30, self.line, "Comment: ")
        for i in comment_rows:
            self.c.drawString(96, self.line, i)
            self.line -= 12

        self.line -= 12


# Is Palindrome
# --------------------------------------------------------------------------------
# Strings like "Able was I, ere I saw Elba" or "Madam, I'm Adam" could be considered palindromes, because (if we ignore spaces, punctuation and capitalization) the letters are the same from front and back. Create a function that returns a boolean whether the string is a strict palindrome. For "a x a" or "racecar", return true. Do not ignore spaces, punctuation and capitalization: if given "Dud" or "oho!", return false.
# racecar
def remove_blanks(text):
    new_string= ""
    for char in text:
        if char != " " and char != "'" and char != ",":
            new_string += char
    return new_string

def palindrome(text):
    # i = 0
    text = remove_blanks(text)
    text.upper()
    print(text)
    j = len(text)-1

    for x in range (0, len(text)):
        if text[x] != text[j]:
            return False
        else:
            return True

print(palindrome('racecar'))
print(palindrome('able was I ere I saw elba'))
print(palindrome("Madam, I'm Adam"))

# Longest Palindrome
# --------------------------------------------------------------------------------
# For this challenge, we will look not only at the entire string, but also substrings within it. For a string, return the longest palindromic substring. Given "what up, dada?", return "dad". Given "not much", return "n". Include spaces as well (i.e. be strict, as in the “Is Palindrome” challenge): given "My favorite racecar erupted!", return "e racecar e".


import os
import json
import torch
import argparse
from torch.utils.data import DataLoader
from collections import OrderedDict
from model import Generator
from preprocess import CustomDataset
from multiprocessing import cpu_count
from torchtext.data.metrics import bleu_score
# from nltk.translate.bleu_score import sentence_bleu

# os.environ['CUDA_LAUNCH_BLOCKING'] = "1"

def to_word(predictions, idx2word, word2idx):
    sent_str = [str()] * len(predictions)
    for i, sent in enumerate(predictions):
        for id in sent:
            if id == word2idx["<pad>"]:
                break
            sent_str[i] += idx2word[str(id.item())] + " "
    return sent_str

def main(args):
    device = "cpu"
    if torch.cuda.is_available():
        device = "cuda"

    typee = 'valid'

    datasets = OrderedDict()

    datasets[typee] = CustomDataset(
        filename=f"{typee}.txt",
        data_dir=args.data_dir,
        data_file=f"{typee}.json",
        file_type=typee,
        max_sequence_length=args.max_sequence_length,
        new_data=False,
    )

    with open(os.path.join(args.data_dir, 'vocab.json'), 'r') as file:
        vocab = json.load(file)
    file.close()

    word2idx, idx2word = vocab['word2idx'], vocab['idx2word']

    params = dict(
        vocab_size=len(word2idx),
        sos_idx=word2idx["<sos>"],
        eos_idx=word2idx["<eos>"],
        pad_idx=word2idx["<pad>"],
        max_sequence_length=args.max_sequence_length,
        embedding_size=args.embedding_size,
        hidden_size=args.hidden_size,
        latent_size=args.latent_size,
        num_layers=args.num_layers,
        bidirectional=args.bidirectional,
        device=device
    )

    data_loader = DataLoader(
        dataset=datasets['valid'],
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=cpu_count(),
        pin_memory=torch.cuda.is_available()
    )

    if not os.path.exists(args.save_model_path):
        raise FileNotFoundError(args.save_model_path)

    model = Generator(**params)

    print("Loading model from: ", os.path.join(args.save_model_path))
    model.load_state_dict(torch.load(os.path.join(args.save_model_path)))
    print("Finished.")

    print(model)

    model = model.to(device)

    model.eval()

    f = open("output.txt","w")
    f_1 = open("duplicate.txt", "w")

    bleu_pred = []
    bleu_targ = []

    for iteration, batch in enumerate(data_loader):

        for k, v in batch.items():
            batch[k] = v.to(device)

        prediction = model.inference(batch["origin"], device=device)
        list_of_inputs = to_word(batch["origin"], idx2word, word2idx)
        list_of_targets = to_word(batch["target"], idx2word, word2idx)
        list_of_predictions = to_word(prediction, idx2word, word2idx)

        for inp, pred, targ in zip(list_of_inputs, list_of_predictions, list_of_targets): #, list_of_targets):
            f.write(f"Inp: {inp}") # Input
            f.write("\n")
            f.write(f"Pre: {pred}") # Prediction
            f.write("\n")
            f.write(f"Tar: {targ}") # Target
            f.write("\n\n")

            if pred == targ:
                f_1.write(f"Inp: {inp}") # Input
                f_1.write("\n")
                f_1.write(f"Pre: {pred}") # Prediction
                f_1.write("\n")
                f_1.write(f"Tar: {targ}") # Target
                f_1.write("\n\n")

            bleu_pred.append(pred.split())
            bleu_targ.append([targ.split()])
            # print(sentence_bleu([targ.split()], pred.split()))
            # print(bleu_score([pred.split()], [[targ.split()]]))
            # print()

        # if iteration == 0:
        #     break

    bleu_s = bleu_score(bleu_pred, bleu_targ)
    print("BLEU Score: ", bleu_s)
    f.write(f"BLEU Score: {bleu_s}")

    f.close()
    f_1.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument('--save_model_path', type=str, default='checkpoints/model')

    parser.add_argument('--data_dir', type=str, default='data')
    parser.add_argument('--max_sequence_length', type=int, default=20)

    parser.add_argument('--batch_size', type=int, default=256)
    parser.add_argument('--embedding_size', type=int, default=300)
    parser.add_argument('--hidden_size', type=int, default=512)
    parser.add_argument('--num_layers', type=int, default=1)
    parser.add_argument('--bidirectional', type=bool, default=False)
    parser.add_argument('--latent_size', type=int, default=300)

    args = parser.parse_args()

    main(args)


from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as image
from conf import get_image_info

import numpy as np
import scipy.misc
import os
import os.path

def count_images(name,dir,step,patch_sz):
    """
    This function evaluates the current solution - false positive and negative, and the total count.
    The method loads the current soltuion as well as the ground-truth image and calaulates the performance
    :param name: name of the image from the dataset (as written in the table in the paper)
    :param dir: the directory where the output is saved (it is declared before calling to main function)
    :param step: number of iteration
    :param patch_sz: the size of the repeating object
    """
    [im_size,_,_,_,gt_image_name,_,_,gt_color,_] = get_image_info(name)
    gt_image = np.array(Image.open(gt_image_name.split('.')[0]+"_gt."+gt_image_name.split('.')[1]))
    gt_image = gt_image[:,:,:3]
    print(gt_image_name.split('.')[0]+"_gt."+gt_image_name.split('.')[1])

    # Read the locations of the repeating object from our solution
    res = np.loadtxt(dir + 'res_ours_' + str(step) + '.txt')
    [row_ours,col_ours] = np.unravel_index(np.int32(res), [im_size[0], im_size[1]])

    # Read the locations from the ground-truth image
    tmp = np.where(np.reshape(gt_image[:,:,0],-1) == gt_color[0])[0]
    tot_tmp = tmp
    tmp = np.where(np.reshape(gt_image[:,:,1],-1) == gt_color[1])[0]
    tot_tmp = np.intersect1d(tmp, tot_tmp)
    tmp = np.where(np.reshape(gt_image[:,:,2],-1) == gt_color[2])[0]
    tot_tmp = np.intersect1d(tmp, tot_tmp)
    [row_gt,col_gt] = np.unravel_index(tot_tmp, [gt_image.shape[0], gt_image.shape[1]])

    ratio = [np.float(gt_image.shape[0])/im_size[0],np.float(gt_image.shape[1])/im_size[1]]
    row_gt = np.int32(row_gt/ratio[0])
    col_gt = np.int32(col_gt/ratio[1])

    sz = 3

    matched_pt = []
    gt_count = row_gt.shape
    count = row_ours.shape
    row_ours_copy = row_ours.copy()
    col_ours_copy = col_ours.copy()
    row_gt_copy = row_gt.copy()
    col_gt_copy = col_gt.copy()

    # The repeating object locations of the ground truth and our locations should be close
    # by 2\3*path_sz in order to be counted
    r = 2*patch_sz/3
    counter = 0
    for i in range(0,len(row_gt)):
        match = []
        for j in range(0,len(row_ours)):
            if np.power(row_gt[i]-row_ours[j],2)+np.power(col_gt[i] - col_ours[j],2) < np.power(r,2) and row_ours_copy[j] != -1:
                match.append([j,np.power(row_gt[i]-row_ours[j],2)+np.power(col_gt[i]-col_ours[j],2)])
        if len(match) > 0:
            counter = counter+1
            match = np.stack(match)
            closer = np.argmin(match[:,1])
            row_ours_copy[match[closer,0]] = -1
            matched_pt.append(i)
    if len(matched_pt)>0:
        matched_pt = np.stack(matched_pt)
    row_gt_copy = np.delete(row_gt_copy,matched_pt)
    col_gt_copy = np.delete(col_gt_copy,matched_pt)
    col_ours_copy = np.delete(col_ours_copy,np.where(row_ours_copy == -1)[0])
    row_ours_copy = np.delete(row_ours_copy,np.where(row_ours_copy == -1)[0])

    return [row_ours_copy.shape,row_gt_copy.shape,gt_count,count]


import csv
import sys

class MyRow:

    equality_condition_typ1_idxs = [1, 3, 4, 5]
    equality_condition_typ2_idxs = [0, 2, 3, 4]
    equality_condition_idxs = {
        1: equality_condition_typ1_idxs, 2: equality_condition_typ2_idxs}

    def __init__(self, row_data: tuple, type_of_row) -> None:
        self.row_data = row_data
        self.row_type = type_of_row

    def __eq__(self, __o: object) -> bool:
        if len(MyRow.equality_condition_typ1_idxs) != len(MyRow.equality_condition_typ2_idxs):
            raise ValueError("Cannot compare. Diff # of cols.")

        for idx in range(len(MyRow.equality_condition_typ2_idxs)):
            my_data, ot_data = self.row_data, __o.row_data
            my_idxs, ot_idxs = MyRow.equality_condition_idxs[
                self.row_type], MyRow.equality_condition_idxs[__o.row_type]
            if my_data[my_idxs[idx]] != ot_data[ot_idxs[idx]]:
                return False
        return True

    def __hash__(self):
        return 0

export_data = set()
key_set = set()

def open_file(arg_pos, mode='r'):
    return open(sys.argv[arg_pos], mode, encoding='UTF8', newline='')

for i in range(1, len(sys.argv)-1):
    with open_file(mode='r', arg_pos=i) as fr:
        rows = csv.reader(fr)
        header = next(rows)
        for rw in rows:
            key_set_size = len(key_set)
            if len(rw) == 6:
                key_set.add((rw[1], rw[3], rw[4], rw[5].upper()))
                if len(key_set) > key_set_size:
                    export_data.add( (rw[0], rw[1], rw[2], rw[3], rw[4], rw[5].upper() ))
            else:
                rw3_upper = rw[3].upper()
                rw3, rw4 = rw3_upper.split('/')[0], rw3_upper.split('/')[1]
                key_set.add((rw[0], rw[2], rw3, rw4))
                if len(key_set) > key_set_size:
                    export_data.add( (rw[0], rw[1], rw[2], rw3, rw4) )

with open_file(mode='w', arg_pos=-1) as fw:
    writer = csv.writer(fw)
    writer.writerow(('source_asset_name', 'source_ip', 'destination_asset_name',
                    'destination_ip', 'destination_port', 'ip_protocol'))
    for my_row in export_data:
        if len(my_row) == 6:
            writer.writerow(my_row)
        else:
            new_data = [''] * 6
            new_idx = MyRow.equality_condition_typ1_idxs[i]
            new_data[1] = my_row[0]
            new_data[3] = my_row[2]
            new_data[4] = my_row[3]
            new_data[5] = my_row[4]
            writer.writerow(new_data)


from datetime import datetime

from sqlalchemy import MetaData, Table, Column, Integer, String, TIMESTAMP, ForeignKey, JSON, Boolean

from models.inventory import inventory
from models.level import level
from models.lobby import lobby
from models.skill import skill
from models.role import role

metadata = MetaData()

user = Table(
    "user",
    metadata,
    Column("id", Integer, primary_key=True),
    Column("email", String, nullable=False),
    Column("username", String, nullable=False),
    Column("registered_at", TIMESTAMP, default=datetime.utcnow),
    Column("hashed_password", String, nullable=False),
    Column("is_active", Boolean, default=True, nullable=False),
    Column("is_superuser", Boolean, default=False, nullable=False),
    Column("is_verified", Boolean, default=False, nullable=False),
    Column("skill_id", Integer, ForeignKey(skill.c.id)),
    Column("role_id", Integer, ForeignKey(role.c.id)),
    Column("level_id", Integer, ForeignKey(level.c.id)),
    Column("lobby_id", Integer, ForeignKey(lobby.c.id)),
    Column("inventory_id", Integer, ForeignKey(inventory.c.id)),

)


def memoize(f):
    memo = {}
    def h(*args):
        if not args in memo:
            memo[args] = f(*args)
        return memo[args]
    return h

@memoize
def fusc_rec(n):
    if n <= 1: return n
    elif n % 2 == 0: return fusc(n / 2)
    else: return fusc(n/2) + fusc(n/2 + 1)

def fusc_tailrec(n):
    def f(a, b, n):
        if n == 1: return a + b
        elif n % 2 == 0: return f(a + b, b, n / 2)
        else: return f(a, a + b, n / 2)
    return 0 if n == 0 else f(1, 0, n)

def fusc(n):
    a, b = 1, 0
    while n > 0:
        if n % 2 == 1: b += a
        else: a += b
        n >>= 1
    return b

def fusc_alt(n):
    d, a, b = 1, 1, 0
    while d <= n: d <<= 1
    while d > 1:
        d >>= 1
        if n >= d:
            n -= d
            b += a
        else:
            a += b
    return b

def fusc_alt2(n):
    a, b = 1, 0
    for i in bin(n)[2:]:
        if i == '1': b += a
        else: a += b
    return b

def fibfusc_rec(n):
    if n == 0: return (1, 0)
    (x, y) = fibfusc_rec(n >> 1)
    if n & 1 == 0: return ((x + y) * (x - y), y * (((x + y) << 1) + y))
    return (-y * (((x + y) << 1) + y), (x + (y << 1)) * (x + (y << 2)))

def fastfib(n):
    x, y = fibfusc_rec((n + 1) / 2)
    return x + y if n % 2 == 1 else y

def fibfusc(n, num_digits=None):
    if num_digits: mod = pow(10, num_digits)
    x, y = 1, 0
    for c in bin(n)[2:]:
        if c == '0': x, y = (x + y) * (x - y), y * (((x + y) << 1) + y)
        else: x, y = -y * (((x + y) << 1) + y), (x + (y << 1)) * (x + (y << 2))
        if num_digits: x, y = x % -mod, y % mod
    return x, y


from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from functions import currencyFormater
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
import os

def setPDFInvoicePrinter (printData ):
    packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=letter)

    cusPhone = printData['namePhone'] if ('namePhone' in printData and printData['namePhone']) else '--'
    cusAdress =  printData['nameAddress'] if 'nameAddress' in printData else '--'

    printValue = not(printData['hideValue']) if 'hideValue' in printData else True

    if int(printData['balance'])>0 :
        invType = 'A/C'+' '+printData['type']

    else:
        invType =printData['type']

    can.setFont("Helvetica", 11)

    can.drawString(410, 820, "DATE")
    can.drawString(450, 820, ": "+printData['date']+' '+ printData['time'][0:5] +' '+printData['time'][-2:])

    can.drawString(440, 710, "No. : "+printData['invoiceSN'])
    # can.drawString(430, 4, ": "+printData['invoiceSN'])

    can.drawString(70, 638, "NAME  : "+printData['name'].upper())

    can.drawString(255, 638, "PHONE  : "+cusPhone)

    can.drawRightString(520, 638, "NIC  : "+(printData['nameNIC'] or '--'))

    can.setFont("Helvetica", 11)

    # can.drawString(370, 548, "Inv. Type")
    # can.drawString(430, 548, ": "+invType.upper())

    # can.drawString(370, 533, "Issued by")
    # can.drawString(430, 533, ": "+printData['issuedby'])

    if (printData['type']=='Paid' or printData['type']=='SMS' ):
        can.setFont("Helvetica-Bold", 11)

        comment = "("+printData['comment']+')' if ('comment' in printData and  printData['comment'] and printData['comment']!='Nothing' ) else ' '
        can.setFont("Helvetica", 11)
        can.drawString(50, 595, "{:^12}".format( '1'))
        can.drawString(90, 595, 'A PAYMENT RECEIVED-CONFIRMATION' )
        can.drawString(370, 595,"{:^18}".format('-'))
        can.drawRightString(545, 595, currencyFormater(printData['total'])+'.00')
        can.setFont("Helvetica", 11)
        can.drawString(90, 580, printData['paidForLabel'].upper() if printData['paidForLabel'] else 'PAID FOR SMS' )
        can.drawString(90, 565, comment )

        can.setFont("Helvetica", 11)
        can.drawString(55, 445, "ISSUED BY : "+printData['issuedby'].upper())

        can.drawString(235, 445, "TYPE : PAYMENT")

        can.setFont("Helvetica-Bold", 12)

        can.drawRightString(420, 445, 'TOTAL')

        can.drawRightString(540, 445, 'Rs. '+currencyFormater(abs(float(printData['total'])))+'0')

    else :
        can.setFont("Helvetica", 10)
        i=0
        for (key, value) in printData['itemList'].items():
            y=595-i*14
            i=i+1
            karadUnit = 'K' if ('GOLD' in value['id'].upper()) else ''
            can.drawString(50, y, "{:^12}".format( str(i)))
            can.drawString(90, y, value['label'].upper() )#80
            can.setFont("Helvetica-Bold", 10)
            can.drawString(340, y, str(value['karad'])+karadUnit )
            can.setFont("Helvetica", 10)
            can.drawString(380, y, "{:^18}".format( str(value['weight'])+'g'))
            if (printValue):
                can.drawRightString(545, y,  currencyFormater(float(value['unitPrice'])*float(value['quantity']))+'0')

        if ('purchase' in printData and  printData['purchase']):
            can.setFont("Helvetica-Bold", 10)
            y= 513
            # if (i!=0 and printValue):
            #     i=0
            #     can.drawString(375, y-i*13, "{:<18}".format( 'TOTAL'))
            #     can.drawRightString(545, y-i*13,currencyFormater(float(printData['total']))+'0')
            i=0

            i=i+1
            can.drawString(90, y-i*12, 'PAYMENTS' )

            i=i+1

            can.setFont("Helvetica", 9)
            printData['payMethod1'] = printData['payMethod1'][0:40]+'...' if len(printData['payMethod1'])>40 else printData['payMethod1']

            can.drawString(90, y-i*11,("ORDER: "+(printData['payMethod1'] or 'Cash').upper() if '-OR' in printData['purchase'] else (printData['payMethod1'] or 'Cash').upper() )  +' (' +printData['purchase']+')')#80
            #can.drawString(360, y-i*11, "{:^18}".format( str(value['weight'])+'g'))
            if(printValue):
                can.drawRightString(545, y-i*11, '('+ currencyFormater(float(printData['payAmount'])-float(printData['payMethod2Amount']))+'0)')

            i=i+1
            can.drawString(90, y-i*11, (printData['payMethod2'] or 'Cash').upper() )#80
            #can.drawString(360, y-i*11, "{:^18}".format( str(value['weight'])+'g'))

            can.drawRightString(545, y-i*11, '('+ currencyFormater(float(printData['payMethod2Amount']))+'0)')
            if (printData['balance']<0):
                can.setFont("Helvetica-Bold", 9)
            i=i+1
            can.drawString(90, y-i*11, 'BALANCE'+ (' (PAY BACK)' if (printData['balance']<0) else '') )#80
            #can.drawString(360, y-i*11, "{:^18}".format( str(value['weight'])+'g'))

            can.drawRightString(545, y-i*11, '('+ currencyFormater(float(printData['balance']))+'0)')

        else :
            can.setFont("Helvetica-Bold", 10)
            can.drawString(90, 492,'PAYMENT DETAILS')
            can.setFont("Helvetica", 10)
            can.drawString(90, 480,printData['payMethod'].upper() )
            can.drawRightString(545, 480,'('+currencyFormater(float(printData['payAmount']))+'0)')
            if (printData['balance']<0):
                can.setFont("Helvetica-Bold", 10)

            if (printValue):
                can.drawString(90, 468, 'BALANCE'+(' (PAY BACK)' if (printData['balance']<0) else '') )#80
                can.drawRightString(545,468,'('+currencyFormater(float(printData['balance']))+'0)')

        balPrefix = '- ' if float(printData['balance'])<0 else ''

        can.setFont("Helvetica", 11)
        can.drawString(70, 445, "ISSUED BY  : "+printData['issuedby'].upper())

        can.drawString(235, 445, "TYPE : "+invType.upper())

        can.setFont("Helvetica-Bold", 12)

        if (printData['type']=='Order' and printValue):
            footerText = 'Est. TOTAL'
            footerValue =printData['total']
        elif (printData['type']=='Order') :
            footerText =  printData['payMethod2'].upper()+' PAID' if  printData['payMethod2Amount']>0 else 'PAYMENT'
            footerValue =  printData['payMethod2Amount']+' PAID' if  printData['payMethod2Amount']>0 else printData['payAmount']

        else :
            footerText = 'TOTAL' if printValue else 'BALANCE'
            footerValue = printData['total'] if printValue else printData['balance']

        can.drawRightString(425, 445, footerText)
        can.drawRightString(540, 445, 'Rs. '+currencyFormater((float(footerValue)))+'0')

    can.save()

    #move to the beginning of the StringIO buffer
    packet.seek(0)

    # create a new PDF with Reportlab
    new_pdf = PdfFileReader(packet)
    # read your existing PDF
    existing_pdf = PdfFileReader(open("invTemp.pdf", "rb")) if (printData['type']=='Paid') else PdfFileReader(open("invTemp.pdf", "rb"))
    output = PdfFileWriter()
    # add the "watermark" (which is the new pdf) on the existing page
    page = existing_pdf.getPage(0)
    page.mergePage(new_pdf.getPage(0))
    output.addPage(page)
    # finally, write "output" to a real file
    outputStream = open("destination.pdf", "wb")
    output.write(outputStream)
    outputStream.close()
    os.system('lp ./destination.pdf')

# from reportlab.pdfgen.canvas import Canvas
# from reportlab.lib.units import inch, mm, cm, pica
# from datetime import date, timedelta

# if __name__ == "__main__":
#     pdf = Canvas("output.pdf")
#     pdf.setFont('Helvetica', 9)

#     master_data = ...
#     start = ...
#     end = ...
#     company = ...
#     today = ...

#     lines = [
#         "Rechnungsdatum: "+'today',
#         "Leistungserbringung: "+ '',
#         "Leistungszeitraum: "+'start'+" - "+'end',
#         "Rechnungsnummer: "+'',
#         "Lieferantennummer: ",
#         "Zahlungsziel: " +str((date.today().replace(day=1) - timedelta(days=1)).day)+ " Tage",
#     ]
#     ys = [600,590,580,570,560,550]
#     width = pdf._pagesize[0]
#     padding = 10 * mm
#     for y, line in zip(ys, lines):
#         pdf.drawRightString(20, y, line)
#     pdf.save()


title = "TYPE ME IN AN X PATTERN COOL CODE WOW VERY AWESOME"
spacing = ""
inversespacing = (len(title) - 1) * " "
spacingcounter = 0
counter = 0

while counter < len(title):
    if counter < (len(title))/2:
        print(spacing + title[counter] + inversespacing + title[counter])
        spacingcounter += 1
        inversespacing = (len(inversespacing) - 2) * " "
    elif (len(title))/2 < counter:
        print(spacing + title[counter] + inversespacing + title[counter])
        spacingcounter += -1
        inversespacing = (len(inversespacing) + 2) * " "
    else:
        print(spacing + title[counter])
        spacingcounter += -1
        inversespacing = (len(inversespacing) + 1) * " "

    spacing = spacingcounter * " "
    counter += 1


#!/usr/bin/env python
"""A recipe..."""
from sbrew import *

r = Recipe()
r.name = "Ithacan Imperial Stout"
r.description = (
    "Ithaca is not very Imperial in attitude, and so it is with this "
    "Imperial Stout that weighs in at only just approaching Imperial "
    "weight (about 8\% ABV). The goal is a well rounded chocolate "
    "and malty taste up front, revealing a roasty and slightly bitter "
    "finish without harshness or lingering hop taste.")

# ithaca water

m = InfusionMash()
m.ingredient('grain', '2-row (briess) malt', '14lb', color='1.8L')
m.ingredient('grain', 'special B malt', '1.0lb', color='65L')
m.ingredient('grain', 'coffee malt', '12oz', color='150.0L')
m.ingredient('grain', 'carafa I (weyermann) malt', '8oz', color='350.0L')
m.ingredient('grain', 'roast barley', '1.25lb', color='300L')
m.ingredient('water', 'strike', '5.0gal')
m.property('temp', '150F')
m.property('t_mashtun', '65F')
r.add(m)

s = BatchSparge(start=m)
s.property('wort_volume', '7.0gal')
r.add(s)

b = Boil(start=s)
b.time = Quantity('90min')
b.ingredient('dme', 'muntons extra light', '0.5lb', time='15min')
b.ingredient('hops', 'centennial', '61 IBU', time='60min', aa='10.4%AA')
b.ingredient('hops', 'fuggles', '1.0oz', time='10min', aa='4.6%AA')
b.ingredient('misc', 'irish moss', '1tsp', time='15min')
b.property('boil_end_volume', '6.25gal')
r.add(b)

f = Ferment(start=b)
f.ingredient('yeast', 'Wyeast 1318 London Ale III', '1 yeast_cake')
# f.property('ABV','8%ABV')
f.property('atten', '75%atten')
r.add(f)

r.solve()
print(r)
# print(r.markdown_narrative())


import subprocess
import asyncio

async def copy_files():
    command = 'scp -r ucsf:/data1/home/wjarrard/projects/cleaned/sample_{0..1000}.orc /Users/wejarrard/projects/atacToChip/atacToChip/data/pretraining/cleaned'
    process = await asyncio.create_subprocess_shell(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = await process.communicate()

    if process.returncode == 0:
        print('Files copied successfully!')
    else:
        print(f'An error occurred while copying the files: {stderr.decode()}')

asyncio.run(copy_files())


#!/usr/bin/python3
"""
Script that extracts the data from the Penn Treebank and converts it to indices.
"""
from collections import Counter, defaultdict
import pickle
import sys
import os.path as osp

import numpy as np

# We include the path of the toplevel package in the system path so we can always use absolute imports within the package.
toplevel_path = osp.abspath(osp.join(osp.dirname(__file__), '../..'))
if toplevel_path not in sys.path:
    sys.path.insert(1, toplevel_path)

from util.settings import parse_arguments  # noqa: E402

__author__ = "Tom Pelsmaeker"
__copyright__ = "Copyright 2020"

def convert_to_indices(files, max_vocab, replace, sos, eos, pad):
    counter = Counter()
    counter.update([replace])
    sentences = []
    for i, file in enumerate(files):
        sentences.append([])
        with open(file, 'r', encoding='utf8') as f:
            sentences[i] = ["{} {} {}".format(sos, line, eos).split() for line in f]
            counter.update([token for sentence in sentences[i] for token in sentence])

    word_to_idx = defaultdict(lambda: 0)
    idx_to_word = {0: replace}
    num = 1
    for i, (token, _) in enumerate(counter.most_common(max_vocab)):
        if token is not replace:
            word_to_idx[token] = i + num
            idx_to_word[i + num] = token
        else:
            num = 0
    word_to_idx[pad] = max_vocab
    idx_to_word[max_vocab] = pad

    for file, dataset in zip(files, sentences):
        with open(file.split('.')[0] + ".indices", 'w', encoding='utf8') as f:
            f.write("\n".join([" ".join([str(word_to_idx[token]) for token in sentence]) for sentence in dataset]))

    pickle.dump(idx_to_word, open("idx_to_word.pickle", 'wb'))
    pickle.dump(dict(word_to_idx), open("word_to_idx.pickle", 'wb'))

    print("Number of unique tokens: {}".format(len(counter)))
    print("Vocab size: {}".format(len(idx_to_word)))

def get_stats(file, ret=False):
    with open(file, 'r', encoding='utf8') as f:
        lengths = np.array([len(line.split()) for line in f])

    mean = lengths.mean()
    std = lengths.std()
    max = lengths.max()
    min = lengths.min()
    num_sent = len(lengths)

    cutoff = int(mean + 3 * std)
    num_outliers = sum([1 for l in lengths if l > cutoff])
    pct_outliers = (float(num_outliers) / num_sent) * 100

    if ret:
        return mean, std, max, cutoff, pct_outliers
    else:
        print("{}| mean: {}, std: {}, max: {}, min: {}, pct outliers: {}".format(
            file, mean, std, max, min, pct_outliers))

if __name__ == '__main__':
    opt = parse_arguments()[0]
    in_files = ['train.txt', 'val.txt', 'test.txt']
    max_vocab = 10001

    convert_to_indices(in_files, max_vocab, opt.unk_token, opt.sos_token, opt.eos_token, opt.pad_token)


import sys

code = []
for line in sys.stdin:
    code.append(line)

for j in range(len(code)):
    acc = 0
    ran = set()
    i = 0
    while i < len(code):
        if i in ran:
            print(f"Stopping at {i} because loop.")
            print(f"Acc: {acc}")
            break
        ran.add(i)
        op, arg = code[i].split()

        if op == "nop":
            if i == j:
                i += int(arg)
            else:
                i += 1
        elif op == "jmp":
            if i == j:
                i += 1
            else:
                i += int(arg)
        elif op == "acc":
            acc += int(arg)
            i += 1

    else:
        print(f"Terminated fine after {i} loops")
        print(f"Acc: {acc}")
        break


import itertools
import json

with open('food.yml', 'r') as f:
   lines = f.readlines()
patterns, responses = lines[::2], lines[1::2]
patterns=map(str.strip, patterns)
responses=map(str.strip, responses)
tag= 'food'
record={}
record['tag']=tag
record['patterns']=patterns
record['responses']= responses
json_data = json.dumps(record)
with open('formatted.json', 'w') as f_out:
        f_out.write(json_data)


import os
import sys
import numpy as np
import pandas as pd
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectPercentile
from sklearn.feature_selection import mutual_info_classif
# Adding the path, else import wouldnt work
# https://stackoverflow.com/questions/4383571/importing-files-from-different-folder
sys.path.insert(0, os.path.dirname(os.getcwd()))
from Preprocess import Prep
from GlobalParameters import DefaultParam
from sklearn.feature_selection import SelectFromModel

#___________________________________________________________________________________________________________________#
# Works on ndarray
def fs_using_randfor(gen_tr_data, gen_ts_data, imp_tr_data, imp_ts_data,fsthreshold): # fsthreshold is [0, 3]
    clf = ExtraTreesClassifier(n_estimators=300, max_features='log2', max_depth=10)
    # Training data does not contain labels explicitly as we can get label anytime
    training_data = np.vstack((gen_tr_data, imp_tr_data))
    train_labels = np.concatenate((Prep.get_labels(gen_tr_data, 1), Prep.get_labels(imp_tr_data, -1)))
    #### Filtering 50% features using statistical tests before selecting them
    # print('Before chi square test.csv training_data.shape:', gen_tr_data.shape)
    ChiSTestModel = SelectPercentile(mutual_info_classif, percentile=70).fit(training_data, train_labels)
    gen_tr_data = ChiSTestModel.transform(gen_tr_data)
    gen_ts_data = ChiSTestModel.transform(gen_ts_data)
    imp_tr_data = ChiSTestModel.transform(imp_tr_data)
    imp_ts_data = ChiSTestModel.transform(imp_ts_data)
    training_data = np.vstack((gen_tr_data, imp_tr_data))
    # print('After chi square test.csv training_data.shape:', gen_tr_data.shape)
    #Applying the random forest based feature ranking
    clf = clf.fit(training_data, train_labels)
    # print('clf.feature_importances_',clf.feature_importances_)
    RFBasedModel = SelectFromModel(clf, prefit=True, threshold=str(fsthreshold)+'*median')
    selected_feature_indices = RFBasedModel.get_support()
    gen_tr_data = RFBasedModel.transform(gen_tr_data)
    gen_ts_data = RFBasedModel.transform(gen_ts_data)
    imp_tr_data = RFBasedModel.transform(imp_tr_data)
    imp_ts_data = RFBasedModel.transform(imp_ts_data)
    # print('After applying the RFBased feature selection:', gen_tr_data.shape)
    return gen_tr_data, gen_ts_data, imp_tr_data, imp_ts_data, selected_feature_indices

#___________________________________________________________________________________________________________________#
# LDA Tranform returns k-1 components.. k is the number of classes
# So the number of components for LDA would be 1 out case as # there are two classes
# LDA is used WHEN feature is CONTINUOUS and CLass is Categorical ..
# But we have only two classes
# https://www.datacamp.com/community/tutorials/feature-selection-python
# Works on ndarray
def fs_using_lda(gen_tr_data, gen_ts_data, imp_tr_data, imp_ts_data, fsthreshold):
    num_component = int(DefaultParam.fsthreshold * gen_tr_data.shape[1])
    # print('num_component',num_component)
    lda = LinearDiscriminantAnalysis(n_components=num_component)
    training_data = np.vstack((gen_tr_data, imp_tr_data))
    training_labels = np.concatenate((Prep.get_labels(gen_tr_data, 1), Prep.get_labels(imp_tr_data, -1)))
    lda = lda.fit(training_data, training_labels)
    gen_tr_data = lda.transform(gen_tr_data)
    gen_ts_data = lda.transform(gen_ts_data)
    imp_tr_data = lda.transform(imp_tr_data)
    imp_ts_data = lda.transform(imp_ts_data)
    # print('Printing the training and testing samples inside LDA')
    # print(gen_tr_data, gen_ts_data, imp_tr_data, imp_ts_data)
    # Returning indices of featues does not apply here as LDA returns transformed component not the features or indices
    return gen_tr_data, gen_ts_data, imp_tr_data, imp_ts_data

#___________________________________________________________________________________________________________________#
# Works on ndarray
def fs_using_FCBF(gen_tr_data, gen_ts_data, imp_tr_data, imp_ts_data, fsthreshold):
    training_data = np.vstack((gen_tr_data, imp_tr_data))
    train_labels = np.concatenate((Prep.get_labels(gen_tr_data, 1), Prep.get_labels(imp_tr_data, -1)))
    # https://stackoverflow.com/questions/29294983/how-to-calculate-correlation-between-all-columns-and-remove-highly-correlated-on
    selected_feature_indices = fcbf(training_data, train_labels, fsthreshold)  # threshold is between 0 to 1 SU is between zero to one
    # print(f'selected features:{good_features}')
    gen_tr_data = gen_tr_data.loc[:, selected_feature_indices]
    gen_ts_data = gen_ts_data.loc[:, selected_feature_indices]
    imp_tr_data = imp_tr_data.loc[:, selected_feature_indices]
    imp_ts_data = imp_ts_data.loc[:, selected_feature_indices]
    return gen_tr_data, gen_ts_data, imp_tr_data, imp_ts_data, selected_feature_indices

# !/usr/bin/env python
# https://github.com/shiralkarprashant/FCBF/blob/master/src/fcbf.py"""
# fcbf.py
# Created by Prashant Shiralkar on 2015-02-06.
# Fast Correlation-Based Filter (FCBF) algorithm as described in
# Feature Selection for High-Dimensional Data: A Fast Correlation-Based
# Filter Solution. Yu & Liu (ICML 2003)
def entropy(vec, base=2):
    " Returns the empirical entropy H(X) in the input vector."
    _, vec = np.unique(vec, return_counts=True)
    prob_vec = np.array(vec / float(sum(vec)))
    if base == 2:
        logfn = np.log2
    elif base == 10:
        logfn = np.log10
    else:
        logfn = np.log
    return prob_vec.dot(-logfn(prob_vec))

def conditional_entropy(x, y):
    "Returns H(X|Y)."
    uy, uyc = np.unique(y, return_counts=True)
    prob_uyc = uyc / float(sum(uyc))
    cond_entropy_x = np.array([entropy(x[y == v]) for v in uy])
    return prob_uyc.dot(cond_entropy_x)

def mutual_information(x, y):
    " Returns the information gain/mutual information [H(X)-H(X|Y)] between two random vars x & y."
    return entropy(x) - conditional_entropy(x, y)

def symmetrical_uncertainty(x, y):
    " Returns 'symmetrical uncertainty' (SU) - a symmetric mutual information measure."
    return 2.0 * mutual_information(x, y) / (entropy(x) + entropy(y))

def getFirstElement(d):
    """
    Returns tuple corresponding to first 'unconsidered' feature

    Parameters:
    __________--
    d : ndarray
        A 2-d array with SU, original feature index and flag as columns.

    Returns:
    _____---
    a, b, c : tuple
        a - SU value, b - original feature index, c - index of next 'unconsidered' feature
    """

    t = np.where(d[:, 2] > 0)[0]
    if len(t):
        return d[t[0], 0], d[t[0], 1], t[0]
    return None, None, None

def getNextElement(d, idx):
    """
    Returns tuple corresponding to the next 'unconsidered' feature.

    Parameters:
    __________---
    d : ndarray
        A 2-d array with SU, original feature index and flag as columns.
    idx : int
        Represents original index of a feature whose next element is required.

    Returns:
    __________
    a, b, c : tuple
        a - SU value, b - original feature index, c - index of next 'unconsidered' feature
    """
    t = np.where(d[:, 2] > 0)[0]
    t = t[t > idx]
    if len(t):
        return d[t[0], 0], d[t[0], 1], t[0]
    return None, None, None

def removeElement(d, idx):
    """
    Returns data with requested feature removed.

    Parameters:
    __________---
    d : ndarray
        A 2-d array with SU, original feature index and flag as columns.
    idx : int
        Represents original index of a feature which needs to be removed.

    Returns:
    __________
    d : ndarray
        Same as input, except with specific feature removed.
    """
    d[idx, 2] = 0
    return d

def c_correlation(X, y):
    """
    Returns SU values between each feature and class.

    Parameters:
    __________---
    X : 2-D ndarray
        Feature matrix.
    y : ndarray
        Class label vector

    Returns:
    __________
    su : ndarray
        Symmetric Uncertainty (SU) values for each feature.
    """
    su = np.zeros(X.shape[1])
    for i in np.arange(X.shape[1]):
        su[i] = symmetrical_uncertainty(X[:, i], y)
    return su

def fcbf(X, y, thresh):
    """
    Perform Fast Correlation-Based Filter solution (FCBF).

    Parameters:
    __________---
    X : 2-D ndarray
        Feature matrix
    y : ndarray
        Class label vector
    thresh : float
        A value in [0,1) used as threshold for selecting 'relevant' features.
        A negative value suggest the use of minimum SU[i,c] value as threshold.

    Returns:
    __________
    sbest : 2-D ndarray
        An array containing SU[i,c] values and feature index i.
    """
    n = X.shape[1]
    slist = np.zeros((n, 3))
    slist[:, -1] = 1

    # identify relevant features
    slist[:, 0] = c_correlation(X, y)  # compute 'C-correlation'
    idx = slist[:, 0].argsort()[::-1]
    slist = slist[idx,]
    slist[:, 1] = idx
    if thresh < 0:
        thresh = np.median(slist[-1, 0])
        print("Using minimum SU value as default threshold: {0}".format(thresh))
    elif thresh >= 1 or thresh > max(slist[:, 0]):
        raise ValueError("No relevant features selected for given threshold.")
    slist = slist[slist[:, 0] > thresh, :]  # desc. ordered per SU[i,c]

    # identify redundant features among the relevant ones
    cache = {}
    m = len(slist)
    p_su, p, p_idx = getFirstElement(slist)
    for i in np.xrange(m):
        p = int(p)
        q_su, q, q_idx = getNextElement(slist, p_idx)
        if q:
            while q:
                q = int(q)
                if (p, q) in cache:
                    pq_su = cache[(p, q)]
                else:
                    pq_su = symmetrical_uncertainty(X[:, p], X[:, q])
                    cache[(p, q)] = pq_su

                if pq_su >= q_su:
                    slist = removeElement(slist, q_idx)
                q_su, q, q_idx = getNextElement(slist, q_idx)

        p_su, p, p_idx = getNextElement(slist, p_idx)
        if not p_idx:
            break

    sbest = slist[slist[:, 2] > 0, :2]
    return sbest

# Another source of implementation is https://github.com/SantiagoEG/FCBF_module


import discord
from discord.ext import commands

class HelpCommand (commands.Cog):
    def __init__ (self, Client):
        self.Client = Client

    @commands.command ()
    async def help (self, ctx):
        ctx.channel.send ('Help is on it\'s way haha')


from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from unittestzero import Assert

__author__ = 'Artur'

class BasePage(object):
    url = None

    def __init__(self, driver):
        self.driver = driver

    _search_box_locator = (By.ID, 'searchInput')
    _search_button_locator = (By.ID, 'searchButton')
    header_link_list = [
        {
            'locator': (By.CSS_SELECTOR, '#header a.phones'),
            'url_suffix': '/phones',
            'link_text': 'Telefony',
        },
        {
            'locator': (By.CSS_SELECTOR, '#header a.design'),
            'url_suffix': 'features',
            'link_text': 'Funkcje',
        },
        {
            'locator': (By.CSS_SELECTOR, '#header a.marketplace'),
            'url_suffix': 'store',
            'link_text': 'Aplikacje+Gry',
        },
        {
            'locator': (By.CSS_SELECTOR, '#header a.support'),
            'url_suffix': 'how-to/wp8',
            'link_text': 'Porady',
        },
    ]

    footer_link_list = [
        {
            'locator': (By.LINK_TEXT, 'Dla deweloperów'),
            'url_suffix': 'developer.windowsphone.com/',
            'link_text': 'Dla deweloperów',
        },
        {
            'locator': (By.LINK_TEXT, 'Dla firm'),
            'url_suffix': 'fwlink/?linkId=260887&clcid=0x415',
            'link_text': 'Dla firm',
        },
        {
            'locator': (By.LINK_TEXT, 'Praca'),
            'url_suffix': 'windowsphonecareers.com/',
            'link_text': 'Praca',
        },
        {
            'locator': (By.LINK_TEXT, 'Mapa witryny'),
            'url_suffix': 'sitemap',
            'link_text': 'Mapa witryny',
        },
        {
            'locator': (By.LINK_TEXT, 'Kontakt z nami'),
            'url_suffix': 'contact-us',
            'link_text': 'Kontakt z nami',
        },
        {
            'locator': (By.LINK_TEXT, 'Opinie'),
            'url_suffix': '#',
            'link_text': 'Opinie',
        },
        {
            'locator': (By.LINK_TEXT, 'Prywatność i pliki cookie'),
            'url_suffix': 'fwlink/?linkId=248681&clcid=0x415',
            'link_text': 'Prywatność i pliki cookie',
        },
        {
            'locator': (By.LINK_TEXT, 'Warunki korzystania'),
            'url_suffix': 'fwlink/?linkId=123158&clcid=0x415',
            'link_text': 'Warunki korzystania',
        },
        {
            'locator': (By.LINK_TEXT, 'Znaki towarowe'),
            'url_suffix': '?linkId=4412893&clcid=0x415',
            'link_text': 'Znaki towarowe',
        },
        {
            'locator': (By.LINK_TEXT, 'Polska (polski)'),
            'url_suffix': 'markets',
            'link_text': 'Polska (polski)',
        },
    ]

    _explore_dropdown_menu = (By.ID, 'exploreTitle')

    #Navigate to selected adress
    def go_to_page(self):
        self.driver.get(self.url)

    def link_url(self, locator):
        url = self.driver.find_element(*locator)
        return url.get_attribute('href')

    def link_title(self, locator):
        title = self.driver.find_element(*locator)
        return title.text

    def mouse_click_element(self, element):
        self.driver.find_element(*element).click()

    #Check if links url and title are corect
    def check_links(self, link_list):
        bad_urls = []
        bad_titles = []
        for link in link_list:
            url = self.link_url(link.get('locator'))
            title = self.link_title(link.get('locator'))
            if not url.endswith(link.get('url_suffix')):
                bad_urls.append('%s don\'t end with %s' % (url, link.get('url_suffix')))
            if not title == link.get('link_text'):
                bad_titles.append('%s don\'t equal %s' % (title, link.get('link_text')))
        Assert.equal(0, len(bad_urls), '%s bad url\'s found: ' % len(bad_urls) + ', '.join(bad_urls))
        Assert.equal(0, len(bad_titles), '%s bad title\'s found: ' % len(bad_titles) + ', '.join(bad_titles))

    #Searching with search box
    def search_in_page(self, text):
        search_box = self.driver.find_element(*self._search_box_locator)
        search_box.send_keys(text)
        search_box.send_keys(Keys.RETURN)
        assert 'Nie znaleziono odpowiednich aplikacji.' not in self.driver.page_source
        assert 'Nie znaleziono odpowiednich artykułów z poradami.' not in self.driver.page_source

    #Check page title
    def is_page_title_matches(self):
        assert self.page_title in self.driver.title


import re

def analiseLexica():
    f = open("nome-do-arquivo.c", "r")  # Abre o arquivo para leitura
    lines = f.readlines()

    tokens = {}
    qtdLines = 1
    identificador_count = 150

    for line in lines:
        line = re.sub("{", " {", line)
        line = re.sub(";", " ;", line)
        line = re.sub(",", " ,", line)
        line = re.sub("=", " = ", line)
        line = re.sub("[ ]{2,}", " ", line)
        if line.strip() != '':
            line = line.strip()

            if re.search("^#include <.*[.]h>$", line):
                line = line.split()
                tokens[(line[0], qtdLines)] = 150  # Palavra reservada
                biblioteca = re.sub("(<|>)", "", line[1])
                tokens[(biblioteca, qtdLines)] = identificador_count
                identificador_count += 1  # Biblioteca
            elif re.search("^int main\\(\\)( {|)$", line):
                line = line.split()
                tokens[(line[0], qtdLines)] = 150  # Palavra reservada
                tokens[(line[1], qtdLines)] = 150  # Palavra reservada
                if len(line) == 3:
                    tokens[(line[2], qtdLines)] = 151  # Delimitador de início
            elif line == "{":
                tokens[(line, qtdLines)] = 151  # Delimitador de início
            elif line == "}":
                tokens[(line, qtdLines)] = 152  # Delimitador de fim
            else:
                aux = line
                line = line.split()
                for i in line:
                    if i == "int" or i == "return":
                        tokens[(i, qtdLines)] = 150  # Palavra reservada
                    elif i == "=":
                        tokens[(i, qtdLines)] = 153  # Comando de atribuição
                    elif i == "+":
                        tokens[(i, qtdLines)] = 154  # Operador de adição
                    elif i == "*":
                        tokens[(i, qtdLines)] = 155  # Operador de multiplicação
                    elif i == ";":
                        tokens[(i, qtdLines)] = 156  # Finalizador de linha
                    elif re.search("^[a-zA-Z]{1,}[0-9]*$", i):
                        tokens[(i, qtdLines)] = identificador_count
                        identificador_count += 1  # Nome de variável
                    elif re.search("^[0-9]{1,}$", i):
                        tokens[(i, qtdLines)] = 157  # Constante numérica
                    elif i == ",":
                        tokens[(i, qtdLines)] = 158  # Separador
                    else:
                        if i == "#include":
                            i = aux
                        print("O token '" + i + "' na linha " + str(qtdLines) + " é inválido")
                        return
        qtdLines += 1

    with open("output.txt", "w") as output_file:
        for key in tokens:
            output_file.write(str(key[1]) + ": " + str(tokens[key]) + " - " + str(key[0]) + "\n")

def main():
    analiseLexica()

main()


import sys
import os
import time
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
try:
    import cairo
    gi.require_foreign("cairo")
except ImportError:
    from gi.repository import cairo # pycairo
    print("No cairo integration.")
import utils as utils
from locals_constants import *

# =============================
# The Window
# =============================
class Window(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, Gtk.WindowType.POPUP)
        self.set_events(self.get_events() | Gdk.EventMask.BUTTON_PRESS_MASK)
        self.set_decorated(False)
        self.set_size_request(20, 20) # The widget size will then be adjusted to the size of the image.
        self.connect('destroy', Gtk.main_quit)
        self.connect('draw', self.draw)

        screen = self.get_screen()
        visual = screen.get_rgba_visual()
        if visual and screen.is_composited():
            self.set_visual(visual)
        self.set_app_paintable(True)

        self.x_pos = int(utils.get_resolution_width() / 2)
        self.y_pos = utils.get_resolution_height() - 108 # The value subtracted is to accommodate the image.
        self.move(self.x_pos, self.y_pos)
        self.image = Gtk.Image()
        self.fixed = Gtk.Fixed()
        self.fixed.put(self.image, 0, 0)

        self.menu = Gtk.Menu()
        lbl_menu_item = ["About...", "Exit"]
        for label in lbl_menu_item:
            menu_items = Gtk.MenuItem(label)
            self.menu.append(menu_items)
            # When there is an event on the MenuItem (in this case left click)
            menu_items.connect("activate", self.clicked_item)
            menu_items.show()
        # When there is an event on the toon (in this case right click)
        self.connect("button_press_event", self.on_clicked)
        self.add(self.fixed)
        self.show_all()

    def draw(self, widget, context):
        context.set_source_rgba(0, 0, 0, 0)
        context.set_operator(cairo.OPERATOR_SOURCE)
        context.paint()
        context.set_operator(cairo.OPERATOR_OVER)

    def update(self, toon):
        action = toon.action
        action_name = action.get_name()
        orientation = action_name != "base" and f"-{action.orientation}" or ""
        frame = action.current_frame
        src_img = f"-{action_name}{orientation}{frame}.png"
        pixbuf = utils.load_new_pixbuf(src_img)
        self.image.set_from_pixbuf(pixbuf)
        self.image.show()
        self.fixed.set_size_request(100, 100)
        self.fixed.show()
        self.x_pos += toon.calculate_advance()
        self.move(self.x_pos, self.y_pos)
        Gtk.Widget.show(self.image)
        self.show()

    # This is for capturing events on the widget
    def on_clicked(self, window, event):
        if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
            event.button = 1
            window.menu.popup(None, None, None, None, event.button, event.time)

    def clicked_item(self, menu_item):
        if menu_item.get_label() == "About...":
            about = About(self)
            about.run()
            about.destroy()
        else: # Exit
            Gtk.main_quit()
            sys.exit()

class About(Gtk.AboutDialog):
    def __init__(self, parent):
        Gtk.AboutDialog.__init__(self, transient_for=parent, modal=True)
        authors = [AUTHOR]
        develop_year = 2019
        current_year = time.strftime("%Y")
        time_lapse = develop_year # -> For example: 2019-2020
        if int(current_year) > develop_year:
            time_lapse = f"{develop_year}-{current_year}"
        self.set_authors(authors)
        self.set_license(LICENSE)
        self.set_program_name(APP_NAME)
        self.set_version(VERSION)
        self.set_copyright(f"Copyright © {time_lapse} {authors[0].split('<')[0]}")
        self.set_comments("A little toon that moves on your desktop")
        self.set_website("https://andy-thor.github.io/StickMan")
        self.set_website_label("Visit StickMan Homepage")
        self.set_logo(utils.load_pixbuf_from_file(os.path.join(DATADIR, DIR_ICONS, APP_NAME.lower() + ".png")))


import math
a=int(input("enter a limit"))
l=[]
print("enter 4 digit nos into the list with each digits in a number as even")
for i in range(0,a):
	e=int(input())
	l.append(e)
print(l)
for e in l:
  	root = math.sqrt(e)
  	if int(root + 0.5) ** 2 == e:
  		print(e, "is a perfect square")
  	else:
  		print(e,"is not a perfect square")


import sys
sys.stdin = open("stack1_종이붙이기.txt")

T = int(input())

m = [1, 1]                          # f(0) = 1, f(1) = 1
for i in range(2, 31):
    m.append(m[i-1] + 2*m[i-2])     # 점화식 f(n) = f(n-1) + 2*f(n-2)

for tc in range (1, T+1):
    N = int(input())//10
    print('#{} {}'.format(tc, m[N]))


from django.conf.urls import include, patterns, url
from django.views.generic import TemplateView

from .views import (
    BoundaryAPIView, DetailAPIView, FakeBoundaryAPIView, FeedbackView,
    ScoreAPIView)

api_urls = patterns(
    '',
    url(r'^score-fake/.*$', 'healthdata.views.fake_api'),
    url(r'^score-old/(?P<lon>-?[\d.]+),(?P<lat>-?[\d.]+)/$',
        'healthdata.views.score_by_location'),
    url(r'^score/(?P<lon>-?[\d.]+),(?P<lat>-?[\d.]+)/$',
        ScoreAPIView.as_view(), name='score'),
    url(r'^boundary/(?P<slug>fake_[-_\d.]*)/$',
        FakeBoundaryAPIView.as_view(), name='fake-boundary'),
    url(r'^boundary/(?P<slug>[a-z\-_\d]*)/$', BoundaryAPIView.as_view(),
        name='boundary'),
    url(r'^detail/(?P<boundary_slug>[a-z\-_\d.]*)'
        r'/(?P<node_slug>[a-z\-_\d]*)/$',
        DetailAPIView.as_view(), name='metric-detail'),
    url(r'feedback/$', FeedbackView.as_view(), name='feedback')
)

urlpatterns = patterns(
    'healthdata.views',
    url(r'^$', TemplateView.as_view(template_name='healthdata/home.jinja2'),
        name='home'),
    url(r'^tryit/$',
        TemplateView.as_view(template_name='healthdata/try_it.jinja2'),
        name='try_it'),
    url(r'^api/', include(api_urls, 'api')),
)


"""
📝 Author: Saud Hashmi
🧷 Problem Index: C-1.22
🚩 Problem Statement:
     Write a short Python program that takes two arrays a and b of length n
    storing int values, and returns the dot product of a and b. That is, it returns
    an array c of length n such that c[i] = a[i] · b[i], for i = 0,...,n-1.
"""

a = [1,2,3,4,5]
b = [2,3,4,5,6]
assert len(a) == len(b)

dot = lambda a,b : sum([a[i]*b[i] for i in range(len(a))])
print(dot(a,b))


def numbers(*data1):
    positives = 0
    negatives = 0
    for i in data:
        if i > 0:
            positives += i
        else:
            negatives += i
    print(negatives)
    print(positives)

    if positives > abs(negatives):
        return print("The positives are stronger than the negatives")

    else:
        return print("The negatives are stronger than the positives")

data = [int(x) for x in input().split(" ")]

numbers()


import numpy as np

"Какой-то массив из блокнота"
game_zone = np.array([
    ['_', '_', '_', '_'],
    ['_', '*', '*', '_'],
    ['_', '*', '*', '_'],
    ['_', '*', '*', '_'],
    ['_', '_', '_', '_'],
])

def print_matrix(matrix):
    for i in range(0, matrix.shape[0]):
        for j in range(0, matrix.shape[1]):
            print(matrix[i][j], end=' ')
        print()
    print('_______')

def step(matrix, neighbours=0):
    for i in range(0, matrix.shape[0]):
        for j in range(0, matrix.shape[1]):
            if matrix[i][j] == '*':
                neighbours += 1
    if (matrix[1][1] == '*') and (neighbours < 3 or neighbours > 4):
        matrix[1][1] = '_'
    elif (matrix[1][1] == '_') and (neighbours == 3):
        matrix[1][1] = '*'

    return matrix

def detect_alive_block(field):
    for i in range(1, field.shape[0] - 1):
        for j in range(1, field.shape[1] - 1):
            print_matrix(step(field[i - 1:i + 2, j - 1:j + 2]))

"если убрать тут step, то будет обычный вывод матрицы 3х3"

"Печать первого живого блока"
print_matrix(detect_alive_block(game_zone))

"Полная печать"

def life(opperations):
    pass
    while opperations > 0:
        print_matrix(step(detect_alive_block(game_zone)))
        opperations -= 1

#life(int(input()))
#         "Таймер где-то тут"


import hashlib

print(hashlib.sha256("1"+"31780"+"Brian").hexdigest())

index = "1"
text = "Brian"
max_nonce = 2 ** 32

def proof_of_work(index, data, difficulty_bits):
    target = 2 ** (256 - difficulty_bits)
    for nonce in xrange(max_nonce):
        hash_result = hashlib.sha256(str(index)+str(nonce)+str(data)).hexdigest()
        if long(hash_result, 16) < target:
            print("Success with nonce", nonce)
            print("Hash is", hash_result)
            return (hash_result, nonce)

proof_of_work(index, text, 16)


from distutils.core import setup
with open('README.rst') as file:
        long_description = file.read()

setup(
    name='powerlaw',
    py_modules=['powerlaw'],
    version='1.3',
    description='Toolbox for testing if a probability distribution fits a power law',
    long_description=long_description,
    author='Jeff Alstott',
    author_email='jeffalstott@gmail.com',
    url='http://code.google.com/p/powerlaw/',
        requires=['scipy', 'numpy', 'matplotlib', 'mpmath'],
        license='MIT',
        classifiers=[
            'License :: OSI Approved :: MIT License',
            'Programming Language :: Python',
            'Programming Language :: Python :: 2.7',
            'Programming Language :: Python :: 3',
            'Operating System :: OS Independent',
            'Topic :: Scientific/Engineering :: Mathematics',
            'Development Status :: 5 - Production/Stable',
            'Intended Audience :: Science/Research'
        ]
)


import torch as t
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence

#paper:NEURAL MACHINE TRANSLATION_BY_JOINTLY LEARNING_TO_ALIGN_AND_TRANSLATE.pdf
#https://arxiv.org/pdf/1409.0473.pdf
class PlainEncoder(nn.Module):
    def __init__(self, embeddings, opts):
        super(PlainEncoder, self).__init__()
        self.embed = nn.Embedding.from_pretrained(embeddings=t.FloatTensor(embeddings),
                                                  freeze=False)
        self.net = nn.Sequential(
            nn.Dropout(opts.drop_rate),
            nn.GRU(opts.embed_size, opts.hidden_size, num_layers=opts.num_layers, batch_first=True,
                   bidirectional=True, dropout=opts.drop_rate)
        )

    '''
        text:batch,seq
        embed:batch,seq,embed
        gpu:batch,seq,embed
    '''
    def forward(self, text, length):
        '''
             (seq_len, batch, num_directions * hidden_size):
        '''
        embed = self.embed(text)
        output,h_n = self.net(embed)
        '''
           output: seq,batch,direction*hidden
           h_0: layer*direction,batch,hidden
        '''
        return output,h_n  # 2,batch,hidden

class PlainDecoder(nn.Module):
    def __init__(self, embeddings, opts):
        super(PlainDecoder, self).__init__()
        self.embed = nn.Embedding.from_pretrained(embeddings=t.FloatTensor(embeddings),
                                                   freeze=False)
        self.dropout = nn.Dropout(opts.drop_rate)
        self.gru = nn.GRU(opts.embed_size, opts.hidden_size, num_layers=opts.num_layers, batch_first=True,
                          bidirectional=True, dropout=opts.drop_rate)
        self.fc = nn.Linear(2 * opts.hidden_size, len(opts.TEXT.vocab.itos))
        self.max_len = opts.maxlen

    # target: batch,seq
    # hidden:num_layer * direction, batch, hidden
    def forward(self, target, target_length, context, encoder_outputs=None):

        seq_len = target.shape[1]

        embed = self.embed(target) #embed:batch,seq,hidden * dir
        embed = self.dropout(embed)

        output_hiddens = []
        hidden = context

        for i in range(seq_len):
            output, hidden = self.gru(embed[:,i,:].unsqueeze(dim=1), hidden)
            output_hiddens.append(output)

        output = t.stack(output_hiddens, dim=1).squeeze(2) #output: batch,seq, hidden
        '''
            output:batch,seq,direction*hidden
            h_0:layer*direction,batch,hidden
        '''
        output = self.fc(output) #batch,seq,vocab
        output = F.log_softmax(output, dim= 2)
        return output, None

class PlainSeq2Seq(nn.Module):
    def __init__(self, encoder, decoder):
        super(PlainSeq2Seq, self).__init__()
        self.encoder = encoder
        self.decoder = decoder
        #self._liner = nn.Linear(opts.hidden_size, words) #batch,seq_len,hidden -> batch,seq_len,words

    def forward(self, sources, source_length, targets, targets_length):
        output, context = self.encoder(sources, source_length)
        target, atten = self.decoder(targets, targets_length,context)
        # target：seq,batch,direction*hidden
        return target, atten


import evaluate
import numpy as np
import pandas as pd
from torch.optim import AdamW, lr_scheduler
from datasets import Dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import TrainingArguments, Trainer

metric = evaluate.load("accuracy")

def tokenize_dataset(data):
    return tokenizer(
        data["text"], max_length=416, truncation=True, padding="max_length"
    )

def compute_metrics(eval_pred):
    logits, labels = eval_pred
    predictions = np.argmax(logits, axis=-1)
    return metric.compute(predictions=predictions, references=labels)

if __name__ == "__main__":
    MODEL_NAME = "airesearch/wangchanBERTa-base-att-spm-uncased"

    tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

    labels = {
        "pos": 0,
        "neu": 1,
        "neg": 2,
        "q": 3,
    }

    df = pd.read_csv("data/train.csv")
    df["label"] = df["label"].map(labels)

    np.random.seed(112)
    df_train, df_val, df_test = np.split(
        df.sample(frac=1, random_state=42), [int(0.8 * len(df)), int(0.9 * len(df))]
    )

    hg_train_data = Dataset.from_pandas(df_train)
    hg_eval_data = Dataset.from_pandas(df_val)
    hg_test_data = Dataset.from_pandas(df_test)

    train_dataset = hg_train_data.map(tokenize_dataset)
    eval_dataset = hg_eval_data.map(tokenize_dataset)
    test_dataset = hg_test_data.map(tokenize_dataset)

    train_dataset = train_dataset.remove_columns(["text", "__index_level_0__"])
    eval_dataset = eval_dataset.remove_columns(["text", "__index_level_0__"])
    test_dataset = test_dataset.remove_columns(["text", "__index_level_0__"])

    train_dataset = train_dataset.rename_column("label", "labels")
    eval_dataset = eval_dataset.rename_column("label", "labels")
    test_dataset = test_dataset.rename_column("label", "labels")

    train_dataset.set_format("torch")
    eval_dataset.set_format("torch")
    test_dataset.set_format("torch")

    model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME, num_labels=4)

    optimizer = AdamW(model.parameters(), lr=1e-5)
    lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)

    training_args = TrainingArguments(
        output_dir="test_trainer",
        evaluation_strategy="epoch",
        per_device_train_batch_size=16,
        per_device_eval_batch_size=8,
    )

    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset,
        eval_dataset=eval_dataset,
        compute_metrics=compute_metrics,
        optimizers=(optimizer, lr_scheduler),
    )

    trainer.train()


from aitextgen.TokenDataset import TokenDataset
from aitextgen.tokenizers import train_tokenizer
from aitextgen.utils import GPT2ConfigCPU
from aitextgen import aitextgen
from flask import Flask
from flask import request
from os.path import exists

app = Flask(__name__)

tname = "aitextgen.tokenizer.json"
ai = aitextgen(tokenizer_file=tname, model_folder="trained_model")

@app.route('/generate', methods=['GET', 'POST'])
def generate():
    if request.method == 'GET':
        gentext = ai.generate_one()
        return(str(gentext))
    elif request.method == 'POST':
        context = request.json['context']
        gentext = ai.generate_one(prompt=context)
        return(str(gentext))
    else:
        return "hm."

@app.route('/')
def hello_world():
    return "gaming"