import urllib.request
import urllib.parse
import traceback
import zmq
import json
import socket
import struct

from werp import froxly_checker_log
from werp.common import sockets
from werp.common import timeouts
from werp.common import red_keys

def run(url):
    try:
        ctx = zmq.Context()

        froxly_checker_worker_socket = ctx.socket(zmq.PULL)
        froxly_checker_worker_socket.connect(sockets.format_socket_uri(sockets.froxly_checker_worker, url=url))

        ugently_data_server_socket = ctx.socket(zmq.REQ)
        ugently_data_server_socket.connect(sockets.ugently_data_server)

        froxly_checker_sink_socket = ctx.socket(zmq.PUSH)
        froxly_checker_sink_socket.connect(sockets.format_socket_uri(sockets.froxly_checker_sink, url=url))

        froxly_checker_finish_socket = ctx.socket(zmq.SUB)
        froxly_checker_finish_socket.connect(sockets.format_socket_uri(sockets.froxly_checker_finish, url=url))
        froxly_checker_finish_socket.setsockopt_string(zmq.SUBSCRIBE, '')

        poller = zmq.Poller()
        poller.register(froxly_checker_worker_socket, zmq.POLLIN)
        poller.register(froxly_checker_finish_socket, zmq.POLLIN)

        while True:
            socks = dict(poller.poll())

            if froxly_checker_worker_socket in socks and socks[froxly_checker_worker_socket] == zmq.POLLIN:
                task = json.loads(froxly_checker_worker_socket.recv_unicode())
                ugently_data_server_socket.send_unicode('')
                rnd_user_agent = ugently_data_server_socket.recv_unicode()
                try:
                    if task['proxy']['protocol'] == 'socks4/5':
                        s = socket.socket()
                        s.settimeout(timeouts.froxly_checker)
                        url_obj = urllib.parse.urlparse(task['url'])
                        s.connect((task['proxy']['ip'], int(task['proxy']['port'])))
                        ipaddr = socket.inet_aton(socket.gethostbyname(url_obj.netloc))
                        destport = 80
                        conn_req = struct.pack(">BBH", 0x04, 0x01, destport) + ipaddr
                        conn_req = conn_req + chr(0x00).encode()
                        s.sendall(conn_req)
                        conn_resp = s.recv(8)
                        if conn_resp[0:1] == chr(0x00).encode() or conn_resp[1:2] == chr(0x5A).encode():
                            s.close()
                            raise Exception('Socks proxy error')
                        req_str = 'GET ' + task['url'] + ' HTTP/1.1\r\nHost:' + url_obj.netloc + '\r\n\r\n'
                        s.sendall(req_str.encode())
                        res = s.recv(15).decode()
                        s.close()
                        if res == 'HTTP/1.0 200 OK' or res == 'HTTP/1.1 200 OK':
                            task['proxy']['http_status'] = 200
                            task['proxy']['http_status_reason'] = None
                            task['proxy']['protocol_version'] = '4'
                        else:
                            task['proxy']['http_status'] = -1
                            task['proxy']['http_status_reason'] = res
                    else:
                        is_1_1 = False

                        # HTTP 1.1
                        s = socket.socket()
                        s.settimeout(timeouts.froxly_checker)
                        url_obj = urllib.parse.urlparse(task['url'])
                        s.connect((task['proxy']['ip'], int(task['proxy']['port'])))
                        req_str = 'GET ' + task['url'] + ' HTTP/1.1\r\nHost:' + url_obj.netloc + '\r\n\r\n'
                        s.sendall(req_str.encode())
                        res = s.recv(15).decode()
                        s.close()
                        if res == 'HTTP/1.1 200 OK':
                            is_1_1 = True
                            task['proxy']['http_status'] = 200
                            task['proxy']['http_status_reason'] = None
                            task['proxy']['protocol_version'] = '1.1'
                        else:
                            task['proxy']['http_status'] = -1
                            task['proxy']['http_status_reason'] = res

                        # HTTP 1.0
                        if not is_1_1:
                            s = socket.socket()
                            s.settimeout(timeouts.froxly_checker)
                            url_obj = urllib.parse.urlparse(task['url'])
                            s.connect((task['proxy']['ip'], int(task['proxy']['port'])))
                            req_str = 'GET ' + task['url'] + ' HTTP/1.0\r\nHost:' + url_obj.netloc + '\r\n\r\n'
                            s.sendall(req_str.encode())
                            res = s.recv(15).decode()
                            s.close()
                            if res == 'HTTP/1.0 200 OK':
                                task['proxy']['http_status'] = 200
                                task['proxy']['http_status_reason'] = None
                                task['proxy']['protocol_version'] = '1.0'
                            else:
                                task['proxy']['http_status'] = -1
                                task['proxy']['http_status_reason'] = res
                except Exception as e:
                    task['proxy']['http_status'] = -1
                    task['proxy']['http_status_reason'] = str(e)
                froxly_checker_sink_socket.send_unicode(json.dumps(task))

            if froxly_checker_finish_socket in socks and socks[froxly_checker_finish_socket] == zmq.POLLIN:
                break
    except:
        froxly_checker_log.exception('worker "run"\n\n' + traceback.format_exc())

def socks_recvall(self, count):
    data = self.recv(count)
    while len(data) < count:
        d = self.recv(count-len(data))
        if not d:
            raise GeneralProxyError((0, "connection closed unexpectedly"))
        data = data + d
    return data


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

# In[11]:

num1= float(input("Lutfen bir sayi giriniz"))
num2= float(input("Lutfen bir sayi giriniz"))
num3= float(input("Lutfen bir sayi giriniz"))
if num1>num2 and num1>num3 :
    largest=num1
    print("the largest number is:",largest)

elif  num2>num1 and num2>num3 :
    largest=num2
    print("the largest number is:",largest)

else :
    largest=num3
    print("the largest number is :",largest)

# In[16]:

score=int(input("Enter Your Score"))

if score >= 90 :
    if score >= 95 :
        score_letter="A+"
    else:
            score_letter = "A"

elif score >= 80 :
    if score >= 85 :

        score_letter = "B+"
    else :
            score_letter = "B"

else:
    score_letter = "B-"

print("Your degree is :",score_letter)

# In[18]:

age = input("enter your age please :")

while not age.isdigit():
    print("you entered incorrect(sayi girmen lazim)")
    age= input ("enter your age(sayiyla yaz sayiyla)")
    print("aferin dogru girdin!",age)

# In[ ]:

while True :
    number = int(input("sayi gir :"))
    plaka = 55
if  number < plaka :

        print("dusuk yazdin biraz daha buyuk bir sayi dene")
elif  number > plaka :
        print("fazla yazdin daha dusuk bir sayi dene")
else:
        print("aferin plakayi tutturdun")

        break

# In[7]:

list1=[]

for i in range (1,6):
    list1 +=[i]

print(list1)

# In[31]:

x = input("kelime yaz:")
for i in x:
    print(i,end = "-")

# In[34]:

test = [(1,2),(3,4),(5,6)]
for i, j in test :
     print(test)

# In[42]:

test = [1,2,3,4]
for i in test :
     print(i)

# In[51]:

number=int(input("bir sayi giriniz"))
for i in range (11):
    print(number, "x", i, "=",i*number)

# In[57]:

count = 0
for i in range(1,10):
    count +=1
    print(i*str(count))

# In[91]:

evens=[]
odds=[]
for i in range(10):
    if i % 2 == 1:
        odds.append(i)
    else:
            evens.append(i)
            print(evens)
            print(odds)

# In[ ]:

count=0

for i in range(75):

     count+=i

     print(count)

# In[10]:

names = ["susan","tom","edward"]

mood= [ "happy","sad"]

for i in names:
    for ii in mood:
        print(i + " " +  "is" +" "  +ii)

# In[21]:

v= ("five",5,True)

# In[22]:

v

# In[23]:

v=(x,y,z)

# In[24]:

x

# In[27]:

p=(1,2,3)

# In[28]:

p

# In[31]:

p=("u","y","o")

# In[34]:

"u"

# In[36]:

(m,t,s,w)=tuple(range(1,5))

# In[41]:

# In[47]:

x,y,*_,t= (11,22,33,44,55,66,77)

# In[50]:

_

# # List Comprehension
# {expression for otem in iterable}
#
# for item in iterable :
#      expression
#

# In[55]:

sayilar = []
for i in range(5):
    sayilar.append(i)

sayilar

# In[58]:

[i for i in range(5)]

# In[59]:

[i**2 for i in range(1,10)]

# In[ ]:

# In[86]:

my_list=[1,2,3,4,5,6]
[i**2 for i in my_list if i % 2 ==1]

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:

# In[ ]:


import numpy as np

from py4DSTEM.process.utils import get_CoM

def get_probe_size(DP, thresh_lower=0.01, thresh_upper=0.99, N=100):
    """
    Gets the center and radius of the probe in the diffraction plane.

    The algorithm is as follows:
    First, create a series of N binary masks, by thresholding the diffraction pattern
    DP with a linspace of N thresholds from thresh_lower to thresh_upper, measured
    relative to the maximum intensity in DP.
    Using the area of each binary mask, calculate the radius r of a circular probe.
    Because the central disk is typically very intense relative to the rest of the DP, r
    should change very little over a wide range of intermediate values of the threshold.
    The range in which r is trustworthy is found by taking the derivative of r(thresh)
    and finding identifying where it is small.  The radius is taken to be the mean of
    these r values. Using the threshold corresponding to this r, a mask is created and
    the CoM of the DP times this mask it taken.  This is taken to be the origin x0,y0.

    Args:
        DP (2D array): the diffraction pattern in which to find the central disk.
            A position averaged, or shift-corrected and averaged, DP works best.
        thresh_lower (float, 0 to 1): the lower limit of threshold values
        thresh_upper (float, 0 to 1): the upper limit of threshold values
        N (int): the number of thresholds / masks to use

    Returns:
        (3-tuple): A 3-tuple containing:

            * **r**: *(float)* the central disk radius, in pixels
            * **x0**: *(float)* the x position of the central disk center
            * **y0**: *(float)* the y position of the central disk center
    """
    from py4DSTEM.braggvectors import Probe

    # parse input
    if isinstance(DP, Probe):
        DP = DP.probe

    thresh_vals = np.linspace(thresh_lower, thresh_upper, N)
    r_vals = np.zeros(N)

    # Get r for each mask
    DPmax = np.max(DP)
    for i in range(len(thresh_vals)):
        thresh = thresh_vals[i]
        mask = DP > DPmax * thresh
        r_vals[i] = np.sqrt(np.sum(mask) / np.pi)

    # Get derivative and determine trustworthy r-values
    dr_dtheta = np.gradient(r_vals)
    mask = (dr_dtheta <= 0) * (dr_dtheta >= 2 * np.median(dr_dtheta))
    r = np.mean(r_vals[mask])

    # Get origin
    thresh = np.mean(thresh_vals[mask])
    mask = DP > DPmax * thresh
    x0, y0 = get_CoM(DP * mask)

    return r, x0, y0


# bot.py
import os
import math
from cv2 import add
from dotenv import load_dotenv
from discord.ext import commands

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

bot = commands.Bot(command_prefix='!Newton ')

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')

@bot.command(name="add")
async def addition(ctx, num1: float, num2: float):
    response = num1 + num2
    await ctx.send(response)

@bot.command(name="Compute")
async def computation(ctx, problem):
    ans = 0
    if("+" in problem):
        problemArray = problem.split('+')
        for i, v in enumerate(problemArray):
            problemArray[i] = float(v)
        ans += math.fsum(problemArray)
    response = "```\n" + str(problem) + "\n" + str(ans) + "```"
    await ctx.send(response)

bot.run(TOKEN)


from django.http import HttpResponse
from django.shortcuts import render, redirect
from movies.models import Person, Movie

filmy_list = ['Titanic', 'Avatar', 'New Hope', 'Noce i Dnie', 'Coś', 'The Crown']
kina_list = ['Helios', 'Cinema City', 'Nowe Horyzonty']

# Create your views here.

def index(request):
    return render(request, 'base.html')

def wyszukaj(zapytanie, lista):
    ret_lst = []
    for movie in lista:
        if zapytanie in movie.lower():
            ret_lst.append(movie)
    return ret_lst

def filmy(request):
    ret_lst = Movie.objects.all()
    return render(request, 'list_view.html', {'object_list': ret_lst})

def aktorzy(request):
    # zapytanie = request.GET.get('zapytanie', '').lower()
    ret_lst = Person.objects.all()
    return render(request, 'list_view.html', {'object_list': ret_lst})

