'''
This holds the file where we're going to dump the dictionary
holding all the delicious inverted index information from a directory
'''

###################################################################
#                           Imports                               #
###################################################################
import json
import pickle
import os
import datetime
import math

###################################################################
#                          Functions                              #
###################################################################

def dumpToPickle(index: dict[str, list], number: int) -> None:
    """Dump dictionary to pickle file."""
    with open(f'dumps/dump{number}.pickle', 'wb') as dump_file:
        pickle.dump(index, dump_file, pickle.HIGHEST_PROTOCOL)

def savePageRanks(index: dict[str, list]) -> None:
    """Dump hash dictionary to json file."""
    with open(f'./pageRanks/pageRankIndex.json', 'w') as json_file:
        print(f"{datetime.datetime.now()} Started Saving Page Ranks")
        json.dump(index, json_file)
        print(f"{datetime.datetime.now()} Finished Saving Page Ranks")

def saveHashes(index: dict[str, list]) -> None:
    """Dump hash dictionary to json file."""
    with open(f'./docHashes/hashIndex.json', 'w') as json_file:
        print(f"{datetime.datetime.now()} Started Saving Hash Index")
        json.dump(index, json_file)
        print(f"{datetime.datetime.now()} Finished Saving Hash Index")

def load_index(index_num: int) -> dict[str, int]:
    """Loads index of character start and end locations for each token in file."""
    with open(f'./indexIndex/index{index_num}.pickle', 'rb') as pickle_data:
        location_index = pickle.load(pickle_data)
    return location_index

def load_page_rank_index() -> dict[int, int]:
    """Loads index of Page Ranks"""
    print("Loading PageRanks Index...")
    with open(f'./pageRanks/pageRankIndex.json', 'r') as json_file:
        page_rank_index = json.load(json_file)
    print("\tFinished")
    return page_rank_index

def load_token_idf_index() -> dict[int, int]:
    """Loads index of token idf index."""
    print("Loading tokenIdfIndex Index...")
    with open(f'./tokenIdfIndex/tokenIdf.pickle', 'rb') as pickle_file:
        token_idf_index = pickle.load(pickle_file)
    print("\tFinished")
    return token_idf_index


class Student:
    def __init__(self, name, surname, gender):
        self.name = name
        self.surname = surname
        self.gender = gender
        self.finished_courses = []
        self.courses_in_progress = []
        self.grades = {}

    def rate_a_lector(self, lector, course, grade):
        if isinstance(lector,Lector) and course in self.courses_in_progress and course in lector.courses_attached:
            if course in lector.lector_grade.keys():
                lector.lector_grade.get(course).append(grade)
            else:
                lector.lector_grade[course] = [grade]
        else:
           return (f'Ошибка! Студент {self.name} и лектор {lector.name} {lector.surname} не участвуют в обучении '
                  f'в рамках одного курса')

    def average_grade(self):
        total_sum_of_all_grades = 0
        count_of_all_grades = 0
        for i in self.grades.values():
            for j in i:
                total_sum_of_all_grades += j
                count_of_all_grades += 1
        if count_of_all_grades == 0:
            return "Ошибка"
        else:
            return total_sum_of_all_grades/count_of_all_grades

    def __str__(self):
        student_presentation = (f'Имя: {self.name} \n'
              f'Фамилия: {self.surname} \n'
              f'Средняя оценка за домашние задания: {self.average_grade()} \n'
              f'Курсы в процессе изучения: {", ".join(self.courses_in_progress)} \n'
              f'Завершенные курсы: {", ".join(self.finished_courses)}')
        return student_presentation

    def __lt__(self, other):
        if not isinstance(other, Student):
            print("Not a student!")
            return
        return self.average_grade() < other.average_grade()

class Mentor:
    def __init__(self, name, surname):
        self.name = name
        self.surname = surname
        self.courses_attached = []

class Lector(Mentor):
    def __init__(self, name, surname):
        super().__init__(name, surname)
        self.lector_grade = {}

    def average_grade(self):
        total_sum_of_all_grades = 0
        count_of_all_grades = 0
        for i in self.lector_grade.values():
            for j in i:
                total_sum_of_all_grades += j
                count_of_all_grades += 1
        if count_of_all_grades == 0:
            return "Ошибка"
        else:
            return total_sum_of_all_grades / count_of_all_grades

    def __str__(self):
        lector_presentation = (f'Имя: {self.name} \n'
              f'Фамилия: {self.surname} \n'
              f'Средняя оценка за лекции: {self.average_grade()} \n')
        return lector_presentation

    def __lt__(self, other):
        if not isinstance(other, Lector):
            print("Not a lector!")
            return
        return self.average_grade() < other.average_grade()

class Reviewer(Mentor):
    def rate_hw(self, student, course, grade):
        if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:
            if course in student.grades:
                student.grades[course] += [grade]
            else:
                student.grades[course] = [grade]
        else:
            return 'Ошибка'

    def __str__(self):
        reviewer_presentation = (f'Имя: {self.name} \n'
              f'Фамилия: {self.surname}')
        return reviewer_presentation


#%%
import requests
import dateparser
import pandas as pd
import time

from bs4 import BeautifulSoup as bs
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

chrome_options = Options()
chrome_options.add_argument("--headless")

driver = webdriver.Firefox(options=chrome_options)
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

#%%

listo = []

for page in range(1,7):

    start_url = f'https://coronavirus.nt.gov.au/updates?page={page}'

    print(f"Starting page{page}")
    driver.get(start_url)

    time.sleep(3)

    soup = bs(driver.page_source, 'html.parser')

    links = soup.find_all(class_='py-4')
    links = [x.a['href'] for x in links]

    print(f"There are {len(links)} links.")

    for link in links:
        r = requests.get(link)
        soup2 = bs(r.text, 'html.parser')

        datter = soup2.find(class_='publishedDate').text

        datto = dateparser.parse(datter)

        datto = datto.strftime('%Y-%m-%d')

        print(datto)

        stringo = ''
        texto = soup2.find_all("p")
        texto = [x.text for x in texto]

        # print(texto)

        for par in texto:
            if "in hospital" in par:
                stringo += par
                stringo += " "

        if len(stringo) > 1:
            print(stringo)

            data = [{'Date': datto, 'Text': stringo}]
            inter = pd.DataFrame.from_records(data)

            listo.append(inter)

            fin = pd.concat(listo)

            with open('archive/nt_scraping/scraped.csv', 'w') as f:
                fin.to_csv(f, index=False, header=True)

    # print(r.status_code)
    # print(links)
    # print(r.text)

# %%


from tkinter import*
from tkinter import ttk
from tkinter import ttk
import tkinter as tk
import math

def solve():
   """it needs to input sides to resolve the equation.
      Label mirrors information on the frame of Tkinter.
      config helps to reflect the solution of equation on the frame of Tkinter.
      Entry a space to input some type of data for colcutation.

   """
   a=float(E1.get())
   b=float(E2.get())
   c=float(E3.get())

   D = b**2 - 4 * a * c
   if D<0:

        result.config(text="The equation has no real roots")

   else:
        x1 = (-b + D**0.5) / (2*a)
        x2 = (-b - D**0.5) / (2*a)
        result.config(text=f"roots of the equation:\n x1 = {x1}\n x2 = {x2}")

window=tk.Tk()#responds for formation
window.title('Math')
window.geometry('600x300')# change size

lbl=tk.Label(window,text='Square level solution', font='Arial 20', bg="lightblue")
lbl1=tk.Label(window,text='x**2+')
lbl2=tk.Label(window,text='x+')
lbl3=tk.Label(window,text='=0')
result = tk.Label( text="Solution", bg="yellow", width=25, height=4, font=("Arial", 16))
#lbl.pack(pady=10)

#E1 = Entry(window, bd =5)
#E1.pack(side = RIGHT)

#ent.pack(side="left", padx="10")
#E1=Entry(window,fg='black', bg='paleturquoise' ,) #Text box
#E2=Entry(window,fg='black', bg='#32a852' ,) #Text box
#E3=Entry

E1 =tk.Entry(window,  width=10, bg="lightblue")
#E1.pack(side="left", padx=10)

E2 =tk.Entry(window,  width=10, bg="lightblue")
#E2.pack(side="right", padx=10)

E3=tk.Entry(window, width=10, bg="lightblue")

btn=Button(window, text='to solve',font='Arial 20', fg='black', bg='#32a852', command=solve)

E1.grid(row=1,column=0)
lbl1.grid(row=1, column=1)
E2.grid(row=1, column=2)
lbl2.grid(row=1,column=3)
E3.grid(row=1, column=4)
lbl3.grid(row=1, column=5)
lbl.grid(row=0,column=0, columnspan=10)
btn.grid(row=1, column=6, )
result.grid(row=4, column=0,columnspan=10)

window.mainloop() # start the window


import numpy as np
import yfinance as yf
import pandas as pd
from collections import OrderedDict
import pycountry_convert as pc
import concurrent.futures
import matplotlib.pyplot as plt
import csv
from scipy.stats import multivariate_normal, norm

def gather_data(ticker, factors):
    """Reads issuer info"""
    temp_factor = []

    for factor in factors:
        k = yf.Ticker(ticker).info[factor]

        if k == "Consumer Defensive":
            temp_factor.append("Consumer Services")

        if factor == "country":
            country_code = pc.country_name_to_country_alpha2(
                k, cn_name_format="default"
            )
            continent_name = pc.country_alpha2_to_continent_code(country_code)
            temp_factor.append(continent_name)

        else:
            temp_factor.append(k)

    return temp_factor

