from safepickling import SafePickling
from dataclasses import dataclass
import pytest

@dataclass
class UselessData:
    cat: str = "cat"
    dog: str = "dog"
    chicken: str = "chicken"
    cat_count: int = 3
    dog_count: int = 1
    chicken_count: int = 12

def test_flow():
    data = UselessData()

    server = SafePickling()
    server.generate_key()

    client = SafePickling()
    client.add_trusted_keys([server.key])

    safe_data = server.pickle(data)

    client_data = client.unpickle(safe_data)
    assert client_data == data

#Tests that make sure it fails early
def test_nokey():
    with pytest.raises(Exception):
        server = SafePickling()
        server.pickle("data")

def test_notrustedkeys():
    with pytest.raises(Exception):
        client = SafePickling()
        client.unpickle("data")

def test_invaludkeylength():
    with pytest.raises(Exception):
        server = SafePickling()
        server.set_key(b"12345")


# -*- coding: utf-8 -*-
import math
import numpy as np
from numpy import linalg

def main():
    x, y, r = map(float, input().split())
    center = np.array([x, y])
    g_left_up_x, g_left_up_y = x - r, y - r
    g_len = 2 * r
    sin45 = math.sin(math.radians(45))
    cos45 = math.cos(math.radians(45))
    n_left_up_x = x - r * cos45
    n_left_up_y = y - r * sin45
    n_len = 2 * r * cos45

    x0 = g_left_up_x
    x1 = n_left_up_x
    x2 = n_left_up_x + n_len
    x3 = g_left_up_x + g_len
    y0 = g_left_up_y
    y1 = n_left_up_y
    y2 = n_left_up_y + n_len
    y3 = g_left_up_y + g_len
    ans_set = set()

    print(x0)
    print(x1)
    print(x2)
    print(x3)
    # exit()
    ans = (int(x3) - math.ceil(x2)) * \
        (int(y3) - math.ceil(y2))
    print(ans)
    for i_x in range(math.ceil(x0), int(x1) + 1):
        for i_y in range(math.ceil(y0), int(y3) + 1):
            if linalg.norm(np.array([i_x, i_y]) - center) <= r:
                # print(i_x)
                # print(i_y)
                # print('--------')
                ans_set.add((i_x, i_y))

    for i_x in range(math.ceil(x2), int(x3) + 1):
        for i_y in range(math.ceil(y0), int(y3) + 1):
            if linalg.norm(np.array([i_x, i_y]) - center) <= r:
                # print(i_x)
                # print(i_y)
                # print('--------')
                ans_set.add((i_x, i_y))

    for i_x in range(math.ceil(x1), int(x2) + 1):
        for i_y in range(math.ceil(y0), int(y1) + 1):
            if linalg.norm(np.array([i_x, i_y]) - center) <= r:
                # print(i_x)
                # print(i_y)
                # print('--------')
                ans_set.add((i_x, i_y))

    for i_x in range(math.ceil(x1), int(x2) + 1):
        for i_y in range(math.ceil(y2), int(y3) + 1):
            if linalg.norm(np.array([i_x, i_y]) - center) <= r:
                # print(i_x)
                # print(i_y)
                # print('--------')

                ans_set.add((i_x, i_y))

    print(ans + len(ans_set))

if __name__ == '__main__':
    main()


import pandas as pn
import sys
import numpy as np
import os
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import ticker
import datetime
from matplotlib.backends.backend_pdf import PdfPages

def plot_angle(fig, pdfdata, pndata, index, cmap, cmap_num):
    ax = fig.add_subplot(111)
    ax.plot('time', index, data=pndata, marker='x', lw=0.5, c=cmap(cmap_num))
    ax.set_title(index, fontsize=15)
    ax.set_xlim(np.array(pndata['time'])[0], np.array(pndata['time'])[-1])
    Minute_fmt = mdates.DateFormatter("%Y-%m-%d\n%H:%M:%S")
    ax.xaxis.set_major_formatter(Minute_fmt)
    ax.set_ylabel('(tanθ)')
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    pdfdata.savefig()
    fig.clf()
    cmap_num += 1
    return cmap_num

print(len(sys.argv))
if len(sys.argv) < 2:
    sys.exit('command line error, please input csv path')
path = sys.argv[1]
edit_path = path[:-4] + '_edit.csv'
pdf_path = path[:-4] + '.pdf'
print(path)
print(edit_path)
print(pdf_path)
if not os.path.exists(path):
    sys.exit('there are not tha path :{}'.format(path))
input = pn.read_csv(path)

input = input.drop(input.index[0:2])
input = input.drop(columns=['No.7', 'No.8'])
input = input.reset_index(drop=True)
print(len(input))
a = 0.2167
b = 0.5432
x1 = []
y1 = []
x2 = []
y2 = []
x3 = []
y3 = []
time_all = []

for i in range(0, len(input)):
    # print(input['No.1'][i])
    tan1 = a * float(input['No.1'][i]) - b
    tan2 = a * float(input['No.2'][i]) - b
    tan3 = a * float(input['No.3'][i]) - b
    tan4 = a * float(input['No.4'][i]) - b
    tan5 = a * float(input['No.5'][i]) - b
    tan6 = a * float(input['No.6'][i]) - b
    x1.append(-tan1)
    y1.append(-tan2)
    x2.append(tan3)
    y2.append(tan4)
    x3.append(tan6)
    y3.append(-tan5)
    time_all.append(datetime.datetime.strptime(input['Date/Time'][i], '%Y-%m-%d %H:%M:%S'))

input['time'] = time_all
input['x1'] = x1
input['y1'] = y1
input['x2'] = x2
input['y2'] = y2
input['x3'] = x3
input['y3'] = y3
input['x1-x2'] = np.array(x1) - np.array(x2)
input['y1-y2'] = np.array(y1) - np.array(y2)
input['x3-x2'] = np.array(x3) - np.array(x2)
input['y3-y2'] = np.array(y3) - np.array(y2)

input = input[:-5]

input.to_csv(edit_path, index=False)

fig = plt.figure(tight_layout=True)
cmap_num = 0
cmap = plt.get_cmap("tab10")
out_pdf = PdfPages(pdf_path)
for i in range(1, 4):
    cmap_num = plot_angle(fig, out_pdf, input, 'x{}'.format(i), cmap, cmap_num)
for i in range(1, 4):
    cmap_num = plot_angle(fig, out_pdf, input, 'y{}'.format(i), cmap, cmap_num)

cmap_num = plot_angle(fig, out_pdf, input, 'x1-x2', cmap, cmap_num)
cmap_num = plot_angle(fig, out_pdf, input, 'y1-y2', cmap, cmap_num)
cmap_num = plot_angle(fig, out_pdf, input, 'x3-x2', cmap, cmap_num)
cmap_num = plot_angle(fig, out_pdf, input, 'y3-y2', cmap, cmap_num)
out_pdf.close()


from django.test import Client, TestCase

class StaticURLTests(TestCase):
    def setUp(self):
        self.guest_client = Client()

    def test_about_url_exists_at_desired_location(self):
        """Проверка доступности адресов /author/ и /tech/."""
        pages = (
            '/about/author/',
            '/about/tech/'
        )
        for page in pages:
            with self.subTest(page=page):
                response = self.guest_client.get(page)
                self.assertEqual(response.status_code, 200)

    def test_about_url_uses_correct_template(self):
        """Проверка шаблонов для адресов /author/ и /tech/."""
        template_names = {
            'about/author.html': '/about/author/',
            'about/tech.html': '/about/tech/',
        }
        for template, url in template_names.items():
            with self.subTest(url=url):
                response = self.guest_client.get(url)
                self.assertTemplateUsed(response, template)


b=int(input("enter a number"))
a={1:"monday",2:"tuesday",3:"wednesday",4:"thursday",5:"friday",6:"saturday",7:"sunday"}
for i in a:
    if i==b:
        print(a.get(i))
        break
else:
    print("invalid")


__author__ = "Alejo Herrera"

# Cargar por teclado una frase, pero a razón de un caracter por vez en una variable. La frase debe terminar con un
# punto (al aparecer el punto, la carga debe finalizar). El programa debe informar

# a) Cuántas vocales existen en la frase

# b) Cuántas letras en total existen en la frase (no contar símbolos como comas, puntos y comas, números, etc).

# c) El porcentaje de vocales respecto al total de letras.

# Modulos
def puntoa(letra):
    contvocal = 0
    if letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra == "u":
        contvocal = 1
    return contvocal

def puntob(letra):
    contletra = 0
    if letra.isalpha():
        contletra = 1
    return contletra

# Programa principal

# Carga de variables
letra = ""
palabra = ""
contvocal = 0
contletra = 0

# Ciclo
while letra != ".":
    # Ingreso por teclado
    letra = input("Ingrese letra (Punto para finalizar): ")
    letra = letra.lower()
    palabra += letra
    # Punto a
    contvocal += puntoa(letra)
    # Punto b
    contletra += puntob(letra)

porcentajevocal = round((contvocal * 100 / contletra), 2)

# Imprimir resultados

print("Resultados")
print("-"*30)
print("La cantidad de vocales son: ", contvocal)
print("La cantidad de letras ingresadas fueron ", contletra)
print("El porcentaje es: %", porcentajevocal)

Guía de Ejercicios Practicos/Guia de Ejercicios Prácticos-Ficha 07/Ej13-Vocales y consonantes.py


#! python3
# Copies an entire folder and its cotents into a ZIP file whose filename increments on a Windows based machine

import zipfile
import os

def backup_to_zip(folder):

    # Backup entire contents of "folder" into a ZIP file.
    folder = os.path.abspath('D:\\Zippy_Folder') # make sure folder is absolute

    # Figure out the filename this code should use based on what file already exist.
    number = 1
    while True:
        zip_file_name = os.path.basename(folder) + '_' + str(number) + '.zip'
        if not os.path.exists(zip_file_name):
            break
        number = number + 1

    # Create the ZIP file.
    print(f'Creating {zip_file_name}...')
    backupZip = zipfile.ZipFile(zip_file_name, 'w')

        # Walk the entire folder tree and compress the files in each folder.
    for foldername, subfolders, filenames in os.walk(folder):
        print(f'Adding files in {foldername}...')
        # Add the current folder to the ZIP file.
        backupZip.write(foldername)
        # Add all the files in this folder to the ZIP file.
        for filename in filenames:
            newBase = os.path.basename(folder) + '_'
            if filename.startswith(newBase) and filename.endswith('.zip'):
                continue # don't back up the backup ZIP files
            backupZip.write(os.path.join(foldername, filename))
    backupZip.close()
    print('Done')

backup_to_zip('D:\\Zippy_Folder')


from flask import Flask
from flask_admin import Admin, AdminIndexView, BaseView
from flask_admin import expose
from flask_admin.menu import MenuLink

import stub

class DashoboardView(AdminIndexView):

    @expose('/')
    def index(self):
        self.name = 'Dashboard'
        self.messages = stub.get_messages_summary()
        self.tasks = stub.get_tasks()
        self.alerts = stub.get_alerts()
        return self.render('admin/dashboard.html')

class FlotChartsView(BaseView):
    @expose('/')
    def index(self):
        self.name = 'FlotCharts'
        return self.render('admin/flot_charts.html')

admin = Admin(template_mode='bootstrap3', index_view=DashoboardView(
    menu_icon_type='glyph', menu_icon_value='glyphicon-dashboard'))

admin.add_view(FlotChartsView(
    name='Flot Charts', category='Charts',
    menu_icon_type='fa', menu_icon_value='fa-bar-chart-o'))

# 以下 link 会向左靠齐
admin.add_link(MenuLink(name='Back Home', url='/admin', category='Links'))
admin.add_link(MenuLink(name='Flask-Demos',
                        url='https://github.com/AngelLiang/Flask-Demos',
                        category='Links'))
admin.add_link(MenuLink(
    name='Baidu', url='http://www.baidu.com/', category='Links'))
# 以下 link 会向右靠齐
# admin.add_link(MenuLink(name='Logout', url='#'))