def detail_actor_view(request, id):
    aktor = Person.objects.get(id=id)
    if request.method == 'GET':
        return render(request, 'actor_detail.html', {'object': aktor})
    imie = request.POST.get('imie')
    nazwisko = request.POST.get('nazwisko')
    description = request.POST.get('description')
    aktor.first_name = imie
    aktor.last_name = nazwisko
    aktor.description = description
    aktor.save()
    return render(request, 'actor_detail.html', {'object': aktor})

def dodaj_aktora(request):
    if request.method == 'GET':
        return render(request, 'add_actor.html')
    imie = request.POST.get('imie')
    nazwisko = request.POST.get('nazwisko')
    p = Person(first_name=imie, last_name=nazwisko)
    p.save()
    return render(request, 'add_actor.html')

def kina(request):
    zapytanie = request.GET.get('zapytanie', '').lower()
    ret_lst = wyszukaj(zapytanie, kina_list)
    return render(request, 'list_view.html', {'object_list': ret_lst})

def dodaj_film(request):
    if request.method == 'GET':
        return render(request, 'dodaj_film.html')
    tytul = request.POST.get('title')
    year = request.POST.get('year')
    m = Movie(title=tytul, year=year)
    m.save()
    return redirect("/filmy/")

def delete_person_view(request, id):
    p = Person.objects.get(pk=id)
    if request.method == 'GET':
        return render(request, 'del_p.html', {'person':p})
    ans = request.POST.get('conf')
    if ans == 'tak':
        p.delete()
    return redirect('/aktorzy/')


from chatterbot.adapters import Adapter

class InputAdapter(Adapter):
    """
    This is an abstract class that represents the
    interface that all input adapters should implement.
    """

    def process_input(self, *args, **kwargs):
        """
        Returns a statement object based on the input source.
        """
        raise self.AdapterMethodNotImplementedError()

    def process_input_statement(self, *args, **kwargs):
        """
        Return an existing statement object (if one exists).
        """
        input_statement = self.process_input(*args, **kwargs)

        self.logger.info('Received input statement: {}'.format(input_statement.text))

        existing_statement = self.chatbot.storage.find(input_statement.text)

        if existing_statement:
            self.logger.info('"{}" is a known statement'.format(input_statement.text))
            input_statement = existing_statement
        else:
            self.logger.info('"{}" is not a known statement'.format(input_statement.text))

        return input_statement


import os
import json
import networkx as nx

__all__ = ['common_working_graph', 'classproperty']

# taken from https://stackoverflow.com/a/39542816, licensed under CC BY-SA 3.0
# not needed in py39+
class classproperty(property):
    def __get__(self, obj, objtype=None):
        return super(classproperty, self).__get__(objtype)

def common_working_graph(graph0, graph1):
    """Creates a graph using the common nodes and edges of two given graphs.

    This function finds the edges and nodes with common labels. Note that this
    not the same as finding the greatest common subgraph with isomorphisms.

    Args:
        graph0: (dict[dict]/:obj:`~networkx.Graph`)
            A NetworkX graph or a dictionary of dictionaries adjacency
            representation.

        graph1: (dict[dict]/:obj:`~networkx.Graph`)
            A NetworkX graph or a dictionary of dictionaries adjacency
            representation.

    Returns:
        :obj:`~networkx.Graph`: A graph with the nodes and edges common to both
        input graphs.

    Examples:

        This example creates a graph that represents a part of a particular
        Advantage quantum computer's working graph.

        >>> import dwave_networkx as dnx
        >>> from dwave.system import DWaveSampler, common_working_graph
        ...
        >>> sampler = DWaveSampler(solver={'topology__type': 'pegasus'})
        >>> P3 = dnx.pegasus_graph(3)
        >>> p3_working_graph = common_working_graph(P3, sampler.adjacency)

    """

    G = nx.Graph()
    G.add_nodes_from(v for v in graph0 if v in graph1)
    G.add_edges_from((u, v) for u in graph0 for v in graph0[u]
                     if v in graph1 and u in graph1[v])

    return(G)

class FeatureFlags:
    """User environment-level Ocean feature flags pertinent to dwave-system."""

    # NOTE: This is an experimental feature. If we decide to keep it, we'll want
    # to move this machinery level up to Ocean-common.

    @staticmethod
    def get(name, default=False):
        try:
            return json.loads(os.getenv('DWAVE_FEATURE_FLAGS')).get(name, default)
        except:
            return default

    @classproperty
    def hss_solver_config_override(cls):
        return cls.get('hss_solver_config_override')


import sys

p, k = map(int, sys.stdin.readline().split())
tmp = [True] * k
for i in range(2, k):
    if tmp[i]:
        for j in range(i + i, k, i):
            tmp[j] = False
prior = [i for i in range(2, k) if tmp[i]]

ans = "GOOD"
for i in prior:
    if p % i == 0:
        ans = f"BAD {i}"
        break
print(ans)


import sqlite3
from sqlite3 import Error

from ReferenceStructure import *

# Checked
def createDB(db_path):
    conn = createConnectionToDB(db_path)
    if conn is not None:
        # create projects table
        initTables(conn)
    else:
        print("Error! cannot create the database connection.")

def initTables(dbConnection):
    # Create Article table
    # sql_create_article_table = """ CREATE TABLE IF NOT EXISTS "Article" (
    #                                     `ID` INTEGER NOT NULL PRIMARY KEY UNIQUE,
    #                                     `Title` TEXT NOT NULL,
    #                                     `Author` TEXT,
    #                                     `Type` TEXT NOT NULL,
    #                                     `Journal` TEXT,
    #                                     `Year` INTEGER NOT NULL,
    #                                     `Labels` TEXT,
    #                                     `AddedTime` TEXT NOT NULL
    #                                 ); """
    # print(sql_create_article_table)
    for type in BibTeXTypes:
        tablename = type.capitalize()
        sql_head = " CREATE TABLE IF NOT EXISTS " + "\"" + tablename + "\" ("
        DB_BaseStr = "`ID` INTEGER NOT NULL PRIMARY KEY UNIQUE," \
                   + "`RefAbsID` INTEGER NOT NULL," \
                   + "`Labels` TEXT," \
                   + "`AddedTime` TEXT NOT NULL," \
                   + "`Citekey` TEXT," \
                   + "`Flags` TEXT," \
                   + "`Attachments` TEXT," \
                   + "`Links` TEXT,"
        DB_FieldsStrList = []
        DB_ExtendFieldsStrList = []
        for field in DatabaseStandardStructure[tablename]:
            tempStr = "`" + field + "` TEXT"
            DB_FieldsStrList.append(tempStr)
        for field in DB_ExtendFields:
            tempStr = "`" + field + "` TEXT"
            DB_ExtendFieldsStrList.append(tempStr)
        DB_FieldsStr = ",".join(DB_FieldsStrList + DB_ExtendFieldsStrList)
        sql_tail = "); "
        sql_create_table_expr =  sql_head + DB_BaseStr + DB_FieldsStr + sql_tail
        createTable(dbConnection, sql_create_table_expr)

    # Create Citation table
    sql_create_citation_table = """ CREATE TABLE IF NOT EXISTS "Citation" (
                                        `ID` INTEGER NOT NULL PRIMARY KEY UNIQUE,
                                        `Self` TEXT,
                                        `Cited` TEXT,
                                        `CitedBy` TEXT
                                    ); """
    createTable(dbConnection, sql_create_citation_table)
    # Create Labels table
    sql_create_labels_table = """ CREATE TABLE IF NOT EXISTS "Labels" (
                                        `ID` INTEGER NOT NULL PRIMARY KEY UNIQUE,
                                        `Name` TEXT NOT NULL UNIQUE
                                    ); """
    createTable(dbConnection, sql_create_labels_table)
    # Create PubIn table
    sql_create_pubin_table = """ CREATE TABLE IF NOT EXISTS "PubIn" (
                                        `ID` INTEGER NOT NULL PRIMARY KEY UNIQUE,
                                        `Name` TEXT NOT NULL UNIQUE
                                    ); """
    createTable(dbConnection, sql_create_pubin_table)
    # Create Trash table
    sql_create_trash_table = """ CREATE TABLE IF NOT EXISTS "Trash" (
                                        `ID` INTEGER NOT NULL PRIMARY KEY UNIQUE,
                                        `Title` TEXT NOT NULL UNIQUE
                                    ); """
    createTable(dbConnection, sql_create_trash_table)
    # Create Years table
    sql_create_years_table = """ CREATE TABLE IF NOT EXISTS "Years" (
                                        `ID` INTEGER NOT NULL PRIMARY KEY UNIQUE,
                                        `Year` TEXT NOT NULL UNIQUE
                                    ); """
    createTable(dbConnection, sql_create_years_table)

# Checked
def createTable(dbConnection, create_table_sql):
    """ create a table from the create_table_sql statement
    :param conn: Connection object
    :param create_table_sql: a CREATE TABLE statement
    :return:
    """
    try:
        c = dbConnection.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)

# Checked
def createConnectionToDB(db_file):
    """ create a database connection to the SQLite database
        specified by the db_file
    :param db_file: database file
    :return: Connection object or None
    """
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)
        return None

def countAllRefsInDB(dbConnection):
    allRefNum = 0
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempNum = countRefsInTable(dbConnection, tablename)
        allRefNum = allRefNum + tempNum
    return allRefNum

def countRefsInTable(dbConnection, tablename):
    sql = "SELECT Count(*) FROM " + tablename
    cur = dbConnection.cursor()
    cur.execute(sql)
    refNum = cur.fetchone()
    return refNum[0]

# Checked
def countRefs(dbConnection):
    sql = "SELECT Count(*) FROM ReferencesData"
    cur = dbConnection.cursor()
    cur.execute(sql)
    refNum = cur.fetchone()
    return refNum[0]

# Checked
def createTempCitationTable(dbConnection):
    """
    Create a table in the database
    """
    sql = ''' CREATE TABLE TempCitation
              (ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, Self TEXT, Cited TEXT, CitedBy TEXT)'''
    cur = dbConnection.cursor()
    cur.execute(sql)
    dbConnection.commit()

# Checked
def deleteTempCitationTable(dbConnection):
    """
    Delete temp citation table from the database
    """
    sql = ''' DROP TABLE TempCitation'''
    cur = dbConnection.cursor()
    cur.execute(sql)
    dbConnection.commit()

def readRefFromDBByDict(dbConnection, refItem1):
    """
    Read one piece of reference from database with reference dictionary
    :param dbConnection: the Connection object
    :param refItem: reference dictionary
    :return:
    """
    tablename = refItem1['MType']
    sql = "SELECT * FROM " + tablename + " WHERE title=? AND author=? AND year=?"
    cur = dbConnection.cursor()
    cur.execute(sql, (refItem1['title'], refItem1['author'], refItem1['year']))
    rows = cur.fetchall()
    refItem2 = {}
    tempDBFieldsList = DB_BaseFields + DatabaseStandardStructure[tablename] + DB_ExtendFields
    if len(rows) >= 1:
        if len(rows[0]) <= len(tempDBFieldsList):
            for i in range(len(rows[0])):
                refItem2[tempDBFieldsList[i]] = rows[0][i]

    return refItem2

# Checked
def writeRefToDB(dbConnection, refDict):
    # Check item existance first
    tempItem = readRefFromDBByDict(dbConnection, refDict)
    if len(tempItem):
        tempItem1 = {}
        tempItem1['title'] = tempItem['title']
        tempItem1['author'] = tempItem['author']
        tempItem1['year'] = tempItem['year']
        tempItem2 = {}
        tempItem2['title'] = refDict['title']
        tempItem2['author'] = refDict['author']
        tempItem2['year'] = refDict['year']
        if tempItem1 == tempItem2:
            pass
        else:
            # Not exact the same, wait to check by users
            tablename = refDict['MType']
            tempDBFieldsList = DB_BaseFields + DatabaseStandardStructure[tablename] + DB_ExtendFields
            sql = "INSERT INTO " + tablename + "(" + ",".join(tempDBFieldsList[1:]) + ") VALUES(" + ",".join(["?"]*len(tempDBFieldsList[1:])) + ")"
            task = ()
            for field in tempDBFieldsList[1:]:
                task = task + (refDict[field],)
            cur = dbConnection.cursor()
            cur.execute(sql, task)
            dbConnection.commit()
    else:
        # Not exist, add to database
        tablename = refDict['MType']
        tempDBFieldsList = DB_BaseFields + DatabaseStandardStructure[tablename] + DB_ExtendFields
        sql = "INSERT INTO " + tablename + "(" + ",".join(tempDBFieldsList[1:]) + ") VALUES(" + ",".join(["?"]*len(tempDBFieldsList[1:])) + ")"
        task = ()
        for field in tempDBFieldsList[1:]:
            task = task + (refDict[field],)
        cur = dbConnection.cursor()
        cur.execute(sql, task)
        dbConnection.commit()