if __name__ == "__main__":
    issuers = []
    threshhold = []
    model = ["country", "sector"]

    with open('issuer_heavy_correlated.csv') as f:
        read = csv.reader(f, delimiter=',')
        next(read)
        for row in read:
            issuers.append(str(row[0]))
            threshhold.append(float(row[1]))

    all_factors = []

    with concurrent.futures.ThreadPoolExecutor() as executor:
        values = [executor.submit(gather_data, ticker, model) for ticker in issuers]

        concurrent.futures.wait(values, timeout=None, return_when='ALL_COMPLETED')
        for f in values:
            all_factors.append(f.result())

    dict_region = {}
    dict_score = {}
    dict_sect = {}
    for issuer in all_factors:
        if issuer[0] not in dict_region.keys():
            # if issuer[0] == "NA":
            #     issuer[0] = "North America"
            # if issuer[0] == "EU":
            #     issuer[0] = "Europe"
            dict_region[issuer[0]] = 1
        else:
            dict_region[issuer[0]] += 1

        if issuer[1] not in dict_sect.keys():
            dict_sect[issuer[1]] = 1
        else:
            dict_sect[issuer[1]] += 1

    for score in threshhold:
        if score == 0.000141:
            score = "AA"
        if score == 0.000544:
            score = "A"
        if score == 0.001997:
            score = "BBB"
        if score == 0.008538:
            score = "BB"
        if score == 0.2433872:
            score = "CCC"
        if score not in dict_score.keys():
            dict_score[score] = 1
        else:
            dict_score[score] += 1

    label_region = dict_region.keys()
    label_sect = dict_sect.keys()
    label_score = dict_score.keys()
    region_size = []
    sect_size = []
    score_size = []
    for key in label_region:
        region_size.append(dict_region[key])
    for key in label_sect:
        sect_size.append(dict_sect[key])
    for key in label_score:
        score_size.append(dict_score[key])

    fig, (ax1, ax2) = plt.subplots(1, 2)

    ax1.pie(region_size, labels=label_region, autopct='%1.1f%%')
    ax1.set_title("Portfolio region distribution")
    # plt.show()
    ax2.pie(sect_size, labels=label_sect, autopct='%1.1f%%')
    ax2.set_title("Portfolio sector distribution")
    plt.show()
    plt.pie(score_size, labels=label_score, autopct='%1.1f%%')
    plt.title("Portfolio credit score distribution")
    plt.show()


import hashlib
import requests

from BluenetLib._EventBusInstance            import BluenetEventBus
from BluenetLib.lib.cloud.CloudBase          import CloudBase
from BluenetLib.lib.topics.SystemCloudTopics import SystemCloudTopics
from BluenetLib.lib.topics.SystemTopics      import SystemTopics

from threading import Timer

class CloudSphereHandler(CloudBase):
    sphereId = None
    sphereData = None

    pendingTimer = None
    pollingEnabled = False

    def __init__(self, sphereId, eventBus):
        super().__init__(eventBus)
        self.sphereId = sphereId
        BluenetEventBus.subscribe(SystemTopics.cleanUp, lambda x: self.stopPollingPresence())

    def init(self):
        self.sphereData = self.getSphereData()

    def getSphereData(self):
        r = requests.get('https://my.crownstone.rocks/api/Spheres/' + self.sphereId + "?access_token=" + self.accessToken)

        sphereData = None
        if r.status_code == 200:
            reply = r.json()

            sphereData = {
                "name": reply["name"],
                "cloudId": reply["id"],
                "iBeaconUUID": reply["uuid"]
            }
        else:
            print(r.text)
            print("Could not get Sphere data")

        return sphereData

    def getStones(self):
        r = requests.get('https://my.crownstone.rocks/api/Stones?access_token='+self.accessToken)
        stones = []

        if r.status_code == 200:
            reply = r.json()

            for stone in reply:
                if stone["sphereId"] == self.sphereId:
                    stoneData = {
                        "id": stone["uid"],
                        "name": stone["name"],
                        "cloudId": stone["id"],
                        "address": stone["address"],
                        "type": stone["type"],
                        "dimmingEnabled": stone["dimmingEnabled"],
                        "major": stone["major"],
                        "minor": stone["minor"],
                        "firmwareVersion": stone["firmwareVersion"],
                    }

                    BluenetEventBus.emit(SystemCloudTopics.stoneDownloadedFromCloud, stoneData)
                    stones.append(stone)
        else:
            print(r.text)
            print("Could not get Stones")

        return stones

    def getLocations(self):
        r = requests.get('https://my.crownstone.rocks/api/Spheres/' + self.sphereId + '/ownedLocations?access_token=' + self.accessToken)
        locations = []

        if r.status_code == 200:
            reply = r.json()

            for location in reply:
                locations.append({"id": location["uid"], "cloudId": location['id'], "name": location["name"]})
        else:
            print(r.text)
            print("Could not get locations")

        return locations

    def getKeys(self):
        r = requests.get('https://my.crownstone.rocks/api/users/' + self.userId + '/keys?access_token=' + self.accessToken)

        if r.status_code == 200:
            reply = r.json()

            for keySet in reply:
                if keySet["sphereId"] == self.sphereId:
                    return keySet["keys"]
        else:
            print(r.text)
            print("Could not get keys")

    def startPollingPresence(self, interval=10, firstRun=True):
        if interval < 10:
            interval = 10
            print("Forcing presence polling interval back to 10 to avoid overloading server.")

        # start with a syncing run for the presenceManager.
        if firstRun:
            self.getPresence()

        self.pollingEnabled = True
        self.pendingTimer = Timer(interval, lambda: self._presencePoller(interval))
        self.pendingTimer.start()

    def _presencePoller(self, interval):
        self.getPresence()
        if self.pollingEnabled:
            self.startPollingPresence(interval, False)
        elif self.pendingTimer is not None:
            self.pendingTimer.cancel()

    def getPresence(self):
        r = requests.get('https://my.crownstone.rocks/api/Spheres/' + self.sphereId + '/ownedLocations?filter=%7B%22include%22%3A%22presentPeople%22%7D&access_token=' + self.accessToken)

        locations = []
        if r.status_code == 200:
            reply = r.json()

            for location in reply:
                presentPeople = []
                for person in location["presentPeople"]:
                    presentPeople.append({"id": person["id"], "email":person["email"], "name": person["firstName"] + " " + person["lastName"]})
                locationData = {"cloudId": location["id"], "id": location["uid"], "name": location["name"], 'presentPeople': presentPeople}
                locations.append(locationData)
                BluenetEventBus.emit(SystemCloudTopics.presenceInLocationDownloadedFromCloud, locationData)
        else:
            print(r.text)
            print("Could not get presence")

        return locations

    def stopPollingPresence(self):
        self.pollingEnabled = False
        if self.pendingTimer is not None:
            self.pendingTimer.cancel()


from json import loads
from django.http import HttpResponse
from django.shortcuts import render,redirect
from .models import Swimmer,Award,Fact
from django.core.paginator import Paginator
from django.contrib.auth import login, logout
from .forms import SearchForm, UserRegisterForm, UserLoginForm, UserCreationForm
from django.contrib import messages
from django.db.models import Q

def HomePageRender(request):
    Swimmers = Swimmer.objects.all()
    paginator = Paginator(Swimmers, 12)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    return render( request, 'main/HomePage.html', {'page_obj': page_obj} )

def Register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            if form.cleaned_data['password1']==form.cleaned_data['password2']:
                user = form.save()
                login(request, user)
                messages.success(request, 'Вы успешно зарегистрировались')
                return redirect('Login')
            else:
                messages.error(request, 'Ошибка регистрации')
        else:
            messages.error(request, 'Ошибка регистрации')
    else:
        form = UserRegisterForm()
    return render(request, 'main/Register.html', {'form': form})

def Login(request):
    if request.method == 'POST':
        form = UserLoginForm(data=request.POST)
        if form.is_valid():
            user=form.get_user()
            login(request, user)
            messages.success(request, 'Вы успешно вошли')
            return redirect('Home')
        else:
            messages.error(request, 'Ошибка входа')
    else:
        form = UserLoginForm()
    return render(request, 'main/Login.html',  {'form':form})

def Logout(request):
    logout(request)
    return redirect('Login')

def Search(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)

        if form.is_valid():

            qr = form.cleaned_data['search'].split()
            res = list()
            if qr != []:
                for i in qr:

                    a = Swimmer.objects.filter(Q(Name__icontains= i))
                    res.append(*a)
            return render( request, 'main/searchresult.html', {'swimmers':res} )
    else:
        form = SearchForm()
        return render(request, 'main/Search.html', {'form': form})

def SwimmerPage(request, id):
    Swimmers = Swimmer.objects.get(pk=id)
    return render(request, 'main/Swimmer.html', {'swimmer': Swimmers})

def renderadd(request):
    return render(request, 'main/AddSwimmer.html')

def createswimmer(request):
    my_json = request.body.decode('utf8')

    my_json = loads(my_json)
    print(type(my_json))
    sw = Swimmer.objects.create(Name = my_json['Name'], Age = int(my_json['Age']), Weight = int(my_json['Weight']))
    Awards = my_json['Awards']
    Facts = my_json['Facts']

    for award in Awards:
        aw = Award.objects.create(Name = award[0], Date = award[1])
        sw.Awards.add(aw)

    for fact in Facts:
        fc = Fact.objects.create(Name = fact[0], Content = fact[1])
        sw.Facts.add(fc)

    return HttpResponse()