app = Flask(__name__)
app.config['FLASK_ADMIN_FLUID_LAYOUT'] = True

@app.cli.command()
def build():
    """Build sb-admin-2 frontend"""
    import os
    import subprocess

    path = os.path.join(app.root_path, 'static', 'sb-admin-2')
    os.chdir(path)
    subprocess.call(['bower', 'install'], shell=True)

admin.init_app(app)

@app.route('/')
def index():
    return 'Click me to go to Admin!'

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


import json
import re
import requests
import os
from pathlib import Path

"""
Módulo de ingestión de datos.
-------------------------------------------------------------------------------

"""

url_path_raw = "https://raw.githubusercontent.com/jdvelasq/datalabs/master/datasets/precio_bolsa_nacional/xls/"
url_tree_repo = "https://api.github.com/repos/jdvelasq/datalabs/git/trees/master"
cwd = os.getcwd()

def get_tree_sha(files, folder):
    """ "
    funcion que retorna la url de la subcarpeta *folder* dentro del arreglo de diccionarios *files*
    >>> files = [{ 'path' : 'folder1' , 'url' : 'https://1.com' },{ 'path' : 'folder2' , 'url' : 'https://2.com' }]
    >>> get_tree_sha(files,"folder1")
    'https://1.com'
    """
    url = [file["url"] for file in files if file["path"] == folder][0]
    return str(url)

def guardar_data(url, path):
    """
    Funcion que descarga el archivo desde la *url* y guarda el contenido en
    el *path*
    """
    response = requests.get(url, allow_redirects=True)
    filename = Path(path)
    filename.write_bytes(response.content)

def get_file_list():
    """
    funcion que retorna arreglo con diccionarios de los archivos que se
    van a descargar del repo
    >>> get_file_list()[0]['path']
    '1995.xlsx'
    """

    folders = ["datasets", "precio_bolsa_nacional", "xls"]

    root_folder_tree = requests.get(url_tree_repo)

    folder_tree = root_folder_tree

    for folder in folders:

        f = get_tree_sha(folder_tree.json()["tree"], folder)
        folder_tree = requests.get(f)

    return folder_tree.json()["tree"]

def ingest_data():
    """Ingeste los datos externos a la capa landing del data lake.

    Del repositorio jdvelasq/datalabs/precio_bolsa_nacional/xls/ descarge los
    archivos de precios de bolsa nacional en formato xls a la capa landing. La
    descarga debe realizarse usando únicamente funciones de Python.

    """
    try:
        for archivo in get_file_list():
            url = url_path_raw + str(archivo["path"])
            path = os.path.join(cwd, "data_lake/landing/" + str(archivo["path"]))
            guardar_data(url, path)
    except:
        return False

if __name__ == "__main__":
    import doctest

    ingest_data()
    doctest.testmod()


from threading import Thread
import os
import time
from queue import Queue

global a
a = 0
#q.put(a)

mobile_counter_customer = []

clear = lambda: os. system('cls')
class Counter:
      def __init__(self,counter_id):
        self.counter_id = counter_id
        #self.length = 0
        self.queue = []
        self.OF = 0.0
        self.output = 0                 # number of cust exiting counter in interval of five minutes
        self.weightage = 0

class Customer:
  def __init__(self,customer_id):  #instance of the class counter
    self.customer_id = customer_id
    self.counter = 0

global total_counters
total_counters = []

global open_counters
open_counters = []   #array of counter class instances

global closed_counters
closed_counters = []  #array of counter class instances

global cutomer_list
customer_list = dict()

max_length = int(input("Enter maximum length for each counter:\n"))
num_counter = int(input("Enter number of counters:\n"))

threshold = max_length//2

counters= dict()  #key: value :: counter_name: counter_class

for i in range(num_counter):
    counter_num = "counter_%d" % (i+1)
    counters[counter_num] = Counter(i+1)
    closed_counters.append(counters[counter_num])

def Weightage(Counter_input):
    if len(Counter_input.queue) != 0:                                      # if counter has customers in it
        Counter_input.weightage = Counter_input.OF/(len(Counter_input.queue))
    else:                                                                  # if counter has no customers in it
        Counter_input.weightage = 0

def Entry(customer):
  if open_counters== []:                                                  # first customer condition
    open_counters.append(closed_counters.pop(0))
    open_counters[-1].queue.append(customer.customer_id)
    customer.counter = open_counters[-1].counter_id

    print("customer" + str(customer.customer_id) +  " is assigned to counter: " + str(open_counters[-1].counter_id))

  else:

    potential = -1
    c = 0                                                                                # to check later how many counters are above threshold
    for item in open_counters:

      if len(item.queue) < threshold:
        c = 1
        if(item.weightage>potential):
          potential = item.weightage                                                              # Finding that node that holds the largest weightage
          potential_data = item

    if c == 1:                                                                                # if there is a counter with less than threshold customers
      customer.counter = potential_data.counter_id                                                  # assign that counter to customer
      potential_data.queue.append(customer.customer_id)                                                         # add customer to that counter's queue
      print ("customer" + str(customer.customer_id) +  " is assigned to counter:", potential_data.counter_id)
      Weightage(potential_data)                                                                    # update weightage of that counter

    elif c==0:                                                                                # all open counters have reached threshold length
          if closed_counters!=[]:                                                                 # all open > threshold AND closed counters EXIST
                open_counters.append(closed_counters.pop(0))
                customer.counter = open_counters[-1].counter_id
                open_counters[-1].queue.append(customer.customer_id)                              # add customer to that counter's queue'
                print("customer" + str(customer.customer_id) + " is assigned to counter:", open_counters[-1].counter_id)
                Weightage(open_counters[-1])

          else:                                                                                # all open > threshold AND NO closed counters exist
                max_weightage_allOpen_allAboveThreshold = -1
                z = 0
                for i in open_counters:

                      #print(i.weightage)
                      if i.weightage > max_weightage_allOpen_allAboveThreshold and len(i.queue) < max_length:       # finding the counter with the largest weightage and counter is not full

                            z = 1
                            max_weightage_allOpen_allAboveThreshold = i.weightage
                            max_weightage_allOpen_allAboveThreshold_data = i

                if z==1:                                                                            # at least one counter which is not FULL
                      customer.counter = max_weightage_allOpen_allAboveThreshold_data.counter_id
                      max_weightage_allOpen_allAboveThreshold_data.queue.append(customer.customer_id)
                      print("customer" + str(customer.customer_id) +  " is assigned to counter:" , max_weightage_allOpen_allAboveThreshold_data.counter_id)
                      Weightage(max_weightage_allOpen_allAboveThreshold_data)
                else:                                                                               # all counters are open and full
                      print("OPEN MOBILE COUNTERS")
                      mobile_counter_customer.append(customer)
                      customer.counter = -1                                                         # -1 indicates mobile counters

  customer_list.update({customer.customer_id:[customer, customer.counter]})

def Exit(customer):
    counter_of_exit_id = customer.counter                                                   #find "id" of the counter from which customer exits
    if customer.customer_id == counters["counter_%d" % counter_of_exit_id].queue[0]:

      print("customer " , customer.customer_id,  "exited from counter ", counter_of_exit_id)

      counters["counter_%d" % counter_of_exit_id].queue.pop(0)                                       #remove customer from that counter's queue **************************
      customer.counter = 0                                                                          #remove customer: counter relationship

      if (len((counters["counter_%d" % counter_of_exit_id]).queue) == 0):
          closed_counters.append(open_counters.pop(open_counters.index(counters["counter_%d" % counter_of_exit_id])))

          closed_counters[-1].OF = 0

      else:

          counters["counter_%d" % counter_of_exit_id].output += 1

      customer_list.pop(customer.customer_id)
      Weightage(counters["counter_%d" % counter_of_exit_id])

    else:
          print("Invalid Exit\n\n")

def main(threadname,q):
    cont = 0

    while(cont==0):

        a = int(input("Enter \n 1.Entry \n 2.Exit \n 3.Exit Program \n"))
        if(a==1):
            b = int(input("Enter customer id:\n"))
            if b not in customer_list.keys():
              Entry(Customer(b))

            else:
              print("Customer", b, "already present in counter: ", customer_list[b][1])
        elif(a==2):
            b = int(input("Enter customer id:\n"))
            Exit(customer_list[b][0])
        elif(a==3):
            q.put(a)
            exit()
        for i in open_counters:
            #print("Counter:", i.counter_id, " has ", (i.queue))
            #print()
            """for i in closed_counters:
            print("Counter:", i.counter_id, " has ", (i.queue))
            print()"""
        #print(customer_list)
        print()
        for i, values in counters.items():

            print(i, ":", values.queue)

def os_of_calculator(threadname,q):

    while(True):
        a = q.get()
        if a==3:
            quit()

        time.sleep(5)

        for i in open_counters:
            i.OF = i.output / 2             # calculate OF for a every open counter
            i.output = 0
            #print(i.counter_id, i.OF)
            #print()

q=Queue()
abc = Thread(target = main,args=("thread1",q))

bcd = Thread(target = os_of_calculator,args=("thread2",q))

abc.start()
bcd.start()
abc.join()
bcd.join()
printf("added changes1")
printf("added changes ")


import os
import re
import RPi.GPIO as GPIO
#from Tkinter import *

while True:
    msg=os.popen('/usr/bin/nfc-poll').read()
    print(msg)

    buffers= msg.splitlines()
    #print buffers
    for buffer in buffers:
        if(buffer.find('NFCID1') != -1):
                rfid=re.sub(" ","",buffer.split(':',1)[1])
                msg=""
                buffer=""
                buffers=""
                break

    str_RFID = str(rfid)
    print(str_RFID)
    str_RFID=""


"""
Q15: Implement Dijkstra’s algorithm for a weighted graph data structure (you have to update
your previous data structure so that it can deal with weights).
"""
class node():
    def __init__(self, value):
        self.tentativeWeight = float("inf")
        g.addNode(int(value))
        self.value = value
        self.previous = 0

class graph():
    def __init__(self):
        self.nodes = [] #A list of nodes
        self.matrix = []
        for i in range(10):
            self.matrix.append([float("inf")] * 10) #Setting all nodes to infinity

        print("The basic matrix looks like:  \n")
        for i in range (len(self.matrix)):
            print(self.matrix[i])

        #related to searching
        self.depthVisited = []
        self.breadthVisited = []
        self.searchStack = []
        self.searchQueue = []

    def addNode(self, value):
        self.nodes.append(value)

    def addEdge(self, a, b, weight):
        self.matrix[a.value][b.value] = weight
        self.matrix[b.value][a.value] = weight

    def display(self):
        print("\n\nHere is the matrix with all of the edges added.\n")
        print("         0    1    2     3    4    5   6    7    8    9")
        for i in range (0, len(self.matrix)):
            print(i, "     ", self.matrix[i])

    def depthFirstSearch(self, node):
        self.searchStack.append(node) # add the current node onto the stack
        while self.searchStack: # when the stack is empty, all nodes have been visited
            node = self.searchStack.pop() # pop the node currently being viewed into node
            if node not in self.depthVisited: # if the node currently being viewed is not in the visited list
                with open("depthVisited.txt", "a") as file:
                    file.write(str(node))
                self.depthVisited.append(node) # add it to the visited list
                print("visited via depth first search so far:  ", self.depthVisited)

                for idx, value in enumerate(self.matrix[node]):
                    if value != float("inf"):
                        self.searchStack.append(idx)

        print("visited with depth first search:  ", self.depthVisited, "\n\n")
        return self.depthVisited

    def breadthFirstSearch(self, node):
        self.searchQueue.append(node)
        while self.searchQueue:
            node = self.searchQueue.pop(0)
            if node not in self.breadthVisited:
                self.breadthVisited.append(node)
                with open("breadthVisited.txt", "a") as file:
                    file.write(str(node))
                print("visited via breadth first search so far:  ", self.breadthVisited)
                for idx, value in enumerate(self.matrix[node]):
                    if value != float("inf"):
                        self.searchQueue.append(idx)

        print ("visited with breadth first search:  ", self.breadthVisited, "\n\n")
        return self.breadthVisited

    def dijkstra(self, currentNode, destNode, nodeList):
        currentNode.tentativeWeight = 0
        visited = []
        while currentNode != destNode: #not yet reached the destination
            for idx, value in enumerate(self.matrix[currentNode.value]):
                if value != float("inf"):
                    #if the current path taken is shorter than that of the new nodes weight
                    if currentNode.tentativeWeight + nodeList[idx].tentativeWeight < nodeList[idx].value:
                        nodeList[idx].tentativeWeight = currentNode.tentativeWeight + nodeList[idx].tentativeWeight
                        nodeList[idx].previous = currentNode
                        print(nodeList[idx], nodeList[idx].tentativeWeight)
            visited.append(currentNode)
            minimum = float("inf")
            for i in nodeList:
                if i == 0:
                    pass

                elif i not in visited and i.tentativeWeight <= minimum:
                    currentNode = i
                    minimum = i.tentativeWeight

        return visited