# Checked
def writeRefsToDB(dbConnection, refDictList):
    if len(refDictList):
        for refDict in refDictList:
            writeRefToDB(dbConnection, refDict)
            updateRefAbsID(dbConnection, refDict)

def updateRefAbsID(dbConnection, refDict):
    tempItem = readRefFromDBByDict(dbConnection, refDict)
    tablename = refDict['MType']
    sql = "UPDATE " + tablename + " SET  RefAbsID= ? WHERE id = ?"
    refAbsID = int(str(DB_TypeCode[tablename])+str(tempItem['ID']).zfill(8))
    task = (refAbsID, tempItem['ID'])
    cur = dbConnection.cursor()
    cur.execute(sql, task)
    dbConnection.commit()

def readRefInDBTableByID(dbConnection, refType, refAbsID):
    tablename = refType
    cur = dbConnection.cursor()
    cur.execute("SELECT * FROM " + tablename +" WHERE RefAbsID=?", (refAbsID,))
    rows = cur.fetchall()
    refItem = {}
    tempDBFieldsList = DB_BaseFields + DatabaseStandardStructure[refType] + DB_ExtendFields
    row = rows[0]
    refItem = DB2Dict(rows, tablename)[0]
    return refItem

# Checked
def readRefFromDBByID(dbConnection, refAbsID):
    """
    Read one piece of reference from database with reference id
    :param dbConnection: the Connection object
    :param refAbsID: reference absolution id
    :return:
    """
    cur = dbConnection.cursor()
    cur.execute("SELECT * FROM ReferencesData WHERE id=?", (refAbsID,))
    rows = cur.fetchall()
    refItem = {}
    if len(rows[0]) <= len(DatabaseReferenceStructure):
        for i in range(len(rows[0])):
            refItem[DatabaseReferenceStructure[i]] = rows[0][i]
    return refItem

# Checked
def readRefsFromDBByIDs(dbConnection, refAbsIDList):
    refDictList = []
    for refID in refAbsIDList:
        refItem = readRefFromDBByID(dbConnection, refID)
        refDictList.append(refItem)
    return refDictList

def readAllRecentInDB(dbConnection, timeStr):
    allRefItemList = []
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempList = readRecentInTable(dbConnection, tablename, timeStr)
        allRefItemList = allRefItemList + tempList
    return allRefItemList

def readRecentInTable(dbConnection, tablename, timeStr):
    cur = dbConnection.cursor()
    cur.execute("SELECT * FROM " + tablename + " WHERE AddedTime>?", (timeStr,))
    rows = cur.fetchall()
    refItemList = DB2Dict(rows, tablename)
    return refItemList

def DB2Dict(dbRows, tablename):
    refItemList = []
    tempDBFieldsList = DB_BaseFields + DatabaseStandardStructure[tablename] + DB_ExtendFields
    if len(dbRows):
        for row in dbRows:
            if len(row) <= len(tempDBFieldsList):
                refItem = {}
                refItem['MType'] = tablename
                refItem['PubIn'] = ""
                baseLength = len(DB_BaseFields)
                for i in range(baseLength):
                    refItem[DB_BaseFields[i]] = row[i]

                for i in range(baseLength, len(row)):
                    tempFieldName = tempDBFieldsList[i].capitalize()
                    if tempFieldName == 'Journal':
                        tempFieldName = 'PubIn'
                    elif tempFieldName == 'Booktitle':
                        tempFieldName = 'PubIn'
                    refItem[tempFieldName] = row[i]
                    if row[i] is None:
                        refItem[tempFieldName] = ""
                refItemList.append(refItem)
    return refItemList

def readAllRefsInDBByField(dbConnection, fieldList, keywordList):
    allRefItemList = []
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempList = readAllRefsInTableByField(dbConnection, tablename, fieldList, keywordList)
        allRefItemList = allRefItemList + tempList
    return allRefItemList

def readAllRefsInTableByField(dbConnection, tablename, fieldList, keywordList):
    checkFlag = False
    tempFieldList = list(fieldList)
    if 'PubIn' not in fieldList:
        checkFlag = True
    else:
        tempInd = tempFieldList.index('PubIn')
        if tablename == 'Article':
            tempFieldList[tempInd] = 'journal'
            checkFlag = True
        elif tablename == 'Conference':
            tempFieldList[tempInd] = 'booktitle'
            checkFlag = True

    refItemList = []
    if checkFlag:
        sql = "SELECT * FROM " + tablename + " WHERE "
        if len(fieldList) == 1:
            sql = sql + tempFieldList[0] + "=?"
            cur = dbConnection.cursor()
            cur.execute(sql, (keywordList[0],))
        elif len(fieldList) == 2:
            sql = sql + tempFieldList[0] + "=? AND " + tempFieldList[1] + "=?"
            cur = dbConnection.cursor()
            cur.execute(sql, (keywordList[0],keywordList[1]))

        rows = cur.fetchall()
        refItemList = DB2Dict(rows, tablename)
    return refItemList

def readAllRefsInDBByLabelPartialMatch(dbConnection, keyword):
    allRefItemList = []
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempList = readAllRefsInTableByLabelPartialMatch(dbConnection, tablename, keyword)
        allRefItemList = allRefItemList + tempList
    return allRefItemList

def readAllRefsInTableByLabelPartialMatch(dbConnection, tablename, keyword):
    refItemList = []
    sql = '''SELECT * FROM ''' + tablename + ''' WHERE Labels LIKE "%''' + keyword + '''%"'''
    cur = dbConnection.cursor()
    cur.execute(sql)
    rows = cur.fetchall()
    if len(rows) > 0:
        refItemList = DB2Dict(rows, tablename)
    return refItemList

def searchRefInTable(dbConnection, tablename, searchTarget):
    refItemList = []
    # sql = '''SELECT * FROM ''' + tablename + ''' WHERE Year=?'''
    # values = (searchTarget[0][1], )
    sql_base = '''SELECT * FROM ''' + tablename + ''' WHERE '''
    query_str = ""
    pubinField = ""
    for tarItem in searchTarget:
        tarKey = tarItem[0]
        tarValue = tarItem[1]
        if tarKey == 'Year':
            if len(query_str) == 0:
                query_str = query_str + "Year=" + tarValue
            else:
                query_str = query_str + " AND Year=" + tarValue
        elif tarKey == 'Title':
            if len(query_str) == 0:
                query_str = query_str + '''title LIKE "%''' + tarValue + '''%"'''
            else:
                query_str = query_str + ''' AND title LIKE "%''' + tarValue + '''%"'''
        elif tarKey == 'Author':
            if len(query_str) == 0:
                query_str = query_str + '''author LIKE "%''' + tarValue + '''%"'''
            else:
                query_str = query_str + ''' AND author LIKE "%''' + tarValue + '''%"'''
        elif tarKey == 'PubIn':
            if tablename == 'Article':
                pubinField = 'journal'
            elif tablename == 'Inproceedings':
                pubinField = 'booktitle'
            else:
                pass
            if len(pubinField) > 0:
                if len(query_str) == 0:
                    query_str = query_str + pubinField + ''' LIKE "%''' + tarValue + '''%"'''
                else:
                    query_str = query_str + " AND " + pubinField + ''' LIKE "%''' + tarValue + '''%"'''
    sql_str = sql_base + query_str
    if len(pubinField)==0 and len(query_str) == 0:
        pass
    else:
        cur = dbConnection.cursor()
        cur.execute(sql_str)
        rows = cur.fetchall()
        if len(rows) > 0:
            refItemList = DB2Dict(rows, tablename)
    return refItemList

def searchRefInDB(dbConnection, searchTarget):
    allRefItemList = []
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempList = searchRefInTable(dbConnection, tablename, searchTarget)
        allRefItemList = allRefItemList + tempList
    return allRefItemList

def readAllRefsFromDB(dbConnection):
    cur = dbConnection.cursor()
    cur.execute("SELECT * FROM ReferencesData")
    rows = cur.fetchall()
    refItemList = []
    if len(rows):
        for row in rows:
            if len(row) <= len(DatabaseReferenceStructure):
                refItem = {}
                for i in range(len(row)):
                    refItem[DatabaseReferenceStructure[i]] = row[i]
                refItemList.append(refItem)
    return refItemList

def readAllRefsInDB(dbConnection):
    allRefItemList = []
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempList = readAllRefsInTable(dbConnection, tablename)
        allRefItemList = allRefItemList + tempList
    return allRefItemList

def readAllRefsInTable(dbConnection, tablename):
    sql = "SELECT * FROM " + tablename
    cur = dbConnection.cursor()
    cur.execute(sql)
    rows = cur.fetchall()
    refItemList = []
    # tempDBFieldsList = DB_BaseFields + DatabaseStandardStructure[tablename] + DB_ExtendFields
    if len(rows):
        refItemList = DB2Dict(rows, tablename)
    return refItemList

def updateRefToDBByID(dbConnection, refAbsID, value):
    sql = ''' UPDATE ReferencesData
              SET Labels = ?
              WHERE id = ?'''
    task = (value, refAbsID)
    cur = dbConnection.cursor()
    cur.execute(sql, task)
    dbConnection.commit()

# Checked
def updateRefFieldToDBByID(dbConnection, refAbsID, field, value):
    sql = ''' UPDATE ReferencesData
              SET ''' + field + ''' = ?
              WHERE id = ?'''
    task = (value, refAbsID)
    cur = dbConnection.cursor()
    cur.execute(sql, task)
    dbConnection.commit()

# New
def updateRefLabelByID(dbConnection, tablename, refAbsID, value):
    sql = ''' UPDATE ''' + tablename + '''
              SET Labels = ?
              WHERE RefAbsID = ?'''
    task = (value, refAbsID)
    cur = dbConnection.cursor()
    cur.execute(sql, task)
    dbConnection.commit()

# Checked
def getLabelsFromDB(dbConnection):
    """
    Get labels from database
    This function will concentrate the labels to a list
    """
    labelRows = readLabelsFromDB(dbConnection)
    labels = list(map(lambda x: x[1], labelRows))
    return labels

# Checked
def readLabelsFromDB(dbConnection):
    """
    Read labels from Labels table of the database
    """
    cur = dbConnection.cursor()
    cur.execute("SELECT * FROM Labels")
    rows = cur.fetchall()
    return rows

def addLabelToLabelsTable(dbConnection, labelText):
    tempLabelList = getLabelsFromDB(dbConnection)
    if labelText not in tempLabelList:
        sql = ''' INSERT INTO Labels(Name)
                  VALUES(?) '''
        task = (labelText,)
        cur = dbConnection.cursor()
        cur.execute(sql, task)
        dbConnection.commit()

# Checked
def getCitationsFromDB(dbConnection, refAbsID):
    citationRows = readCitationsFromDB(dbConnection, refAbsID)
    citationListStr = None
    if len(citationRows):
        citations = citationRows[0][2]
        if len(citations):
            try:
                citationListStr = citations.split(",")
            except:
                pass
    return citationListStr

# Checked
def readCitationsFromDB(dbConnection, refAbsID):
    cur = dbConnection.cursor()
    cur.execute("SELECT * FROM Citation WHERE Self=?", (refAbsID,))
    rows = cur.fetchall()
    return rows

# Checked
def copyCitationData(dbConnection, refAbsID):
    citationRows = readCitationsFromDB(dbConnection, refAbsID)
    if len(citationRows) > 0:
        cur = dbConnection.cursor()
        cur.execute("SELECT * FROM TempCitation WHERE Self=?", (refAbsID,))
        rows = cur.fetchall()
        if len(rows) == 0:
            sql = ''' INSERT INTO TempCitation(Self, Cited, CitedBy)
                      VALUES(?,?,?) '''
            task = (citationRows[0][1], citationRows[0][2], citationRows[0][3])
            cur = dbConnection.cursor()
            cur.execute(sql, task)
            dbConnection.commit()
        else:
            pass

# Checked
def getTempCitationsFromDB(dbConnection):
    citationRows = readTempCitationsFromDB(dbConnection)
    return citationRows

# Checked
def readTempCitationsFromDB(dbConnection):
    cur = dbConnection.cursor()
    cur.execute("SELECT * FROM TempCitation")
    rows = cur.fetchall()
    return rows

def UpdateDatabase(dbConnection):
    indexYearsInDB(dbConnection)
    indexPubInDB(dbConnection)