def fun_calc(num1: int, num2: int, operator: str):
    tmp = str(num1)+operator+str(num2)
    product = eval(tmp)
    process = tmp+'='+str(product)
    return product, process
product, process = fun_calc(50, 2, '$')
print(f'Product: {product}')
print(f'Process: {process}')


#https://programmers.co.kr/learn/courses/30/lessons/42888

def solution(record):
    di_re = {}
    answer = []

    for i in record:
        sp_re = i.split(' ')
        if sp_re[0] == 'Enter' or sp_re[0] == 'Change':
            di_re[sp_re[1]] = sp_re[2]

    for i in record:
        sp_re = i.split(' ')
        if sp_re[0] == 'Enter':
            answer.append(di_re[sp_re[1]] + '님이 들어왔습니다.')
        elif sp_re[0] == 'Leave':
            answer.append(di_re[sp_re[1]] + '님이 나갔습니다.')
        else:
            continue

    return answer


import json
import websockets
import asyncio

PORT = 7890
print("Server listening on Port " + str(PORT))

games = {}
idCount = 0

async def echo(websocket, path):
    print("A client just connected: ", websocket)

    try:
        # this will continue to get anything from server
        async for string_obj in websocket:

            # convert back to object
            obj = json.loads(string_obj)
            # do something with object
            #
            #
            #
            #

            # turn back into string and send back
            str_obj = json.dumps({})
            await websocket.send(str_obj)

    except websockets.exceptions.ConnectionClosed as e:
        print("A client just disconnected")

start_server = websockets.serve(echo, "localhost", PORT)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


import pandas as pd

# filenames
excel_names = ["August2016_0599.csv", "August2016_2808.csv", "December2016_0599.csv", "December2016_2808.csv", "February2016_0599.csv", "February2016_2808.csv", "January2016_0599.csv", "January2016_2808.csv", "July2016_0599.csv", "July2016_2808.csv",  "June2016_0599.csv", "June2016_2808.csv",  "November2016_0599.csv", "November2016_2808.csv",  "October2016_0599.csv", "October2016_2808.csv", "September2016_0599.csv", "September2016_2808.csv"]

# read them in
excels = [pd.ExcelFile(name) for name in excel_names]

# turn them into dataframes
frames = [x.parse(x.sheet_names[0], header=None,index_col=None) for x in excels]

# delete the first row for all frames except the first
# i.e. remove the header row -- assumes it's the first
frames[1:] = [df[1:] for df in frames[1:]]

# concatenate them..
combined = pd.concat(frames)

# write it out
combined.to_csv("c.csv", header=False, index=False)


import heapq

'''
다익스트라 알고리즘은 특정 노드에서 다른 노드들로 가는 최단경로를 찾는 알고리즘
- 방문한 노드 체크 및 노드 거리를 나타내기 위한 노드길이(n)만큼의 리스트 두 개 선언
- 시작 노드부터 시작하여 각 노드와 연결되어 있는 노드를 거치며 거리 리스트를 갱신
'''

INF = int(1e9)
DISTANCE = 1
NODE = 0

def dijkstra(graph, start_node, node_quantity) :
    distance = [INF] * node_quantity
    q = []
    visited = [False] * node_quantity

    # 시작 노드에 대해서 초기화
    setup(start_node, distance, q)

    while q : # 큐가 비어있지 않다면
        # 최단 거리가 가장 짧은 노드에 대한 정보 꺼내기
        # 최단 거리가 가장 짧은 거리인 노드를 뽑아야만 정상적인 갱신이 가능
        now_distance, now_node = heapq.heappop(q)
        # 현재 노드가 이미 처리된 적 있는 노드라면 무시
        if distance[now_node] < now_distance :
            continue
        # 현재 노드와 연결된 다른 인접한 노드들을 확인
        for node_distance in graph[now_node] :
            cost = now_distance + node_distance[DISTANCE]
            # 현재 노드를 거쳐서, 다른 노드로 이동하는 거리가 더 짧은 경우
            if cost < distance[node_distance[NODE]] :
                distance[node_distance[NODE]] = cost
                heapq.heappush(q, (cost, node_distance[NODE]))

def setup(node, distance, q) :
    heapq.heappush(q, (0, node))  # (거리, 노드)
    distance[node] = 0


'''
프로그램에서 의도적으로 에러를 발생시키는 경우
'''

try:
    print("한 자리 숫자 전용 계산기 입니다")
    num = []
    num.append(int(input("첫 번째 숫자를 입력하세요:\n ")))
    num.append(int(input("두 번째 숫자를 입력하세요:\n")))
    num.append(num[0]/num[1])

    if num[0] >= 10 or num[1] >= 10:
        raise ValueError
    print("{0} / {1} = {2}".format(num[0], num[1], num[2]))

except ValueError:
    print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요")

18. 에러 발생시키기.py

18. 에러 발생시키기.py


import math as m
from module_bissecao import Bissecao, funcao, calculo_de_raiz_a, calculo_de_raiz_b

a = float(input('Inicio do intervalo:\n'))
b = float(input('Fim do intervalo:\n'))
precisao = float(input('Precisao para parada, em decimal:\n'))

cont = 0

while True:
    cont += 1
    objeto = Bissecao(a,b,precisao)
    x = objeto.media()

    a = calculo_de_raiz_a(x,a)
    b = calculo_de_raiz_b(x,b)

    if objeto.erroabsoluto():
        break

    if cont == 1001:
        print('Houve algum erro no algoritimo!!')
        break

print(f'O valor da raiz é {x}')


"""Test the hypotheses specified in the instructions.

> There are effects of image novelty
> (i.e., between images shown for the first time/new vs. repeated/old images)
> within the time-range from 300-500 ms ...
> a. ... on EEG voltage at fronto-central channels.
> b. ... on theta power at fronto-central channels.
> c. ... on alpha power at posterior channels.

"""

# %%
# Imports
import itertools
import pickle
import sys
from functools import partial
from pathlib import Path

import matplotlib.pyplot as plt
import mne
import numpy as np
from mne.channels import find_ch_adjacency
from mne.stats import spatio_temporal_cluster_1samp_test, ttest_1samp_no_p
from mne.time_frequency import tfr_morlet
from scipy import stats

from config import (
    FNAME_EPO_CLEAN_TEMPLATE,
    FNAME_HYPOTHESES_2_TEMPLATE,
    FNAME_REPORT_H2,
    OVERWRITE_MSG,
    SUBJS,
    TRIGGER_CODES,
)
from utils import parse_overwrite

# %%
# Filepaths and settings
overwrite = True
fname_report = FNAME_REPORT_H2
fname_h2a = Path(FNAME_HYPOTHESES_2_TEMPLATE.format(h="h2a_cluster.pkl"))
fname_h2b_wavelet = Path(FNAME_HYPOTHESES_2_TEMPLATE.format(h="h2b_wavelet.pkl"))
fname_h2b_cluster = Path(FNAME_HYPOTHESES_2_TEMPLATE.format(h="h2b_cluster.pkl"))
fname_h2c_wavelet = Path(FNAME_HYPOTHESES_2_TEMPLATE.format(h="h2c_wavelet.pkl"))
fname_h2c_cluster = Path(FNAME_HYPOTHESES_2_TEMPLATE.format(h="h2c_cluster.pkl"))

# Make sure the save directories exist
for _fname in [
    fname_h2a,
    fname_h2b_wavelet,
    fname_h2b_cluster,
    fname_h2c_wavelet,
    fname_h2c_cluster,
]:
    _fname.parent.mkdir(parents=True, exist_ok=True)

# Settings for cluster test
pthresh = 0.05  # general significance alpha level
pthresh_cluster = 0.001  # cluster forming alpha level
tail = 0  # two-tailed, see also "pthresh / 2" below
sigma = 1e-3  # sigma for the small variance correction
thresh = stats.distributions.t.ppf(1 - pthresh_cluster / 2, len(SUBJS) - 1)
stat_fun_hat = partial(ttest_1samp_no_p, sigma=sigma)
nperm = 5000
seed_H2 = 1991

# Time frequency
n_cycles = 7
alpha_freqs = np.arange(8, 12.5, 0.5)  # define frequencies of interest
theta_freqs = np.arange(4, 7.5, 0.5)  # define frequencies of interest
# Roi & toi
ch_fronto_central = ["FC3", "FC4", "Fz", "FC1", "FC2"]
ch_posterior = ["POz", "PO3", "PO4", "Oz", "O1", "O2", "PO7", "PO8"]
toi_min = 0.3
toi_max = 0.5
# List of all trigger combinations for a new image
triggers_new_list = list(
    itertools.product(
        list(TRIGGER_CODES[0].values()),
        ["new"],
        list(TRIGGER_CODES[2].values()),
        list(TRIGGER_CODES[3].values()),
    )
)
# List of all trigger combinations for an old image
triggers_old_list = list(
    itertools.product(
        list(TRIGGER_CODES[0].values()),
        ["old"],
        list(TRIGGER_CODES[2].values()),
        list(TRIGGER_CODES[3].values()),
    )
)
# %%
# When not in an IPython session, get command line inputs
# https://docs.python.org/3/library/sys.html#sys.ps1
if not hasattr(sys, "ps1"):
    defaults = dict(
        overwrite=overwrite,
    )
    defaults = parse_overwrite(defaults)
    overwrite = defaults["overwrite"]

# %%
# Check overwrite
if fname_report.exists() and not overwrite:
    raise RuntimeError(OVERWRITE_MSG.format(fname_report))

# %%
# Start a report to save figures
report = mne.Report(title="Hypothesis 2")