nodeList = [0]*10
print(nodeList)
g = graph()

nodeOne = node(1)
nodeList[1] = nodeOne
nodeTwo = node(2)
nodeList[2] = nodeTwo
nodeThree = node(3)
nodeList[3] = nodeThree
nodeFour = node(4)
nodeList[4] = nodeFour
nodeFive = node(5)
nodeList[5] = nodeFive
nodeSix = node(6)
nodeList[6] = nodeSix
nodeSeven = node(7)
nodeList[7] = nodeSeven

g.addEdge(nodeOne,nodeFour, 5)
g.addEdge(nodeOne,nodeTwo, 4)
g.addEdge(nodeTwo,nodeFour, 7)
g.addEdge(nodeOne,nodeFive, 2)
g.addEdge(nodeTwo,nodeThree, 1)
g.addEdge(nodeSeven,nodeFour, 3)
g.display()
print("\n")
with open ("depthVisited.txt", "w") as file:
    pass
g.depthFirstSearch(1)
with open ("breadthVisited.txt", "w") as file:
    pass
g.breadthFirstSearch(1)
x = g.dijkstra(nodeTwo,nodeFive,nodeList)

for i in x:
    print("Node ", i.value, "has tentative weight ", i.tentativeWeight)
for i in x:
    print("Path is ", i.previous)


import smtplib, re, ConfigParser
from datetime import datetime

class msging():
  phone_number = ''
  email = ''
  provider_handles = {
    'tmobile': 'tmomail.net'
  }
  config = ConfigParser.ConfigParser()

  def __init__(self, number=None, provider='tmobile'):
    if number:
      self.phone_number = number
      self.set_email(self.phone_number, provider)
    self.config.readfp(open('config.cfg'))

  def send_sms(self, msg):
    server = smtplib.SMTP()
    server.connect('smtp.gmail.com', 587)
    server.starttls()
    server.login(self.config.get('default','username'), self.config.get('default', 'password'))
    message = u'From: {0}\nTo: {1}\nSubject: {2}\nDate: {3}\n\n{4}'.format('maurop123@gmail.com', self.email, 'foobar', datetime.now(), msg)
    server.sendmail('maurop123@gmail.com',self.email,message)
    server.quit()

  def set_email(self, number, provider):
    self.email = '{0}@{1}'.format(re.sub(r'[^0-9]','',number), self.provider_handles[provider])


"""Windows-specific functions and variables for input_no_newline."""
import ctypes
from msvcrt import getwch  # pylint: disable=import-error, unused-import
from shared_stuff import ANSI

try:
    import colorama  # pylint: disable=import-error
except ImportError:
    kernel32 = ctypes.windll.kernel32
    # Enable ANSI support
    kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
else:
    colorama.init()

def get_clipboard_data():
    """Return string previously copied from Windows clipboard.

    Adapted from <http://stackoverflow.com/a/23285159/6379747>.
    """
    CF_TEXT = 1
    user32 = ctypes.windll.user32
    user32.OpenClipboard(0)
    try:
        if user32.IsClipboardFormatAvailable(CF_TEXT):
            data = user32.GetClipboardData(CF_TEXT)
            data_locked = kernel32.GlobalLock(data)
            text = ctypes.c_char_p(data_locked)
            kernel32.GlobalUnlock(data_locked)
    finally:
        user32.CloseClipboard()
    return text.value

def sigtstp():
    """Raise EOFError from Ctrl-Z since SIGTSTP doesn't exist."""
    raise EOFError

input_code = {
    **ANSI,
    'CSI': [['\xe0', '\x00'], ''],
    'up': 'H',
    'down': 'P',
    'right': 'M',
    'left': 'K',
    'end': 'O',
    'home': 'G',
    'backspace': '\b',
    'del': 'S',
    }


import pygame
import random

tutorial = [
"Welcome to disco snake. The classic snake game but with a twist",
"You can eat the bait if your snake is the same color as the bait.",
"Every time you eat the bait, the bait changes color. You can change ",
"the color of your snake if you collide with your snake's body. BUT it ",
"works only if your snake is a different color than the bait. You lose if ",
"your snake is the same color as the bait and you try to change color or ",
"you go out of bounds or you eat the bait while your snake has a different color",
"arrow keys to move, click left mouse button to play and again to initialize the snake",
"There's an issue which i'm hoping to fix, where the snake won't eat the bait every time",
]
# modifying these changes the screen size
rows = 100
cols = 100
# step is the size of an individual square
step = 10
# initial length of the snake
length = 20
# initial colors for the snake and the bait
snakecolor = (89, 212, 151)
baitcolor = (89, 212, 151)
# the colors a snake or a bait can inherit
colors = [
    (89, 212, 151),
    (89, 205, 212),
    (212, 89, 91),
    (212, 206, 89),

]
# ^   feel free to change
#/ \  or add to
# |   these values
# |

# of course it needs a score
score = 0

# starting up pygame
pygame.init()
# display size is tied to the number of rows and columns in the matrix (below)
DISPLAY_WIDTH = (rows + 2)*step
DISPLAY_HEIGHT = (cols + 2)*step
# setting the screen parameters
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
# screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT), pygame.RESIZABLE) -- see line 187
pygame.display.set_caption("disco snake")
fps = pygame.time.Clock()

# making an empty matrix or a grid with the size of cols*rows in which the snake can move
basegrid = [0] * rows           # 0 0 0 0  --> (times cols)
for i in range(rows):           # 0 0 0 0
    basegrid[i] = [0] * cols    # 0 0 0 0   |
# print(basegrid)                           v  (times rows)

snakehead = 0
# this holds the links of the snake
rectlist = []
# initial location of the bait, a random location on the screen, with the size of 'step'
bait = (random.randrange(step, DISPLAY_WIDTH-step, step), random.randrange(step, DISPLAY_HEIGHT-step, step),  step, step)
# the directions the snake can travel in
direction = ""
dirs = ["LEFT", "RIGHT", "UP", "DOWN"]

# populating the coordinate system
y_coord = step
x_coord = step
for i in basegrid:
    x_coord = step
    for x in range(len(basegrid[0])):                                       #   for example with a step of 25:
        basegrid[basegrid.index(i)][x] = str(x_coord) + "," + str(y_coord)  # [0, 0] [25, 0] [50, 0]   --> (times cols)
        x_coord += step                                                     # [0,25] [25,25] [50,25]
    y_coord += step                                                         # [0,50] [25,50] [50,50]    |
                                                                            #                           v  (times rows)

# making a 1px wide grid dependent on the coordinate system, for testing purposes
def grid(mt):
    for i in mt:
        for x in range(len(mt[0])):
            p = mt[mt.index(i)][x]
            p = p.split(",")
            pygame.draw.rect(screen, (255, 0, 0), (int(p[0]), int(p[1]), step, step), 1)

# click -> start the snake in the selected square
def drawsquare(mt1):
    global snakehead
    global rectlist
    global direction
    global dirs
    z, y = pygame.mouse.get_pos() # stores the mouse x, y coords in a tuple eg 467, 332
    print(z, y)                   # for testing
    for i in mt1:
        for x in range(len(mt1[0])):
            p = mt1[mt1.index(i)][x]
            p = p.split(",")    # eg [450, 300] gets split into '450' and '300', therefore:
            p[0] = int(p[0])    # p[0] = 450
            p[1] = int(p[1])    # p[1] = 300
            if p[0] < z < (p[0] + step) and p[1] < y < (p[1] + step):   # checks if the mouse coords are in any square eg with the previous example 'if 450 < 467 < 500 and 300 < 332 < 350':
                snakehead = pygame.Rect(p[0], p[1], step, step)         # it draws the snake's head
                direction = random.choice(dirs) # snake starts to move in a random direction
                print(int(p[0]), int(p[1]))     # just for testing
                rectlist.append(snakehead)      # see below, line 217

# moving the snake
def movesquare():
    global snakehead
    global rectlist
    global direction
    keys = pygame.key.get_pressed()
    # basic controls
    if keys[pygame.K_LEFT] and direction != "RIGHT": # the snake can't change direction to right if its moving left etc
        print("K_LEFT")
        snakehead = pygame.Rect.move(snakehead, -step, 0) # moves the snake along the x and/or y axis
        rectlist.append(snakehead)  # see belowm line 217
        direction = "LEFT"

    if keys[pygame.K_RIGHT] and direction != "LEFT":
        print("K_RIGHT")
        snakehead = pygame.Rect.move(snakehead, step, 0)
        rectlist.append(snakehead)
        direction = "RIGHT"

    if keys[pygame.K_UP] and direction != "DOWN":
        print("K_UP")
        snakehead = pygame.Rect.move(snakehead, 0, -step)
        rectlist.append(snakehead)
        direction = "UP"

    if keys[pygame.K_DOWN] and direction != "UP":
        print("K_DOWN")
        snakehead = pygame.Rect.move(snakehead, 0, step)
        rectlist.append(snakehead)
        direction = "DOWN"

# spawning the bait
def spawn():
    global bait
    global baitcolor
    x = random.randrange(step, DISPLAY_WIDTH-step, step)
    y = random.randrange(step, DISPLAY_HEIGHT-step, step)
    bait = pygame.Rect((x), (y), step, step)
    baitcolor = random.choice(colors)

# drawing the initial bait
pygame.draw.rect(screen, (random.choice(colors)), (bait), 0, -1)

# basically these loops continue until thing X happens
endloop = False
gameloop = False

# creates the main screen
while endloop is False:
    screen.fill((0, 0, 0))
    myfont = pygame.font.SysFont("Britannic Bold", 20)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        if event.type== pygame.MOUSEBUTTONDOWN:
            endloop = True # if you click LMB, the main menu loop ends
            gameloop = True # and the game begins
    y_text = DISPLAY_HEIGHT/6
    for i in tutorial:                                  # renders the
        line = myfont.render(str(i), 1, (255, 0, 0))    # tutorial text
        screen.blit(line,(DISPLAY_WIDTH/8,y_text))      # as seen above
        y_text = y_text + 30
    pygame.display.flip()