def indexYearsInDB(dbConnection):
    allYearList = []
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempYearList = indexYearsInTable(dbConnection, tablename)
        allYearList = allYearList + tempYearList
    allYearList = list(set(allYearList))
    allYearList.sort()
    updateYearsTable(dbConnection, allYearList)

def updateYearsTable(dbConnection, yearList):
    cur = dbConnection.cursor()
    cur.execute("DELETE FROM Years")
    for year in yearList:
        sql = "INSERT INTO Years (Year) VALUES(?)"
        cur = dbConnection.cursor()
        cur.execute(sql, (year,))
        dbConnection.commit()

def indexYearsInTable(dbConnection, tablename):
    cur = dbConnection.cursor()
    cur.execute("SELECT GROUP_CONCAT(Year, ',') FROM " + tablename)
    tempValue = cur.fetchone()
    yearList = []
    if len(tempValue):
        if tempValue[0] is None:
            pass
        else:
            yearList = tempValue[0].split(',')
    return yearList

def indexPubInDB(dbConnection):
    allPubInList = []
    for type in BibTeXTypes:
        tablename = type.capitalize()
        tempPubInList = indexPubInTable(dbConnection, tablename)
        allPubInList = allPubInList + tempPubInList
    allPubInList = list(set(allPubInList))
    allPubInList.sort()
    updatePubInTable(dbConnection, allPubInList)

def updatePubInTable(dbConnection, pubInList):
    cur = dbConnection.cursor()
    cur.execute("DELETE FROM PubIn")
    for pubin in pubInList:
        sql = "INSERT INTO PubIn (Name) VALUES(?)"
        cur = dbConnection.cursor()
        cur.execute(sql, (pubin,))
        dbConnection.commit()

def indexPubInTable(dbConnection, tablename):
    fieldname = ""
    if tablename == 'Article':
        fieldname = 'journal'
    elif tablename == 'Conference':
        fieldname = 'booktitle'
    elif tablename == 'Inproceedings':
        fieldname = 'booktitle'
    pubInList = []
    if len(fieldname)>0:
        sql = "SELECT GROUP_CONCAT(" + fieldname + ", ';') FROM " + tablename
        cur = dbConnection.cursor()
        cur.execute(sql)
        tempValue = cur.fetchone()
        if len(tempValue):
            if tempValue[0] is None:
                pass
            else:
                pubInList = tempValue[0].split(';')
    return pubInList

if __name__ == "__main__":
    createDB("Test.db")


from re import sub

def validarCPF(num):
    sum, validacao = 0, 0
    for i in range(10,1,-1):
        sum += int(num[10-i]) * i

    validacao = 11 - (sum % 11)
    validacao =  0 if validacao > 9 else validacao

    if validacao == int(num[9]):
        sum = 0 #
        for j in range(11,1,-1):  # 11,2,-1
            sum += int(num[11-j]) * j #

        # sum += validacao * 2
        validacao = 11 - (sum % 11)
        validacao = 0 if validacao > 9 else validacao

        if validacao == int(num[10]):
            print("CPF Válido")

        else: print("CPF Inválido")
    else: print("CPF Inválido")

cpf = str(input("Digite seu CPF:\n"))
# Remove os traços, pontos e espaços do CPF
cpf = sub(r"[-.\s]", "", cpf)

print(validarCPF(cpf))


import json
import datetime
import os

class IOController(object):
  def __init__(self):
    self.Incoming = "MarketService/Incoming/NewStocks_{date}.json".format(date = datetime.datetime.now())
    self.IncomingDirectory = "MarketService/Incoming"
    self.ReadMode = "r"
    self.WriteMode = "w"

  def Read(self, file):
    jsonResult = None
    try:
      with open(file, self.ReadMode) as reader:
        for line in reader.readlines():
          jsonResult = json.loads(line)

    except Exception as error:
      raise error("Error Occurred")

    return jsonResult

    return self.Stocks

  def Write(self, stock):
    try:
      with open(self.Incoming, self.WriteMode) as json_file:
        json.dump(stock, json_file)
    except Exception as exception:
      raise("Failed to write file")

  def RemoveAll(self):
    try:
      incomingFiles = os.listdir(self.IncomingDirectory)
      for incomingFile in incomingFiles:
        fullFilePath = os.path.join(self.IncomingDirectory, incomingFile)
        os.remove(fullFilePath)
    except Exception as exception:
      raise exception("failed to remove files.")


import information_process
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable

class ZivInformationPlane():
    # The code by Ravid Schwartz-Ziv is very hard to understand
    # (the reader is encouraged to try it themselves)
    # Solution: wrap it into this class and don't touch it with a 10-meter pole

    def __init__(self, X, Y, bins = np.linspace(-1, 1, 30)):
        """
        Inititalize information plane (set X and Y and get ready to calculate I(T;X), I(T;Y))
        X and Y have to be discrete
        """

        plane_params = dict(zip(['pys', 'pys1', 'p_YgX', 'b1', 'b',
                                 'unique_a', 'unique_inverse_x', 'unique_inverse_y', 'pxs'],
                                information_process.extract_probs(np.array(Y).astype(np.float), X)))

        plane_params['bins'] = bins
        plane_params['label'] = Y
        plane_params['len_unique_a'] = len(plane_params['unique_a'])
        del plane_params['unique_a']
        del plane_params['pys']

        self.X = X
        self.Y = Y
        self.plane_params = plane_params

    def mutual_information(self, layer_output):
        """
        Given the outputs T of one layer of an NN, calculate MI(X;T) and MI(T;Y)

        params:
            layer_output - a 3d numpy array, where 1st dimension is training objects, second - neurons

        returns:
            IXT, ITY - mutual information
        """

        information = information_process.calc_information_for_layer_with_other(layer_output, **self.plane_params)
        return information['local_IXT'], information['local_ITY']

class BufferedSequential(nn.Module):
    def __init__(self, layers, buffer_or_not):
        super(BufferedSequential, self).__init__()
        self.layers = layers
        self.buffer_or_not = buffer_or_not
        self.n_buffers = np.sum(buffer_or_not)

    def parameters(self):
        return [param for layer in self.layers for param in layer.parameters()]

    def forward(self, x):
        if not isinstance(x, Variable):
            if not isinstance(x, torch.Tensor):
                x = torch.Tensor(x)
            x = Variable(x)

        self.buffer = []

        for layer, is_buffered in zip(self.layers, self.buffer_or_not):
            x = layer(x)
            if is_buffered:
                self.buffer.append(x)

        return x

class ReshapeLayer(nn.Module):
    def __init__(self, new_shape):
        super(ReshapeLayer, self).__init__()
        self.new_shape = new_shape

    def parameters(self):
        return []

    def forward(self, x):
        return x.view(self.new_shape)

def mutual_information_for_network_family(infoplane, buffered_networks):
    # Make the mutual information model more 'stochastic' by splitting
    # the dataset among a family of similar neural networks
    layer_outputs = [[] for layer in range(np.sum(buffered_networks[0].buffer_or_not))]
    for x in infoplane.X:
        network = np.random.choice(buffered_networks)
        network(x)
        for i, variable in enumerate(network.buffer):
            layer_outputs[i].append(variable.data.numpy())

    return [infoplane.mutual_information(np.array(otp)) for otp in layer_outputs]


import pyspark
from pyspark import SparkConf, SparkContext
import sys
import os
os.environ['SPARK_HOME'] = "D:\spark-2.4.3-bin-hadoop2.7"
sys.path.append("D:\spark-2.4.3-bin-hadoop2.7\python")
sys.path.append("D:\spark-2.4.3-bin-hadoop2.7\python\lib")
sc = pyspark.SparkContext( 'local', 'test')

logFile = "test.txt"
text = sc.textFile(logFile)
print(text)
words = text.flatMap(lambda line:line.split(" "))
counts = words.map(lambda word:(word,1)).reduceByKey(lambda x,y:x+y)

result=counts.collect()

print(result)
for (word,count) in result:

    print(word,count)
#numAs = logData.filter(lambda line: 'a' in line).count()
#count = word.map(lambda word: (a, 1)).reduceByKey(lambda x, y: x + y)
#count.foreach(print)
#print(numAs+"123")
#numBs = logData.filter(lambda line: 'b' in line).count()

#print('Lines with a: %s, Lines with b: %s' % (numAs, numBs))


import torch
import matplotlib.pyplot as plt
import numpy as np

def evaluate_model(model, dataloader, device):
    model.eval()
    reconstructions = []
    with torch.no_grad():
        for data in dataloader:
            inputs, labels = data
            inputs = inputs.to(device)
            reconstructed = model(inputs)
            reconstructions.append((inputs.cpu(), reconstructed.cpu()))
    return reconstructions

def visualize_reconstructions(reconstructions, num_images=5):
    # Asegúrate de que num_images no exceda el número de elementos en reconstructions
    num_images = min(num_images, len(reconstructions))

    fig, axes = plt.subplots(nrows=num_images, ncols=2, figsize=(10, 2 * num_images))

    for i in range(num_images):
        # Desempaquetar la tupla
        original_batch, reconstructed_batch = reconstructions[i]

        # Indexar para obtener la primera imagen del batch
        original = original_batch[0]
        reconstructed = reconstructed_batch[0]

        # Verifica si el tensor tiene una dimensión extra y elimínala
        if original.dim() == 4:
            original = original.squeeze(0)
        if reconstructed.dim() == 4:
            reconstructed = reconstructed.squeeze(0)

        # Permutar los ejes para que el canal venga al final
        original = original.numpy().transpose(1, 2, 0)
        reconstructed = reconstructed.numpy().transpose(1, 2, 0)

        # Asegúrate de que los datos están en el rango [0, 1]
        original = np.clip(original, 0, 1)
        reconstructed = np.clip(reconstructed, 0, 1)

        # Visualización
        axes[i, 0].imshow(original)
        axes[i, 0].set_title('Original')
        axes[i, 0].axis('off')

        axes[i, 1].imshow(reconstructed)
        axes[i, 1].set_title('Reconstructed')
        axes[i, 1].axis('off')

    plt.tight_layout()
    plt.show()

def save_model(model, path):
    torch.save(model.state_dict(), path)

# Use these functions after training
#reconstructions = evaluate_model(autoencoder, val_loader, device)
#visualize_reconstructions(reconstructions)
#save_model(autoencoder, 'autoencoder.pth')


import platform
from types import MethodType

IS_PY3 = (platform.python_version() >= '3')

if IS_PY3:
    iteritems = lambda d: iter(d.items()) # not dict.items!!! See above
    itervalues = lambda d: iter(d.values())

    create_instance_method = MethodType
    basestring = str
    string_types = (basestring,)
    from functools import reduce
else:
    iteritems = lambda d: d.iteritems() # not dict.iteritems!!! we support ordered dicts as well
    itervalues = lambda d: d.itervalues()

    from __builtin__ import basestring
    string_types = (str,)
    from __builtin__ import reduce

def items_list(dictionary):
    return list(iteritems(dictionary))


import json
import requests
from sense_hat import SenseHat
from requests import ReadTimeout, ConnectTimeout, HTTPError, Timeout, ConnectionError
import time
import datetime

sense = SenseHat()
sense.set_rotation(180)
sense.low_light = True
sync_frequency = 30
#Kingsbury, Preston Road
trainStations = ['jubilee', '940GZZLUKBY'], ['metropolitan', '940GZZLUPRD']
#79, 204 to Kingsbury, 204 to Preston Road
busStops = [['79', '490013367N1'], ['204', '490009792K'], ['204', '490009792J']]

jubileeTerminuses = ['Stratford Underground Station', 'Canning Town Underground Station', 'West Ham Underground Station',
        'North Greenwich Underground Station']
metropolitanTerminuses = ['Baker Street Underground Station, Aldgate Underground Station']

jubilee = [128, 128, 128]
metropolitan = [128, 0, 32]
edgeware = [255, 0, 0]
sudburyTown = [65, 105, 205]
alperton = [255, 128, 0]
O = [0,0,0]

def displayError():
    sense.show_message("Server Error")

def getNext(stations, direction):
    toReturn = []
    for station in stations:
        temp = getFromAPI(station[0],station[1], direction)
        if (temp != []):
            for x in temp:
                toReturn.append(x)
        else:
            toReturn.append([station[0] + ": updates unavailable", 0])
    return toReturn

def getFromAPI(line, stop, direction):
    url = 'https://api.tfl.gov.uk/Line/' + line + '/Arrivals/' + stop + '?direction=' + direction
    try:
        response = requests.get(url, timeout = 10)
    except (ConnectTimeout, ReadTimeout, Timeout, HTTPError, ConnectionError):
        displayError()
        return
    if (response.status_code != 200):
        displayError()
        return
    else:
        returns = []
        for result in response.json():
            returns.append([result['destinationName'], int(result['timeToStation'] / 60)])
        return returns