# %%
# Makes triggercodes for subsetting the epochs
triggers_new = [
    "/".join(map(str, triggers_new_list[i])) for i in range(0, len(triggers_new_list))
]
triggers_old = [
    "/".join(map(str, triggers_old_list[i])) for i in range(0, len(triggers_old_list))
]
# %%
# Reads in all epochs
epochs_complete = [
    mne.read_epochs(fname=FNAME_EPO_CLEAN_TEMPLATE.format(sub=sub)) for sub in SUBJS
]

# %%
# Get a list of epochs in the desired time range and with the desired channels.
# already put it into the format needed for permutation test
# required format: (n_observations (subs), time, n_vertices (channels)).
evokeds_diff_list = list(
    [
        np.subtract(
            x[triggers_old]
            .filter(h_freq=40, l_freq=None)
            .apply_baseline(baseline=(None, 0))
            .crop(toi_min, toi_max)
            .pick_channels(ch_fronto_central)
            .average()
            .get_data(),
            x[triggers_new]
            .filter(h_freq=40, l_freq=None)
            .apply_baseline(baseline=(None, 0))
            .crop(toi_min, toi_max)
            .pick_channels(ch_fronto_central)
            .average()
            .get_data(),
        )
        for x in epochs_complete
    ]
)
# add list elements along array axis and reshape for permutation test
# Concatanate conditions for use with cluster based permutation test
evokeds_diff_arr = np.stack(evokeds_diff_list, axis=2).transpose(2, 1, 0)

# %%
# Calculate adjacency matrix between sensors from their locations
sensor_adjacency, ch_names = find_ch_adjacency(
    epochs_complete[1].copy().pick_channels(ch_fronto_central).info, "eeg"
)
# %%
# Calculate statistical thresholds
# Check overwrite
# If there is a cluster test, and overwrite is false, load data
if fname_h2a.exists() and not overwrite:
    with open(fname_h2a, "rb") as fin:
        clusterstats = pickle.load(fin)

# If overwriting is false compute everything again
else:
    clusterstats = spatio_temporal_cluster_1samp_test(
        evokeds_diff_arr,
        threshold=thresh,
        n_permutations=nperm,
        adjacency=sensor_adjacency,
        n_jobs=6,
        stat_fun=stat_fun_hat,
        out_type="mask",
        tail=tail,
        seed=seed_H2,
    )
    with open(fname_h2a, "wb") as fout:
        pickle.dump(clusterstats, fout)

t_obs_h2a, clusters_h2a, cluster_pv_h2a, h0_h2a = clusterstats

# %%
# Visualize the voltage, taking the average of all subjects
# old images
epochs_old_plot = list(
    [
        epo[triggers_old].pick_channels(ch_fronto_central).average()
        for epo in epochs_complete
    ]
)
epochs_new_plot = list(
    [
        epo[triggers_new].pick_channels(ch_fronto_central).average()
        for epo in epochs_complete
    ]
)
# calculate difference wave
evoked = mne.combine_evoked(
    [mne.grand_average(epochs_old_plot), mne.grand_average(epochs_new_plot)],
    weights=[1, -1],
)
time_unit = dict(time_unit="s")
# show difference wave
joint = evoked.plot_joint(
    title="Old - New images",
    ts_args=time_unit,
    times=[0.3, 0.35, 0.4, 0.45, 0.5],
    topomap_args=time_unit,
)
report.add_figure(
    fig=joint,
    title="h2a",
    caption="This figure shows the difference between old and new "
    + "image presentation as well as the scalp distribution in the times of interest",
    image_format="PNG",
)

# Create ROIs by checking channel labels
# only check tois
# Visualize the results
toi_evoked = evoked.copy().crop(toi_min, toi_max)
h2a_test = toi_evoked.plot_image(
    colorbar=False,
    show=False,
    # mask=clusters_h2a[0],
    show_names="all",
    titles="Significant timepoints",
    **time_unit,
)

report.add_figure(
    fig=h2a_test,
    title="h2a sig",
    caption="This figure shows where the difference between old and new"
    + "image presentation are significant according"
    + "to a cluster based permutation test."
    + "Only greyscales imply that there is"
    + "no significant difference in the time window of interest",
    image_format="PNG",
)

# %%
# get times and sensors of signifcant clusters

# get cluster defining start time and end time
cluster_time_h2a = [
    [
        np.min(
            np.asarray(toi_evoked.times)[np.unique(np.where(clusters_h2a[clusters])[0])]
        ),  # get min time of cluster
        np.max(
            np.asarray(toi_evoked.times)[np.unique(np.where(clusters_h2a[clusters])[0])]
        ),  # get max time of cluster
    ]
    for clusters in range(0, len(clusters_h2a))
]

# get cluster defining channels
cluster_chs_h2a = [
    np.asarray(ch_fronto_central)[np.unique(np.where(clusters_h2a[clusters])[1])]
    for clusters in range(0, len(clusters_h2a))
]

# %%
# Hypothesis 2b.
# Do wavelet tranformation on whole epoch to get tfr
# If there is a wavelet file, and overwrite is false, load data
# Note: apply baseline after TF decomposition
# (https://www.youtube.com/watch?v=9dXG50ychsQ)
if fname_h2b_wavelet.exists() and not overwrite:
    with open(fname_h2b_wavelet, "rb") as fin:
        tfr_diff_list = pickle.load(fin)

else:
    tfr_diff_h2b_list = list(
        [
            np.subtract(
                tfr_morlet(
                    x[triggers_new].pick_channels(ch_fronto_central),
                    theta_freqs,
                    n_cycles=n_cycles,
                    average=True,
                    return_itc=False,
                    n_jobs=6,
                )
                .apply_baseline(baseline=(None, -0.1))
                .crop(toi_min, toi_max)
                .data,
                tfr_morlet(
                    x[triggers_old].pick_channels(ch_fronto_central),
                    theta_freqs,
                    n_cycles=n_cycles,
                    average=True,
                    return_itc=False,
                    n_jobs=6,
                )
                .apply_baseline(baseline=(None, -0.1))
                .crop(toi_min, toi_max)
                .data,
            )
            for x in epochs_complete
        ]
    )
    with open(fname_h2b_wavelet, "wb") as fout:
        pickle.dump(tfr_diff_h2b_list, fout)

# %%
# Concatanate conditions for use with cluster based permutation test
# required format: (n_observations (subs),freq, time, n_vertices (channels)).
tfr_theta_diff_arr = np.stack(tfr_diff_h2b_list, axis=2).transpose(2, 1, 3, 0)

# %%
# Make sensor-frequency adjacancy matrix
tf_timepoints = tfr_theta_diff_arr.shape[2]
tfr_adjacency = mne.stats.combine_adjacency(
    len(theta_freqs), tf_timepoints, sensor_adjacency
)

# %%
# Calculate statistical thresholds
if fname_h2b_cluster.exists() and not overwrite:
    with open(fname_h2b_cluster, "rb") as fin:
        clusterstats = pickle.load(fin)

else:
    clusterstats = spatio_temporal_cluster_1samp_test(
        tfr_theta_diff_arr,
        threshold=thresh,
        n_permutations=nperm,
        adjacency=tfr_adjacency,
        n_jobs=6,
        stat_fun=stat_fun_hat,
        out_type="mask",
        tail=tail,
        seed=seed_H2,
    )
    with open(fname_h2b_cluster, "wb") as fout:
        pickle.dump(tfr_diff_h2b_list, fout)

t_obs_h2b, clusters_h2b, cluster_pv_h2b, h0_h2b = clusterstats

# %%
# calculate power difference
tfr_theta_diff = np.average(tfr_theta_diff_arr, axis=0)
t_obs_h2b_t = t_obs_h2b.transpose(1, 0, 2)

# %%
# make h2b figure
h2b_test, axs = plt.subplots(
    nrows=len(ch_names), ncols=2, figsize=(20, 20), constrained_layout=True
)

for ch_idx in range(0, len(ch_names)):
    plt.sca(axs[ch_idx, 0])
    plt.imshow(
        tfr_theta_diff[:, :, ch_idx],
        aspect="auto",
        origin="lower",
        extent=[toi_min, toi_max, theta_freqs[0], theta_freqs[-1]],
    )
    plt.colorbar()
    plt.xlabel("Time (ms)")
    plt.ylabel("Frequency (Hz)")
    plt.title(f"Power difference new - old \n ({ch_names[ch_idx]})")

    plt.sca(axs[ch_idx, 1])
    plt.imshow(
        t_obs_h2b_t[:, :, ch_idx],
        aspect="auto",
        origin="lower",
        extent=[toi_min, toi_max, theta_freqs[0], theta_freqs[-1]],
    )
    plt.colorbar()
    plt.xlabel("Time (ms)")
    plt.ylabel("Frequency (Hz)")
    plt.title(f"Cluster T_val difference new -old \n ({ch_names[ch_idx]})")

report.add_figure(
    fig=h2b_test,
    title="h2a sig",
    caption="This figure shows where the difference in theta"
    + "power between old and new images. The first column shows "
    + "The first column shows raw power  difference, the second "
    + "show the corresponding T-statistic",
    image_format="PNG",
)
# %%
# get times, sensors and frequencies of signifcant clusters

# get cluster defining start time and end time
cluster_time_h2b = [
    [
        np.min(
            np.asarray(toi_evoked.times)[
                np.unique(np.where(clusters_h2b[clusters_h2b_idx])[1])
            ]
        ),  # get min time of cluster
        np.max(
            np.asarray(toi_evoked.times)[
                np.unique(np.where(clusters_h2b[clusters_h2b_idx])[1])
            ]
        ),  # get max time of cluster
    ]
    for clusters_h2b_idx in range(0, len(clusters_h2b))
]