# the main gameloop
while gameloop is True:
    screen.fill((0,0,0))
    #grid(basegrid)  -- un-# if you wanna see the grid
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit() # if you press X it closes the game
        elif event.type == pygame.MOUSEBUTTONDOWN:
            drawsquare(basegrid) # press LMB to initialise the snake
        elif event.type == pygame.KEYDOWN:
            movesquare() # if you press a key, the program checks if the snake changes the direction as a result

    #DISPLAY_WIDTH, DISPLAY_HEIGHT = pygame.display.get_surface().get_size() -- for testing purposes only, you can resize the screen and it would add more cols rows, but it doesn't really work well
    #cols = sqrt(DISPLAY_WIDTH)
    #rows = sqrt(DISPLAY_HEIGHT)
    #step = (DISPLAY_WIDTH//cols + DISPLAY_HEIGHT//rows)/2

    # snake is moving based on the direction
    if direction == "LEFT":
        snakehead = pygame.Rect.move(snakehead, -step, 0)
        rectlist.append(snakehead)
        direction = "LEFT"

    if direction == "RIGHT":
        snakehead = pygame.Rect.move(snakehead, step, 0)
        rectlist.append(snakehead)
        direction = "RIGHT"

    if direction == "UP":
        snakehead = pygame.Rect.move(snakehead, 0, -step)
        rectlist.append(snakehead)
        direction = "UP"

    if direction == "DOWN":
        snakehead = pygame.Rect.move(snakehead, 0, step)
        rectlist.append(snakehead)
        direction = "DOWN"
    scorefont = pygame.font.SysFont("Britannic Bold", 20)
    scoretext = scorefont.render('score: ' + str(score), 1, (255, 0, 0)) # renders the score
    screen.blit(scoretext, (20, 20))
    pygame.draw.rect(screen, baitcolor, (bait), 0, -1)

    for i in rectlist[::-1]:                        # so basically the snake is a list of rect objects like these: <rect(330, 540, 10, 10)>
        pygame.draw.rect(screen, snakecolor, i)     # the list keeps changing all the time, adding new rects and deleting prior ones
                                                    # so at all times theres 'length' amount of rects, which the programs draws onto the screen
                                                    # rectlist[-1] is the last rect added to the list, so the snake's head, like so: [0(tail)] [1] [2] [3] [4] [5(head)]
                                                    # because every time the snake moves, it appends the last rect to the list depending on the direction

    if len(rectlist) > 0 and rectlist[-1] == bait:  # if the snake head == bait, the snake eats the bait
        if snakecolor == baitcolor:                 # only on the condition that their RGB values are the same...
            print(bait) # testing
            spawn() # create a new bait
            length += 1 # enlongen the snake
            score += 5

        elif snakecolor != baitcolor:               # ...but if their RGB values are different,
            pygame.quit()                           # the program quits

    for i in rectlist:
        if len(rectlist) > length:  # if the snake gets added a new value [0(tail)] [1] [2] [3] [4] [5(head)] [6(newhead)] because the snake is continuously moving and adding to the list, the tail bit needs to get chopped off
            rectlist.pop(0)         # without this line for example, the snake would get infinitely long. this line removes the tail or the  rectlist[0] in the list

    try:
        if rectlist[-1].left < 0 or rectlist[-1].right > DISPLAY_WIDTH or rectlist[-1].top < 0 or rectlist[-1].bottom > DISPLAY_HEIGHT: # if the snake moves out of bounds,
            pygame.quit()                                                                                # the program quits
    except:
        pass

    for i in rectlist:                                                      # the color changing algorithm
        testlist = rectlist[:]                                              # creates a new list identical to the snake's list

        try:                                                                # can only do it when there's enough elements in the list
            testlist.remove(i)                                              # it removes 'i' from testlist and
            for x in testlist[testlist.index(i):]:                          # compares it to the testlist (so i isn't in testlist) because if i wasn't removed, it would always be on the list and the program would not work as intended
                if i == x and rectlist[-1] == i:                            # if i overlaps x (meaning if any 2 rects overlap meaning if the snake touches itself) and if rectlist[-1] (snake's head) touches 'i' --> meaning any other part in the snake's body
                    if snakecolor != baitcolor:                             # and if you can change the color - meaning if the snake has a different color than the bait (it wouldn't be fun if you could endlessly change colors)
                        newcolors = [x for x in colors if x != snakecolor]  # then it creates a new list excluding the color the snake already has, so the snake wouldn't get the same color
                        snakecolor1 = random.choice(newcolors)              # randomly picks a new color
                    elif snakecolor == baitcolor:                           # as i said,
                        pygame.quit()                                       # it wouldn't be fun if you could endlessly change colors
                if i == x:                                                  # if 2 rects (parts of the snake) overlap,
                    for x in testlist[testlist.index(i):]:                  # then it takes the list from the overlapping point to the end (front part of the snake) [tail] [don't draw] [don't draw] [don't draw] [overlaps] [draw] [draw] [draw] [snake's head]
                        pygame.draw.rect(screen, snakecolor1, x)            # and draws every square, basically overrinding the line 217 command for drawing the snake
            if i == rectlist[0]:                                            # if there aren't any more overlapping rects,
                snakecolor = snakecolor1                                    # set a new color. without this line, the snake would start moving with a new color, but as soon as no rects overlap, it would turn to the previous color
        except:
            pass

    pygame.display.update() # updates the display
    fps.tick(20)            # 20 times per second. fps is tied to the snake's speed, because every time the screen updates, the snake moves 1 instance, so changing this accelerates/decelerates the snake in a way


import re
import math

class DmsFormatError(Exception):
    pass

def meters_per_user_unit(units):

    if   units == 'meters': return 1.0
    elif units == 'sft':    return 12.0 / 39.37
    elif units == 'int_ft': return 0.0254 * 12.0
    elif units == 'chains': return 66.0 * 12.0 / 39.37
    else:
        raise ValueError('Bad units: \'{0}\''.format(units))

def user_units_per_meter(units):
    return 1.0 / meters_per_user_unit(units)

def dms_radians(dms):
    """ Convert degrees-minutes and degrees-minutes-seconds string to radians.
    """

    dms = dms.strip()
    if len(dms) == 0:
        raise DmsFormatError('Empty dms string.')

    if dms[0] == '-':
        sign = -1.0
        v = dms[1:].split('-')
    else:
        sign = 1.0
        v = dms.split('-')

    if len(v) > 3:
        raise DmsFormatError('s=%s' % dms)

    if v[0].isdigit():
        degrees = float(v[0])
    else:
        raise DmsFormatError('s=%s' % dms)

    minutes = 0.0
    if len(v) > 1:
        if re.match('^\d{1,2}$', v[1]):
            minutes = float(v[1])
        else:
            raise DmsFormatError('s=%s' % dms)

    seconds = 0.0
    if len(v) > 2:
        if re.match('^\d{1,2}(\.\d+)?$', v[2]):
            seconds = float(v[2])
        else:
            raise DmsFormatError('s=%s' % dms)

    if not (minutes < 60.0 and seconds < 60.0):
        raise DmsFormatError('s=%s' % dms)

    return math.radians(sign * (degrees + minutes/60.0 + seconds/3600.0))

if __name__ == "__main__":

    pass


import hashlib
import random
import socket
import threading
import time
from keep_alive import keep_alive

keep_alive()

class MoneroSoloMiner:
    def __init__(self, wallet_address, host, port):
        self.wallet_address = wallet_address
        self.host = host
        self.port = port

        self.nonces = set()
        self.found_blocks = 0

        self.threads = 1

    def mine(self):
        while True:
            nonce = random.randint(0, 2**32)

            if nonce not in self.nonces:
                hash = hashlib.sha256(nonce.to_bytes(32, byteorder="big")).hexdigest()

                if hash.startswith("0000000000000000000000000000000000000000000000000000000000000000"):
                    block_header = hashlib.sha256(hash.encode()).hexdigest()
                    block_data = "0000000000000000000000000000000000000000000000000000000000000000"
                    block = block_header + block_data

                    connection = socket.create_connection((self.host, self.port))
                    connection.sendall(block.encode())
                    connection.close()

                    self.found_blocks += 1
                    print("Found a block!")
                    break

            else:
                self.nonces.add(nonce)

    def start(self):
        while True:
            t = threading.Thread(target=self.mine)
            t.daemon = True
            t.start()

            if self.found_blocks > 0:
                break

        print("Exiting...")

def main():
    wallet_address = "42uESmGzAFqjhuDaVby5S12cxnHSo2NMoWQxUcXgJqYKbj6NkupFJxUZkxrYt6oatsAnnzkFuHPH5GhmaVJt2b4H8LXreY1"
    host = "localhost"
    port = 18080

    miner = MoneroSoloMiner(wallet_address, host, port)
    miner.start()

    while True:
        command = input("Enter command: ")

        if command == "stop":
            # Verander de `if`-voorwaarde in `and`
            if self.found_blocks > 0 and command == "stop":
                miner.stop()
                break

if __name__ == "__main__":
    main()


from collections import deque

def bfs(n, arr, queue):
    i = j = 0
    queue.append([arr[i][j], i, j])
    arr[i][j] = -2
    while queue:
        jump = queue.popleft()
        if jump[0] == -1:
            print("HaruHaru")
            return
        i,j = jump[1], jump[2]
        if i + jump[0] < n:
            if arr[i + jump[0]][j] != -2:
                queue.append([arr[i + jump[0]][j], jump[0] + i, j])
                arr[i + jump[0]][j] = -2
        if j + jump[0] < n:
            if arr[i][j + jump[0]] != -2:
                queue.append([arr[i][j + jump[0]], i, jump[0] + j])
                arr[i][j + jump[0]] = -2
    print("Hing")
    return

n = int(input())
arr = [list(map(int, input().split())) for _ in range(n)]
queue = deque()

bfs(n, arr, queue)

백준/Silver/16173. 점프왕 쩰리 （Small）/점프왕 쩰리 （Small）.py

점프왕 쩰리 （Small）.py


import os
import shutil

fromDir = "C:/Users/JOY/OneDrive/Desktop/PDF"

toDir = "C:/Users/JOY/OneDrive/Desktop/School"

list_of_files= os.listdir(fromDir)
#print(list_of_files)

for file_name in list_of_files:
   # print(file_name)

   name,extension = os.path.splitext(file_name)
#    print(name)
#    print(extension)
   if (extension == ""):
        continue
   if extension in ['.pdf','.doc','.txt']:

        path1=fromDir+'/'+file_name

        path2 = toDir+'/'+"newDocFolder"

        path3= toDir+'/'+"newDocFolder"+"/"+file_name

        if os.path.exists(path2):
            print("moving files....")
            shutil.move(path1,path3)

        else:
            os.makedirs(path2)
            print("moving files....")
            shutil.move(path1,path3)


#----------------------------------------------------------------------------
# Created By  : Sayak Mukherjee
# Created Date: 09-May-2023
#
# ---------------------------------------------------------------------------
# Contains the main driver code for pretraining
# ---------------------------------------------------------------------------

import os
import click
import torch
import pytorch_lightning as pl

from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import ModelCheckpoint
from omegaconf import OmegaConf
from pathlib import Path
from datasets import get_dataset
from models import get_model
from optim import get_methods

@click.command()
@click.option('--exp_config', type=click.Path(exists=True), default=None,
              help='Configuration file for the experiment (default: None).')
@click.option('--chkpt_path', type=click.Path(exists=True), default=None,
              help='Configuration file for the experiment (default: None).')
def main(exp_config, chkpt_path):

    # Load defaults and overwrite by command-line arguments
    config = OmegaConf.load(Path(exp_config))
    # cmd_config = OmegaConf.from_cli()
    # config = OmegaConf.merge(config, cmd_config)
    print(OmegaConf.to_yaml(config))

    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Using device: {device}")

    # Seed everything. Note that this does not make training entirely
    # deterministic.
    pl.seed_everything(config.seed, workers=True)

    wandb_path = Path(config.wandb.dir)
    if not Path.exists(wandb_path):
        Path.mkdir(wandb_path, exist_ok=True, parents=True)

    # Set cache dir to W&B logging directory
    os.environ["WANDB_CACHE_DIR"] = wandb_path.as_posix()
    wandb_logger = WandbLogger(
        save_dir=wandb_path,
        project=config.wandb.project,
        name=config.wandb.experiment_name + '_pretrain',

        # log_model='all' if config.wandb.log else None,
        offline=not config.wandb.log,

        # Keyword args passed to wandb.init()
        entity=config.wandb.entity,
        config=OmegaConf.to_object(config),
    )

    # Create datasets and loaders
    dataset = get_dataset(config.dataset.name)(config=config)

    pretrain_dataset_loader = dataset.get_pretrain_loader()

    # Create model
    model = get_model(config.train.model)(config)

    # Pre-training method
    method = get_methods(config.train.method)(config, model)

    checkpoint_callback = ModelCheckpoint(
        dirpath= Path(config.train.save_dir),
        every_n_epochs=10,
        filename= config.wandb.experiment_name + '-pretrain-{epoch:02d}')

    trainer = pl.Trainer(
        max_epochs=config.train.epochs,
        logger=wandb_logger,
        # Use DDP training by default, even for CPU training
        strategy="ddp",
        gpus=torch.cuda.device_count(),
        callbacks=[checkpoint_callback]
    )

    # Train + validate (if validation dataset is implemented)
    if chkpt_path is not None:
        trainer.fit(model=method, train_dataloaders=pretrain_dataset_loader, ckpt_path=chkpt_path)
    else:
        trainer.fit(model=method, train_dataloaders=pretrain_dataset_loader)

    if not Path.exists(Path('../pretrained_models')):
        Path.mkdir(Path('../pretrained_models'))

    export_path = Path('../pretrained_models').joinpath(config.wandb.experiment_name + '.pth')
    torch.save({'net_dict': model.state_dict()}, export_path)