def getStatus():
    updates = []
    for lines in trainStations:
        response = requests.get('https://api.tfl.gov.uk/Line/' + lines[0] + '/Disruption')

        if (response.status_code != 200):
            displayError()
        else:
            json = response.json()
            if len(json) != 0:
                updates.append([json[0]['closureText'], json[0]['description']])

def scroll(array):
    if array != None:
        for item in array:
            print(item[0] + " will arrive at " + str(item[1]))

def calculateBlobs(time):
    if time > 15:
        return 7
    elif time > 10:
        return 6
    elif time > 8:
        return 5
    elif time > 6:
        return 4
    elif time > 4:
        return 3
    elif time > 2:
        return 2
    elif time > 1:
        return 1
    else:
        return 0

def draw(trains, buses):
    toDraw = [
            [O,O,O,O,O,O,O,O],
            [O,O,O,O,O,O,O,O],
            [O,O,O,O,O,O,O,O],
            [O,O,O,O,O,O,O,O],
            [O,O,O,O,O,O,O,O],
            [O,O,O,O,O,O,O,O],
            [O,O,O,O,O,O,O,O],
            [O,O,O,O,O,O,O,O]
            ]
    for station, time in trains:
        blob = calculateBlobs(time)
        if station in jubileeTerminuses:
            toDraw[0][7 - blob] = jubilee
        elif station in metropolitanTerminuses:
            toDraw[3][7 - blob] = metropolitan

    for stop, time in buses:
        blob = calculateBlobs(time)
        if stop == 'Sudbury Town':
            toDraw[4][7 - blob] = sudburyTown
        elif stop == "Alperton, Sainsbury's":
            toDraw[5][7 - blob] = alperton
        elif stop == 'Edgware Station':
            toDraw[1][7 - blob] = edgeware

    transpose = []
    for i in range(0,8):
        for j in range(0,8):
            transpose.append(toDraw[j][i])

    sense.set_pixels(transpose)

def main():
    sense.clear()
    while True:
        #hour = datetime.datetime.now().hour
        #if hour > 10:
        #    sense.clear()
        #    time.sleep ((24 - hour) * 60 * 60)
        #if hour < 6:
        #    sense.clear()
        #    time.sleep ((6 - hour) * 60 * 60)

        statuses = getStatus()
        trains = getNext(trainStations, 'outbound')
        buses = getNext(busStops, 'all')

        trains.sort(key = lambda x: x[1])
        buses.sort(key = lambda x: x[1])

        #scroll(statuses)
        #scroll(trains)
        #scroll(buses)

        if statuses != None and len(statuses) > 0:
            for status in statuses:
                sense.show_message(status[0] + ":" + status[1])

        draw(trains, buses)
        time.sleep(sync_frequency)

main()


from ._base import *
from ..tinygrail.bigc import BigC
from ..tinygrail.model import TBid

@click.command()
@click.argument("player_name", type=TG_PLAYER)
@click.argument("character_ids", type=int, nargs=-1)
def force_view(player_name, character_ids):
    for cid in character_ids:
        big_c = BigC(player_name, cid)
        big_c.create_bid(TBid(Price=2, Amount=2))


import inspect
from typing import Protocol, runtime_checkable

import frappe
from frappe import _
from frappe.model.base_document import get_controller

@runtime_checkable
class VirtualDoctype(Protocol):
	"""This class documents requirements that must be met by a doctype controller to function as virtual doctype

	Additional requirements:
	- DocType controller has to inherit from `frappe.model.document.Document` class

	Note:
	- "Backend" here means any storage service, it can be a database, flat file or network call to API.
	"""

	# ============ class/static methods ============

	@staticmethod
	def get_list(args) -> list[frappe._dict]:
		"""Similar to reportview.get_list"""
		...

	@staticmethod
	def get_count(args) -> int:
		"""Similar to reportview.get_count, return total count of documents on listview."""
		...

	@staticmethod
	def get_stats(args):
		"""Similar to reportview.get_stats, return sidebar stats."""
		...

	# ============ instance methods ============

	def db_insert(self, *args, **kwargs) -> None:
		"""Serialize the `Document` object and insert it in backend."""
		...

	def load_from_db(self) -> None:
		"""Using self.name initialize current document from backend data.

		This is responsible for updatinng __dict__ of class with all the fields on doctype."""
		...

	def db_update(self, *args, **kwargs) -> None:
		"""Serialize the `Document` object and update existing document in backend."""
		...

	def delete(self, *args, **kwargs) -> None:
		"""Delete the current document from backend"""
		...

def validate_controller(doctype: str) -> None:
	try:
		controller = get_controller(doctype)
	except ImportError:
		frappe.msgprint(
			_("Failed to import virtual doctype {}, is controller file present?").format(doctype)
		)
		return

	def _as_str(method):
		if hasattr(method, "__module__"):
			return f"{method.__module__}.{method.__qualname__}"
		return "None"

	expected_static_method = ["get_list", "get_count", "get_stats"]
	for m in expected_static_method:
		method = inspect.getattr_static(controller, m, None)
		if not isinstance(method, staticmethod):
			frappe.msgprint(
				_("Virtual DocType {} requires a static method called {} found {}").format(
					frappe.bold(doctype), frappe.bold(m), frappe.bold(_as_str(method))
				),
				title=_("Incomplete Virtual Doctype Implementation"),
			)

	expected_instance_methods = ["db_insert", "db_update", "load_from_db", "delete"]
	parent_class = controller.mro()[1]
	for m in expected_instance_methods:
		method = getattr(controller, m, None)
		original_method = getattr(parent_class, m, None)
		if method == original_method:
			frappe.msgprint(
				_("Virtual DocType {} requires overriding an instance method called {} found {}").format(
					frappe.bold(doctype), frappe.bold(m), frappe.bold(_as_str(method))
				),
				title=_("Incomplete Virtual Doctype Implementation"),
			)


# Day 7
import re
INPUT = open('Day 07.txt', 'r')
r = re.compile(r"Step (\w) must be finished before step (\w) can begin\.")
steps = {}
for line in INPUT:
    m = r.match(line)
    if m.group(2) in steps:
        steps[m.group(2)].append(m.group(1))
    else:
        steps[m.group(2)] = [m.group(1)]
first = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ") - set(steps.keys())

for i in first:
    steps[i] = ["#"]
ready = ["#"]
order = []
while len(ready) > 0:
    ready.sort()
    ready.reverse()
    order.append(ready.pop())
    ready = list(set([i for i in steps if set(steps[i]).issubset(set(order)) and i not in order]))
print("part_1:", "".join(order[1:]))

time = 0
active = {}
done = {"#"}
ready = list(set([i for i in steps if set(steps[i]).issubset(done) and i not in done and i not in active]))
while len(ready) > 0 or len(active) > 0:
    ready.sort()
    ready.reverse()
    for i in range(5):
        if len(active.keys()) == 5 or len(ready) == 0:
            break
        active[ready.pop()] = 0
    for i in active:
        active[i] += 1
        if active[i] >= 60 + ord(i) - 64:
            done.add(i)
    for i in done:
        if i in active:
            del active[i]
    time += 1
    ready = list(set([i for i in steps if set(steps[i]).issubset(done) and i not in done and i not in active]))
print("part_2:", time)
INPUT.close()


import torch
import torch.nn as nn
import torch.nn.functional as functional
from torch.autograd import Variable

def sort_batch(batch, lengths):
	#inputs: batch_size*_
	#lengths: batch_size
	sorted_lengths, sorted_indices = torch.sort(lengths, dim=0, descending=True)
	#sorted_lengths how to convert it to cuda?
	sorted_batch = batch[sorted_indices]
	original_indices = lengths.new(sorted_indices.shape[0]).zero_()
	for i,value in enumerate(sorted_indices):
		original_indices[value] = i
	return sorted_batch, sorted_lengths, original_indices.long()

def unsort_batch(batch, original_indices):
	#inputs: batch_size*_
	return batch[original_indices]

def sequence_mask(lengths, max_len=-1):
	#lengths: batch_size
	batch_size = lengths.size(0)
	if max_len == -1:
		max_len = lengths.data.max()
	mask = lengths.data.new(batch_size, max_len).zero_().long()
	for i in range(batch_size):
		mask[i][:lengths.data[i]] = 1
	return mask #batch_size*seq_len #Convert to a Variable?

def mask_sequence(sequence, mask):
	#sequence: batch_size*seq_len*_
	#mask: batch_size*seq_len
	mask = mask.float()
	mask = mask.unsqueeze(-1) #mask: batch_size*seq_len*1
	return sequence*mask #batch_size*seq_len*_

def masked_softmax(vector, mask): #change it to tensor and mask after the pytorch version accpeting dim
	#vector: flatten_size*num_words
	#mask: flatten_size*num_words
	result = functional.softmax(vector * mask)
	result = result * mask
	result = result / (result.sum(dim=1, keepdim=True) + 1e-13)
	return result #result: flatten_size*num_words

def attention_pooling(attention_weights, sequence):
	#sequence: batch_size*num_words*iembed
	#attention_weights: batch_size*num_words_new*num_words or batch_size*num_words
	if attention_weights.dim() == 2:
		pooled_sequence = torch.matmul(attention_weights.unsqueeze(1), sequence).squeeze(1) #pooled_sequence: batch_size*iembed
	elif attention_weights.dim() == 3:
		pooled_sequence = torch.matmul(attention_weights, sequence) #pooled_sequence: batch_size*num_words_new*iembed
	return pooled_sequence

def reverse_sequence(sequence, dim=1):
	#sequence: batch_size*num_words*iembed --> dim=1
	#mask: batch_size*num_words --> dim=1
	idx = [i for i in range(sequence.size(dim)-1, -1, -1)]
	idx = Variable(torch.LongTensor(idx))
	#idx = Variable(torch.LongTensor(idx)).cuda()
	reverse_sequence = sequence.index_select(dim, idx)
	return reverse_sequence

if __name__=='__main__':
	lengths = torch.LongTensor([4,2,3])
	#print(sequence_mask(lengths))
	#print(masked_softmax(Variable(torch.LongTensor([[1,2,3]]).float()),\
		#Variable(torch.LongTensor([[1,1,0]]).float())))
	sequence = Variable(torch.randn(3,5,4))
	mask = Variable(torch.LongTensor(3,5))
	print(sequence)
	print(reverse_sequence(sequence))
	print(mask)
	print(reverse_sequence(mask))


amt = int(input("Please specify the amount of money you would like to withdraw: "))

five_hundred = amt // 500
one_hundred = amt % 500 // 100
fifty = amt % 500 % 100 // 50
two = amt % 500 % 100 % 50 // 2
one = amt % 500 % 100 % 50 % 2

print("""we may give you:
      %d bills(s) of 500 bath
      %d bills(s) of 100 bath
      %d bills(s) of 50 bath
      %d coin(s) of 2 bath
      %d coin(s) of 1 bath
      """ % (five_hundred, one_hundred, fifty, two, one))


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

"""
Tools for getting metric actual or forecast data from BigQuery.
"""
import pandas as pd

KPI_QUERIES = {
    "desktop": '''
        SELECT
            submission_date as date,
            sum(mau) AS global_mau,
            SUM(IF(country IN ('US', 'FR', 'DE', 'GB', 'CA'), mau, 0)) AS tier1_mau
        FROM
            `moz-fx-data-derived-datasets.telemetry.firefox_desktop_exact_mau28_by_dimensions_v1`
        GROUP BY
            date
        ORDER BY
            date
    ''',
    "mobile": '''
        SELECT
            submission_date as date,
            SUM(mau) AS global_mau,
            SUM(tier1_mau) AS tier1_mau
        FROM
            `moz-fx-data-derived-datasets.telemetry.firefox_nondesktop_exact_mau28_by_product_v1`
        WHERE
            product != "FirefoxForFireTV"
        GROUP BY
            submission_date
        ORDER BY
            date
    ''',
    "fxa": '''
        SELECT
            submission_date AS date,
            SUM(mau) AS global_mau,
            SUM(seen_in_tier1_country_mau) AS tier1_mau
        FROM
            `moz-fx-data-derived-datasets.telemetry.firefox_accounts_exact_mau28_by_dimensions_v1`
        GROUP BY
            submission_date
        ORDER BY
            submission_date
    '''
}