# get cluster defining sensors
cluster_chs_h2b = [
    np.asarray(ch_fronto_central)[
        np.unique(np.where(clusters_h2b[clusters_h2b_idx])[2])
    ]
    for clusters_h2b_idx in range(0, len(clusters_h2b))
]
# get cluster defining freqs
cluster_freqs_h2b = [
    np.asarray(theta_freqs)[np.unique(np.where(clusters_h2b[clusters_h2b_idx])[0])]
    for clusters_h2b_idx in range(0, len(clusters_h2b))
]

# %%
# Hypothesis 2c.
# Do wavelet tranformation on whole epoch to get tfr
# If there is a wavelet file, and overwrite is false, load data
if fname_h2c_wavelet.exists() and not overwrite:
    with open(fname_h2c_wavelet, "rb") as fin:
        tfr_diff_h2c_list = pickle.load(fin)

else:
    tfr_diff_h2c_list = list(
        [
            np.subtract(
                tfr_morlet(
                    x[triggers_new].pick_channels(ch_posterior),
                    alpha_freqs,
                    n_cycles=n_cycles,
                    average=True,
                    return_itc=False,
                    n_jobs=6,
                )
                .apply_baseline(baseline=(None, -0.1))
                .crop(toi_min, toi_max)
                .data,
                tfr_morlet(
                    x[triggers_old].pick_channels(ch_posterior),
                    alpha_freqs,
                    n_cycles=n_cycles,
                    average=True,
                    return_itc=False,
                    n_jobs=6,
                )
                .apply_baseline(baseline=(None, -0.1))
                .crop(toi_min, toi_max)
                .data,
            )
            for x in epochs_complete
        ]
    )
    with open(fname_h2c_wavelet, "wb") as fout:
        pickle.dump(tfr_diff_h2c_list, fout)

# %%
# Concatanate conditions for use with cluster based permutation test
# required format: (n_observations (subs),freq, time, n_vertices (channels)).
tfr_alpha_diff_arr = np.stack(tfr_diff_h2c_list, axis=2).transpose(2, 1, 3, 0)

# %%
# Make sensor-frequency adjacancy matrix for alpha channels
sensor_adjacency_alpha, ch_names_alpha = find_ch_adjacency(
    epochs_complete[1].copy().pick_channels(ch_posterior).info, "eeg"
)
tf_timepoints_alpha = tfr_alpha_diff_arr.shape[2]
tfr_adjacency_alpha = mne.stats.combine_adjacency(
    len(alpha_freqs), tf_timepoints_alpha, sensor_adjacency_alpha
)

# %%
# Calculate statistical thresholds
if fname_h2c_cluster.exists() and not overwrite:
    with open(fname_h2c_cluster, "rb") as fin:
        clusterstats_h2c = pickle.load(fin)

else:
    clusterstats_h2c = spatio_temporal_cluster_1samp_test(
        tfr_alpha_diff_arr,
        threshold=thresh,
        n_permutations=nperm,
        adjacency=tfr_adjacency_alpha,
        stat_fun=stat_fun_hat,
        out_type="mask",
        tail=tail,
        seed=seed_H2,
        n_jobs=6,
    )
    with open(fname_h2c_cluster, "wb") as fout:
        pickle.dump(tfr_diff_h2c_list, fout)

t_obs_h2c, clusters_h2c, cluster_pv_h2c, h0_h2c = clusterstats_h2c
significant_points_h2c = np.where(cluster_pv_h2c < pthresh)[0]

# %%
# calculate power difference
tfr_alpha_diff = np.average(tfr_alpha_diff_arr, axis=0)
t_obs_h2c_t = t_obs_h2c.transpose(1, 0, 2)
# %%
# make h2b figure
h2c_test, axs = plt.subplots(
    nrows=len(ch_names_alpha), ncols=2, figsize=(20, 20), constrained_layout=True
)

for ch_idx in range(0, len(ch_names_alpha)):
    # power difference
    plt.sca(axs[ch_idx, 0])
    plt.imshow(
        tfr_alpha_diff[:, :, ch_idx],
        aspect="auto",
        origin="lower",
        extent=[toi_min, toi_max, alpha_freqs[0], alpha_freqs[-1]],
    )
    plt.colorbar()
    plt.xlabel("Time (ms)")
    plt.ylabel("Frequency (Hz)")
    plt.title(f"Power difference new - old \n ({ch_names_alpha[ch_idx]})")

    # T values
    plt.sca(axs[ch_idx, 1])
    plt.imshow(
        t_obs_h2c_t[:, :, ch_idx],
        aspect="auto",
        origin="lower",
        extent=[toi_min, toi_max, alpha_freqs[0], alpha_freqs[-1]],
    )
    plt.colorbar()
    plt.xlabel("Time (ms)")
    plt.ylabel("Frequency (Hz)")
    plt.title(f"Cluster T_val difference new -old \n ({ch_names_alpha[ch_idx]})")

report.add_figure(
    fig=h2c_test,
    title="h2a sig",
    caption="This figure shows where the difference in alpha"
    + "power between old and new images. The first column shows "
    + "The first column shows raw power  difference, the second "
    + "show the corresponding T-statistic",
    image_format="PNG",
)

# %%
# get times, sensors and frequencies of signifcant clusters

# get cluster defining start time and end time
cluster_time_h2c = [
    [
        np.min(
            np.asarray(toi_evoked.times)[np.unique(np.where(clusters_h2c[clusters])[1])]
        ),  # get min time of cluster
        np.max(
            np.asarray(toi_evoked.times)[np.unique(np.where(clusters_h2c[clusters])[1])]
        ),  # get max time of cluster
    ]
    for clusters in range(0, len(clusters_h2c))
]
# get cluster defining sensors
cluster_chs_h2c = [
    np.asarray(ch_posterior)[np.unique(np.where(clusters_h2c[clusters_h2c_idx])[2])]
    for clusters_h2c_idx in range(0, len(clusters_h2c))
]
# get cluster defining freqs
cluster_freqs_h2c = [
    np.asarray(alpha_freqs)[np.unique(np.where(clusters_h2b[clusters_h2c_idx])[0])]
    for clusters_h2c_idx in range(0, len(clusters_h2c))
]

# %%
# Save report
report.save(fname_report, open_browser=False, overwrite=overwrite)

# %%


import io
import sys

_INPUT = """\
6
6 6
6 3
2 5
4 2
1 3
6 5
3 2
110001
3 3
3 1
3 2
1 2
000
"""
sys.stdin = io.StringIO(_INPUT)
case_no=int(input())
for __ in range(case_no):
  ans=[]
  def EulerTour(G, s):
    tmp=[0]*len(G)
    depth=[-1]*len(G)
    depth[s]=0
    done = [0]*len(G)
    Q = [~s, s] # 根をスタックに追加
    parent=[-1]*len(G)
    ET = []
    left,right=[-1]*len(G),[-1]*len(G)
    while Q:
      i = Q.pop()
      if i >= 0: # 行きがけの処理
        ans.append(i)
        tmp[i]^=1
        done[i] = 1
        ET.append(i)
        for a in G[i][::-1]:
          if done[a]: continue
          depth[a]=depth[i]+1
          parent[a]=i
          Q.append(~a) # 帰りがけの処理をスタックに追加
          Q.append(a) # 行きがけの処理をスタックに追加
      else: # 帰りがけの処理
        ans.append(parent[-i-1])
        tmp[parent[-i-1]]^=1
        if tmp[-i-1]!=int(S[-i-1]):
          if parent[-i-1]!=-1:
            ans.append(-i-1)
            ans.append(parent[-i-1])
            tmp[-i-1]^=1
            tmp[parent[-i-1]]^=1
          else:
            ans.pop()
            tmp[parent[-i-1]]^=1
        ET.append(i)
    ans.pop()

  class UnionFind():
    def __init__(self, n):
      self.n = n
      self.parents = [-1] * n
    def find(self, x):
      if self.parents[x] < 0:
        return x
      else:
        self.parents[x] = self.find(self.parents[x])
        return self.parents[x]
    def union(self, x, y):
      x = self.find(x)
      y = self.find(y)
      if x == y:
        return
      if self.parents[x] > self.parents[y]:
        x, y = y, x
      self.parents[x] += self.parents[y]
      self.parents[y] = x
    def size(self, x):
      return -self.parents[self.find(x)]
    def same(self, x, y):
      return self.find(x) == self.find(y)
    def members(self, x):
      root = self.find(x)
      return [i for i in range(self.n) if self.find(i) == root]
    def roots(self):
      return [i for i, x in enumerate(self.parents) if x < 0]
    def group_count(self):
      return len(self.roots())
    def all_group_members(self):
      return {r: self.members(r) for r in self.roots()}
    def __str__(self):
      return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

  N,M=map(int,input().split())
  uf=UnionFind(N)
  G=[[] for _ in range(N)]
  for _ in range(M):
    u,v=map(lambda x: int(x)-1, input().split())
    if uf.find(u)!=uf.find(v):
      uf.union(u,v)
      G[u].append(v)
      G[v].append(u)
  S=input()
  EulerTour(G,0)
  print(len(ans))
  print(*[ans[i]+1 for i in range(len(ans))])


import os
from jparse.parser import JSONParser