if __name__ == '__main__':
    main()


'''
Enables program variables to be adjusted with keyboard while program is running

Must define variables, starting values, key associated with variable, and return all variables

v1 09.02.2021
Tom Zimmerman CCC, IBM Research March 2020
This work is funded by the National Science Foundation (NSF) grant No. DBI-1548297, Center for Cellular Construction.
Disclaimer:  Any opinions, findings and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the National Science Foundation.
'''

import numpy as np
import cv2

keypad=['t','b','x','y']    # define what key character is associated with variable
keyValue=[76,2,4,6]         # define starting value
stepValue=[1,2,1,1]         # define scaling of value, i.e., how much variable changes with each key increment.... not implimented yet in V1
keyState=0;                 # the current selected key
keyBuf=np.zeros((256),dtype=int)    # where are the key values are stored (before scaling)
run=1                       # set to 0 if 'q' is hit, to end program

# initialize key buffer with starting values
for i in range(len(keypad)):
    keyBuf[ord(keypad[i])]=keyValue[i]

def processKey():
    global keyState,run;

    key=cv2.waitKey(500) # value is delay in milliseconds to slow down video, must be > 0
    if key!=-1:
        keyList=[ord('='),ord('-'),ord('+'),ord('_')]
        value=[1,-1,+10,-10]
        inc=0
        if key in keyList:
            index=keyList.index(key)
            inc=value[keyList.index(key)]
            keyBuf[keyState]+=inc
            if keyBuf[keyState]<0:
                keyBuf[keyState]=0
        else:
            keyState=key
        print (chr(keyState),'=',keyBuf[keyState])

        # update variables
        for i in range(len(keypad)):
            keyValue[i]=keyBuf[ord(keypad[i])]

        # check to see if user wants to quit program by pressing 'q' key
        if key==(ord('q')):
            run=0           # variable program checks to see if user wants to quit program
    return(keyValue)        # return all the variable values, must be received in the proper order!


from datetime import datetime

import icalendar
import pytz
from babel.dates import get_timezone
from sqlalchemy import Date, Time, or_
from sqlalchemy.sql import cast
from werkzeug.datastructures import MultiDict, OrderedMultiDict

from indico.core.config import config
from indico.core.db import db
from indico.core.errors import IndicoError
from indico.modules.auth import Identity
from indico.modules.rb.models.locations import Location
from indico.modules.rb.models.reservations import ConflictingOccurrences, RepeatFrequency, RepeatMapping, Reservation
from indico.modules.rb.models.rooms import Room
from indico.modules.rb.util import rb_check_user_access
from indico.modules.users import User
from indico.util.date_time import utc_to_server
from indico.web.http_api import HTTPAPIHook
from indico.web.http_api.metadata import ical
from indico.web.http_api.responses import HTTPAPIError
from indico.web.http_api.util import get_query_parameter

class RoomBookingHookBase(HTTPAPIHook):
    GUEST_ALLOWED = False

    def _getParams(self):
        super()._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        self._occurrences = _yesno(get_query_parameter(self._queryParams, ['occ', 'occurrences'], 'no'))

    def _has_access(self, user):
        return config.ENABLE_ROOMBOOKING and rb_check_user_access(user)

@HTTPAPIHook.register
class RoomHook(RoomBookingHookBase):
    # e.g. /export/room/CERN/23.json
    TYPES = ('room',)
    RE = r'(?P<location>[\w\s]+)/(?P<idlist>\w+(?:-[\w\s]+)*)'
    DEFAULT_DETAIL = 'rooms'
    MAX_RECORDS = {
        'rooms': 500,
        'reservations': 100
    }
    VALID_FORMATS = ('json', 'jsonp', 'xml')

    def _getParams(self):
        super()._getParams()
        self._location = self._pathParams['location']
        self._ids = list(map(int, self._pathParams['idlist'].split('-')))
        if self._detail not in {'rooms', 'reservations'}:
            raise HTTPAPIError('Invalid detail level: %s' % self._detail, 400)

    def export_room(self, user):
        loc = Location.query.filter_by(name=self._location, is_deleted=False).first()
        if loc is None:
            return

        # Retrieve rooms
        rooms_data = list(Room.get_with_data(filters=[Room.id.in_(self._ids), Room.location_id == loc.id]))

        # Retrieve reservations
        reservations = None
        if self._detail == 'reservations':
            reservations = OrderedMultiDict(_export_reservations(self, True, False, [
                Reservation.room_id.in_(x['room'].id for x in rooms_data)
            ]))

        for result in rooms_data:
            yield _serializable_room(result, reservations)

@HTTPAPIHook.register
class RoomNameHook(RoomBookingHookBase):
    # e.g. /export/roomName/CERN/pump.json
    GUEST_ALLOWED = True
    TYPES = ('roomName', )
    RE = r'(?P<location>[\w\s]+)/(?P<room_name>[\w\s/\-]+)'
    DEFAULT_DETAIL = 'rooms'
    MAX_RECORDS = {
        'rooms': 500
    }
    VALID_FORMATS = ('json', 'jsonp', 'xml')

    def _getParams(self):
        super()._getParams()
        self._location = self._pathParams['location']
        self._room_name = self._pathParams['room_name']

    def _has_access(self, user):
        # Access to RB data (no reservations) is public
        return config.ENABLE_ROOMBOOKING

    def export_roomName(self, user):
        loc = Location.query.filter_by(name=self._location, is_deleted=False).first()
        if loc is None:
            return

        search_str = f'%{self._room_name}%'
        rooms_data = Room.get_with_data(
            filters=[
                Room.location_id == loc.id,
                or_(Room.name.ilike(search_str),
                    Room.verbose_name.ilike(search_str))
            ])

        for result in rooms_data:
            yield _serializable_room(result)

@HTTPAPIHook.register
class ReservationHook(RoomBookingHookBase):
    # e.g. /export/reservation/CERN.json
    TYPES = ('reservation', )
    RE = r'(?P<loclist>[\w\s]+(?:-[\w\s]+)*)'
    DEFAULT_DETAIL = 'reservations'
    MAX_RECORDS = {
        'reservations': 100
    }
    VALID_FORMATS = ('json', 'jsonp', 'xml', 'ics')

    @property
    def serializer_args(self):
        return {'ical_serializer': _ical_serialize_reservation}

    def _getParams(self):
        super()._getParams()
        self._locations = self._pathParams['loclist'].split('-')

    def export_reservation(self, user):
        locations = Location.query.filter(Location.name.in_(self._locations), ~Location.is_deleted).all()
        if not locations:
            return

        for room_id, reservation in _export_reservations(self, False, True):
            yield reservation