def get_kpi_data(bq_client, types=list(KPI_QUERIES.keys())):
    data = {}
    if not isinstance(types, list):
        types = [types]
    for q in types:
        raw_data = bq_client.query(KPI_QUERIES[q]).to_dataframe()
        data['{}_global_mau'.format(q)] = raw_data[
            ["date", "global_mau"]
        ].rename(
            index=str, columns={"date": "ds", "global_mau": "y"}
        )
        data['{}_tier1_mau'.format(q)] = raw_data[
            ["date", "tier1_mau"]
        ].rename(
            index=str, columns={"date": "ds", "tier1_mau": "y"}
        )
    for k in data:
        data[k]['ds'] = pd.to_datetime(data[k]['ds']).dt.date
    return data

NONDESKTOP_QUERY = '''
    SELECT
        submission_date as date,
        SUM(mau) AS global_mau,
        product
    FROM
        `moz-fx-data-derived-datasets.telemetry.firefox_nondesktop_exact_mau28_by_product_v1`
    GROUP BY
        submission_date,
        product
    ORDER BY
        date
    '''

def get_nondesktop_data(bq_client):
    data = {}
    raw_data = bq_client.query(NONDESKTOP_QUERY).to_dataframe()
    for p in [
        "Fennec Android", "Focus iOS", "Focus Android", "Fennec iOS", "Fenix",
        "Firefox Lite", "FirefoxForFireTV", "FirefoxConnect"
    ]:
        data['{} MAU'.format(p)] = raw_data.query("product == @p")[
            ["date", "global_mau"]
        ].rename(
            index=str, columns={"date": "ds", "global_mau": "y"}
        )
    for k in data:
        data[k]['ds'] = pd.to_datetime(data[k]['ds']).dt.date
    return data

FORECAST_QUERY = '''
    SELECT
        date,
        asofdate,
        mau,
        low90,
        high90
    FROM
        `{project}.{dataset}.{table}`
    WHERE
        datasource = '{product}'
        AND type = 'forecast'
        AND asofdate BETWEEN "{asofdate_start}" AND "{asofdate_end}"
    ORDER BY
        date
    '''

def get_forecast_data(
    bq_client, project, dataset, table, product, asofdate_start, asofdate_end
):
    raw_data = bq_client.query(FORECAST_QUERY.format(
        project=project,
        dataset=dataset,
        table=table,
        product=product,
        asofdate_start=asofdate_start,
        asofdate_end=asofdate_end,
    )).to_dataframe().rename(columns={
        "date": "ds",
        "mau": "yhat",
        "high90": "yhat_upper",
        "low90": "yhat_lower",
    })
    raw_data['ds'] = pd.to_datetime(raw_data['ds']).dt.date
    return raw_data


# Report functions
#import sys
from operator import itemgetter

file_name = "game_stat.txt"
year = 2000
genre = 'RPG'
title = 'StarCraft'

def main():
    '''print(count_games(file_name))
    t = decide(file_name, year)
    print(t)
    get_latest(file_name)
    print(get_latest(file_name))
    print(count_by_genre(file_name, genre))
    print(get_line_number_by_title(file_name, title))
    print(sort_abc(file_name))
    print(get_genres(file_name))'''
    when_was_top_sold_fps(file_name)

def read_from_file(file_name):
    with open(file_name, 'r') as f:
        f = f.read().split('\n')
        f.pop()
        list_games = list(
            list(item for item in element.split('\t') if item) for element in f)
        return list_games

def list_from_column(table, column_number):
    list_something = []
    for element in table:
        if element[column_number-1]:
            list_something.append(element[column_number-1])
    return list_something

def sort_list(list_something):
    sorted_list = []
    while list_something:
        sorted_list += [list_something.pop(
            list_something.index(min(list_something)))]
    return sorted_list

def count_games(file_name):
    list_games = read_from_file(file_name)
    return len(list_games)

def decide(file_name, year):
    list_games = read_from_file(file_name)
    year = str(year)
    for element in list_games:
        for item in element:
            if year == item:
                return True
    return False

def get_latest(file_name):
    list_games = read_from_file(file_name)
    max_year_game = max(list_games, key=itemgetter(2))[0]
    return max_year_game

def count_by_genre(file_name, genre):
    list_games = read_from_file(file_name)
    count = 0
    for element in list_games:
        if genre in element:
            count += 1
    if count == 0:
        count = 'Game with such genre ' + genre + ' is not found'
    return count

def get_line_number_by_title(file_name, title):
    list_games = read_from_file(file_name)
    i = 0
    for element in list_games:
        if title in list_games[i]:
            ind = i
            break
        i += 1
    return ind+1

def sort_abc(file_name):
    list_games = read_from_file(file_name)
    list_title = list_from_column(list_games, 1)
    sorted_list_title = sort_list(list_title)
    sorted_games_list = []
    for item in sorted_list_title:
        for element in list_games:
            if item == element[0]:
                sorted_games_list.append(element)
    return sorted_list_title

def get_genres(file_name):
    list_games = read_from_file(file_name)
    list_genres = list_from_column(list_games, 4)
    list_genres = set(list_genres)
    list_genres = list(list_genres)
    sorted_list_genres = sort_list(list_genres)
    return sorted_list_genres

def when_was_top_sold_fps(file_name):
    list_games = read_from_file(file_name)
    genre = "First-person shooter"
    list_shooters = []
    for element in list_games:
        for item in element:
            if item == genre:
                list_shooters.append(element)
    list_sold = list_from_column(list_shooters, 2)
    max_sold = max(float(item) for item in list_sold)
    max_sold = str(max_sold)
    for element in list_shooters:
        for item in element:
            if max_sold == element[1] and genre == element[3]:
                year_of_max_sold = element[2]
    return int(year_of_max_sold)

main()


import scrapy
import logging
from datetime import date
from scrapy.linkextractors import LinkExtractor
import crawler.items.html_item as item
import crawler.utils.common as common
from datetime import datetime
from scrapy import log

class MyCrawler(scrapy.Spider):

    name = "my_crawler"

    def start_requests(self):

        urls = self.get_seed_urls()

#Sending request for seed urls
        for url in urls:
            try:
                request = scrapy.Request(url=url, callback=self.crawl_page)
                request.meta['depth'] = 1
                request.meta['parent_url'] = None
                request.meta['anchor_text'] = None
                request.meta['seed_url'] = url

                yield request

            except Exception as ex:
                log.msg("Exception on start request %s" %(ex), level=log.ERROR)

#Load seed url from file
    def get_seed_urls(self):

        try:
            seed_file = open(self.settings['SEED_URL_FILE_NAME'], 'rb')
            urls = []

            for line in seed_file.readlines():
                urls.append(common.addHttpWithUrl(line.strip()))

            return urls
        except Exception as ex:
            log.msg("Exception on Seed File loading %s" % (ex), level=log.ERROR)

#This function is used to fetch item and store them
    def crawl_page(self, response):

        html_page_item = item.HtmlItem()

        html_page_item['html_content'] = response.body
        html_page_item['url'] = response.url
        html_page_item['crawled_time'] = datetime.now()
        html_page_item['parent_url'] = response.meta['parent_url']
        html_page_item['anchor_text'] = response.meta['anchor_text']
        html_page_item['depth'] = response.meta['depth']

        yield html_page_item
#Extract link from the page and send request for the next depth
        links = LinkExtractor(unique=True, allow_domains=common.get_domain_name(response.meta["seed_url"])).extract_links(response)

        for link in links:

            try:
                new_request = scrapy.Request(url=link.url, callback=self.crawl_page)
                new_request.meta['depth'] = response.meta['depth'] + 1
                new_request.meta['anchor_text'] = link.text
                new_request.meta['parent_url'] = response.url
                new_request.meta['seed_url'] = response.meta['seed_url']

                yield new_request

            except Exception as ex:
                log.msg("Exception on New Request %s" % (ex), level=log.ERROR)


def identity(x): return x

class Closure:
    def __init__(self, func, args):
        self.patch(func, args)

    def __repr__(self):
        return "<Closure {!r} {!r}>".format(self.func, self.args)

    @staticmethod
    def stub():
        return Closure(None, None)

    @staticmethod
    def of_value(value):
        return Closure(identity, [value])

    @staticmethod
    def of_func(func):
        return Closure(identity, [func])

    @staticmethod
    def of_dc(tag, *args):
        return Closure(identity, [DataCons(tag, *args)])

    def patch(self, func, args):
        self.func = func
        self.args = args

    def patch_value(self, value):
        self.patch(identity, [value])

    def patch_func(self, func):
        self.patch(identity, [func])

    def patch_dc(self, tag, *args):
        self.patch(identity, [DataCons(tag, *args)])

    def force(self):
        val = self.func(*self.args)
        self.func = identity
        self.args = [val]
        return val

class DataCons:
    def __init__(self, tag, *args):
        self.tag = tag
        self.args = args
        for arg in args:
            assert(isinstance(arg, Closure))

    def __repr__(self):
        return "({}, {})".format(self.tag, ", ".join(map(repr, self.args)))

def force(closure):
    return closure.force()

zero = Closure.of_value(0)
one  = Closure.of_value(1)
fibs     = Closure.stub()
fibstail = Closure.stub()
fibsrest = Closure.stub()

def run_plus(x, y):
    xx = force(x)
    yy = force(y)
    return xx + yy

plus = Closure.of_func(run_plus)

def run_minus(x, y):
    xx = force(x)
    yy = force(y)
    return xx - yy

minus = Closure.of_func(run_minus)

nil = Closure.of_dc("nil")

def run_cons(x, xs):
    return ("cons", x, xs)

cons = Closure.of_func(run_cons)

def apply(func, *args):
    funcc = force(func)
    return funcc(*args)

zipWith = Closure.stub()

def run_zipWith(op, x, y):
    xx = force(x)
    assert(isinstance(xx, DataCons))
    if xx.tag == "nil":
        return DataCons("nil")
    elif xx.tag == "cons":
        yy = force(y)
        assert(isinstance(yy, DataCons))
        if yy.tag == "nil":
            return DataCons("nil")
        elif yy.tag == "cons":
            xx_head, xx_tail = xx.args
            yy_head, yy_tail = yy.args

            head = Closure(apply, [op, xx_head, yy_head])
            tail = Closure(apply, [zipWith, op, xx_tail, yy_tail])
            return DataCons("cons", head, tail)
        else:
            raise Exception("y is neither nil nor cons")
    else:
        raise Exception("x is neither nil nor cons")

zipWith.patch_func(run_zipWith)

fibsrest.patch(apply, [zipWith, plus, fibs, fibstail])

fibstail.patch_dc("cons", one, fibsrest)

fibs.patch_dc("cons", zero, fibstail)

take = Closure.stub()

def run_take(num, lst):
    numm = force(num)
    assert(isinstance(numm, int))
    if numm == 0:
        return DataCons("nil")
    else:
        lstt = force(lst)
        assert(isinstance(lstt, DataCons))
        if lstt.tag == "nil":
            return DataCons("nil")
        elif lstt.tag == "cons":
            head, tail = lstt.args
            num_minus_1 = Closure(apply, [minus, num, one])
            rest = Closure(apply, [take, num_minus_1, tail])
            return DataCons("cons", head, rest)
        else:
            raise Exception("lstt is neither nil nor cons")

take.patch_func(run_take)

ten = Closure.of_value(10)

fibs10 = Closure(apply, [take, ten, fibs])

def show():
    cur = fibs10
    while True:
        # print(cur)
        node = force(cur)
        assert(isinstance(node, DataCons))
        if node.tag == "nil":
            break
        else:
            assert(node.tag == "cons")
            head, tail = node.args
            head_val = force(head)
            assert(isinstance(head_val, int))
            print(head_val)
        cur = tail


#!/usr/bin/env python

from __future__ import print_function, absolute_import # NEED TO STAY AS TOP IMPORT
import vtk
import sys
import math
from vmtk import vtkvmtk

def ReadPolyData(filename):
   reader = vtk.vtkXMLPolyDataReader()
   reader.SetFileName(filename)
   reader.Update()
   return reader.GetOutput()

def WritePolyData(input,filename):
   writer = vtk.vtkXMLPolyDataWriter()
   writer.SetFileName(filename)
   writer.SetInputData(input)
   writer.Write()