def main(filename="jsons/glossary.json", **kwargs):
    my_parser = JSONParser()

    this_folder = os.path.dirname(__file__)
    json_file = os.path.join(this_folder, filename)

    result = my_parser.from_file(json_file, debug_colors=True, **kwargs)

    print(f"Input:\n {filename} \n")
    print(f"Result\n {result} \n")
    print(f"Result Type\n {type(result)} \n")

if __name__ == "__main__":
    main(filename="jsons/web_app.json", debug=True)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 23 16:11:40 2015

@author: Simon
"""

import cv2

fr=open("fichier.txt","r")
ligne=fr.read()
i=int(ligne)
i+=1
fw=open("fichier.txt","w")
fw.write("{}".format(i))
fw.close()
fr.close()
tennis=cv2.imread("tennis.jpg")
#cv2.imshow("lol",tennis)
x=int(input("x?\t"))
y=int(input("y?\t"))
RegionOfInterest=tennis[y:y+50,x:x+50]
cv2.imwrite("tennis{}.png".format(i), RegionOfInterest)

roxaaaaane if youre gonna put on the red liiighht.py


import numpy as np
from scipy.special import factorial
from scipy import sparse
import math
import matplotlib.pyplot as plt

class UniformPeriodicGrid:

    def __init__(self, N, length):
        self.values = np.linspace(0, length, N, endpoint=False)
        self.dx = self.values[1] - self.values[0]
        self.length = length
        self.N = N

class NonUniformPeriodicGrid:

    def __init__(self, values, length):
        self.values = values
        self.length = length
        self.N = len(values)

class DifferenceUniformGrid:

    def __init__(self, derivative_order, convergence_order, grid, stencil_type='centered'):

        self.derivative_order = derivative_order
        self.convergence_order = convergence_order
        self.stencil_type = stencil_type
        #print("Check1")
        #Goal: Return D
        #initial parameters
        N=grid.N
        h=grid.dx
        ddx=derivative_order
        convE=convergence_order

        #print("Check2")
        #Create R matrix
        convE=2*math.ceil(convE/2)
        d=2*math.floor((ddx+convE-1)/2)+1
        mid=math.floor(d/2)

        R=np.zeros((d,d))
        r0=np.ones(d)
        r=h*np.arange(start=-(d-1)/2, stop=(d+1)/2, step=1)

        R[0]=r0
        i=1
        while i<d:
            R[i]=r**i
            i+=1

        #print("Check3")
        # Create k vector
        k=np.zeros(d)
        k[ddx]=1

        #Solve for coefficients, a
        a=math.factorial(ddx)*np.linalg.inv(R)@k

        #print("Check4")
        #Arrange coefficients in a sparse, derivative matrix: D
        lowerTri=np.arange(start=-N+1, stop=-N+mid+1, step=1)
        upperTri=np.arange(start=N-mid, stop=N, step=1)
        mainDiag=np.arange(start=-mid, stop=mid+1, step=1)

        #print("Main Diag: ", mainDiag)
        #print("a: ", a)
        Dmd = sparse.diags(a, mainDiag, shape=(N, N))
        DuT = sparse.diags(a[:mid], upperTri, shape=(N, N))
        DlT = sparse.diags(a[mid+1:], lowerTri, shape=(N, N))
        D = Dmd + DuT + DlT
        plot_2D(D.A)
        self.matrix = D
        pass

    def __matmul__(self, other):
        return self.matrix @ other

class DifferenceNonUniformGrid:

    def __init__(self, derivative_order, convergence_order, Grid, stencil_type='centered'):

        self.derivative_order = derivative_order
        self.convergence_order = convergence_order
        self.stencil_type = stencil_type
        self.grid = Grid

        grid=Grid.values
        length=Grid.length
        N=Grid.N
        ddx=derivative_order
        convE=convergence_order

        #Create R matrix
        convE=2*math.ceil(convE/2)
        d=2*math.floor((ddx+convE-1)/2)+1
        mid=math.floor(d/2)

        # Create k vector
        k=np.zeros(d)
        k[ddx]=math.factorial(ddx)

        #Begin iteration to construct D by individual stencil
        D = sparse.csr_matrix(np.zeros((N,N)))
        i=0
        while i<N:
            R=np.zeros((d,d))
            r0=np.ones(d)
            r=np.roll(grid, mid-i)[0:d]-grid[i]*np.ones(d)
            if i<mid:
                j=0
                while j<mid-i:
                    r[j]=r[j]-length
                    j+=1
            elif i>N-mid-1:
                j=-1
                while j>(N-i)-mid-2:
                    r[j]=r[j]+length
                    j-=1

            R[0]=r0
            j=1
            while j<d:
                R[j]=r**j
                j+=1

            Rinv=np.linalg.inv(R)

            #Solve for coefficients, a
            a=Rinv@k

            #Construct D row i, col j
            a_0s=np.concatenate((a,np.zeros(N-d)))
            a_0s_rolled=np.roll(a_0s, i-mid)
            D[i]=a_0s_rolled

            i+=1
        self.matrix = D
        pass

    def __matmul__(self, other):
        return self.matrix @ other

def plot_2D(matrix, title='FD matrix'):
    lim_margin = -0.05
    fig = plt.figure(figsize=(3,3))
    ax = fig.add_subplot()
    I, J = matrix.shape
    matrix_mag = np.log10(np.abs(matrix))
    ax.pcolor(matrix_mag[::-1])
    ax.set_xlim(-lim_margin, I+lim_margin)
    ax.set_ylim(-lim_margin, J+lim_margin)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_aspect('equal', 'box')
    plt.title(title)
    plt.tight_layout()


from flask import Flask, redirect, url_for, render_template, request, session, flash, abort,Blueprint
from datetime import datetime, timedelta
from flask_sqlalchemy import SQLAlchemy
import json
from models import Notification, Tickets, Users, db
from user import User
from flask_login import login_required, current_user, logout_user
from flask_wtf import FlaskForm
# from app.main.forms import MessageForm
from models import Message

mediator = Blueprint("mediator", __name__, static_folder="static", template_folder="templates")

class Mediator(Users):

    def __init__(self, username, groupchat, content):
        self._username = username
        self._groupchat = groupchat
        self._content = content

    def getUsername(self):
        return self._username

    def getGroup(self):
        return self._groupchat

    def getContent(self):
        return self._content

    @mediator.route('/send_message/<recipient>', methods=['GET', 'POST'])
    @login_required
    def send_message(recipient):
        user = User.query.filter_by(username=recipient).first_or_404()
        form = MessageForm()
        if form.validate_on_submit():
            msg = Message(author=current_user, recipient=user,
                        body=form.message.data)
            db.session.add(msg)
            db.session.commit()
            flash(_('Your message has been sent.'))
            return redirect(url_for('main.user', username=recipient))
        return render_template('send_message.html', title=_('Send Message'),
                            form=form, recipient=recipient)

    @mediator.route('/messages')
    @login_required
    def messages():
        current_user.last_message_read_time = datetime.utcnow()
        current_user.add_notification('unread_message_count', 0)
        db.session.commit()

    @mediator.route('/notifications')
    @login_required
    def notifications():
        since = request.args.get('since', 0.0, type=float)
        notifications = current_user.notifications.filter(
            Notification.timestamp > since).order_by(Notification.timestamp.asc())
        return jsonify([{
            'name': n.name,
            'data': n.get_data(),
            'timestamp': n.timestamp
        } for n in notifications])


from pynamodb.models import Model
from pynamodb.indexes import LocalSecondaryIndex, AllProjection, GlobalSecondaryIndex
from pynamodb.attributes import UnicodeAttribute, NumberAttribute, ListAttribute
from botocore.session import Session

from config import experiment_table_name

class RandomizationIdIndex(GlobalSecondaryIndex):
    """
    This class represents a local secondary index
    """
    class Meta:
        # All attributes are projected
        projection = AllProjection()
        billing_mode = "PAY_PER_REQUEST"

    randomization_id = NumberAttribute(hash_key=True)

class SetNumberIndex(GlobalSecondaryIndex):
    """
    This class represents a local secondary index
    """
    class Meta:
        # All attributes are projected
        projection = AllProjection()
        billing_mode = "PAY_PER_REQUEST"

    set_number = NumberAttribute(hash_key=True)

class ProcessedIndex(LocalSecondaryIndex):
    """
    This class represents a local secondary index
    """
    class Meta:
        # All attributes are projected
        projection = AllProjection()
    alias = UnicodeAttribute(hash_key=True)
    processed_status = NumberAttribute(range_key=True)

class ExperimentModel(Model):
    class Meta:
        table_name = experiment_table_name
        billing_mode = "PAY_PER_REQUEST"
        region = Session().get_config_variable('region')
    alias = UnicodeAttribute(hash_key=True)
    filename = UnicodeAttribute(range_key=True)
    video_id = UnicodeAttribute()
    emotion_id = NumberAttribute(default=1000)
    processed_status = NumberAttribute(default=0)
    valence = UnicodeAttribute()
    emotion_id_reply = NumberAttribute(default=1000)
    emotion_options = ListAttribute(of=NumberAttribute)
    set_number = NumberAttribute(default=1000)
    randomization_id = NumberAttribute(default=1000)

    processed_index = ProcessedIndex()
    set_number_index = SetNumberIndex()
    randomization_id_index = RandomizationIdIndex()

def create():
    # Create the table
    if not ExperimentModel.exists():
        ExperimentModel.create_table(wait=True)

if __name__ == "__main__":
    create()


import numpy as np
from scipy import stats

import matplotlib.pyplot as plt

incomes = np.random.normal(27000, 15000, 10000) # 27000-> centered around, std = 150000 with 10000 data points
m = np.mean(incomes)

print(m)

plt.hist(incomes, 50)
plt.show()

median = np.median(incomes)
print(median)

ages = np.random.randint(18, high=90, size=500)
print(ages)
mode = stats.mode(ages)
print(mode)


import User
import Order
import Market
import Currency
import datetime

class MainMenu:
    def __init__(self):
        self.user = User
        self.order = Order
        self.market = Market
        self.currency = Currency
        self.list_of_coins = [["DCC", "DCCapital Exchange"]]
        self.deleted_orders = []
        self.pre_orders_review = []
        self.list_of_trader = []
        self.list_of_matches = []
        self.running = bool
        self.show_options = {
                            "1": self.log_in,
                            "2": self.create_new_user,
                            "3": self.exit
                            }

    def display_menu(self):
        print('''
            Menu:
                1: Ingresar
                2: Crear cuenta
                3: Salir
            ''')

    def run_main_menu(self):
        self.running = True
        while self.running:
            self.display_menu()
            choice = input("Ingrese opción: ")
            action = self.show_options.get(choice)
            if action:
                action()
            else:
                print("{} no es una opción válida".format(choice))

    def log_in(self):
        username = input("Ingresar nombre de usuario: ")
        for user in self.user.User.list_of_users:
            if username == user.username:
                self.user.User.this_menu = True
                while self.user.User.this_menu:
                    if user.get_age() < 18:
                        self.user.Underaged.run_user(user)
                    elif user.has_priority:
                        self.user.Investor.run_user(user)
                    else:
                        self.user.Trader.run_user(user)
                    return
        print("Nombre de usuario inválido, pruebe nuevamente")
        return

    def create_new_user(self):
        username = input("Ingrese nombre de usuario: ")
        for user in self.user.User.list_of_users:
            if username in user.username:
                print("Nombre de usuario ya existe, pruebe nuevamente")
                return
        name = input("Ingrese su nombre: ")
        lastname = input("Ingrese su apellido: ")
        birthday = input("Ingrese su fecha de nacimiento de la siguiente forma -> YYYY-MM-DD: ")
        birth_list = birthday.split("-")
        try:
            if birthday != str(datetime.datetime.strptime(birthday, "%Y-%m-%d").date()):
                raise ValueError
            elif int(birth_list[0]) < 1900 or int(birth_list[0]) > 2017:
                raise ValueError
            else:
                self.user_assignment(username, name, lastname, birthday)
                for user in self.user.User.list_of_traders:
                    if user.username == username:
                        for coin in user.currency_balances:
                            if coin.symbol == "DCC":
                                coin.amount += 100000
                        user._save_users_csv()
                        user._save_money_csv()
                print("\n¡Usuario creado exitosamente! Por favor inicie sesión")
                return
        except ValueError:
            print("Fecha inválida, pruebe nuevamente")
            return

    def exit(self):
        self.running = False
        for user in self.user.User.list_of_users:
            user._save_all_csv()
            break
        print("Gracias por usar nuestra aplicación ¡Esperamos verte pronto!")

    def instantiate_users(self):  # Abre el archivo 'users.csv' y
        users = [line.split(';') for line in open('users.csv', 'r', encoding='UTF-8').read().split('\n')]
        list_of_kwargs = self._kwargs_master(users)
        for kwarg in list_of_kwargs:
            self.user_assignment(**kwarg)
        self._destroy_underaged_pair_orders()

    def instantiate_orders(self):  # creo las orders anteriores
        orders = [line.split(';') for line in open('orders.csv', 'r', encoding='UTF-8').read().split('\n')]
        list_of_kwargs = self._kwargs_master(orders)
        for kwarg in list_of_kwargs:
            self.order.Order(**kwarg)
        self.order.Order.list_of_orders.sort(key=lambda x: x.date_created)

    def instantiate_currencies(self):  # creo las currencies anteriores
        currencies = [line.split(';') for line in open('Currencies.csv', 'r', encoding='UTF-8').read().split('\n')]
        list_of_kwargs = self._kwargs_master(currencies)
        for kwarg in list_of_kwargs:
            values = kwarg.values()
            values_to_append = []
            short_value = ""
            long_value = ""
            for value in values:
                if len(value) == 3:
                    short_value = value
                else:
                    long_value = value
                if len(short_value) != 0 and short_value != "DCC" and len(long_value) != 0:
                    values_to_append.append(short_value)
                    values_to_append.append(long_value)
                    self.list_of_coins.append(values_to_append)
                    short_value = ""
                    long_value = ""

        for i in range(len(self.list_of_coins)):
            for j in range(len(self.list_of_coins)):
                if self.list_of_coins[i] != self.list_of_coins[j]:
                    self.market.Market(self.list_of_coins[i][0] + self.list_of_coins[j][0])

    def instantiate_money(self):
        try:
            money = [line.split(';') for line in open('money.csv', 'r', encoding='UTF-8').read().split('\n')]
            list_of_kwargs = self._kwargs_master(money)
            for kwarg in list_of_kwargs:
                for user in self.user.User.list_of_users:
                    if kwarg["username"] == user.username:
                        for coin in user.currency_balances:
                            if kwarg["symbol"] == coin.symbol:
                                coin.amount = float(kwarg["amount"])
        except:
            return

    def instantiate_historical_orders(self):
        try:
            orders = [line.split(';') for line in open('orderHistory.csv', 'r', encoding='UTF-8').read().split('\n')]
            list_of_kwargs = self._kwargs_master(orders)
            new_order = NotImplemented
            for kwarg in list_of_kwargs:
                new_order = self.order.Order(**kwarg)
                self.order.Order.list_of_orders.pop(self.order.Order.list_of_orders.index(new_order))
            orders_to_del = []
            self.order.Order.order_history.sort(key=lambda x: (x.order_id, x.date_created))
            for i in range(len(self.order.Order.order_history) - 1):
                o = self.order.Order.order_history[i]
                oo = self.order.Order.order_history[i + 1]
                if o.order_id == oo.order_id and o.ticker == oo.ticker and o.price == oo.price and \
                                o.date_created == oo.date_created and o.amount == o.amount and o.type == oo.type and \
                                o.date_match == oo.date_match and o not in orders_to_del:
                    orders_to_del.append(o)
            for order in orders_to_del:
                if order in self.order.Order.order_history:
                    self.order.Order.order_history.pop(self.order.Order.order_history.index(order))
            self.order.Order.order_history.sort(key=lambda x: x.date_created)
            self.order.Order._save_order_history(new_order)
            for user in self.user.User.list_of_users:
                list_of_orders = user.all_orders_id.split(":")
                if list_of_orders[0] == "":
                    return
                for i in range(len(list_of_orders)):
                    for order in self.order.Order.order_history:
                        if order.order_id == list_of_orders[i]:
                            user.list_of_my_historical_orders.append(order)
        except:
            return

    def instantiate_registered_markets(self):
        try:
            markets = [line.split(';') for line in open('registeredMarkets.csv', 'r', encoding="utf-8").read().split('\n')]
            list_of_kwargs = self._kwargs_master(markets)
            for user in self.user.User.list_of_users:
                user_markets = []
                user_markets_to_add = []
                for market in user.list_of_markets_registered:
                    user_markets.append(market.name)
                for kwarg in list_of_kwargs:
                    if kwarg["username"] == user.username:
                        if kwarg["name"] not in user_markets:
                            user_markets_to_add.append(kwarg["name"])
                for market in user.list_of_all_markets:
                    if market.name in user_markets_to_add:
                        user.list_of_markets_registered.append(market)
        except:
            return

    def user_assignment(self, username, name, lastname, birthday, orders=''):  # creo los users anteriores
        birth_date = birthday.split("-")
        year = int(datetime.datetime.now().strftime("%Y")) - int(birth_date[0])
        month = int(datetime.datetime.now().strftime("%m"))
        day = int(datetime.datetime.now().strftime("%d"))
        if month < int(birth_date[1]) or (month == int(birth_date[1]) and day > int(birth_date[2])):
            year -= 1
        if year < 18:
            new_user = self.user.Underaged(username, name, lastname, birthday, orders)
            self.destroy_underaged_orders(new_user)
        elif username[-8:] == "INVESTOR":
            investor_username = username[:-8]
            new_user = self.user.Investor(investor_username, name, lastname, birthday, orders)
            new_user.has_priority = True
        else:
            new_user = self.user.Trader(username, name, lastname, birthday, orders)
            self.go_to_order_preview(new_user)
        self.user.User.get_money(new_user, self.list_of_coins)
        return type(self.user)

    def destroy_underaged_orders(self, underaged):  # aca destruyo todas las orders de los usuarios underaged
        if len(underaged.orders_id) != 0:
            list_of_orders = underaged.orders_id.split(":")
            for i in range(len(list_of_orders)):
                for order in self.order.Order.list_of_orders:
                    if order.order_id == list_of_orders[i]:
                        self.deleted_orders.append(order)
                        self.order.Order.list_of_orders.pop(self.order.Order.list_of_orders.index(order))
            underaged.orders_id = ""

    def go_to_order_preview(self, trader):  # add orders from traders and investors for being checked
        list_of_orders = trader.orders_id.split(":")
        if list_of_orders[0] == "":
            return
        for i in range(len(list_of_orders)):
            for order in self.order.Order.list_of_orders:
                if order.order_id == list_of_orders[i] and order.order_id not in self.pre_orders_review:
                    self.pre_orders_review.append(order)

    def _destroy_underaged_pair_orders(self):  # checks the matches between wrong orders, taking them out
        for i in range(len(self.pre_orders_review)):
            order = self.pre_orders_review[i]
            for j in range(len(self.deleted_orders)):
                del_order = self.deleted_orders[j]
                if order.price == del_order.price and order.amount == del_order.amount and order != del_order:
                    self.order.Order.list_of_orders.pop(self.order.Order.list_of_orders.index(order))
        self._add_trader_orders_and_markets_to_user()

    def _add_trader_orders_and_markets_to_user(self):  # add orders and markets to user
        for market in self.market.Market.list_of_markets:
            self.user.User.list_of_all_markets.append(market)
        for user in self.user.User.list_of_users:
            if len(user.orders_id) > 0:
                list_of_orders = user.orders_id.split(":")
                for order in self.order.Order.list_of_orders:
                    if order.order_id in list_of_orders and order.order_id not in user.list_of_orders:
                        user.list_of_orders.append(order)
                        for market in self.market.Market.list_of_markets:
                            if market.name == order.ticker and market not in user.list_of_markets_registered:
                                user.list_of_markets_registered.append(market)
        self._get_matches()

    def _get_matches(self):  # Agarra las orders que ya se ejecutaron, las guarda y elimina
        for order in self.order.Order.list_of_orders:
            if order.date_match != "":
                for user in self.user.User.list_of_users:
                    if order in user.list_of_orders and order.type == "bid":
                        for user_coin in user.currency_balances:
                            if order.ticker[:3] == user_coin.symbol:
                                user_coin.amount -= float(order.amount)
                            elif order.ticker[3:] == user_coin.symbol:
                                user_coin.amount += float(order.price)
                        user.list_historical_matches.append(order)
                        user.list_historical_matches.sort(key=lambda x: x.date_match)
                        user.list_of_orders.pop(user.list_of_orders.index(order))
                        break
                    elif order in user.list_of_orders and order.type == "ask":
                        for user_coin in user.currency_balances:
                            if order.ticker[:3] == user_coin.symbol:
                                user_coin.amount += float(order.amount)
                            elif order.ticker[3:] == user_coin.symbol:
                                user_coin.amount -= float(order.price)
                        user.list_historical_matches.append(order)
                        user.list_historical_matches.sort(key=lambda x: x.date_match)
                        user.list_of_orders.pop(user.list_of_orders.index(order))
                        break
                self.list_of_matches.append(order)
        self._add_matches_to_respective_places()

    def _add_matches_to_respective_places(self):
        for order in self.list_of_matches:
            self.order.Order.list_of_orders.pop(self.order.Order.list_of_orders.index(order))
        if len(self.list_of_matches) > 0:  # en caso de que no haya ningun match en el csv
            self.list_of_matches.sort(key=lambda x: x.date_match)
            for user in self.user.User.list_of_users:
                for market in user.list_of_all_markets:
                    for i in range(len(user.list_of_markets_registered)):
                        if market.name == user.list_of_markets_registered[i].name:
                            user.list_of_markets_registered[i] = market
            for user in self.user.User.list_of_users:
                user._save_markets()
                break
        self._get_order_ids_right()

    def _get_order_ids_right(self):
        for user in self.user.User.list_of_users:
            actual_ids = []
            user.orders_id = ""
            for user_order in user.list_of_orders:
                actual_ids.append(user_order.order_id)
            for i in range(len(actual_ids)):
                user.orders_id += str(actual_ids[i]) + ":"
            user.orders_id = user.orders_id[:-1]
            user.all_orders_id = user.orders_id[:-1]
        for order in self.order.Order.order_history:
            order._save_orders_csv()
            break

    def _kwargs_master(self, list_to_turn):  # obtiene los kwargs para ser entregados
        list_of_headers = []
        list_of_kwargs = []
        for i in range(len(list_to_turn)):
            if i == 0:
                for j in range(len(list_to_turn[0])):
                    header = ""
                    for string in list_to_turn[0][j]:
                        if string != ":":
                            header += string
                        else:
                            list_of_headers.append(header)
                            break
            elif i < len(list_to_turn) - 1:
                kwargs = {}
                for j in range(len(list_to_turn[i])):
                    kwarg1 = {list_of_headers[j]: list_to_turn[i][j]}
                    kwargs.update(kwarg1)
                list_of_kwargs.append(kwargs)
        return list_of_kwargs

menu = MainMenu()
MainMenu.instantiate_orders(menu)
MainMenu.instantiate_currencies(menu)
MainMenu.instantiate_users(menu)
MainMenu.instantiate_money(menu)
MainMenu.instantiate_historical_orders(menu)
MainMenu.instantiate_registered_markets(menu)
menu.run_main_menu()


import random
from algorithm.base_algorithm import *
from queue import PriorityQueue

class RSMP(BaseAlgorithm):
    def __init__(self, network: Network, tenants: List[Tenant]):
        super().__init__(network, tenants)

    def build_feasible_assignment(self, tenant):
        self.network.forwarder_set.sort()
        sharding = self.network.forwarder_set[:tenant.max_sharding_size]
        sharding.sort()
        sharding_heap = PriorityQueue()
        for fwd in sharding:
            sharding_heap.put_nowait(fwd)

        for ins in tenant.ins_list:
            best_fwd = sharding_heap.get_nowait()
            best_fwd.cap_remain -= ins.cost
            ins.forwarder = best_fwd
            sharding_heap.put_nowait(best_fwd)

    def main_procedure(self):
        for tenant in self.tenants:
            self.build_feasible_assignment(tenant)


# -*- coding: utf-8 -*-
"""
Created on Fri Apr 08 11:33:01 2016