@HTTPAPIHook.register
class BookRoomHook(HTTPAPIHook):
    PREFIX = 'api'
    TYPES = ('roomBooking',)
    RE = r'bookRoom'
    GUEST_ALLOWED = False
    VALID_FORMATS = ('json', 'xml')
    COMMIT = True
    HTTP_POST = True

    def _getParams(self):
        super()._getParams()
        self._fromDT = utc_to_server(self._fromDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._fromDT else None
        self._toDT = utc_to_server(self._toDT.astimezone(pytz.utc)).replace(tzinfo=None) if self._toDT else None
        if not self._fromDT or not self._toDT or self._fromDT.date() != self._toDT.date():
            raise HTTPAPIError('from/to must be on the same day')
        elif self._fromDT >= self._toDT:
            raise HTTPAPIError('to must be after from')
        elif self._fromDT < datetime.now():
            raise HTTPAPIError('You cannot make bookings in the past')

        username = get_query_parameter(self._queryParams, 'username')
        if not username:
            raise HTTPAPIError('No username provided')
        users = User.query.join(User.identities).filter(~User.is_deleted, Identity.identifier == username).all()
        if not users:
            raise HTTPAPIError('Username does not exist')
        elif len(users) != 1:
            raise HTTPAPIError(f'Ambiguous username ({len(users)} users found)')
        user = users[0]

        self._params = {
            'room_id': get_query_parameter(self._queryParams, 'roomid'),
            'reason': get_query_parameter(self._queryParams, 'reason'),
            'booked_for': user,
            'from': self._fromDT,
            'to': self._toDT
        }
        missing = [key for key, val in self._params.items() if not val]
        if missing:
            raise HTTPAPIError('Required params missing: {}'.format(', '.join(missing)))
        self._room = Room.get(self._params['room_id'])
        if not self._room:
            raise HTTPAPIError('A room with this ID does not exist')

    def _has_access(self, user):
        if not config.ENABLE_ROOMBOOKING or not rb_check_user_access(user):
            return False
        if self._room.can_book(user):
            return True
        elif self._room.can_prebook(user):
            raise HTTPAPIError('The API only supports direct bookings but this room only allows pre-bookings.')
        return False

    def api_roomBooking(self, user):
        data = MultiDict({
            'start_dt': self._params['from'],
            'end_dt': self._params['to'],
            'repeat_frequency': RepeatFrequency.NEVER,
            'repeat_interval': 0,
            'room_id': self._room.id,
            'booked_for_user': self._params['booked_for'],
            'booking_reason': self._params['reason']
        })
        try:
            reservation = Reservation.create_from_data(self._room, data, user)
        except ConflictingOccurrences:
            raise HTTPAPIError('Failed to create the booking due to conflicts with other bookings')
        except IndicoError as e:
            raise HTTPAPIError(f'Failed to create the booking: {e}')
        db.session.add(reservation)
        db.session.flush()
        return {'reservationID': reservation.id}

def _export_reservations(hook, limit_per_room, include_rooms, extra_filters=None):
    """Export reservations.

    :param hook: The HTTPAPIHook instance
    :param limit_per_room: Should the limit/offset be applied per room
    :param include_rooms: Should reservations include room information
    """
    filters = list(extra_filters) if extra_filters else []
    if hook._fromDT and hook._toDT:
        filters.append(cast(Reservation.start_dt, Date) <= hook._toDT.date())
        filters.append(cast(Reservation.end_dt, Date) >= hook._fromDT.date())
        filters.append(cast(Reservation.start_dt, Time) <= hook._toDT.time())
        filters.append(cast(Reservation.end_dt, Time) >= hook._fromDT.time())
    elif hook._toDT:
        filters.append(cast(Reservation.end_dt, Date) <= hook._toDT.date())
        filters.append(cast(Reservation.end_dt, Time) <= hook._toDT.time())
    elif hook._fromDT:
        filters.append(cast(Reservation.start_dt, Date) >= hook._fromDT.date())
        filters.append(cast(Reservation.start_dt, Time) >= hook._fromDT.time())
    filters += _get_reservation_state_filter(hook._queryParams)
    occurs = [datetime.strptime(x, '%Y-%m-%d').date()
              for x in [_f for _f in get_query_parameter(hook._queryParams, ['occurs'], '').split(',') if _f]]
    data = []
    if hook._occurrences:
        data.append('occurrences')
    order = {
        'start': Reservation.start_dt,
        'end': Reservation.end_dt
    }.get(hook._orderBy, Reservation.start_dt)
    if hook._descending:
        order = order.desc()
    reservations_data = Reservation.get_with_data(*data, filters=filters, limit=hook._limit, offset=hook._offset,
                                                  order=order, limit_per_room=limit_per_room, occurs_on=occurs)
    for result in reservations_data:
        yield result['reservation'].room_id, _serializable_reservation(result, include_rooms)

def _serializable_room(room_data, reservations=None):
    """Serializable room data.

    :param room_data: Room data
    :param reservations: MultiDict mapping for room id => reservations
    """
    from indico.modules.rb.schemas import RoomLegacyAPISchema
    data = RoomLegacyAPISchema().dump(room_data['room'])
    data['_type'] = 'Room'
    if reservations is not None:
        data['reservations'] = reservations.getlist(room_data['room'].id)
    return data

def _serializable_room_minimal(room):
    """Serializable minimal room data (inside reservations).

    :param room: A `Room`
    """
    from indico.modules.rb.schemas import RoomLegacyMinimalAPISchema
    data = RoomLegacyMinimalAPISchema().dump(room)
    data['_type'] = 'Room'
    return data

def _serializable_reservation(reservation_data, include_room=False):
    """Serializable reservation (standalone or inside room).

    :param reservation_data: Reservation data
    :param include_room: Include minimal room information
    """
    from indico.modules.rb.schemas import ReservationLegacyAPISchema, ReservationOccurrenceLegacyAPISchema
    reservation = reservation_data['reservation']
    data = ReservationLegacyAPISchema().dump(reservation)
    data['_type'] = 'Reservation'
    data['repeatability'] = None
    if reservation.repeat_frequency:
        data['repeatability'] = RepeatMapping.get_short_name(*reservation.repetition)
    if include_room:
        data['room'] = _serializable_room_minimal(reservation_data['reservation'].room)
    if 'occurrences' in reservation_data:
        data['occurrences'] = ReservationOccurrenceLegacyAPISchema(many=True).dump(reservation_data['occurrences'])
    return data

def _ical_serialize_repeatability(data):
    start_dt_utc = data['startDT'].astimezone(pytz.utc)
    end_dt_utc = data['endDT'].astimezone(pytz.utc)
    week_days = 'MO TU WE TH FR SA SU'.split()
    recur = ical.vRecur()
    recur['until'] = end_dt_utc
    if data['repeat_frequency'] == RepeatFrequency.DAY:
        recur['freq'] = 'daily'
    elif data['repeat_frequency'] == RepeatFrequency.WEEK:
        recur['freq'] = 'weekly'
        recur['interval'] = data['repeat_interval']
    elif data['repeat_frequency'] == RepeatFrequency.MONTH:
        recur['freq'] = 'monthly'
        recur['byday'] = f'{start_dt_utc.day // 7}{week_days[start_dt_utc.weekday()]}'
    return recur

def _ical_serialize_reservation(cal, data, now):
    start_dt_utc = data['startDT'].astimezone(pytz.utc)
    end_dt_utc = datetime.combine(data['startDT'].date(), data['endDT'].timetz()).astimezone(pytz.utc)

    event = icalendar.Event()
    event.add('uid', 'indico-resv-%s@cern.ch' % data['id'])
    event.add('dtstamp', now)
    event.add('dtstart', start_dt_utc)
    event.add('dtend', end_dt_utc)
    event.add('url', data['bookingUrl'])
    event.add('summary', data['reason'])
    event.add('location', '{}: {}'.format(data['location'], data['room']['fullName']))
    event.add('description', data['reason'] + '\n\n' + data['bookingUrl'])
    if data['repeat_frequency'] != RepeatFrequency.NEVER:
        event.add('rrule', _ical_serialize_repeatability(data))
    cal.add_component(event)

def _add_server_tz(dt):
    if dt.tzinfo is None:
        return dt.replace(tzinfo=get_timezone(config.DEFAULT_TIMEZONE))
    return dt

def _yesno(value):
    return value.lower() in {'yes', 'y', '1', 'true'}

def _get_reservation_state_filter(params):
    cancelled = get_query_parameter(params, ['cxl', 'cancelled'])
    rejected = get_query_parameter(params, ['rej', 'rejected'])
    confirmed = get_query_parameter(params, ['confirmed'])
    archived = get_query_parameter(params, ['arch', 'archived', 'archival'])
    repeating = get_query_parameter(params, ['rec', 'recurring', 'rep', 'repeating'])
    booked_for = get_query_parameter(params, ['bf', 'bookedfor'])

    filters = []
    if cancelled is not None:
        filters.append(Reservation.is_cancelled == _yesno(cancelled))
    if rejected is not None:
        filters.append(Reservation.is_rejected == _yesno(rejected))
    if confirmed is not None:
        if confirmed == 'pending':
            filters.append(Reservation.is_pending)
        elif _yesno(confirmed):
            filters.append(Reservation.is_accepted)
        else:
            filters.append(~Reservation.is_accepted)
            filters.append(Reservation.is_rejected | Reservation.is_cancelled)
    if archived is not None:
        filters.append(Reservation.is_archived == _yesno(archived))
    if repeating is not None:
        if _yesno(repeating):
            filters.append(Reservation.repeat_frequency != 0)
        else:
            filters.append(Reservation.repeat_frequency == 0)
    if booked_for:
        like_str = '%{}%'.format(booked_for.replace('?', '_').replace('*', '%'))
        filters.append(Reservation.booked_for_name.ilike(like_str))
    return filters


import cv2
import matplotlib.pyplot as plt
import math
import numpy as np

#統計每個強度有多少pixels
def hist_unnormalized(img_ravel, L):
    hist_unnormalized = [0]*L

    for i in range(len(img_ravel)):
        hist_unnormalized[img_ravel[i]] = hist_unnormalized[img_ravel[i]] + 1

    return hist_unnormalized

#統計每個強度佔圖片多少比例
def hist_normalized(img_ravel, L, img_size):

    hist_img = hist_unnormalized(img_ravel, L)

    hist_img_normalized = [0]*L

    for i in range(len(hist_img)):
        hist_img_normalized[i] = hist_img[i] / (img_size[0]*img_size[1])

    return hist_img_normalized

#找到新的圖案標準
def intensities_new(img_ravel, L, img_size):

    hist_img_normalized = hist_normalized(img_ravel, L, img_size)

    #將比例累加
    intensity_new = [0]*L
    for i in range(L):
        if i == 0:
            intensity_new[i] = hist_img_normalized[i]

        else:
            intensity_new[i] = intensity_new[i-1] + hist_img_normalized[i]
    #將比例累加

    for i in range(L):
        intensity_new[i] = round(intensity_new[i]*(L-1))

    #print("intensity_new[L-1] : {}".format(intensity_new[L-1]))
    return intensity_new

def intensities_mean(img_ravel, L, img_size):
    hist_img_normalized = hist_normalized(img_ravel, L, img_size)

    intensity_mean = 0
    for i in range(len(hist_img_normalized)):
        intensity_mean = intensity_mean + (i*hist_img_normalized[i])

    return intensity_mean

def intensities_standard(img_ravel, L, img_size):
    hist_img_normalized = hist_normalized(img_ravel, L, img_size)
    intensity_mean = intensities_mean(img_ravel, L, img_size)

    intensity_standard = 0
    for i in range(len(hist_img_normalized)):
        diff_temp = i - intensity_mean
        intensity_standard = intensity_standard + math.pow(diff_temp, 2)*hist_img_normalized[i]

    return intensity_standard

def part_of_img(img, size_range, i_now, j_now):
    size_part = (size_range*2) + 1
    temp_img_oneArray = [0]*size_part*size_part
    temp_img = np.array(temp_img_oneArray).reshape(size_part, size_part)  #宣告二維矩陣

    x = y = 0
    for i in range(i_now - size_range, i_now + size_range + 1):
        for j in range(j_now - size_range, j_now + size_range + 1):
            temp_img[x][y] = img[i][j]
            y = y+1

        x = x+1
        y = 0

    temp_img_ravel = temp_img.ravel()
    return temp_img_ravel

#HW3_2_1
img = cv2.imread("hidden object.jpg", cv2.IMREAD_GRAYSCALE)  #以灰階的形式讀取

L = int(math.pow(2, 8))
hist_img = hist_unnormalized(img.ravel(), L)

img_size = img.shape

#周圍補零
img_3_oneArray = [0]*( (img_size[0]+2) * (img_size[1]+2))
img_3 = np.array(img_3_oneArray).reshape(img_size[0]+2, img_size[1]+2)

for i in range(img_size[0]):
    for j in range(img_size[1]):
        img_3[i+1][j+1] = img[i][j]

img_3_size = img_3.shape
#周圍補零

#Local enhancement
size_range = 1
size_part = (size_range*2) + 1
size_temp_img = [size_part]*2
print("size_temp_img : {}".format(size_temp_img))
img_2_oneArray = [0]*img_size[0]*img_size[1]
img_2 = np.array(img_2_oneArray).reshape(img_size[0], img_size[1])  #Local enhancement的img
for i in range(1, img_3_size[0]-1):  # i = 1 ~ 654
    for j in range(1, img_3_size[1]-1):  # j = 1 ~ 651
        temp_img_oneArray = part_of_img(img_3, size_range, i, j)  #取圖像的局部
        intensity_new_temp = intensities_new(temp_img_oneArray, L, size_temp_img)  #找新的強度

        temp_img_2_oneArray = [0]*size_part*size_part
        for k in range(len(temp_img_oneArray)):
            temp_img_2_oneArray[k] = intensity_new_temp[ temp_img_oneArray[k] ]

        temp_img_2 = np.array(temp_img_2_oneArray).reshape(size_part, size_part)

        img_2[i-1][j-1] = temp_img_2[size_range][size_range]
#Local enhancement

plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(img, cmap = 'gray')
plt.title("ORIGINAL")
plt.subplot(1, 2, 2)
plt.title("LOCAL_ENHANCE")
plt.imshow(img_2, cmap = 'gray')

#Histogram Statistics
m_G = intensities_mean(img.ravel(), L, img_size)
sigma_G = math.pow(intensities_standard(img.ravel(), L, img_size), 0.5)
print("m_G : {}, sigma_G : {}".format(m_G, sigma_G))

img_4_oneArray = [0]*img_size[0]*img_size[1]
img_4 = np.array(img_4_oneArray).reshape(img_size[0], img_size[1])  #statistic的method
print("img_size : {}".format(img_size))
print("img_3_size : {}".format(img_3_size))
C = 22.8
k_0 = 0; k_1 = 0.25; k_2 = 0; k_3 = 0.1
for i in range(1, img_3_size[0]-1):  # i = 1 ~ 654
    for j in range(1, img_3_size[1]-1):  # j = 1 ~ 651
        temp_img = part_of_img(img_3, size_range, i, j)
        m_xy = intensities_mean(temp_img, L, size_temp_img)
        sigma_xy = math.pow(intensities_standard(temp_img, L, size_temp_img), 0.5)

        #print("i : {}, j : {}".format(i, j))
        if(k_0*m_G <= m_xy and m_xy <= k_1*m_G):
            if(k_2*sigma_G <= sigma_xy and sigma_xy <= k_3*sigma_G):
                img_4[i-1][j-1] = C*img_3[i][j]

            else:
                img_4[i-1][j-1] = img_3[i][j]

        else:
            img_4[i-1][j-1] = img_3[i][j]

plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(img, cmap = 'gray')
plt.title("ORIGINAL")
plt.subplot(1, 2, 2)
plt.title("HISTOGRAM_STATISTICS")
plt.imshow(img_4, cmap = 'gray', vmin = 0, vmax = 255)
#Histogram Statistics

plt.show()


triangle = [[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]]

LT = len(triangle)
arr = [[0] * a for a in range(1, LT+1)]
arr[0][0] = triangle[0][0]
for i in range(LT-1):
    for j in range(i+1):
        left = arr[i][j] + triangle[i+1][j]
        right = arr[i][j] + triangle[i+1][j+1]
        if arr[i+1][j] < left:
            arr[i+1][j] = left
        if arr[i+1][j+1] < right:
            arr[i+1][j+1] = right
print(max(arr[LT-1]))


import didactic_meme as model_suite

class Config(model_suite.Config):
    def default_values(self):
        return dict(
            learning_rate=1e-2,
            n_epochs=10,
            momentum=0.5,
            cuda=True,
            batch_size=64,
            eval_batch_size=1000,
            seed=123,
            log_interval=100,
        )


import random
import googlesearch
import requests
from requests.api import get
from bs4 import BeautifulSoup
import pandas as pd
import ssl
from html_cleaner import cleanhtml

ssl._create_default_https_context = ssl._create_unverified_context

def search_engine_result(query):
    '''
    input: query = give your question to the tool

    process:
        * search google for the given query
        * remove blacklistet webpages

    return: google results without blacklistet webpages
    '''

    # add some websites which you don't want to see in your analysis
    blacklist = ['wikipedia', 'youtube']

    # result list of links to webpages
    links = []
    results=googlesearch.search(query, lang='de')
    results=[x for x in results if "http" in x]
    # get google search engine results with given parameters
    for link in results:
        # cick the blacklistet webpages
        if not [string for string in blacklist if(string in link)]:
            links.append(link)

    # pick random five webpages for further crawling
    return links

def get_page_content(url):
    '''
    input: url = give the required url

    process:
        * webpage is parsed by BeautifulSoup
        * get Title of Webpage
        * get amount of
 Tags in page
        * append all
 tags

    return: webpage title and all
 Tag content
    '''

    # Request webpage from WWW with request package
    page = requests.get(url)

    # getting the different html content parsed by BeautifulSoup
    soup = BeautifulSoup(page.content, 'html.parser')

    # get title of Webpage
    title = soup.title.text

    # get amount of
 elements in html file
    tags = soup.findAll('p')

    # add all
 elements into list
    content = ''
    for i in range(len(tags)):
        content = content + '' + str(soup.select('p')[i].text.strip()) # delete all leading and tailing whitespaces from string with .strip()

    # return title and content of given webpage
    return cleanhtml(title), cleanhtml(content)

def get_work_done(question):
    '''
    input: question = something you want to know from the web

    process:
        * search google for your question
        * get their title and content
        * sort content by length

    return: dataframe with = |title|content|url|
    '''

    articles = pd.DataFrame(columns = ['Title', 'Content', 'URL', 'content_length'])
    urls = search_engine_result(question)
    for url in urls:
        title, content = get_page_content(url)  # get title and content of webpage
        content_length = len(content)           # sort by content length
        content = content[:1000] + ' ...'       # truncate content to 500 digits
        articles.loc[len(articles)] = [title, content, url.rstrip('/'), content_length]

    articles.sort_values(by=['content_length'], ascending=False, inplace=True)  # sort length ascending
    articles.drop(['content_length'], axis=1, inplace=True)                     # delete help column content_length

    articles['URL'] = '' + articles['URL'] + ''

    return articles


import time

from __function.default import *
from __function.music import *
from __function.weather import *

from __configure.mubby_value import RESPONSE_FILE_NAME
from __utils.socket_module import SocketAction

def action_thread(client_info=None):
    socket_action = SocketAction(client_info)

    if client_info:
        try:
            # 01. STT Streaming
            header, language = understand_func(client_info, socket_action)
            print("header >> {}\nlanguage >> {}".format(header, language))
        except Exception as e:
            print('\t★ default function error >> {}'.format(e))

        try:
            # 02. What should the server do?
            # Aibril 의 header.command 를 이용하여 어떤 동작을 할 것인지 정한다.

            if header['command'] == "chat":
                # tts 에 다녀온다.
                response_func(client_info)

            elif header['command'] == "weather":
                # aibril 과 대화를 한 번 더 하고 tts 에 다녀온다.
                output_audio_path = weather_func()

            elif header['command'] == "music":
                # (현재) tts 에 다녀오고 파일을 합치고 나서 반환한다.
                # ps. 클라이언트와 상의해보고 동작방법을 바꿔야 할 수도 있다.
                output_audio_path = music_func()
            else:
                print("기본 음성 들어가게 해야하는데ㅔㅔㅔㅔㅔ")
                # 잘못된 접근이라는 것을 알려주어야 한다.

        except Exception as e:
            print('\t★ 함수명 function error >> {}'.format(e))

        try:
            # < The server sent data to client_info >
            # 음성 파일을 돌려주어야 한다. (확인)
            # output_audio_path = "__user_audio/"+sock.getpeername()[0] + "/output_tts.wav"
            print("out_audio_path >> {}".format(client_info['folder_path'] + RESPONSE_FILE_NAME))
            socket_action.sending_wav(RESPONSE_FILE_NAME)
        except Exception as e:
            print('\t★ __send function error >> {}'.format(e))

        if socket_action.closing():
            client_info['request_socket_from_client'] = ''

    else:
        print('info가 선언이 안될 수 있나 지금 상황에.. 몰라.. 일단.. 뭐.. 안되면.. 생각해보자..')

    print("Thread end")


from django.shortcuts import render, redirect
from django.views import View
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse

from .models import Vacancy

# Create your views here.
class VacancyListView(View):
    def get(self, request, *args, **kwargs):
        vacancies = Vacancy.objects.all()
        context = {"vacancies": vacancies}
        return render(request, "vacancy/index.html", context=context)

class CreateVacancyView(View):
    def get(self, request):
        return render(request, "vacancy/create.html")

    def post(self, request):
        if request.user.is_authenticated and request.user.is_staff:
            description = request.POST.get("description")
            author = request.user
            Vacancy.objects.create(description=description, author=author)
            return redirect("/home")
        else:
            return HttpResponse(status=403)


from collections import defaultdict
import numpy as np
from scipy import sparse
from scipy import stats
from scipy.ndimage import gaussian_filter
from peakachu.utils import image_normalize, distance_normalize, calculate_expected
#from statsmodels.sandbox.stats.multicomp import multipletests

class Chromosome():
    def __init__(self, M, model, raw_M=None, weights=None,
        lower=6, upper=300, cname='chrm', res=10000, width=5):

        lower = max(lower, width+1)
        upper = min(upper, M.shape[0]-2*width)
        # calculate expected values
        if weights is None:
            self.exp_arr = calculate_expected(M, upper+2*width, raw=True)
            if M is raw_M:
                self.background = self.exp_arr
            else:
                self.background = calculate_expected(raw_M, upper+2*width, raw=True)
        else:
            self.exp_arr = calculate_expected(M, upper+2*width, raw=False)
            self.background = self.exp_arr

        self.raw_M = raw_M
        self.weights = weights

        # lower down the memory usage
        R, C = M.nonzero()
        validmask = np.isfinite(M.data) & (C-R > (-2*width)) & (C-R < (upper+2*width))
        R, C, data = R[validmask], C[validmask], M.data[validmask]
        self.M = sparse.csr_matrix((data, (R, C)), shape=M.shape)
        self.get_candidate(lower, upper)
        self.chromname = cname
        self.r = res
        self.w = width
        self.model = model

    def get_candidate(self, lower, upper):

        x_arr = np.array([], dtype=int)
        y_arr = np.array([], dtype=int)
        p_arr = np.array([], dtype=float)
        idx = np.arange(self.raw_M.shape[0])
        for i in range(lower, upper+1):
            diag = self.raw_M.diagonal(i)
            e = self.background[i]
            if (diag.size > 0) and (e > 0):
                xi = idx[:-i]
                yi = idx[i:]
                if self.weights is None:
                    exp = np.ones(diag.size, dtype=float) * e
                else:
                    b1 = self.weights[:-i]
                    b2 = self.weights[i:]
                    exp = np.ones(diag.size, dtype=float) * e / (b1 * b2)

                Poiss = stats.poisson(exp)
                pvalues = Poiss.sf(diag)
                mask = (diag > 0) & np.isfinite(pvalues)
                x_arr = np.r_[x_arr, xi[mask]]
                y_arr = np.r_[y_arr, yi[mask]]
                p_arr = np.r_[p_arr, pvalues[mask]]

        #qvalues = multipletests(p_arr, method = 'fdr_bh')[1]
        mask = p_arr < 0.01
        self.ridx, self.cidx = x_arr[mask], y_arr[mask]

    def getwindow(self, coords):

        w = self.w
        coords = np.r_[coords]
        xi, yi = coords[:,0], coords[:,1]
        mask = (xi - w >= 0) & (yi + w + 1 <= self.M.shape[0])
        xi, yi = xi[mask], yi[mask]
        seed = np.arange(-w, w+1)
        delta = np.tile(seed, (seed.size, 1))
        xxx = xi.reshape((xi.size, 1, 1)) + delta.T
        yyy = yi.reshape((yi.size, 1, 1)) + delta
        v = np.array(self.M[xxx.ravel(), yyy.ravel()]).ravel()
        vvv = v.reshape((xi.size, seed.size, seed.size))
        windows, clist = distance_normalize(vvv, self.exp_arr, xi, yi, w)
        fea = []
        for arr in windows:
            tmp = gaussian_filter(arr, sigma=1, order=0)
            scaled_arr = image_normalize(tmp)
            fea.append(scaled_arr.ravel())

        fea = np.r_[fea]
        clist = np.r_[clist]

        return fea, clist

    def score(self, thre=0.5):

        print('scoring matrix {}'.format(self.chromname))
        print('number of candidates {}'.format(self.ridx.size))
        total_coords = [(r, c) for r, c in zip(self.ridx, self.cidx)]
        ri = np.r_[[]]
        ci = np.r_[[]]
        prob_pool = np.r_[[]]
        # to lower down the memory usage
        batch_size = 100000
        for t in range(0, len(total_coords), batch_size):
            coords = total_coords[t:t+batch_size]
            fea, clist = self.getwindow(coords)
            if fea.shape[0] > 1:
                p = self.model.predict_proba(fea)[:, 1]
                pfilter = p > thre
                ri = np.r_[ri, clist[:, 0][pfilter]]
                ci = np.r_[ci, clist[:, 1][pfilter]]
                prob_pool = np.r_[prob_pool, p[pfilter]]
        ri = ri.astype(int)
        ci = ci.astype(int)

        result = sparse.csr_matrix((prob_pool, (ri, ci)), shape=self.M.shape)
        if ri.size > 0:
            data = np.array(self.M[ri, ci]).ravel()
            self.M = sparse.csr_matrix((data, (ri, ci)), shape=self.M.shape)
        else:
            self.M = result

        return result, self.M

    def writeBed(self, outfil, prob_csr, raw_csr):

        with open(outfil, 'a') as out:
            r, c = prob_csr.nonzero()
            for i in range(r.size):
                line = [self.chromname, r[i]*self.r, (r[i]+1)*self.r,
                        self.chromname, c[i]*self.r, (c[i]+1)*self.r,
                        prob_csr[r[i],c[i]], raw_csr[r[i],c[i]]]
                out.write('\t'.join(list(map(str, line)))+'\n')


'''
Import dependencies
'''
import os
import warnings
import time
import numpy as np
import random
from glob import glob
from PIL import Image
import matplotlib.pyplot as plt

from keras.initializers import TruncatedNormal
from keras.layers import Activation, BatchNormalization, Conv2D, Conv2DTranspose, Dense, Flatten, Input, LeakyReLU, Reshape
from keras.models import Model
from keras.optimizers import Adam
#
warnings.filterwarnings("ignore")

'''
Hyperparameters
'''
IMAGE_SIZE = 64
NOISE_SIZE = 100
LR_D = 0.00004
LR_G = 0.0004
BATCH_SIZE = 64
EPOCHS = 50
BETA1 = 0.5
WEIGHT_INIT_STDDEV = 0.02
EPSILON = 0.00005
SAMPLES_TO_SHOW = 5

'''
GAN
'''
def generator_model(z=(NOISE_SIZE,)):
    # Input Layer [100]
    input_layer=Input(z)
    # Fully connected layer [100 -> 4x4x1024]
    fully_connected = Dense(4*4*1024) (input_layer)
    fully_connected = Reshape((4, 4, 1024)) (fully_connected)
    # Default alpha of keras is 0.3;
    # Default alpha of tf is 0.2;
    # For consistency with original code, alpha defined as 0.2
    fully_connected = LeakyReLU(alpha=0.2) (fully_connected)

    # Convolutional Layer 1 [4x4x1024 -> 8x8x512]
    trans_conv1 = Conv2DTranspose(filters=512,
    			   			      kernel_size=[5,5],
	    					      strides=[2,2],
    						      padding="same",
    						      kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (fully_connected)
    batch_trans_conv1 = BatchNormalization(epsilon=EPSILON) (trans_conv1)
    trans_conv1_out = LeakyReLU(alpha=0.2) (batch_trans_conv1)

    # Convolutional Layer 2 [8x8x512 -> 16x16x256]
    trans_conv2 = Conv2DTranspose(filters=256,
    						  	  kernel_size=[5,5],
	    					  	  strides=[2,2],
    						  	  padding="same",
    						  	  kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (trans_conv1_out)
    batch_trans_conv2 = BatchNormalization(epsilon=EPSILON) (trans_conv2)
    trans_conv2_out = LeakyReLU(alpha=0.2) (batch_trans_conv2)

    # Convolutional Layer 3 [16x16x256 -> 32x32x128]
    trans_conv3 = Conv2DTranspose(filters=128,
    						  	  kernel_size=[5,5],
	    					  	  strides=[2,2],
    						  	  padding="same",
    						  	  kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (trans_conv2_out)
    batch_trans_conv3 = BatchNormalization(epsilon=EPSILON) (trans_conv3)
    trans_conv3_out = LeakyReLU(alpha=0.2) (batch_trans_conv3)

    # Convolutional Layer 4 [32x32x128 -> 64x64x64]
    trans_conv4 = Conv2DTranspose(filters=64,
    						  	  kernel_size=[5,5],
	    					  	  strides=[2,2],
    						  	  padding="same",
    						  	  kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (trans_conv3_out)
    batch_trans_conv4 = BatchNormalization(epsilon=EPSILON) (trans_conv4)
    trans_conv4_out = LeakyReLU(alpha=0.2) (batch_trans_conv4)

    # Output layer [64x64x64 -> 64x64x3]
    logits = Conv2DTranspose(filters=3,
    						 kernel_size=[5,5],
	    					 strides=[1,1],
    						 padding="same",
    						 kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (trans_conv4_out)
    out = Activation('tanh') (logits)

    #
    model = Model(inputs=input_layer, outputs=out)
    model.summary()
    return model

def discriminator_model(input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)):
    # Input Layer [64x64x3]
    input_layer = Input(input_shape)

	# Convolutional Layer 1 [64x64x3 -> 32x32x64]
    conv1 = Conv2D(filters=64,
				   kernel_size=[5,5],
				   strides=[2,2],
				   padding="same",
    			   kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (input_layer)
    batch_norm1 = BatchNormalization(epsilon=EPSILON) (conv1)
    conv1_out = LeakyReLU(alpha=0.2) (batch_norm1)

	# Convolutional Layer 2 [32x32x64 -> 16x16x128]
    conv2 = Conv2D(filters=128,
				   kernel_size=[5,5],
				   strides=[2,2],
				   padding="same",
    			   kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (conv1_out)
    batch_norm2 = BatchNormalization(epsilon=EPSILON) (conv2)
    conv2_out = LeakyReLU(alpha=0.2) (batch_norm2)

	# Convolutional Layer 3 [16x16x128 -> 8x8x256]
    conv3 = Conv2D(filters=256,
				   kernel_size=[5,5],
				   strides=[2,2],
				   padding="same",
    			   kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (conv2_out)
    batch_norm3 = BatchNormalization(epsilon=EPSILON) (conv3)
    conv3_out = LeakyReLU(alpha=0.2) (batch_norm3)

	# Convolutional Layer 4 [8x8x256 -> 8x8x512]
    conv4 = Conv2D(filters=512,
				   kernel_size=[5,5],
				   strides=[1,1],
				   padding="same",
    			   kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (conv3_out)
    batch_norm4 = BatchNormalization(epsilon=EPSILON) (conv4)
    conv4_out = LeakyReLU(alpha=0.2) (batch_norm4)

	# Convolutional Layer 5 [8x8x512 -> 4x4x1024]
    conv5 = Conv2D(filters=1024,
				   kernel_size=[5,5],
				   strides=[2,2],
				   padding="same",
    			   kernel_initializer=TruncatedNormal(stddev=WEIGHT_INIT_STDDEV)) (conv4_out)
    batch_norm5 = BatchNormalization(epsilon=EPSILON) (conv5)
    conv5_out = LeakyReLU(alpha=0.2) (batch_norm5)

    # Flattened Convolutional Filter Output Layer [4x4x1024 -> 16384] ###?#?#?#?#??#
    flatten = Flatten() (conv5_out)

    # Fully connected layer [16384 -> 1]
    out = Dense(1, activation='sigmoid') (flatten)

    # ??????
    model = Model(inputs=input_layer, outputs=out)
    model.summary()
    return model

# Discriminator
discriminator = discriminator_model((IMAGE_SIZE, IMAGE_SIZE, 3))
discriminator.compile(loss='binary_crossentropy',optimizer=Adam(lr=LR_D, beta_1=BETA1),metrics=['accuracy'])
discriminator.trainable = False

# Generator
generator = generator_model((NOISE_SIZE,))

# GAN
gan_input = Input(shape=(NOISE_SIZE,))
x = generator(gan_input)
gan_out = discriminator(x)
gan = Model(gan_input, gan_out)
gan.summary()

gan.compile(loss='binary_crossentropy',optimizer=Adam(lr=LR_G, beta_1=BETA1))

'''
PLOT SAMPLE IMAGES
'''
def show_samples(sample_images, name, epoch):
    figure, axes = plt.subplots(1, len(sample_images), figsize = (IMAGE_SIZE, IMAGE_SIZE))
    for index, axis in enumerate(axes):
        axis.axis('off')
        image_array = sample_images[index]
        axis.imshow(image_array)
        image = Image.fromarray(image_array)
        image.save(name+"_"+str(epoch)+"_"+str(index)+".png")
    plt.savefig(name+"_"+str(epoch)+".png", bbox_inches='tight', pad_inches=0)
    plt.show()
    plt.close()

'''

'''
def test(input_z, epoch, OUTPUT_DIR):
    samples = generator.predict(input_z[:SAMPLES_TO_SHOW])
    sample_images = [((sample + 1.0) * 127.5).astype(np.uint8) for sample in samples]
    show_samples(sample_images, OUTPUT_DIR + "samples", epoch)

def summarize_epoch(d_losses, g_losses , data_shape, epoch, duration, input_z, OUTPUT_DIR):
    minibatch_size = int(data_shape[0]//BATCH_SIZE)
    print("Epoch {}/{}".format(epoch, EPOCHS),
          "\nDuration: {:.5f}".format(duration),
          "\nD Loss: {:.5f}".format(np.mean(d_losses[-minibatch_size:])),
          "\nG Loss: {:.5f}".format(np.mean(g_losses[-minibatch_size:])))
    fig, ax = plt.subplots()
    plt.plot(d_losses, label='Discriminator', alpha=0.6)
    plt.plot(g_losses, label='Generator', alpha=0.6)
    plt.title("Losses")
    plt.legend()
    plt.savefig(OUTPUT_DIR + "losses_" + str(epoch) + ".png")
    plt.show()
    plt.close()
    test(input_z, epoch, OUTPUT_DIR)

def get_batches(data):
    batches = []
    for i in range(int(data.shape[0]//BATCH_SIZE)):
        batch = data[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]
        augmented_images = []
        for img in batch:
            image = Image.fromarray(img)
            if random.choice([True, False]):
                image = image.transpose(Image.FLIP_LEFT_RIGHT)
            augmented_images.append(np.asarray(image))
        batch = np.asarray(augmented_images)
        normalized_batch = (batch / 127.5) - 1.0
        batches.append(normalized_batch)
    return np.array(batches)

# Training
def train():
    '''
LOAD DATA
'''
    INPUT_DATA_DIR = "./simpsons-faces/cropped/" # Path to the folder with input images. For more info check simspons_dataset.txt
    OUTPUT_DIR = './model/'
    if not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)

    # Training
    # Import Data
    exclude_img = ["9746","9731","9717","9684","9637","9641","9642","9584","9541","9535",
    "9250","9251","9252","9043","8593","8584","8052","8051","8008","7957",
    "7958""7761","7762","9510","9307","4848","4791","4785","4465","2709",
    "7724","7715","7309","7064","7011","6961","6962","6963","6960","6949",
    "6662","6496","6409","6411","6406","6407","6170","6171","6172","5617",
    "4363","4232","4086","4047","3894","3889","3493","3393","3362","2780",
    "2710","2707","2708","2711","2712","2309","2056","1943","1760","1743",
    "1702","1281","1272","772","736","737","691","684","314","242","191"]
    exclude_img = [s + ".png" for s in exclude_img]
    input_images = np.asarray([np.asarray(Image.open(file).resize((IMAGE_SIZE, IMAGE_SIZE))) for file in glob(INPUT_DATA_DIR + '*') if file not in exclude_img])
    print ("Image Samples\nInput: " + str(input_images.shape))
    np.random.shuffle(input_images)

    print("Training Starts!")
    # Load weights from last completed epoch if they exists
    discriminator_weights = glob('discriminator_simpson_weights.h5_*')
    gan_weights = glob('generator_simpson_weights.h5_*')
    if discriminator_weights:
        discriminator_weights.sort()
        discriminator.load_model(discriminator_weights[-1])
    if gan_weights:
        gan_weights.sort()
        gan.load_model(gan_weights[-1])

    d_losses = []
    g_losses = []
    cum_d_loss = 0
    cum_g_loss = 0

    #EPOCHS = 50
    for epoch in range(EPOCHS):
        epoch += 1
        start_time = time.time()
        for batch_images in get_batches(input_images):
            noise_data = np.random.normal(0, 1, size=(BATCH_SIZE, NOISE_SIZE))

            # We use same labels for generated images as in the real training batch
            generated_images = generator.predict(noise_data)

            # Prepare real target labels
            noise_prop = 0.05 # Randomly flip 5% of targets
            real_labels = np.zeros((BATCH_SIZE, 1)) + np.random.uniform(low=0.0, high=0.1, size=(BATCH_SIZE, 1))
            flipped_idx = np.random.choice(np.arange(len(real_labels)), size=int(noise_prop*len(real_labels)))
            real_labels[flipped_idx] = 1 - real_labels[flipped_idx]

            # Train discriminator on real data
            d_loss_real = discriminator.train_on_batch(batch_images, real_labels)

            # Prepare labels for generated data
            fake_labels = np.ones((BATCH_SIZE, 1)) - np.random.uniform(low=0.0, high=0.1, size=(BATCH_SIZE, 1))
            flipped_idx = np.random.choice(np.arange(len(fake_labels)), size=int(noise_prop*len(fake_labels)))
            fake_labels[flipped_idx] = 1 - fake_labels[flipped_idx]

            # Train discriminator on generated data
            d_loss_fake = discriminator.train_on_batch(generated_images, fake_labels)
            d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
            cum_d_loss += d_loss
            d_losses.append(d_loss[0])

            # Train generator
            noise_data = np.random.normal(0, 1, size=(BATCH_SIZE, NOISE_SIZE))
            g_loss = gan.train_on_batch(noise_data, np.zeros((BATCH_SIZE, 1)))
            cum_g_loss += g_loss
            g_losses.append(g_loss)

        if epoch > 0 and epoch % 5 == 0 :
            print("saving model")
            discriminator.save_weights(OUTPUT_DIR + "discriminator_simpson_weights.h5_" + str(epoch))
            gan.save_weights(OUTPUT_DIR + "gan_simpson_model.h5_" + str(epoch))
            summarize_epoch(d_losses, g_losses, input_images.shape, epoch, time.time()-start_time, noise_data, OUTPUT_DIR)

train()