def ExtractCylindricInterpolationVoronoiDiagram(cellId,pointId,cylinderRadius,voronoi,centerlines):
   isInside = 0

   if (cellId == 0):
      cylinderTop = centerlines.GetPoint(pointId)
      cylinderCenter = centerlines.GetPoint(pointId-interpolationHalfSize)
      cylinderBottom = centerlines.GetPoint(pointId-interpolationHalfSize*2)
   else:
      cylinderTop = centerlines.GetPoint(pointId)
      cylinderCenter = centerlines.GetPoint(pointId+interpolationHalfSize)
      cylinderBottom = centerlines.GetPoint(pointId+interpolationHalfSize*2)

   interpolationDataset = vtk.vtkPolyData()
   interpolationDatasetPoints = vtk.vtkPoints()
   interpolationDatasetCellArray = vtk.vtkCellArray()

   maskArray = vtk.vtkIntArray()
   maskArray.SetNumberOfComponents(1)
   maskArray.SetNumberOfTuples(voronoi.GetNumberOfPoints())
   maskArray.FillComponent(0,0)

   for i in range(voronoi.GetNumberOfPoints()):
      point = voronoi.GetPoint(i)
      isInside = IsPointInsideInterpolationCylinder(point,cylinderTop,cylinderCenter,cylinderBottom,cylinderRadius)

      if (isInside == 1):
         maskArray.SetTuple1(i,1)

   numberOfInterpolationPoints = ComputeNumberOfMaskedPoints(maskArray)

   radiusArray = vtk.vtkDoubleArray()
   radiusArray.SetNumberOfComponents(1)
   radiusArray.SetNumberOfTuples(numberOfInterpolationPoints)
   radiusArray.SetName(radiusArrayName)
   radiusArray.FillComponent(0,0.0)

   count = 0
   for i in range(voronoi.GetNumberOfPoints()):
      value = maskArray.GetTuple1(i)
      if (value == 1):
         interpolationDatasetPoints.InsertNextPoint(voronoi.GetPoint(i))
         interpolationDatasetCellArray.InsertNextCell(1)
         interpolationDatasetCellArray.InsertCellPoint(count)
         radius = voronoi.GetPointData().GetArray(radiusArrayName).GetTuple1(i)
         radiusArray.SetTuple1(count,radius)
         count +=1

   interpolationDataset.SetPoints(interpolationDatasetPoints)
   interpolationDataset.SetVerts(interpolationDatasetCellArray)
   interpolationDataset.GetPointData().AddArray(radiusArray)

   return interpolationDataset

def IsPointInsideInterpolationCylinder(x,t,c,b,r):
  halfheigth = math.sqrt(vtk.vtkMath.Distance2BetweenPoints(b,t))/2.0

  xc = [0.0,0.0,0.0]
  tb = [0.0,0.0,0.0]

  xc[0] = x[0]-c[0]
  xc[1] = x[1]-c[1]
  xc[2] = x[2]-c[2]

  tb[0] = t[0]-b[0]
  tb[1] = t[1]-b[1]
  tb[2] = t[2]-b[2]

  xcnorm = vtk.vtkMath.Norm(xc)
  vtk.vtkMath.Normalize(xc)
  vtk.vtkMath.Normalize(tb)

  alpha = math.acos(vtk.vtkMath.Dot(xc,tb))

  parallelxc = xcnorm*math.cos(alpha)
  perpendicularxc =  xcnorm*math.sin(alpha)

  thetamin = math.atan(r/halfheigth)
  thetamax = thetamin + (math.pi - 2*thetamin)

  inside = 0
  if (thetamin<=alpha<=thetamax):
    if (abs(perpendicularxc)<=r): inside = 1
  else:
    if (abs(parallelxc)<=halfheigth): inside = 1

  return inside

def ComputeNumberOfMaskedPoints(dataArray):
   numberOfPoints = 0
   for i  in range(dataArray.GetNumberOfTuples()):
      value = dataArray.GetTuple1(i)
      if (value ==1): numberOfPoints +=1
   return numberOfPoints

def VoronoiDiagramInterpolation(interpolationcellid,id0,id1,voronoiDataset0,voronoiDataset1,centerlines,direction):
    print('Interpolating cells ',id0,id1)
    cellLine = ExtractLine(interpolationcellid,centerlines)

    startPoint = clippingPoints.GetPoint(id0)
    endPoint = clippingPoints.GetPoint(id1)

    startId = cellLine.FindPoint(startPoint)
    endId = cellLine.FindPoint(endPoint)

    if (direction == 1):
       gapStartId = startId + 1
       gapEndId = endId - 1
       arrivalId = gapEndId + 1
       endSavingInterval = gapEndId + 1
       step = 1
    else:
       gapStartId = startId - 1
       gapEndId = endId + 1
       arrivalId = gapEndId - 1
       endSavingInterval = gapEndId - 1
       step = -1

    numberOfGapPoints = int(math.fabs(gapEndId - gapStartId)) + 1
    numberOfInterpolationPoints = voronoiDataset0.GetNumberOfPoints()
    numberOfCenterlinesPoints = cellLine.GetNumberOfPoints()
    numberOfAddedPoints = numberOfGapPoints*numberOfInterpolationPoints
    print('from id ',gapStartId,'to id ',gapEndId,'; number of points added ',numberOfAddedPoints)

    finalNewVoronoiPoints = vtk.vtkPoints()
    cellArray = vtk.vtkCellArray()
    finalRadiusArray = vtk.vtkDoubleArray()
    finalRadiusArray.SetNumberOfComponents(1)
    finalRadiusArray.SetNumberOfTuples(numberOfAddedPoints)
    finalRadiusArray.SetName(radiusArrayName)
    finalRadiusArray.FillComponent(0,0.0)
    count = 0

    for i in range(numberOfInterpolationPoints):
       voronoiPoint = voronoiDataset0.GetPoint(i)
       voronoiPointRadius = voronoiDataset0.GetPointData().GetArray(radiusArrayName).GetTuple1(i)

       centerlinePointLocator = vtk.vtkPointLocator()
       centerlinePointLocator.SetDataSet(cellLine)
       centerlinePointLocator.BuildLocator()

       closestPointId = centerlinePointLocator.FindClosestPoint(voronoiPoint)
       closestPoint = cellLine.GetPoint(closestPointId)

       voronoiVector = [0.0,0.0,0.0]
       voronoiVector[0] = voronoiPoint[0] - closestPoint[0]
       voronoiVector[1] = voronoiPoint[1] - closestPoint[1]
       voronoiVector[2] = voronoiPoint[2] - closestPoint[2]
       voronoiVectorNorm = vtk.vtkMath.Norm(voronoiVector)

       rotationAngle = ComputeVoronoiVectorToCenterlineAngle(closestPointId,voronoiVector,cellLine)

       PTPoints = vtk.vtkPoints()
       for j in range(closestPointId,arrivalId,step):
          localtangent = [0.0,0.0,0.0]
          localnormal = [0.0,0.0,0.0]
          newVoronoiVector = [0.0,0.0,0.0]
          newVoronoiPoint = [0.0,0.0,0.0]

          transform = vtk.vtkTransform()

          point0 = [0.0,0.0,0.0]
          point0 = cellLine.GetPoint(j)

          if (j<numberOfCenterlinesPoints-1):
             point1 = [0.0,0.0,0.0]
             cellLine.GetPoint(j+1,point1)
             localtangent[0] += point1[0] - point0[0]
             localtangent[1] += point1[1] - point0[1]
             localtangent[2] += point1[2] - point0[2]
          if (j>0):
             point2 = [0.0,0.0,0.0]
             cellLine.GetPoint(j-1,point2)
             localtangent[0] += point0[0] - point2[0]
             localtangent[1] += point0[1] - point2[1]
             localtangent[2] += point0[2] - point2[2]

          localnormal = cellLine.GetPointData().GetArray(parallelTransportNormalsArrayName).GetTuple3(j)
          localnormaldot = vtk.vtkMath.Dot(localtangent,localnormal)

          localtangent[0] -= localnormaldot*localnormal[0]
          localtangent[1] -= localnormaldot*localnormal[1]
          localtangent[2] -= localnormaldot*localnormal[2]
          vtk.vtkMath.Normalize(localtangent)

          transform.RotateWXYZ(rotationAngle,localtangent)
          transform.TransformNormal(localnormal,newVoronoiVector)
          vtk.vtkMath.Normalize(newVoronoiVector)

          newVoronoiPoint[0] = point0[0] + voronoiVectorNorm*newVoronoiVector[0]
          newVoronoiPoint[1] = point0[1] + voronoiVectorNorm*newVoronoiVector[1]
          newVoronoiPoint[2] = point0[2] + voronoiVectorNorm*newVoronoiVector[2]

          PTPoints.InsertNextPoint(newVoronoiPoint)
       numberOfPTPoints = PTPoints.GetNumberOfPoints()

       lastPTPoint = PTPoints.GetPoint(PTPoints.GetNumberOfPoints()-1)

       voronoiPointLocator = vtk.vtkPointLocator()
       voronoiPointLocator.SetDataSet(voronoiDataset1)
       voronoiPointLocator.BuildLocator()

       arrivalVoronoiPointId = voronoiPointLocator.FindClosestPoint(lastPTPoint)
       arrivalVoronoiPoint = voronoiDataset1.GetPoint(arrivalVoronoiPointId)
       arrivalVoronoiPointRadius = voronoiDataset1.GetPointData().GetArray(radiusArrayName).GetTuple1(arrivalVoronoiPointId)

       arrivalCenterlinePointLocator = vtk.vtkPointLocator()
       arrivalCenterlinePointLocator.SetDataSet(cellLine)
       arrivalCenterlinePointLocator.BuildLocator()

       arrivalCenterlineClosestPointId = arrivalCenterlinePointLocator.FindClosestPoint(arrivalVoronoiPoint)
       arrivalCenterlineClosestPoint = cellLine.GetPoint(arrivalCenterlineClosestPointId)

       arrivalVoronoiVector = [0.0,0.0,0.0]
       arrivalVoronoiVector[0] = arrivalVoronoiPoint[0] - arrivalCenterlineClosestPoint[0]
       arrivalVoronoiVector[1] = arrivalVoronoiPoint[1] - arrivalCenterlineClosestPoint[1]
       arrivalVoronoiVector[2] = arrivalVoronoiPoint[2] - arrivalCenterlineClosestPoint[2]
       arrivalVoronoiVectorNorm = vtk.vtkMath.Norm(arrivalVoronoiVector)

       radiusArray = ComputeSpline(voronoiPointRadius,arrivalVoronoiPointRadius,numberOfPTPoints)
       vectorNormArray = ComputeSpline(voronoiVectorNorm,arrivalVoronoiVectorNorm, numberOfPTPoints)

       if (direction==1):
          pointsToGap = gapStartId - closestPointId
       else:
          pointsToGap = closestPointId - gapStartId

       pointId = pointsToGap
       for k in range(gapStartId,endSavingInterval,step):
          ptpoint = PTPoints.GetPoint(pointsToGap)
          clpoint = cellLine.GetPoint(k)

          vector = [0.0,0.0,0.0]
          vector[0] = ptpoint[0] - clpoint[0]
          vector[1] = ptpoint[1] - clpoint[1]
          vector[2] = ptpoint[2] - clpoint[2]
          vtk.vtkMath.Normalize(vector)

          norm = vectorNormArray.GetTuple1(pointsToGap)

          newvector = [0.0,0.0,0.0]
          newvector[0] = norm*vector[0]
          newvector[1] = norm*vector[1]
          newvector[2] = norm*vector[2]

          newpoint = [0.0,0.0,0.0]
          newpoint[0] = clpoint[0] + newvector[0]
          newpoint[1] = clpoint[1] + newvector[1]
          newpoint[2] = clpoint[2] + newvector[2]

          finalNewVoronoiPoints.InsertNextPoint(newpoint)
          cellArray.InsertNextCell(1)
          cellArray.InsertCellPoint(count)
          finalRadiusArray.SetTuple1(count,radiusArray.GetTuple1(pointsToGap))
          pointsToGap +=1
          count +=1

    return finalNewVoronoiPoints,finalRadiusArray

def ExtractLine(cellid,centerlines):
   cell = vtk.vtkGenericCell()
   centerlines.GetCell(cellid,cell)

   numberOfPoints = cell.GetNumberOfPoints()

   line = vtk.vtkPolyData()
   cellArray = vtk.vtkCellArray()
   cellArray.InsertNextCell(numberOfPoints)

   linePoints = cell.GetPoints()

   ptnArray = vtk.vtkDoubleArray()
   ptnArray.SetNumberOfComponents(3)
   ptnArray.SetNumberOfTuples(numberOfPoints)
   ptnArray.SetName(parallelTransportNormalsArrayName)
   ptnArray.FillComponent(0,0.0)
   ptnArray.FillComponent(1,0.0)
   ptnArray.FillComponent(2,0.0)

   for i in range(numberOfPoints):
      cellArray.InsertCellPoint(i)
      normal = centerlines.GetPointData().GetArray(parallelTransportNormalsArrayName).GetTuple3(cell.GetPointId(i))
      ptnArray.SetTuple3(i,normal[0],normal[1],normal[2])

   line.SetPoints(linePoints)
   line.SetLines(cellArray)
   line.GetPointData().AddArray(ptnArray)
   return line