@author: Leander Kotzur
"""

import tsib

def test_get_ID():
    # parameterize a building
    bdgcfg = tsib.BuildingConfiguration(
        {
            "refurbishment": False,
            "nightReduction": False,
            "occControl": False,
            "capControl": True,
            "n_persons": 2,
            "roofOrientation": 0.0,
            "n_apartments": 1,
            "latitude": 49.,
            "longitude": 12.,
        }
    )

    bdgObj = tsib.Building(configurator=bdgcfg)
    print('ID is : ' + str(bdgObj.ID))

    return

def test_set_ID():
    # parameterize a building
    bdgcfg = tsib.BuildingConfiguration(
        {
            "buildingYear": 1980,
            "n_persons": 2,
            "roofOrientation": 0.0,
            "n_apartments": 2,
            "a_ref": 300.,
            "surrounding": "Detached",
            "latitude": 52.,
            "longitude": 13.,
        }
    )
    bdgObj = tsib.Building(configurator=bdgcfg)

    bdgObj.ID = 'custom'

    if not bdgObj.ID == 'custom':
        raise ValueError()

    return


import json
import pandas as pd
from pprint import pprint

class SetAttrs:
    """set information about each atom as attribute"""
    def __init__(self, data: dict) -> None:
        self.set_attrs(data)

    def set_attrs(self, data: dict) -> None:
        df = pd.DataFrame.from_dict(data)
        print(df)
        for item in df['atoms']:
            print(item)

with open("param.json") as f:
    data = json.load(f)

for files in data['files']:
    s = SetAttrs(files)

    for atom in files['atoms']:
        if files['symb'] == "D":
            atom['type'] += 2


from PyQRNative import QRCode, QRErrorCorrectLevel, CodeOverflowException

class QR():
	''' Base QR Code API class.'''
	def __init__(self, size=1, level = QRErrorCorrectLevel.M):
		self.qr = QRCode(size, level)
		self.data = ''
		self.level = level
		self.size = size
		self.needs_update = True

	def write(self, text):
		self.data += text.__str__()
		self.needs_update = True

	def make(self):
		if self.needs_update == True:
			self.qr = QRCode(self.size, self.level)
			self.qr.addData(self.data)
			# Check that the data fits into the QR code of the required size:
			size = self.qr.getMinimumSize()
			if self.size < size:
				self.size = size
				self.qr = QRCode(size, self.level)
				self.qr.addData(self.data)
			self.qr.make()
			self.image = self.qr.makeImage()
			self.needs_update = False

	def display(self):
		if self.needs_update:
			self.make()
		self.image.show()

	def save(self, imagename):
		self.image.save(imagename)

class QRFile(QR):
	''' Implements the sending of files, as supported by Scripting Layer for Android (SL4A).
The first line is the filename, the resulting lines are just the file.

Example usage:
>>> f = QRFile(infile='myfile.txt', filename= 'myscript.py', size = 5)
>>> f.make()
>>> f.save('tmpfile.png')
>>> f.display()
'''
	def __init__(self, infile, filename, size=10, level = QRErrorCorrectLevel.L):
		''' Input:
	infile: filehandle or filename (string)
	filename: string for output filename
	size: minimum size of QR-code 1..40; Default 10.
	level: Error correction level, (L, M, Q, H).'''
		QR.__init__(self, size= size, level=level)
		self.loadFile(infile, filename)

	def loadFile(self, infile, filename):
		self.write(filename)
		self.write('\n')
		if isinstance(infile, file):
			self.write(infile.read())
		elif isinstance(infile, str):
			fh = open(infile, 'r')
			self.write(fh.read())
			fh.close()
		else:
			raise Exception('Could not handle input argument for file.')

class QRUrl(QR):
	''' URL/URI class for QR codes.

Pass a url, no checking will be done!'''
	def __init__(self, url, size=1, level = QRErrorCorrectLevel.L):
		QR.__init__(self, size= size, level=level)
		self.write(url) # No formatting checks will be performed to allow more flexibility.

if __name__=='__main__':
	f = QRUrl(url = 'rtsp://sdcard/')
	f.make()
	f.display()