def ComputeVoronoiVectorToCenterlineAngle(pointId,vector,centerline):
    point0 = [0.0,0.0,0.0]
    point1 = [0.0,0.0,0.0]
    point2 = [0.0,0.0,0.0]
    centerline.GetPoint(pointId,point0)
    centerline.GetPoint(pointId+1,point1)
    centerline.GetPoint(pointId-1,point2)

    tangent = [0.0,0.0,0.0]
    tangent[0] += point1[0]-point0[0]
    tangent[1] += point1[1]-point0[1]
    tangent[2] += point1[2]-point0[2]
    tangent[0] += point0[0]-point2[0]
    tangent[1] += point0[1]-point2[1]
    tangent[2] += point0[2]-point2[2]

    ptnnormal = centerline.GetPointData().GetArray(parallelTransportNormalsArrayName).GetTuple3(pointId)

    alpha = ComputeAngleBetweenVectors(ptnnormal,tangent,vector)
    return alpha

def ComputeAngleBetweenVectors(normal,tangent,vector):
    #compute the tangent component orthogonal to normal
    otangent = [0.0,0.0,0.0]
    normalDot = vtk.vtkMath.Dot(tangent,normal)
    otangent[0] = tangent[0] - normalDot*normal[0]
    otangent[1] = tangent[1] - normalDot*normal[1]
    otangent[2] = tangent[2] - normalDot*normal[2]
    vtk.vtkMath.Normalize(otangent)

    #compute the vector component orthogonal to otangent, i.e. parallel to normal
    vtk.vtkMath.Normalize(vector)
    ovector = [0.0,0.0,0.0]
    vectorDot = vtk.vtkMath.Dot(vector,otangent)
    ovector[0] = vector[0] - vectorDot*otangent[0]
    ovector[1] = vector[1] - vectorDot*otangent[1]
    ovector[2] = vector[2] - vectorDot*otangent[2]
    vtk.vtkMath.Normalize(ovector)

    theta = vtkvmtk.vtkvmtkMath.AngleBetweenNormals(normal,ovector)
    theta = vtk.vtkMath.DegreesFromRadians(theta)

    cross = [0.0,0.0,0.0]
    vtk.vtkMath.Cross(ovector,normal,cross)
    tangentDot = vtk.vtkMath.Dot(otangent,cross)
    if (tangentDot<0.0): theta = -1.0*theta
    angle = -theta
    return angle

def ComputeSpline(startValue,endValue,numberOfPoints):
   averageValue = (startValue + endValue)/2.0
   averageId = int(numberOfPoints/2)

   splineArray = vtk.vtkDoubleArray()
   splineArray.SetNumberOfComponents(1)
   splineArray.SetNumberOfTuples(numberOfPoints)
   splineArray.FillComponent(0,0.0)

   spline = vtk.vtkCardinalSpline()
   spline.AddPoint(float(0),startValue)
   spline.AddPoint(float(averageId),averageValue)
   spline.AddPoint(float(numberOfPoints),endValue)
   spline.Compute()

   for i in range(numberOfPoints):
      splineArray.SetTuple1(i,spline.Evaluate(float(i)))

   return splineArray

def InsertNewVoronoiPoints(oldDataset,newPoints,newArray):
   numberOfDatasetPoints = oldDataset.GetNumberOfPoints()
   numberOfNewPoints = newPoints.GetNumberOfPoints()
   numberOfNewVoronoiPoints = numberOfDatasetPoints + numberOfNewPoints

   newDataset = vtk.vtkPolyData()
   radiusArray = vtk.vtkDoubleArray()
   radiusArray.SetNumberOfComponents(1)
   radiusArray.SetNumberOfTuples(numberOfNewVoronoiPoints)
   radiusArray.SetName(radiusArrayName)
   radiusArray.FillComponent(0,0.0)
   cellArray = vtk.vtkCellArray()
   points = vtk.vtkPoints()

   for i in range(numberOfDatasetPoints):
      point = [0.0,0.0,0.0]
      oldDataset.GetPoint(i,point)
      points.InsertNextPoint(point)
      cellArray.InsertNextCell(1)
      cellArray.InsertCellPoint(i)

      value = oldDataset.GetPointData().GetArray(radiusArrayName).GetTuple1(i)
      radiusArray.SetTuple1(i,value)

   for i in range(numberOfNewPoints):
      point = [0.0,0.0,0.0]
      newPoints.GetPoint(i,point)
      points.InsertNextPoint(point)
      cellArray.InsertNextCell(1)
      cellArray.InsertCellPoint(numberOfDatasetPoints+i)

      value = newArray.GetTuple1(i)
      radiusArray.SetTuple1(numberOfDatasetPoints+i,value)

   newDataset.SetPoints(points)
   newDataset.SetVerts(cellArray)
   newDataset.GetPointData().AddArray(radiusArray)
   return newDataset

# -----------------------------------------------------------------------------------------

## Program:	clipvoronoidiagram.py
## Language:	Python
## Date:	2012/02/27
## Version:	1.0
## Application: Cerebral Aneurysms - Parent Vessel Reconstruction
## Author:	Marina Piccinelli

## Description:	Given the parallel transport normal system defined on the interpolated
##		centerlines computes the trajectory of Voronoi Diagram points from one end
##		to the other of the empty area in the clipped Voronoi Diagram. Saves a new
##		complete Voronoi Diagram and recalculates the model surface by merging of
##		maximal inscribed spheres. Recommended use of smoothed clipped Voronoi
##		Diagram.

# -----------------------------------------------------------------------------------------

#SOME COMMON VMTK DATA ARRAY NAMES
radiusArrayName = 'MaximumInscribedSphereRadius'
parallelTransportNormalsArrayName = 'ParallelTransportNormals'

#OPTIONS TO SET
interpolationHalfSize = 3
polyBallImageSize = [90,90,90]   #size of the image for the evaluation of the polyball function

#inputfilenames:
print('USAGE:')
print('      ./paralleltransportvoronoidiagram.py inputfilesDirectory caseID smoothVoronoi')
print('')

inputfiledirectory = sys.argv[1]
ID = sys.argv[2]
smoothedVoronoi = int(sys.argv[3])

print('Inputfiles Directory	', inputfiledirectory)
print('case ID			', ID)
print('')

interpolatedCenterlinesFilename = inputfiledirectory + '/' + ID + '/' + ID + '_interpolatedcl.vtp'
patchCenterlinesFilename        = inputfiledirectory + '/' + ID + '/' + ID + '_patchcl.vtp'
if smoothedVoronoi == 1:
   clippedVoronoiFilename       = inputfiledirectory + '/' + ID + '/' + ID + '_smoothclippedvoronoi.vtp'
else:
   clippedVoronoiFilename       = inputfiledirectory + '/' + ID + '/' + ID + '_clippedvoronoi.vtp'
clippingPointsFilename          = inputfiledirectory + '/' + ID + '/' + ID + '_clippingpoints.vtp'

#outputfilenames:
completeVoronoiFilename         = inputfiledirectory + '/' + ID + '/' + ID + '_completevoronoi.vtp'
surfaceFilename                 = inputfiledirectory + '/' + ID + '/' + ID + '_reconstructedmodel.vtp'

interpolatedCenterlines = ReadPolyData(interpolatedCenterlinesFilename)
patchCenterlines = ReadPolyData(patchCenterlinesFilename)
clippedVoronoi = ReadPolyData(clippedVoronoiFilename)
clippingPoints = ReadPolyData(clippingPointsFilename)

completeVoronoiDiagram = vtk.vtkPolyData()
completeVoronoiDiagram.DeepCopy(clippedVoronoi)

numberOfInterpolatedCenterlinesCells = interpolatedCenterlines.GetNumberOfCells()

for j in range(1,numberOfInterpolatedCenterlinesCells+1):
   interpolationCellId = j-1
   startId = 0
   endId = j

   startCell = vtk.vtkGenericCell()
   patchCenterlines.GetCell(startId,startCell)

   startCellPointId = startCell.GetPointId(startCell.GetNumberOfPoints()-1)
   startCellPoint = patchCenterlines.GetPoint(startCellPointId)
   startCellPointRadius = patchCenterlines.GetPointData().GetArray(radiusArrayName).GetTuple1(startCellPointId)
   startCellPointHalfRadius = startCellPointRadius/7.0

   startInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram(startId,startCellPointId,startCellPointRadius,clippedVoronoi,patchCenterlines)
   startHalfInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram(startId,startCellPointId,startCellPointHalfRadius,clippedVoronoi,patchCenterlines)

   endCell = vtk.vtkGenericCell()
   patchCenterlines.GetCell(endId,endCell)

   endCellPointId = endCell.GetPointId(0)
   endCellPoint = patchCenterlines.GetPoint(endCellPointId)
   endCellPointRadius = patchCenterlines.GetPointData().GetArray(radiusArrayName).GetTuple1(endCellPointId)
   endCellPointHalfRadius = endCellPointRadius/7.0

   endInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram(endId,endCellPointId,endCellPointRadius,clippedVoronoi,patchCenterlines)
   endHalfInterpolationDataset = ExtractCylindricInterpolationVoronoiDiagram(endId,endCellPointId,endCellPointHalfRadius,clippedVoronoi,patchCenterlines)

   newVoronoiPoints, newVoronoiPointsMISR = VoronoiDiagramInterpolation(interpolationCellId,startId,endId,startInterpolationDataset,endHalfInterpolationDataset,interpolatedCenterlines,1)
   completeVoronoiDiagram = InsertNewVoronoiPoints(completeVoronoiDiagram,newVoronoiPoints,newVoronoiPointsMISR)

   newVoronoiPoints, newVoronoiPointsMISR = VoronoiDiagramInterpolation(interpolationCellId,endId,startId,endInterpolationDataset,startHalfInterpolationDataset,interpolatedCenterlines,0)
   completeVoronoiDiagram = InsertNewVoronoiPoints(completeVoronoiDiagram,newVoronoiPoints,newVoronoiPointsMISR)

WritePolyData(completeVoronoiDiagram,completeVoronoiFilename)

print('Reconstructing Surface from Voronoi Diagram')
modeller = vtkvmtk.vtkvmtkPolyBallModeller()
modeller.SetInputData(completeVoronoiDiagram)
modeller.SetRadiusArrayName(radiusArrayName)
modeller.UsePolyBallLineOff()
modeller.SetSampleDimensions(polyBallImageSize)
modeller.Update()

marchingCube = vtk.vtkMarchingCubes()
marchingCube.SetInputData(modeller.GetOutput())
marchingCube.SetValue(0,0.0)
marchingCube.Update()
envelope = marchingCube.GetOutput()
WritePolyData(envelope,surfaceFilename)


"""Functions to download results."""
import zipfile
import json

import streamlit as st
from honeybee.model import Model
from honeybee_display.model import model_to_vis_set
from ladybug_vtk.visualization_set import VisualizationSet as VTKVisualizationSet

from vis_metadata import _leed_daylight_option_one_vis_metadata

def download_files() -> None:
    """Download files from a run on Pollination. This function uses the run
    saved in the sessions state."""
    run = st.session_state.run
    run_folder = st.session_state.run_folder

    _, info = next(run.job.runs_dataframe.input_artifacts.iterrows())
    model_dict = json.load(run.job.download_artifact(info.model))
    hb_model = Model.from_dict(model_dict)

    leed_summary_folder = run_folder.joinpath('leed-summary')

    output = run.download_zipped_output('leed-summary')
    with zipfile.ZipFile(output) as zip_folder:
        zip_folder.extractall(leed_summary_folder)

    if not leed_summary_folder.joinpath('states_schedule_err.json').is_file():
        json.dump({}, leed_summary_folder.joinpath('states_schedule_err.json'))

    results_folder = leed_summary_folder.joinpath('results')
    metric_info_dict = _leed_daylight_option_one_vis_metadata()
    for metric, data in metric_info_dict.items():
        file_path = results_folder.joinpath(metric, 'vis_metadata.json')
        with open(file_path, 'w') as file:
            json.dump(data, file, indent=4)

    vis_set = model_to_vis_set(
        hb_model, color_by=None, include_wireframe=True,
        grid_data_path=str(results_folder), active_grid_data='da'
    )
    vtk_vs = VTKVisualizationSet.from_visualization_set(vis_set)
    vtk_vs.to_vtkjs(folder=run_folder, name='vis_set')