from django.shortcuts import render
from rest_framework.response import Response
from rebbit_hub_app.serializers import UserSerializer, Files_backedupSerializer, DeviceSerializer, UserDetailsSerializer, VersionSerializer
from rebbit_hub_app.models import User, FilesBackedup,Device,UserDetails,Version
from rest_framework import generics
from django.db import connection, transaction
from django.http import JsonResponse

# Create your views here.

class getAllFiles(generics.RetrieveAPIView):
    def get(self,request, *args , **kwargs):
        try:
            cursor = connection.cursor()
            cursor.execute(
                "SELECT u.user_id , d.device_id, f.file_id,f.file_name, f.file_path,f.file_size,f.file_time ,f.is_backedup,f.is_deleted "
                "FROM rebbit_hub.user u , rebbit_hub.device d , rebbit_hub.files_backedup f "
                "WHERE u.user_id = d.user_id and d.device_id = f.device_id and f.is_deleted = 0 "
                "and u.user_id = {0} and d.device_id= {1};".format(request.userTokenPayload["user_id"],request.query_params["device_id"]))
            row = cursor.fetchall()
            if row == None:
                raise Exception("No files for this user_id:"+request.query_params["user_id"])
            print(row)
            cursor.close()
            return Response(row,status=200)
        except Exception as e:
            print("An exception occured: ",e)
            return Response(e.args, status=400)

class getAllDevices(generics.RetrieveAPIView):
    def get(self,request, *args , **kwargs):
        try:
            devices = Device.objects.filter(user_id=request.userTokenPayload["user_id"])
            devices_serialized = DeviceSerializer(devices, many=True)
            if devices_serialized.data == None:
                raise Exception("No device exist")
            return Response(devices_serialized.data,status=200)
        except Exception as e:
            print("An exception occured: ",e)
            return Response(e.args, status=400)

class getUserSubscriptionDetails(generics.RetrieveAPIView):
    def get(self,request, *args, **kwargs):
        try:
            subs = UserDetails.objects.filter(user_id=request.userTokenPayload["user_id"])
            subs_serialized = UserDetailsSerializer(subs, many=True)
            if subs_serialized.data.__len__() == 0:
                raise Exception("No Subscription by this user")
            return Response(subs_serialized.data,status=200)
        except Exception as e:
            print("An exception occured: ",e)
            return Response(e.args, status=400)

class getVersions(generics.RetrieveAPIView):
    def get(self, request , *args, **kwargs):
        try:
            version_obj = Version.objects.filter(file_id = request.query_params['file_id'])
            version_serialized = VersionSerializer(version_obj, many=True)
            if version_serialized.data.__len__() == 0:
                raise Exception("No version for this file")
            return  Response(version_serialized.data,status = 200)
        except Exception as e:
            print("An exception occured",e)
            return Response(e.args, status = 400)

class deleteFile(generics.RetrieveAPIView):
    def patch(self,request, *args , **kwargs):
        try:
            cursor = connection.cursor()
            cursor.execute(
                "UPDATE files_backedup SET is_deleted=1 WHERE file_id = {0};".format(request.query_params["file_id"]))
            row = cursor.fetchone()
            # if row.__len__() == 0:
            #     raise Exception("Cannot delete file id:"+request.query_params["file_id"])
            print(row)
            cursor.close()
            return Response(row,status=200)
        except Exception as e:
            print("An exception occured: ",e)
            return Response(e.args, status=400)

class restoreFile(generics.RetrieveAPIView):
    def patch(self,request, *args , **kwargs):
        try:
            cursor = connection.cursor()
            cursor.execute(
                "UPDATE files_backedup SET is_deleted=0 WHERE file_id = {0} AND is_deleted=1;".format(request.query_params["file_id"]))
            row = cursor.fetchone()
            print(row)
            cursor.close()
            return Response(row,status=200)
        except MySQLdb.Error as e:
            print("MySQL db error",e)
            return Response(e.args,status=400)
        except Exception as e:
            print("An exception occured: ",e)
            return Response(e.args, status=400)

class getAllDeletedFiles(generics.RetrieveAPIView):
    def get(self,request, *args , **kwargs):
        try:
            cursor = connection.cursor()
            cursor.execute(
                "SELECT f.file_id,f.file_name,f.file_path,f.file_size, f.device_id FROM rebbit_hub.device d , rebbit_hub.files_backedup f "
                "WHERE d.device_id = f.device_id and f.is_deleted = 1 and d.user_id = {0};".format(request.userTokenPayload["user_id"]))
            row = cursor.fetchall()
            if row == None:
                raise Exception("No files for this user_id:"+request.query_params["user_id"])
            print(row)
            cursor.close()
            return Response(row,status=200)
        except Exception as e:
            print("An exception occured: ",e)
            return Response(e.args, status=400)

class deleteFilePermanently(generics.RetrieveAPIView):
    def delete(self,request, *args , **kwargs):
        try:
            cursor = connection.cursor()
            cursor.execute(
                "DELETE FROM rebbit_hub.version WHERE file_id = {0};DELETE FROM rebbit_hub.files_backedup WHERE file_id = {0};".format(request.query_params["file_id"]))
            row = cursor.fetchall()
            # if row.__len__() == 0:
            #     raise Exception("Cannot delete file id:"+request.query_params["file_id"])
            print(row)
            cursor.close()
            return Response(row,status=200)
        except Exception as e:
            print("An exception occured: ",e)
            return Response(e.args, status=400)


class Static_Stack:
    def __init__(self,n):
        self.list = [None]*n
        self.top = -1

    def isEmpty(self):
        return self.top == -1

    def pop(self):
        if self.top == -1:
            print("Underflow")
        else:
            self.top -= 1
            return(self.list[self.top+1])

    def push(self,x):
        if self.top == (len(self.list)-1):
            print("overflow")
        else:
            self.top += 1
            self.list[self.top] = x

class StackQueue:
    def __init__(self,n):
        self.head = Static_Stack(n)
        self.tail = Static_Stack(n)

    def dequeue(self):
        if self.tail.isEmpty():
            for _,key in enumerate(self.head.list):
                if key != None:
                    x = self.head.pop()
                    self.tail.push(x)
        self.tail.pop()

    def enqueue(self,x):
        self.head.push(x)

"""Implementering af linked lists

p = Pointer to previous element
k = Key value
n = Pointer to next element
"""
class Node:
    def __init__(self,p,k,n):
        self.key = k
        self.next = n
        self.prev = p

#Assumes nodeSequence[0] to be the head.
class sLinkedStack:
    def __init__(self,head):
        self.head = head

    def isEmpty(self):
        return self.head == None

    def pop(self): #O(1)
        if self.isEmpty():
            print("Underflow")
            return Node(None,"Underflow",None) #So we can keep doing keys ;)
        x = self.head
        self.head = self.head.next
        return x

    def push(self,x): #O(1)
        x.next = self.head
        self.head = x

#Singly linked Q - tager nodes som input
class sLinkedQ:

    def __init__(self,head):
        self.head = sLinkedStack(head)
        self.tail = sLinkedStack(None)

    def enQ(self,x):
        self.head.push(x)

    def deQ(self):
        if self.tail.isEmpty():
            while self.head.isEmpty() == False:
                x = self.head.pop()
                self.tail.push(x)
        return self.tail.pop()

    def isEmpty(self):
        if self.head.isEmpty() and self.tail.isEmpty():
            print("Queue is empty")
            return True
        return False

"""adj simple linear-probing HashTable that uses a modulo function for assigning the places of each input.
"""
class HashTable:
    def __init__(self,divisor):
        self.divisor = divisor
        self.hashArray = [None] * self.divisor
        self.dictSize = 0 #Number of elements in the hashArray

#Slingly Linked List

""" Inserts x0 in a sorted singly listed link, where x1 is the head """
def appendInSorted(x1,x0):
    if x1.key < x0.key:
        if x0.key <= x1.next.key:
            x0.next = x1.next
            x1.next = x0
        elif x1.next is None:
            x0.next = x1
        else:
            appendInSorted(x1.next,x0)

#x0.next = x1
def invert(x0,x1):
    next = x1.next
    x1.next = x0
    if next is None:
        return x1
    else:
        invert(x1,next)

def invertSLinkyList(head):
    firstNext = head.next
    head.next = None
    x = 0
    x = invert(head,firstNext)
    return x

"""Takes an array adj of size n, creates an array B of size 2*n and inserts all elements from adj to B

B = [x1,x2,...,NONE,NONE]
"""
def dynamicResizing(ArrayA):
    ArrayB = [None]*len(ArrayA)*2
    for idx,key in enumerate(ArrayA):
        ArrayB[idx] = key
    return ArrayB

from collections import defaultdict

""" Opgave omkring at finde fra toppen af venstre hjørne til bunden af højre

Vi laver BFS, hvor en edge kun eksisterer, hvis to nodes har forskellige chars"""

"""
Mark and Q enQ'er og markerer alle nodes, som vi kan nå
"""
def markAndQ(unMarked,Q,v,marking):
    x,y,t = v.key[1],v.key[0],v.key[2]
    t += 1
    u = Node(p=v, k=[y + marking[0],x + marking[1], t], n=0)
    Q.enQ(u)
    unMarked[f"{[u.key[0],u.key[1]]}"] = False #Markerer

#finds the quickest path to the bottom starting at S
def BFS_ABA(matrix,N):
    unMarked = defaultdict(lambda: True) #Vi starter med at unmarkere alle vertices
    start = Node(p=None,k=[0,0,0],n=None) #Keyen indeholder y,x og t
    Q = sLinkedQ(None)
    Q.enQ(start)

    while Q.isEmpty() != True: #Så længe, at der er en mulig path i vores Q
        v = Q.deQ()
        x,y = v.key[1],v.key[0]
        char = matrix[y][x]  # V's bogstav
        unMarked[f"{[v.key[0], v.key[1]]}"] = False
        if (x,y) == (N-1,N-1):
            return (v.key[2]+1) #Hvis vi har nået bunden, så returner vi v's tid
        else:
            try:
                if matrix[y+1][x] != char and unMarked[f"{[y+1,x]}"]: #nedenunder
                    markAndQ(unMarked,Q,v,[1,0])
            except:
                pass
            try:
                if matrix[y][x+1] != char and unMarked[f"{[y,x+1]}"]:  # til højre for
                    markAndQ(unMarked, Q, v,[0,1])
            except:
                pass
            try:
                if y>0 and matrix[y-1][x] != char and unMarked[f"{[y-1,x]}"]: #nedenunder
                    markAndQ(unMarked,Q,v,[-1,0])
            except:
                pass
            try:
                if x>0 and matrix[y][x-1] != char and unMarked[f"{[y,x-1]}"]:  # til venstre for
                    markAndQ(unMarked,Q,v,[0,-1])
            except:
                pass
    return False #No path

N = int(input())

def getSplitList(N):
    splitList = []
    for idx in range(N):
        splitList.append(input().split())
    return splitList

def getMatrix(splitList):
    Matrix = []
    for idx, str in enumerate(splitList):
        Matrix += [list(str[0])]
    return(Matrix)

Matrix = getMatrix(getSplitList(N))
print(BFS_ABA(Matrix,N))


import numpy as np
import cv2
import argparse
from collections import deque

# badan bayad kamel konam
def create_hue_mask(image, lower_color, upper_color):
    lower = np.array(lower_color, np.uint8)
    upper = np.array(upper_color, np.uint8)

    # Create a mask from the colors
    mask = cv2.inRange(image, lower, upper)
    output_image = cv2.bitwise_and(image, image, mask=mask)
    return output_image
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video",
	help="path to the (optional) video file")
ap.add_argument("-b", "--buffer", type=int, default=64,
	help="max buffer size")
args = vars(ap.parse_args())
pts = deque(maxlen=args["buffer"])
cap = cv2.VideoCapture(0)

while (True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    output = frame.copy()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (3, 3), 0)
    edged = cv2.Canny(gray, 10, 250)

    # construct and apply a closing kernel to 'close' gaps between 'white'
    # pixels
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))
    closed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)

    im2, contours, hierarchy = cv2.findContours(closed.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    center = None

    # only proceed if at least one contour was found
    if len(contours) > 0:
        # find the largest contour in the mask, then use
        # it to compute the minimum enclosing circle and
        # centroid
        c = max(contours, key=cv2.contourArea)
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        M = cv2.moments(c)
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

        # only proceed if the radius meets a minimum size
        if radius > 10:
            # draw the circle and centroid on the frame,
            # then update the list of tracked points
            cv2.circle(output, (int(x), int(y)), int(radius),
                       (0, 255, 255), 2)
            cv2.circle(output, center, 5, (0, 0, 255), -1)

    # update the points queue
    pts.appendleft(center)

    # loop over the set of tracked points
    for i in xrange(1, len(pts)):
        # if either of the tracked points are None, ignore
        # them
        if pts[i - 1] is None or pts[i] is None:
            continue

        # otherwise, compute the thickness of the line and
        # draw the connecting lines

        cv2.line(output, pts[i - 1], pts[i], (0, 0, 255), 1)

    #im2, cnts, hierarchy = cv2.findContours(closed.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    total = 0
    # print (len(contours))
    # print (contours[0][2][0][0])
    # print(contours[4][2])
    ii = 0
    jj = 0
    x = 0
    y = 0
    x_ave = 0
    y_ave = 0

    for c in contours:
        # approximate the contour
        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.02 * peri, True)

        # if the approximated contour has four points, then assume that the
        # contour is a book -- a book is a rectangle and thus has four vertices
        if len(approx) == 4:
            cv2.drawContours(output, [approx], -1, (0, 255, 0), 4)
            total += 1

    while (ii < (len(contours))):

        # print (contours[ii][0])

        # print(len(contours[ii]))
        # print(ii)
        while (jj < len(contours[ii])):
            # print(contours[ii-1][jj-1])
            # print(contours[ii][jj][0])
            x = x + contours[ii][jj][0][0]
            y = y + contours[ii][jj][0][1]

            # print("ok")
            # print(ii, jj)
            jj = jj + 1

        x_ave = x / len(contours[ii])
        y_ave = y / len(contours[ii])
        # print(x_ave)
        jj = 0
        ii = ii + 1

 #   cv2.drawContours(output, contours, -1, (0, 255, 0), 3)

    cv2.imshow('frame', output)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


#  Game class

import pygwidgets
import pygame
import random

from Constants import *

# Card Class
class Card:

    def __init__(self, window, rank, suit, value):
        # must add code here to save away parameters in instance variables
        # and create two Image objects, one for the current card, one for the backOfCard
        # you can remove this line when you add your own
        self.window = window
        self.rank = rank
        self.CardName = suit
        self.value = value
        self.image = pygwidgets.Image(window, (0, 0), 'images/' + self.rank + ' of ' + self.CardName + '.png')
        self.backOfImage = pygwidgets.Image(window, (0, 0), 'images/BackOfCard.png')
        self.cardImage = self.image
        self.loc = ''

    def conceal(self):
        self.image = self.backOfImage

    def setLoc(self, locTuple):
        self.image.setLoc(locTuple)
        self.loc = locTuple

    def reveal(self):
        self.image = self.cardImage

    def getName(self):
        return self.CardName

    def getValue(self):
        return self.value

    def draw(self):
        self.image.setLoc(self.loc)
        self.image.draw()

    @staticmethod
    def getCardNameAndValue():
        return ("CardName", 0)

# Deck Class
class Deck:
    SUIT_TUPLE = SUIT_TUPLE_VALUE
    RANK_TUPLE = RANK_TUPLE_VALUE
    STANDARD_VALUES_TUPLE = STANDARD_VALUES_TUPLE_VALUE

    def __init__(self, window, valuesTuple=STANDARD_VALUES_TUPLE):
        # If nothing is passed in for valuesTuple, it uses default values
        self.startingDeckList = []
        self.playingDeckList = []
        for suit in Deck.SUIT_TUPLE:
            for index, rank in enumerate(Deck.RANK_TUPLE):
                oCard = Card(window, rank, suit, valuesTuple[index])
                self.startingDeckList.append(oCard)

    def shuffle(self):
        # make a copy of the starting deck and save in the playing deck list
        self.playingDeckList = self.startingDeckList[:]
        for oCard in self.playingDeckList:
            oCard.conceal()
        random.shuffle(self.playingDeckList)

    def getCard(self):
        if len(self.playingDeckList) == 0:
            raise Exception('No more cards')
        oCard = self.playingDeckList.pop()  # pop one off the deck and return it
        return oCard

# Game Class
class Game:
    CARD_OFFSET = GAME_CARD_OFFSET_VALUE
    CARDS_TOP = GAME_CARDS_TOP_VALUE
    CARDS_LEFT = GAME_CARDS_LEFT_VALUE
    NCARDS = GAME_NCARDS_VALUE

    def __init__(self, window):
        self.window = window
        self.oDeck = Deck(self.window)
        self.score = 100
        self.scoreText = pygwidgets.DisplayText(window, (450, 164), 'Score: ' + str(self.score), fontSize=36, textColor=WHITE, justified='right')
        self.messageText = pygwidgets.DisplayText(window, (50, 460), '', width=900, justified='center', fontSize=36, textColor=WHITE)
        self.loserSound = pygame.mixer.Sound("sounds/loser.wav")
        self.winnerSound = pygame.mixer.Sound("sounds/ding.wav")
        self.cardShuffleSound = pygame.mixer.Sound("sounds/cardShuffle.wav")

        self.cardXPositionsList = []
        thisLeft = Game.CARDS_LEFT
        # Calculate the x positions of all cards ... once
        for i in range(Game.NCARDS):
            self.cardXPositionsList.append(thisLeft)
            thisLeft = thisLeft + Game.CARD_OFFSET
        self.reset()  # start a round of the game

    def reset(self):  # This method is called when a new round starts
        self.score = 100
        self.scoreText.setValue('Score: ' + str(self.score))
        self.cardShuffleSound.play()
        self.cardList = []
        self.oDeck.shuffle()
        for cardIndex in range(0, Game.NCARDS):  # Deal out cards
            oCard = self.oDeck.getCard()
            self.cardList.append(oCard)
            thisXPosition = self.cardXPositionsList[cardIndex]
            oCard.setLoc((thisXPosition, Game.CARDS_TOP))

        self.showCard(0)
        self.cardNumber = 0
        self.currentCardName, self.currentCardValue = self.getCardNameAndValue(self.cardNumber)
        self.messageText.setValue(
            'Starting card is ' + self.currentCardName + '. Will the next card be higher or lower?')

    def getCardNameAndValue(self, index):
        oCard = self.cardList[index]
        theName = oCard.getName()
        theValue = oCard.getValue()
        return theName, theValue

    def showCard(self, index):
        oCard = self.cardList[index]
        oCard.reveal()

    def hitHigherOrLower(self, higherOrLower):
        self.cardNumber = self.cardNumber + 1
        self.showCard(self.cardNumber)
        nextCardName, nextCardValue = self.getCardNameAndValue(self.cardNumber)

        if higherOrLower == HIGHER:
            if nextCardValue > self.currentCardValue:
                self.score = self.score + 15
                self.messageText.setValue('Yes, the ' + nextCardName + ' was higher')
                self.winnerSound.play()
            else:
                self.score = self.score - 10
                self.messageText.setValue('No, the ' + nextCardName + ' was lower')
                self.loserSound.play()

        else:  # user hit the lower button:
            if nextCardValue < self.currentCardValue:
                self.score = self.score + 15
                self.messageText.setValue('Yes, the ' + nextCardName + ' was lower')
                self.winnerSound.play()
            else:
                self.score = self.score - 10
                self.messageText.setValue('No, the ' + nextCardName + ' was higher')
                self.loserSound.play()

        self.scoreText.setValue('Score: ' + str(self.score))
        self.currentCardValue = nextCardValue  # set up for next higher/lower button choice

        done = (self.cardNumber == (Game.NCARDS - 1))  # did we reach the last card?
        return done

    def draw(self):
        # Tell each card to draw itself
        for oCard in self.cardList:
            oCard.draw()

        self.scoreText.draw()
        self.messageText.draw()


import numpy
import six.moves

import cellprofiler_core.image
import cellprofiler_core.measurement
import cellprofiler.modules.unmixcolors
import cellprofiler_core.object
import cellprofiler_core.pipeline
import cellprofiler_core.workspace
import tests.modules

INPUT_IMAGE = "inputimage"

def output_image_name(idx):
    return "outputimage%d" % idx

def test_load_v1():
    file = tests.modules.get_test_resources_directory("unmixcolors/v1.pipeline")
    with open(file, "r") as fd:
        data = fd.read()

    pipeline = cellprofiler_core.pipeline.Pipeline()

    def callback(caller, event):
        assert not isinstance(event, cellprofiler_core.pipeline.event.LoadException)

    pipeline.add_listener(callback)
    pipeline.load(six.moves.StringIO(data))
    assert len(pipeline.modules()) == 1
    module = pipeline.modules()[0]
    assert isinstance(module, cellprofiler.modules.unmixcolors.UnmixColors)
    assert module.input_image_name == "Color"
    assert module.stain_count.value == 13
    assert module.outputs[0].image_name == "Hematoxylin"
    assert module.outputs[-1].image_name == "RedWine"
    for i, stain in enumerate(
        (
            cellprofiler.modules.unmixcolors.CHOICE_HEMATOXYLIN,
            cellprofiler.modules.unmixcolors.CHOICE_EOSIN,
            cellprofiler.modules.unmixcolors.CHOICE_DAB,
            cellprofiler.modules.unmixcolors.CHOICE_FAST_RED,
            cellprofiler.modules.unmixcolors.CHOICE_FAST_BLUE,
            cellprofiler.modules.unmixcolors.CHOICE_METHYL_GREEN,
            cellprofiler.modules.unmixcolors.CHOICE_AEC,
            cellprofiler.modules.unmixcolors.CHOICE_ANILINE_BLUE,
            cellprofiler.modules.unmixcolors.CHOICE_AZOCARMINE,
            cellprofiler.modules.unmixcolors.CHOICE_ALCIAN_BLUE,
            cellprofiler.modules.unmixcolors.CHOICE_PAS,
        )
    ):
        assert module.outputs[i].stain_choice == stain
    assert round(abs(module.outputs[-1].red_absorbance.value - 0.1), 7) == 0
    assert round(abs(module.outputs[-1].green_absorbance.value - 0.2), 7) == 0
    assert round(abs(module.outputs[-1].blue_absorbance.value - 0.3), 7) == 0

def make_workspace(pixels, choices):
    """Make a workspace for running UnmixColors

    pixels - input image
    choices - a list of choice strings for the images desired
    """
    pipeline = cellprofiler_core.pipeline.Pipeline()

    def callback(caller, event):
        assert not isinstance(event, cellprofiler_core.pipeline.event.RunException)

    pipeline.add_listener(callback)

    module = cellprofiler.modules.unmixcolors.UnmixColors()
    module.input_image_name.value = INPUT_IMAGE
    module.outputs[0].image_name.value = output_image_name(0)
    module.outputs[0].stain_choice.value = choices[0]
    for i, choice in enumerate(choices[1:]):
        module.add_image()
        module.outputs[i + 1].image_name.value = output_image_name(i + 1)
        module.outputs[i + 1].stain_choice.value = choice

    module.set_module_num(1)
    pipeline.add_module(module)

    image_set_list = cellprofiler_core.image.ImageSetList()
    image_set = image_set_list.get_image_set(0)
    image = cellprofiler_core.image.Image(pixels)
    image_set.add(INPUT_IMAGE, image)

    workspace = cellprofiler_core.workspace.Workspace(
        pipeline,
        module,
        image_set,
        cellprofiler_core.object.ObjectSet(),
        cellprofiler_core.measurement.Measurements(),
        image_set_list,
    )
    return workspace, module

def make_image(expected, absorbances):
    eps = 1.0 / 256.0 / 2.0
    absorbance = 1 - expected
    log_absorbance = numpy.log(absorbance + eps)
    absorbances = numpy.array(absorbances)
    absorbances = absorbances / numpy.sqrt(numpy.sum(absorbances ** 2))
    log_absorbance = (
        log_absorbance[:, :, numpy.newaxis]
        * absorbances[numpy.newaxis, numpy.newaxis, :]
    )
    image = numpy.exp(log_absorbance) - eps
    return image

def test_zeros():
    """Test on an image of all zeros"""
    workspace, module = make_workspace(
        numpy.zeros((10, 20, 3)), [cellprofiler.modules.unmixcolors.CHOICE_HEMATOXYLIN]
    )
    module.run(workspace)
    image = workspace.image_set.get_image(output_image_name(0))
    #
    # All zeros in brightfield should be all 1 in stain
    #
    numpy.testing.assert_almost_equal(image.pixel_data, 1, 2)

def test_ones():
    """Test on an image of all ones"""
    workspace, module = make_workspace(
        numpy.ones((10, 20, 3)), [cellprofiler.modules.unmixcolors.CHOICE_HEMATOXYLIN]
    )
    module.run(workspace)
    image = workspace.image_set.get_image(output_image_name(0))
    #
    # All ones in brightfield should be no stain
    #
    numpy.testing.assert_almost_equal(image.pixel_data, 0, 2)

def test_one_stain():
    """Test on a single stain"""

    numpy.random.seed(23)
    expected = numpy.random.uniform(size=(10, 20))
    image = make_image(expected, cellprofiler.modules.unmixcolors.ST_HEMATOXYLIN)
    workspace, module = make_workspace(
        image, [cellprofiler.modules.unmixcolors.CHOICE_HEMATOXYLIN]
    )
    module.run(workspace)
    image = workspace.image_set.get_image(output_image_name(0))
    numpy.testing.assert_almost_equal(image.pixel_data, expected, 2)

def test_two_stains():
    """Test on two stains mixed together"""
    numpy.random.seed(24)
    expected_1 = numpy.random.uniform(size=(10, 20)) * 0.5
    expected_2 = numpy.random.uniform(size=(10, 20)) * 0.5
    #
    # The absorbances should add in log space and multiply in
    # the image space
    #
    image = make_image(expected_1, cellprofiler.modules.unmixcolors.ST_HEMATOXYLIN)
    image *= make_image(expected_2, cellprofiler.modules.unmixcolors.ST_EOSIN)
    workspace, module = make_workspace(
        image,
        [
            cellprofiler.modules.unmixcolors.CHOICE_HEMATOXYLIN,
            cellprofiler.modules.unmixcolors.CHOICE_EOSIN,
        ],
    )
    module.run(workspace)
    image_1 = workspace.image_set.get_image(output_image_name(0))
    numpy.testing.assert_almost_equal(image_1.pixel_data, expected_1, 2)
    image_2 = workspace.image_set.get_image(output_image_name(1))
    numpy.testing.assert_almost_equal(image_2.pixel_data, expected_2, 2)

def test_custom_stain():
    """Test on a custom value for the stains"""
    numpy.random.seed(25)
    absorbance = numpy.random.uniform(size=3)
    expected = numpy.random.uniform(size=(10, 20))
    image = make_image(expected, absorbance)
    workspace, module = make_workspace(
        image, [cellprofiler.modules.unmixcolors.CHOICE_CUSTOM]
    )
    (
        module.outputs[0].red_absorbance.value,
        module.outputs[0].green_absorbance.value,
        module.outputs[0].blue_absorbance.value,
    ) = absorbance
    module.run(workspace)
    image = workspace.image_set.get_image(output_image_name(0))
    numpy.testing.assert_almost_equal(image.pixel_data, expected, 2)


import difflib
import itertools
import time
from typing import Sequence

from automata import Matcher
from automata import find_all_matches
from nmd.nmd import emd_1d as emd_1d_fast
from nmd.nmd import ngram_movers_distance
from nmd.nmd_bow import bow_ngram_movers_distance
from nmd.nmd_index import ApproxWordListV3
from nmd.nmd_index import WordList
from tokenizer import unicode_tokenize

def emd_1d_slow(positions_x: Sequence[float],
                positions_y: Sequence[float],
                ) -> float:
    # positions_x must be longer
    if len(positions_x) < len(positions_y):
        positions_x, positions_y = positions_y, positions_x

    # sort both lists
    positions_x = sorted(positions_x)
    positions_y = sorted(positions_y)

    # find the minimum cost alignment
    costs = [len(positions_y)]
    for x_combination in itertools.combinations(positions_x, len(positions_y)):
        costs.append(sum(abs(x - y) for x, y in zip(x_combination, positions_y)))

    # the distance is the min cost alignment plus a count of unmatched points
    return len(positions_x) - len(positions_y) + min(costs)

def check_correct_emd_1d(positions_x: Sequence[float],
                         positions_y: Sequence[float],
                         ) -> float:
    """
    kind of like earth mover's distance
    but positions are limited to within the unit interval
    and must be quantized

    :param positions_x: list of positions (each a float from 0 to 1 inclusive)
    :param positions_y: list of positions (each a float from 0 to 1 inclusive)
    :return:
    """

    # sanity checks
    assert isinstance(positions_x, Sequence)
    assert isinstance(positions_y, Sequence)
    assert all(isinstance(x, (int, float)) for x in positions_x)
    assert all(isinstance(y, (int, float)) for y in positions_y)

    # all inputs must be in the unit interval
    assert all(0 <= x <= 1 for x in positions_x)
    assert all(0 <= y <= 1 for y in positions_y)

    # run both slow and fast and check them
    answer_fast = emd_1d_fast(positions_x, positions_y)
    answer_slow = emd_1d_slow(positions_x, positions_y)
    assert abs(answer_fast - answer_slow) < 0.00000001, (answer_slow, answer_fast, positions_x, positions_y)
    return answer_fast

if __name__ == '__main__':

    from experiments.edit_distance import damerau_levenshtein_distance
    from experiments.edit_distance import edit_distance

    def speed_test(word_1: str, word_2: str):
        edit_distance(word_1, word_2)
        damerau_levenshtein_distance(word_1, word_2)
        return ngram_movers_distance(word_1, word_2)

    # num_x = 3
    # num_y = 7
    #
    # xs = [i / (num_x - 1) for i in range(num_x)]
    # ys = [i / (num_y - 1) for i in range(num_y)]
    # # print(xs)
    # # print(ys)
    # xs = xs + xs + xs
    #
    # for x_len in range(len(xs) + 1):
    #     for y_len in range(len(ys) + 1):
    #         print(x_len, y_len)
    #         for x_combi in itertools.combinations(xs, x_len):
    #             for y_combi in itertools.combinations(ys, y_len):
    #                 assert abs(
    #                     check_correct_emd_1d(x_combi, y_combi) - check_correct_emd_1d(y_combi, x_combi)) < 0.0001, (
    #                     x_combi, y_combi)
    #
    # for _ in range(1000):
    #     speed_test('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    #                'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    #     speed_test('aabbbbbbbbaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    #     speed_test('aaaabbbbbbbbaaaa', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    #     speed_test('banana', 'bababanananananananana')
    #     speed_test('banana', 'bababanananananananananna')
    #     speed_test('banana', 'nanananananabababa')
    #     speed_test('banana', 'banana')
    #     speed_test('nanananananabababa', 'banana')
    #     speed_test('banana', 'bababananananananananannanananananananana')
    #     speed_test('banana', 'bababananananananananannananananananananananananananannanananananananana')
    #     speed_test('bananabababanana', 'bababananananananananannananananananananananananananannananabanananananana')
    #
    # # test cases: https://www.watercoolertrivia.com/blog/schwarzenegger
    # with open('schwarzenegger.txt') as f:
    #     for line in f:
    #         print('schwarzenegger', line.strip(), speed_test(line.strip(), 'schwarzenegger'))
    #
    # # real world test cases
    # with open('words_en.txt') as f1:
    #     with open('words_ms.txt') as f2:
    #         for en, ms in zip(f1, f2):
    #             speed_test(en.strip(), ms.strip())
    #             speed_test(en.strip(), en.strip())
    #             speed_test(ms.strip(), ms.strip())

    with open('words_ms.txt', encoding='utf8') as f:
        words_ms = set(f.read().split())

    awl3_ms = ApproxWordListV3((1, 2, 3, 4))
    for word in words_ms:
        awl3_ms.add_word(word)

    awl5_ms = WordList((1, 2, 3, 4))
    for word in words_ms:
        awl5_ms.add_word(word)

    with open('words_en.txt', encoding='utf8') as f:
        # with open('british-english-insane.txt', encoding='utf8') as f:
        words = set(f.read().split())

    awl3_en = ApproxWordListV3((1, 2, 3, 4))
    for word in words:
        awl3_en.add_word(word)

    awl5_en = WordList((1, 2, 3, 4))
    for word in words:
        awl5_en.add_word(word)

    # bananana
    # supercallousedfragilemisticexepialidocus
    # asalamalaikum
    # beewilldermant
    # blackbary
    # kartweel
    # chomosrome
    # chrisanthumem
    # instalatiomn
    print(awl3_ms.lookup('bananananaanananananana'))
    print(awl5_ms.lookup('bananananaanananananana'))
    print(awl3_en.lookup('bananananaanananananana'))
    print(awl5_en.lookup('bananananaanananananana'))

    m = Matcher(sorted(words))

    while True:
        word = input('word:\n')
        word = word.strip()
        if not word:
            break

        t = time.time()
        print('awl3_ms', awl3_ms.lookup(word))
        print(time.time() - t)
        print()

        t = time.time()
        print('awl5_ms', awl5_ms.lookup(word))
        print(time.time() - t)
        print()

        t = time.time()
        print('awl5_ms_denorm', awl5_ms.lookup(word, normalize=False))
        print(time.time() - t)
        print()

        t = time.time()
        print('difflib_ms', difflib.get_close_matches(word, words_ms, n=10))
        print(time.time() - t)
        print()

        t = time.time()
        print('difflib_ms', difflib.get_close_matches(word, words_ms, n=10, cutoff=0.3))
        print(time.time() - t)
        print()

        t = time.time()
        print('awl3_en', awl3_en.lookup(word))
        print(time.time() - t)
        print()

        t = time.time()
        print('awl5_en', awl5_en.lookup(word))
        print(time.time() - t)
        print()

        t = time.time()
        print('awl5_en_denorm', awl5_en.lookup(word, normalize=False))
        print(time.time() - t)
        print()

        t = time.time()
        print('difflib_en', difflib.get_close_matches(word, words, n=10))
        print(time.time() - t)
        print()

        t = time.time()
        print('difflib_en', difflib.get_close_matches(word, words, n=10, cutoff=0.3))
        print(time.time() - t)
        print()

        t = time.time()
        print('automata dist 1 en', list(find_all_matches(word, 1, m)))
        print(time.time() - t)
        print()

        t = time.time()
        print('automata dist 2 en', list(find_all_matches(word, 2, m)))
        print(time.time() - t)
        print()

        t = time.time()
        print('automata dist 3 en', list(find_all_matches(word, 3, m)))
        print(time.time() - t)
        print()

if __name__ == '__main__':

    with open('translate-reference.txt') as f:
        ref_lines = f.readlines()
    with open('translate-google-offline.txt') as f:
        hyp_lines = f.readlines()

    scores_bow = []
    scores_nmd = []
    scores_sim = []
    for ref_line, hyp_line in zip(ref_lines, hyp_lines):
        ref_tokens = list(unicode_tokenize(ref_line.casefold(), words_only=True, merge_apostrophe_word=True))
        hyp_tokens = list(unicode_tokenize(hyp_line.casefold(), words_only=True, merge_apostrophe_word=True))
        scores_bow.append(bow_ngram_movers_distance(ref_tokens, hyp_tokens, 4) / max(len(ref_tokens), len(hyp_tokens)))
        scores_sim.append(
            bow_ngram_movers_distance(ref_tokens, hyp_tokens, 4, invert=True) / max(len(ref_tokens), len(hyp_tokens)))
        scores_nmd.append(ngram_movers_distance(' '.join(ref_tokens), ' '.join(hyp_tokens), 4, normalize=True))
        print(' '.join(ref_tokens))
        print(' '.join(hyp_tokens))
        print(scores_bow[-1])
        print(scores_sim[-1])
        print(scores_nmd[-1])

    from matplotlib import pyplot as plt

    plt.scatter(scores_bow, scores_nmd, marker='.')
    plt.show()
    scores_diff = [a - b for a, b in zip(scores_bow, scores_nmd)]
    tmp = sorted(zip(scores_diff, scores_bow, scores_sim, scores_nmd, ref_lines, hyp_lines))
    print(tmp[0])
    print(tmp[1])
    print(tmp[2])
    print(tmp[3])
    print(tmp[-1])
    print(tmp[-2])
    print(tmp[-3])
    print(tmp[-4])


import cv2
import time

# record a video: trigger the webcam, keep it on for 3 secs and then stop
video = cv2.VideoCapture(0)

a = 1
while True:
    a = a+1
    check, frame = video.read()
    print(check)
    print(frame)

    # gray = cv2.cvtColor(frame, cv2.COLOR_BayerGR2GRAY)

    cv2.imshow("Capturing", frame)
    key = cv2.waitKey(1)

    if key==ord('q'):
        break

print(a)
video.release()
cv2.destroyAllWindows()

# ### code tried earlier
#
# video = cv2.VideoCapture(0)
#
# check, frame = video.read()
# # print(check)
# # print(frame)
#
# time.sleep(2)
# cv2.imshow("Capturing", frame)
#
# cv2.waitKey(2000)
# video.release()
# cv2.destroyAllWindows()


"""
 ******************************************************************************
 * @file    Data Grabber Example server mock/randGen.py
 * @author  Adrian Wojcik
 * @version V1.1
 * @date    17-Apr-2021
 * @brief   Simple IoT server mock: random signal
 ******************************************************************************
"""

# generate random floating point values
from random import seed
from random import random
import json
import time
import signal
# data point
class DataPoint:
	def __init__(self, data):
		self.data = data

# seed random number generator
seed(2)

try:
	while True:
		# generate random numbers between <min,max>
		min = 105.0
		max = -20.0
		v = min + (random() * (max - min))
		dp = DataPoint(v)

		# get json string
		jsonStr = json.dumps(dp.__dict__)

		#save to file
		try:
			datafile = open("chartdata.json","w")
			datafile.write(jsonStr)
		except:
			print("Write Error")
		finally:
			datafile.close()

		#print(jsonStr)

		time.sleep(0.1)

except KeyboardInterrupt:
	pass

Desktop/Data Grabber Example server mock/randGen.py


import argparse
from collections import OrderedDict

from amaranth import *
from amaranth.lib.cdc import ResetSynchronizer
from amaranth.build import *

from amaranth_soc import wishbone
from amaranth_soc.periph import ConstantMap

from amaranth_stdio.serial import AsyncSerial

from amaranth_boards.arty_a7 import ArtyA7_35Platform
from amaranth_boards.ecpix5 import ECPIX545Platform, ECPIX585Platform

from lambdasoc.cpu.minerva import MinervaCPU
from lambdasoc.periph.intc import GenericInterruptController
from lambdasoc.periph.serial import AsyncSerialPeripheral
from lambdasoc.periph.sram import SRAMPeripheral
from lambdasoc.periph.timer import TimerPeripheral
from lambdasoc.periph.sdram import SDRAMPeripheral
from lambdasoc.periph.eth import EthernetMACPeripheral

from lambdasoc.soc.cpu import CPUSoC, BIOSBuilder

from lambdasoc.cores.pll.lattice_ecp5 import PLL_LatticeECP5
from lambdasoc.cores.pll.xilinx_7series import PLL_Xilinx7Series
from lambdasoc.cores import litedram, liteeth
from lambdasoc.cores.utils import request_bare

from lambdasoc.sim.blackboxes.serial import AsyncSerial_Blackbox
from lambdasoc.sim.platform import CXXRTLPlatform

__all__ = ["MinervaSoC"]

class _ClockResetGenerator(Elaboratable):
    def __init__(self, *, sync_clk_freq, with_sdram, with_ethernet):
        if not isinstance(sync_clk_freq, (int, float)) or sync_clk_freq <= 0:
            raise ValueError("Sync domain clock frequency must be a positive integer or float, "
                             "not {!r}"
                             .format(sync_clk_freq))
        self.sync_clk_freq = sync_clk_freq
        self.with_sdram    = bool(with_sdram)
        self.with_ethernet = bool(with_ethernet)

    def elaborate(self, platform):
        m = Module()

        m.domains += [
            ClockDomain("_ref", reset_less=platform.default_rst is None, local=True),
            ClockDomain("sync"),
        ]

        m.d.comb += ClockSignal("_ref").eq(platform.request(platform.default_clk, 0).i)
        if platform.default_rst is not None:
            m.d.comb += ResetSignal("_ref").eq(platform.request(platform.default_rst, 0).i)

        # On the Arty A7, the DP83848 Ethernet PHY uses a 25 MHz reference clock.
        if isinstance(platform, ArtyA7_35Platform) and self.with_ethernet:
            m.domains += ClockDomain("_eth_ref", local=True)
            m.submodules += Instance("BUFGCE",
                i_I  = ClockSignal("_eth_ref"),
                i_CE = ~ResetSignal("_eth_ref"),
                o_O  = platform.request("eth_clk25", 0).o,
            )

        # The LiteDRAM core provides its own PLL, which drives the litedram_user clock domain.
        # We reuse this clock domain as the sync domain, in order to avoid CDC between LiteDRAM
        # and the SoC interconnect.
        if self.with_sdram:
            m.domains += ClockDomain("litedram_input")
            m.d.comb += ClockSignal("litedram_input").eq(ClockSignal("_ref"))
            if platform.default_rst is not None:
                m.d.comb += ResetSignal("litedram_input").eq(ResetSignal("_ref"))

            m.domains += ClockDomain("litedram_user")
            m.d.comb += [
                ClockSignal("sync").eq(ClockSignal("litedram_user")),
                ResetSignal("sync").eq(ResetSignal("litedram_user")),
            ]

            # On the Arty A7, we still use our own PLL to drive the Ethernet PHY reference clock.
            if isinstance(platform, ArtyA7_35Platform) and self.with_ethernet:
                eth_ref_pll_params = PLL_Xilinx7Series.Parameters(
                    i_domain     = "_ref",
                    i_freq       = platform.default_clk_frequency,
                    i_reset_less = platform.default_rst is None,
                    o_domain     = "_eth_ref",
                    o_freq       = 25e6,
                )
                m.submodules.eth_ref_pll = eth_ref_pll = PLL_Xilinx7Series(eth_ref_pll_params)

                if platform.default_rst is not None:
                    eth_ref_pll_arst = ~eth_ref_pll.locked | ResetSignal("_ref")
                else:
                    eth_ref_pll_arst = ~eth_ref_pll.locked

                m.submodules += ResetSynchronizer(eth_ref_pll_arst, domain="_eth_ref")

        # In simulation mode, the sync clock domain is directly driven by the platform clock.
        elif isinstance(platform, CXXRTLPlatform):
            assert self.sync_clk_freq == platform.default_clk_frequency
            m.d.comb += ClockSignal("sync").eq(ClockSignal("_ref"))
            if platform.default_rst is not None:
                m.d.comb += ResetSignal("sync").eq(ResetSignal("_ref"))

        # Otherwise, we use a PLL to drive the sync clock domain.
        else:
            if isinstance(platform, ArtyA7_35Platform):
                sync_pll_params = PLL_Xilinx7Series.Parameters(
                    i_domain     = "_ref",
                    i_freq       = platform.default_clk_frequency,
                    i_reset_less = platform.default_rst is None,
                    o_domain     = "sync",
                    o_freq       = self.sync_clk_freq,
                )
                if self.with_ethernet:
                    sync_pll_params.add_secondary_output(domain="_eth_ref", freq=25e6)
                m.submodules.sync_pll = sync_pll = PLL_Xilinx7Series(sync_pll_params)
            elif isinstance(platform, (ECPIX545Platform, ECPIX585Platform)):
                sync_pll_params = PLL_LatticeECP5.Parameters(
                    i_domain     = "_ref",
                    i_freq       = platform.default_clk_frequency,
                    i_reset_less = platform.default_rst is None,
                    o_domain     = "sync",
                    o_freq       = self.sync_clk_freq,
                )
                m.submodules.sync_pll = sync_pll = PLL_LatticeECP5(sync_pll_params)
            else:
                assert False

            if platform.default_rst is not None:
                sync_pll_arst = ~sync_pll.locked | ResetSignal("_ref")
            else:
                sync_pll_arst = ~sync_pll.locked

            m.submodules += ResetSynchronizer(sync_pll_arst, domain="sync")
            if isinstance(platform, ArtyA7_35Platform) and self.with_ethernet:
                m.submodules += ResetSynchronizer(sync_pll_arst, domain="_eth_ref")

        return m

class MinervaSoC(CPUSoC, Elaboratable):
    def __init__(self,
            sync_clk_freq,
            cpu_core,
            bootrom_addr,
            bootrom_size,
            scratchpad_addr,
            scratchpad_size,
            uart_core,
            uart_addr,
            uart_irqno,
            timer_addr,
            timer_width,
            timer_irqno):
        if not isinstance(sync_clk_freq, (int, float)) or sync_clk_freq <= 0:
            raise ValueError("Sync domain clock frequency must be a positive integer or float, "
                             "not {!r}"
                             .format(sync_clk_freq))
        self.sync_clk_freq = int(sync_clk_freq)

        if not isinstance(cpu_core, MinervaCPU):
            raise TypeError("CPU core must be an instance of MinervaCPU, not {!r}"
                            .format(cpu_core))
        self.cpu = cpu_core

        self._arbiter = wishbone.Arbiter(addr_width=30, data_width=32, granularity=8,
                                         features={"cti", "bte", "err"})
        self._decoder = wishbone.Decoder(addr_width=30, data_width=32, granularity=8,
                                         features={"cti", "bte", "err"})

        self._arbiter.add(self.cpu.ibus)
        self._arbiter.add(self.cpu.dbus)

        self.intc = GenericInterruptController(width=len(self.cpu.ip))

        self.bootrom = SRAMPeripheral(size=bootrom_size, writable=False)
        self._decoder.add(self.bootrom.bus, addr=bootrom_addr)

        self.scratchpad = SRAMPeripheral(size=scratchpad_size)
        self._decoder.add(self.scratchpad.bus, addr=scratchpad_addr)

        self.uart = AsyncSerialPeripheral(core=uart_core)
        self._decoder.add(self.uart.bus, addr=uart_addr)
        self.intc.add_irq(self.uart.irq, index=uart_irqno)

        self.timer = TimerPeripheral(width=timer_width)
        self._decoder.add(self.timer.bus, addr=timer_addr)
        self.intc.add_irq(self.timer.irq, index=timer_irqno)

        self._sdram  = None
        self._sram   = None
        self._ethmac = None

    @property
    def memory_map(self):
        return self._decoder.bus.memory_map

    @property
    def constants(self):
        return super().constants.union(
            SDRAM  = self.sdram .constant_map if self.sdram  is not None else None,
            ETHMAC = self.ethmac.constant_map if self.ethmac is not None else None,
            SOC    = ConstantMap(
                WITH_SDRAM        = self.sdram  is not None,
                WITH_ETHMAC       = self.ethmac is not None,
                MEMTEST_ADDR_SIZE = 8192,
                MEMTEST_DATA_SIZE = 8192,
            ),
        )

    @property
    def mainram(self):
        assert not (self._sdram and self.sram)
        return self._sdram or self._sram

    @property
    def sdram(self):
        return self._sdram

    @property
    def sram(self):
        return self._sram

    def add_sdram(self, core, *, addr, cache_size):
        if self.mainram is not None:
            raise AttributeError("Main RAM has already been set to {!r}".format(self.mainram))
        if core.config.user_clk_freq != self.sync_clk_freq:
            raise ValueError("LiteDRAM user domain clock frequency ({} MHz) must match sync "
                             "domain clock frequency ({} MHz)"
                             .format(core.config.user_clk_freq / 1e6, self.sync_clk_freq / 1e6))
        self._sdram = SDRAMPeripheral(core=core, cache_size=cache_size)
        self._decoder.add(self._sdram.bus, addr=addr)

    def add_internal_sram(self, *, addr, size):
        if self.mainram is not None:
            raise AttributeError("Main RAM has already been set to {!r}".format(self.mainram))
        self._sram = SRAMPeripheral(size=size)
        self._decoder.add(self._sram.bus, addr=addr)

    @property
    def ethmac(self):
        return self._ethmac

    def add_ethmac(self, core, *, addr, irqno, local_ip, remote_ip):
        if self._ethmac is not None:
            raise AttributeError("Ethernet MAC has already been set to {!r}"
                                 .format(self._ethmac))
        self._ethmac = EthernetMACPeripheral(core=core, local_ip=local_ip, remote_ip=remote_ip)
        self._decoder.add(self._ethmac.bus, addr=addr)
        self.intc.add_irq(self._ethmac.irq, index=irqno)

    def elaborate(self, platform):
        m = Module()

        m.submodules.crg = _ClockResetGenerator(
            sync_clk_freq = self.sync_clk_freq,
            with_sdram    = self.sdram is not None,
            with_ethernet = self.ethmac is not None,
        )

        m.submodules.cpu        = self.cpu
        m.submodules.arbiter    = self._arbiter
        m.submodules.decoder    = self._decoder
        m.submodules.uart       = self.uart
        m.submodules.timer      = self.timer
        m.submodules.intc       = self.intc
        m.submodules.bootrom    = self.bootrom
        m.submodules.scratchpad = self.scratchpad

        if self.sdram is not None:
            m.submodules.sdram = self.sdram
        if self.sram is not None:
            m.submodules.sram = self.sram
        if self.ethmac is not None:
            m.submodules.ethmac = self.ethmac

        m.d.comb += [
            self._arbiter.bus.connect(self._decoder.bus),
            self.cpu.ip.eq(self.intc.ip),
        ]

        return m

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--build-dir", type=str,
            default="build/minerva_soc",
            help="local build directory (default: 'build/sdram_soc')")
    parser.add_argument("--platform", type=str,
            choices=("sim", "arty_a7", "ecpix5_45", "ecpix5_85"),
            default="sim",
            help="target platform")
    parser.add_argument("--sync-clk-freq", type=int,
            default=75,
            help="SoC clock frequency, in MHz. (default: 75)")
    parser.add_argument("--with-sdram", action="store_true",
            help="enable SDRAM")
    parser.add_argument("--internal-sram-size", type=int,
            default=8192,
            help="Internal RAM size, in bytes. Ignored if --with-sdram is provided. "
                 "(default: 8192)")
    parser.add_argument("--baudrate", type=int,
            default=9600,
            help="UART baudrate (default: 9600)")
    parser.add_argument("--with-ethernet", action="store_true",
            help="enable Ethernet")
    parser.add_argument("--local-ip", type=str,
            default="192.168.1.50",
            help="Local IPv4 address (default: 192.168.1.50)")
    parser.add_argument("--remote-ip", type=str,
            default="192.168.1.100",
            help="Remote IPv4 address (default: 192.168.1.100)")
    args = parser.parse_args()

    # Platform selection

    if args.platform == "sim":
        platform = CXXRTLPlatform()
    elif args.platform == "arty_a7":
        platform = ArtyA7_35Platform()
    elif args.platform == "ecpix5_45":
        platform = ECPIX545Platform()
    elif args.platform == "ecpix5_85":
        platform = ECPIX585Platform()
    else:
        assert False

    # LiteDRAM

    if args.with_sdram:
        if isinstance(platform, CXXRTLPlatform):
            litedram_config = litedram.ECP5Config(
                memtype        = "DDR3",
                module_name    = "MT41K256M16",
                module_bytes   = 2,
                module_ranks   = 1,
                input_clk_freq = int(platform.default_clk_frequency),
                user_clk_freq  = int(platform.default_clk_frequency),
                init_clk_freq  = int(1e6),
            )
        elif isinstance(platform, ArtyA7_35Platform):
            litedram_config = litedram.Artix7Config(
                memtype          = "DDR3",
                speedgrade       = "-1",
                cmd_latency      = 0,
                module_name      = "MT41K128M16",
                module_bytes     = 2,
                module_ranks     = 1,
                rtt_nom          = 60,
                rtt_wr           = 60,
                ron              = 34,
                input_clk_freq   = int(platform.default_clk_frequency),
                user_clk_freq    = int(args.sync_clk_freq * 1e6),
                iodelay_clk_freq = int(200e6),
            )
        elif isinstance(platform, (ECPIX545Platform, ECPIX585Platform)):
            litedram_config = litedram.ECP5Config(
                memtype        = "DDR3",
                module_name    = "MT41K256M16",
                module_bytes   = 2,
                module_ranks   = 1,
                input_clk_freq = int(platform.default_clk_frequency),
                user_clk_freq  = int(args.sync_clk_freq * 1e6),
                init_clk_freq  = int(25e6),
            )
        else:
            assert False

        if isinstance(platform, CXXRTLPlatform):
            litedram_pins = None
        else:
            litedram_pins = request_bare(platform, "ddr3", 0)

        litedram_core = litedram.Core(litedram_config, pins=litedram_pins)
        litedram_core.build(litedram.Builder(), platform, args.build_dir,
                            sim=isinstance(platform, CXXRTLPlatform))
        mainram_size  = litedram_core.size
    else:
        litedram_core = None
        mainram_size  = args.internal_sram_size

    # LiteEth

    if args.with_ethernet:
        if isinstance(platform, CXXRTLPlatform):
            raise NotImplementedError("Ethernet is currently unsupported in simulation.")
        elif isinstance(platform, ArtyA7_35Platform):
            liteeth_config = liteeth.Artix7Config(
                phy_iface = "mii",
                clk_freq  = int(25e6),
            )
        elif isinstance(platform, (ECPIX545Platform, ECPIX585Platform)):
            liteeth_config = liteeth.ECP5Config(
                phy_iface = "rgmii",
                clk_freq  = int(125e6),
            )
        else:
            assert False

        liteeth_pins = request_bare(platform, f"eth_{liteeth_config.phy_iface}", 0)
        liteeth_core = liteeth.Core(liteeth_config, pins=liteeth_pins)
        liteeth_core.build(liteeth.Builder(), platform, args.build_dir)
    else:
        liteeth_core = None

    # UART

    if isinstance(platform, CXXRTLPlatform):
        uart_core = AsyncSerial_Blackbox(
            data_bits = 8,
            divisor   = 1,
        )
    else:
        uart_core = AsyncSerial(
            data_bits = 8,
            divisor   = int(args.sync_clk_freq * 1e6 // args.baudrate),
            pins      = platform.request("uart", 0),
        )

    # SoC and BIOS

    if isinstance(platform, CXXRTLPlatform):
        sync_clk_freq = platform.default_clk_frequency
    else:
        sync_clk_freq = int(args.sync_clk_freq * 1e6)

    soc = MinervaSoC(
        sync_clk_freq = sync_clk_freq,

        cpu_core = MinervaCPU(
            reset_address = 0x00000000,
            with_icache   = True,
            icache_nlines = 16,
            icache_nwords = 4,
            icache_nways  = 1,
            icache_base   = 0x40000000,
            icache_limit  = 0x40000000 + mainram_size,
            with_dcache   = True,
            dcache_nlines = 16,
            dcache_nwords = 4,
            dcache_nways  = 1,
            dcache_base   = 0x40000000,
            dcache_limit  = 0x40000000 + mainram_size,
            with_muldiv   = True,
        ),

        bootrom_addr    = 0x00000000,
        bootrom_size    = 0x8000,
        scratchpad_addr = 0x00008000,
        scratchpad_size = 0x1000,

        uart_addr       = 0x80000000,
        uart_core       = uart_core,
        uart_irqno      = 1,
        timer_addr      = 0x80001000,
        timer_width     = 32,
        timer_irqno     = 0,
    )

    if args.with_sdram:
        soc.add_sdram(litedram_core, addr=0x40000000, cache_size=4096)
    else:
        soc.add_internal_sram(addr=0x40000000, size=args.internal_sram_size)

    if args.with_ethernet:
        soc.add_ethmac(liteeth_core, addr=0x90000000, irqno=2,
                       local_ip=args.local_ip, remote_ip=args.remote_ip)

    soc.build(build_dir=args.build_dir, do_init=True)

    if isinstance(platform, CXXRTLPlatform):
        platform.build(soc, build_dir=args.build_dir, blackboxes={
            "lambdasoc.sim.blackboxes.serial": "serial_pty",
        })
    else:
        platform.build(soc, build_dir=args.build_dir, do_program=True)


import gym

env = gym.make('Taxi-v2')
env.reset()

for _ in range(1000):
    env.render()

    # action = env.action_space.sample()

    action = input("next action: ")
    action = int(action)

    next_state, reward, done, _ = env.step(action)

    print (next_state, reward)


# MIT License
#
# Copyright (c) 2020 MiscellaneousStuff
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Watch a replay which was made using pylol using the league client."""

from configparser import ConfigParser

from pylol.lib import lol_process
from pylol import run_configs
from pylol.env import lol_env
from pylol.lib import portspicker
from pylol.lib import replay

from absl import flags
from absl import app

flags.DEFINE_string("replay_path", "", "Path to the replay file")
flags.DEFINE_string("config_path", "./config.txt", "File containing directories of GameServer, League client respectively")
flags.DEFINE_string("host", "localhost", "Host for GameServer and league client")
flags.DEFINE_string("players", "Ezreal.BLUE,Ezreal.PURPLE", "NOTE: TEMPORARY")

FLAGS = flags.FLAGS

def main(unused_argv):
    try:
        with open(FLAGS.config_path) as f:
            cfg = ConfigParser()
            cfg.read_string(f.read())
            game_server_dir = cfg.get("dirs", "gameserver")
            client_dir = cfg.get("dirs", "lolclient")
    except:
        raise IOError("Could not open config file: '%s'" % FLAGS.config_path)

    try:
        with open(FLAGS.replay_path) as f:
            replay_info = replay.get_replay_info(f.read())
    except:
        raise IOError("Could not open replay file: '%s'" % FLAGS.config_path)

    try:
        run_config = run_configs.get(game_server_dir=game_server_dir)
        ports = portspicker.pick_contiguous_unused_ports(2)
        client_port = ports[0]
        redis_port = ports[1]
        with run_config.start(replay_path=FLAGS.replay_path,
                                host=FLAGS.host,
                                human_observer=True,
                                players=replay_info["players"],
                                multiplier=replay_info["multiplier"],
                                step_multiplier=1,
                                client_port=client_port,
                                redis_port=redis_port,
                                client_dir=client_dir,
                                map_name=replay_info["map"],
                                cooldowns_enabled=False,
                                manacosts_enabled=False,
                                minion_spawns_enabled=False) as controller:
            controller.connect()
            for _ in range(replay_info["action_count"]):
                controller.observe()
    except KeyboardInterrupt:
        pass

def entry_point():
    app.run(main)

if __name__ == "__main__":
    app.run(main)


# !/usr/bin/python3
import requests, json
from tkinter import *
import os
import sys
from datetime import datetime

def globals():
    with open('defaults/country.txt', "r") as f:
        globals.city = f.read()
globals()
CITY = globals.city
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
URL = "https://api.openweathermap.org/data/2.5/weather?q=+" + CITY + "&units=metric&APPID=0316f9e49bb4c3fe9c8ea0327ea5a71e"
response = requests.get(URL)
#class Crea:
#        y = Tk()
#
 #       y.geometry("500x500")
  #      cvwid2 = 700
   #     cvhei2 = 700
    #    canvasi = Canvas(y, width=cvwid2, height=cvhei2, bg='black')

     #   canvasi.pack(expand=YES, fill=BOTH)

      #  imagei = 'images/home.png'
 #       gif12 = PhotoImage(file=imagei)
#
   #     canvasi.create_image(0, 0, image=gif12, anchor=NW)
  #      e = Entry(y, width=50)
    #    e.place(x=50, y=250)
     #   b = Button(y, text="Choose Country", command=cre)
      #  b.place(x=50, y=300)

def func() :
    def change():
        y = Toplevel()
        y.geometry("200x100")
        en = Entry(y, width=10)
        en.place(x=25, y=25)
        en.focus()

        def getr(e):
            with open('defaults/country.txt', "w") as f:
                f.truncate(0)
                f.write(en.get())

            def restart():
                os.execl(sys.executable, sys.executable, *sys.argv)

            globals.city = en.get()
            restart()

        en.bind("<Return>", getr)
    if response.status_code == 200:

        data = response.json()
        main = data['main']
        temperature = main['temp']
        humidity = main['humidity']
        pressure = main['pressure']
        report = data['weather']
        print(f"{CITY:-^30}")
        print(f"Temperature: {temperature}")
        print(f"Humidity: {humidity}")
        print(f"Pressure: {pressure}")
        print(f"Weather Report: {report[0]['description']}")

        rep = report[0]['main'].lower()
        now = datetime.now()

        time = int(now.strftime("%H"))

        if time >= 21 :
            color = "white"

            if "clear" in rep:
                image = 'images/cleardark.png'
            if "cloud" in rep:
                image = 'images/clouddark.png'
            if "rain" in rep:
                image = 'images/raindark.png'
            if "thunder" in rep:
                image = 'images/thunderdark.png'
            if "mist" in rep:
                image = 'images/mistdark.png'
            if "snow" in rep:
                image = 'images/snowdark.png'
        else :
            color = "white"

            if "clear" in rep:
                image = 'images/sunny.png'
            if "cloud" in rep:
                image = 'images/cloud.png'
            if "rain" in rep:
                image = 'images/rain.png'
            if "thunder" in rep:
                image = 'images/thunder.png'
            if "mist" in rep:
                image = 'images/mist.png'
            if "snow" in rep:
                image = 'images/snow.png'

        x = Tk()
        # Creating Menubar
        menubar = Menu(x)
        menubar.config(bg="#484848", fg="white", font=("Stencil Std", 10))

        # Adding Help Menu
        help_ = Menu(menubar, tearoff=0, bg="#484848", fg="white", font=("Stencil Std", 10))
        menubar.add_cascade(label='Countries', menu=help_)
        help_.add_command(label='Change Current Country', command=change)
        help_.add_command(label='Show Current Country', command=None)
        help_.add_separator()
        help_.add_command(label='Change Timezone', command=None)
        help_.add_command(label='Show Current Timezone', command=None)
        help_.add_separator()
        help_.add_command(label="Exit", command=x.destroy)

        # display Menu
        x.config(menu=menubar)
        x.resizable(False, False)
        gif = PhotoImage(file=image)
        cvwid = gif.width()
        cvhei = gif.height()
        canvas = Canvas(x, width=cvwid, height=cvhei, bg='lightblue')
        canvas.pack(fill=BOTH)

        img = canvas.create_image(0, 0, image=gif, anchor=NW)

        temp = canvas.create_text(cvwid / 2, 350, fill=color, font="Helvetica 30", text=str(int(temperature)) + "°C")
        reportr = canvas.create_text(cvwid / 2, 400, fill=color, font="Helvetica 20", text=report[0]["main"])
        cont = canvas.create_text(cvwid / 2, 200, fill=color, font="Helvetica 20", text=globals.city.title())
        x.title(f"{CITY:-^30}")
        x.mainloop()

func()


from stable_baselines3 import PPO
from train import Train
from cyclesgym.utils.utils import _evaluate_policy
from cyclesgym.utils.paths import PROJECT_PATH
from cyclesgym.utils.plot_utils import set_up_plt
import numpy as np
import matplotlib.pyplot as plt
import wandb
from matplotlib.cm import get_cmap

set_up_plt()

def plot_crop_planning_policy_prob(episode_probs):
    color = get_cmap('Accent').colors
    crop_prob = np.array(list(zip(*episode_probs))[0]).squeeze()
    planting_prob = np.array(list(zip(*episode_probs))[1]).squeeze()
    plt.stackplot(1 + np.arange(crop_prob.shape[0]), *crop_prob.T)
    plt.xticks(1 + np.arange(crop_prob.shape[0]))
    plt.xlabel('Years')
    plt.ylabel('Probability')
    plt.xlim(1, crop_prob.shape[0])
    plt.ylim(0, 1)
    plt.show()

    plt.stackplot(1 + np.arange(planting_prob.shape[0]), *planting_prob.T,
                  colors=color[:planting_prob.shape[0]])
    plt.xticks(1 + np.arange(planting_prob.shape[0]))
    plt.xlabel('Years')
    plt.ylabel('Probability')
    plt.xlim(1, planting_prob.shape[0])
    plt.ylim(0, 1)
    plt.show()

def plot_crop_planning_policy_det(episode_actions, episode_rewards, run, eval_env_class, eval_test):
    color = get_cmap('Accent').colors

    if 'Rotation' in eval_env_class:
        title = 'Rotation observations'
    else:
        title = 'SoilN observations'

    episode_actions = episode_actions.squeeze()
    planting_date = episode_actions[:, 1]
    planting_date = 90 + planting_date * 7
    crop = episode_actions[:, 0]
    fig, ax = plt.subplots(2, 1, sharex=True)

    x = 1980 + np.arange(planting_date.size)

    ax[0].bar(x, np.array(episode_rewards)/1000.,
              color=[color[c] for c in crop])
    ax[0].set_ylabel('Year reward [k\$]')
    ax[0].set_title(title)

    ax[1].scatter(x, planting_date, color=[color[c] for c in crop],
                  s=100, marker='o')
    ax[1].set_xticks(x)
    ax[1].set_xlabel('Years')
    ax[1].set_ylabel('Planting date [DOY]')
    ax[1].set_xlim(min(x) + 0.5, max(x) + 0.5)

    fig.autofmt_xdate()

    plt.legend()
    plt.savefig(PROJECT_PATH.joinpath('figures/crop_planning_policies/' + run.path[-1] + '_' +\
                eval_test + '.pdf'), bbox_inches='tight')
    plt.show()

if __name__ == '__main__':

    config = dict(train_start_year=1980, train_end_year=1998, eval_start_year=1998, eval_end_year=2016,
                  total_timesteps=1000000, eval_freq=1000, n_steps=80, batch_size=64, n_epochs=10, run_id=0,
                  norm_reward=True, method="PPO", verbose=1, n_process=8, device='auto')
    api = wandb.Api()

    # Project is specified by <entity/project-name>
    runs = api.runs("koralabs/experiments_crop_planning")

    summary_list, summary_at_max, config_list, name_list = [], [], [], []
    for run in runs:
        dir = [dir for dir in PROJECT_PATH.joinpath('wandb').iterdir() if run.path[-1] in str(dir)]
        if len(dir) > 0:
            print(run)
            dir = dir[0]
            file = dir.joinpath('files/models/eval_det/best_model')
            run_config = run.config
            print(run_config)

            eval_env_class = 'CropPlanningFixedPlanting'
            if run_config.get('non_adaptive', False) == 'True':
                eval_env_class = 'CropPlanningFixedPlantingRotationObserver'

            config['eval_env_class'] = eval_env_class

            envs = Train(config).create_envs()

            model = PPO.load(file, device='cpu')

            def get_plot(model, env, run, eval_env_class, eval_test, deterministic=True):
                mean_reward, std_reward, episode_actions, episode_rewards, episode_probs, episode_action_rewards = \
                    _evaluate_policy(model, env,  n_eval_episodes=1, deterministic=deterministic)
                plot_crop_planning_policy_det(episode_actions, episode_action_rewards, run, eval_env_class, eval_test)

            for env, eval_test in zip(envs, ['train', 'rs98', 'nh98', 'nh15']):
                get_plot(model, env, run, eval_env_class, eval_test)


import os, glob
from pytest import raises
import bionetgen as bng
from bionetgen.main import BioNetGenTest

tfold = os.path.dirname(__file__)

def test_bionetgen_help():
    # tests basic command help
    with raises(SystemExit):
        argv = ["--help"]
        with BioNetGenTest(argv=argv) as app:
            app.run()
            assert app.exit_code == 0

def test_bionetgen_input():
    argv = [
        "run",
        "-i",
        os.path.join(tfold, "test.bngl"),
        "-o",
        os.path.join(tfold, "test"),
    ]
    to_match = ["test.xml", "test.cdat", "test.gdat", "test.net"]
    with BioNetGenTest(argv=argv) as app:
        app.run()
        assert app.exit_code == 0
        file_list = os.listdir(os.path.join(tfold, "test"))
        assert file_list.sort() == to_match.sort()

def test_bionetgen_plot():
    argv = [
        "plot",
        "-i",
        os.path.join(*[tfold, "test", "test.gdat"]),
        "-o",
        os.path.join(*[tfold, "test", "test.png"]),
    ]
    with BioNetGenTest(argv=argv) as app:
        app.run()
        assert app.exit_code == 0
        assert os.path.isfile(os.path.join(*[tfold, "test", "test.png"]))

def test_bionetgen_model():
    fpath = os.path.join(tfold, "test.bngl")
    fpath = os.path.abspath(fpath)
    m = bng.bngmodel(fpath)

def test_bionetgen_visualize():
    vis_types = [
        "contactmap",
        "ruleviz_pattern",
        "ruleviz_operation",
        "regulatory",
        "atom_rule",
        "all",
    ]
    for vis_name in vis_types:
        argv = [
            "visualize",
            "-i",
            os.path.join(tfold, "test.bngl"),
            "-o",
            os.path.join(tfold, "viz"),
            "-t",
            vis_name,
        ]
        with BioNetGenTest(argv=argv) as app:
            app.run()
            assert app.exit_code == 0
            # gmls = glob.glob("*.gml")
            graphmls = glob.glob(os.path.join(tfold, "viz") + os.sep + "*.graphml")
            if vis_name == "atom_rule":
                assert any(["regulatory" in i for i in graphmls])
            elif not vis_name == "all":
                assert any([vis_name in i for i in graphmls])
            else:
                assert len(graphmls) == 4

def test_bionetgen_all_model_loading():
    # tests library model loading using many models
    mpattern = os.path.join(tfold, "models") + os.sep + "*.bngl"
    models = glob.glob(mpattern)
    succ = []
    fail = []
    success = 0
    fails = 0
    for model in models:
        try:
            m = bng.bngmodel(model)
            success += 1
            mstr = str(m)
            succ.append(model)
        except:
            print("can't load model {}".format(model))
            fails += 1
            fail.append(model)
    print("succ: {}".format(success))
    print(sorted(succ))
    print("fail: {}".format(fails))
    print(sorted(fail))
    assert fails == 0

def test_action_loading():
    # tests a BNGL file containing all BNG actions
    all_action_model = os.path.join(*[tfold, "models", "actions", "all_actions.bngl"])
    m1 = bng.bngmodel(all_action_model)
    assert len(m1.actions) + len(m1.actions.before_model) == 31

    no_action_model = os.path.join(*[tfold, "models", "actions", "no_actions.bngl"])
    m2 = bng.bngmodel(no_action_model)
    assert len(m2.actions) == 0

def test_bionetgen_info():
    # tests info subcommand
    argv = ["info"]
    with BioNetGenTest(argv=argv) as app:
        app.run()
        assert app.exit_code == 0

def test_model_running_CLI():
    # tests running a list of models using the CLI
    mpattern = os.path.join(tfold, "models") + os.sep + "*.bngl"
    models = glob.glob(mpattern)
    succ = []
    fail = []
    success = 0
    fails = 0
    test_run_folder = os.path.join(tfold, "models", "cli_test_runs")
    if not os.path.isdir(test_run_folder):
        os.mkdir(test_run_folder)
    for model in models:
        model_name = os.path.basename(model).replace(".bngl", "")
        try:
            argv = [
                "run",
                "-i",
                model,
                "-o",
                os.path.join(*[tfold, "models", "cli_test_runs", model_name]),
            ]
            with BioNetGenTest(argv=argv) as app:
                app.run()
                assert app.exit_code == 0
            success += 1
            model = os.path.split(model)
            model = model[1]
            succ.append(model)
        except:
            print("can't run model {}".format(model))
            fails += 1
            model = os.path.split(model)
            model = model[1]
            fail.append(model)
    print("succ: {}".format(success))
    print(sorted(succ))
    print("fail: {}".format(fails))
    print(sorted(fail))
    assert fails == 0

def test_model_running_lib():
    # test running a list of models using the library
    mpattern = os.path.join(tfold, "models") + os.sep + "*.bngl"
    models = glob.glob(mpattern)
    succ = []
    fail = []
    success = 0
    fails = 0
    for model in models:
        if "test_tfun" in model:
            continue
        try:
            bng.run(model)
            success += 1
            model = os.path.split(model)
            model = model[1]
            succ.append(model)
        except:
            print("can't run model {}".format(model))
            fails += 1
            model = os.path.split(model)
            model = model[1]
            fail.append(model)
    print("succ: {}".format(success))
    print(sorted(succ))
    print("fail: {}".format(fails))
    print(sorted(fail))
    assert fails == 0

def test_atomize_flat():
    if not os.path.exists(os.path.join(tfold, "test")):
        os.mkdir(os.path.join(tfold, "test"))
    argv = [
        "atomize",
        "-i",
        os.path.join(tfold, "test_sbml.xml"),
        "-o",
        os.path.join(*[tfold, "test", "test_sbml_flat.bngl"]),
    ]
    to_match = ["test_sbml_flat.bngl"]
    with BioNetGenTest(argv=argv) as app:
        app.run()
        assert app.exit_code == 0
        file_list = os.listdir(os.path.join(tfold, "test"))
        assert file_list.sort() == to_match.sort()

def test_atomize_atomized():
    if not os.path.exists(os.path.join(tfold, "test")):
        os.mkdir(os.path.join(tfold, "test"))
    argv = [
        "atomize",
        "-i",
        os.path.join(tfold, "test_sbml.xml"),
        "-o",
        os.path.join(*[tfold, "test", "test_sbml_atom.bngl"]),
        "-a",
    ]
    to_match = ["test_sbml_atom.bngl"]
    with BioNetGenTest(argv=argv) as app:
        app.run()
        assert app.exit_code == 0
        file_list = os.listdir(os.path.join(tfold, "test"))
        assert file_list.sort() == to_match.sort()

def test_network_parse():
    netfile = os.path.join(tfold, "mockup.net")
    from bionetgen.network.network import Network

    try:
        net = Network(netfile)
        res = True
    except:
        res = False
    assert res is True

def test_pattern_reader():
    patfile = os.path.join(tfold, "patterns.txt")
    from bionetgen.modelapi.pattern_reader import BNGPatternReader

    try:
        with open(patfile, "r") as f:
            patterns = f.readlines()
            for pattern in patterns:
                pat_obj = BNGPatternReader(pattern).pattern
                reparsed_pat = BNGPatternReader(str(pat_obj)).pattern
                if pat_obj != reparsed_pat:
                    raise RuntimeError(
                        f"Pattern can't be reparsed correctly, og: {pat_obj}, reparsed: {reparsed_pat}"
                    )
        res = True
    except:
        res = False
    assert res is True

def test_pattern_canonicalization():
    # for now, if the platform is windows, just skip
    if os.name == "nt":
        assert True is True
    # if pynauty is uninstalled, skip the test
    try:
        import pynauty
    except ImportError:
        assert True is True
        return
    # otherwise we will test canonicalization
    from bionetgen.modelapi.pattern_reader import BNGPatternReader

    # the testing file
    testfile = os.path.join(tfold, "canon_label_testing.txt")
    with open(testfile, "r+") as f:
        tests = f.readlines()
    # loop over tests
    res = True
    for ipat, pat in enumerate(tests):
        pat_splt = pat.split("    ")
        pat1, pat2 = pat_splt[0], pat_splt[1]
        try:
            # read patterns
            pat1_obj = BNGPatternReader(pat1).pattern
            pat2_obj = BNGPatternReader(pat2).pattern
            # compare them
            if pat1_obj != pat2_obj:
                res = False
                break
        except:
            res = False
            break
    # assert that everything matched up
    assert res is True

def test_setup_simulator():
    fpath = os.path.join(tfold, "test.bngl")
    fpath = os.path.abspath(fpath)
    try:
        m = bng.bngmodel(fpath)
        librr_simulator = m.setup_simulator()
        res = librr_simulator.simulate(0, 1, 10)
    except:
        res = None
    assert res is not None

# def test_graphdiff_matrix():
#     valid = []
#     invalid = []
#     argv = [
#         "graphdiff",
#         "-i",
#         os.path.join(*[tfold, "models", "testviz1_cm.graphml"]),
#         "-i2",
#         os.path.join(*[tfold, "models", "testviz2_cm.graphml"]),
#         "-m",
#         "matrix",
#     ]
#     to_validate = ["testviz1_cm_recolored.graphml",
#                 "testviz1_cm_testviz2_cm_diff.graphml",
#                 "testviz2_cm_recolored.graphml",
#                 "testviz2_cm_testviz1_cm_diff.graphml",
#                 ]
#     schema_doc = etree.parse(f)
#     xmlschema = etree.XMLSchema(schema_doc)

#     with BioNetGenTest(argv=argv) as app:
#         app.run()
#         assert app.exit_code == 0
#     for test_graphml in to_validate:
#         doc = etree.parse(test_graphml)
#         result = xmlschema.validate(doc)
#         if result == True: valid.append(test_graphml)
#         else:
#             invalid.append(test_graphml)
#     print(sorted(valid))
#     print(sorted(invalid))
#     # assert len(valid) == 4

# def test_graphdiff_union():
#     argv = [
#         "graphdiff",
#         "-i",
#         os.path.join(tfold, "models", "testviz1_cm.graphml"),
#         "-i2",
#         os.path.join(tfold, "models", "testviz2_cm.graphml"),
#         "-m",
#         "union",
#     ]
#     to_validate = "testviz1_cm_testviz2_cm_union.graphml"
#     # xmlschema_doc = etree.parse("INSERT_xsd_path_HERE.xsd")
#     # xmlschema = etree.XMLSchema(xmlschema_doc)
#     with BioNetGenTest(argv=argv) as app:
#         app.run()
#         assert app.exit_code == 0
#     # xml_doc = etree.parse(to_validate)
#     # result = xmlschema.validate(xml_doc)
#     # assert result == True


# Scraping Articles

# Import dependencies
from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import datetime as dt

def scrape_all():
    # Initiate headless driver for deployment
    # headless=True means scraping will be done behind the scenes and no webpage will open to visually watch
    browser = Browser("chrome", executable_path="chromedriver", headless=True)

    # Set news title and paragraph variables, function will return two values. Tells Python to use mars_news function to pull this data.
    news_title, news_paragraph = mars_news(browser)

    # Run all scraping functions and store results in dictionary
    data = {
        "news_title": news_title,
        "news_paragraph": news_paragraph,
        "featured_image": featured_image(browser),
        "facts": mars_facts(),
        "hemispheres": mars_hemisphere_images(browser),
        "last_modified": dt.datetime.now()
    }
    print(data)

    # Stop webdriver and return data
    browser.quit()
    return data

# Set the executable path and initialize the chrome browser in splinter
#executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
#browser = Browser('chrome', **executable_path)
# **executable_path is unpacking the dictionary we’ve stored the path in.

# Declare and define fucntion
def mars_news(browser):
    #Scrape Mars News

    # Visit the mars nasa news site
    url = 'https://mars.nasa.gov/news/'
    browser.visit(url)

    # Optional delay for loading the page
    browser.is_element_present_by_css("ul.item_list li.slide", wait_time=1)
    # Searching for elements with a specific combination of tag (ul and li) and attribute (item_list and slide).
    # Tell browser to wait one second before searching for components. The optional delay is useful because
    #sometimes dynamic pages take a little while to load, especially if they are image-heavy.

    # Set up the HTML Parser
    html = browser.html
    news_soup = BeautifulSoup(html, 'html.parser')

    #Add try/except for error handling
    try:
        # Assigned slide_elem as the variable to look for the <ul /> tag and its descendent (the other tags within the
        # <ul /> element), the <li /> tags. This is the parent element, it holds all of the other elements within it,
        # we reference it when we want to filter search results even further. The . is used for selecting classes, such as
        # item_list, so the code 'ul.item_list li.slide' pinpoints the <li /> tag with the class of slide and the
        # <ul /> tag with a class of item_list. CSS works from right to left, such as returning the last item on the list
        # instead of the first. Because of this, when using select_one, the first matching element returned will be
        # a <li /> element with a class of slide and all nested elements within it.
        slide_elem = news_soup.select_one('ul.item_list li.slide')

        # Use the parent element to find the first `a` tag and save it as `news_title`
        news_title = slide_elem.find("div", class_='content_title').get_text()

        # Use the parent element to find the paragraph text
        news_p = slide_elem.find('div', class_="article_teaser_body").get_text()

    except AttributeError:
        return None, None

    return news_title, news_p

# Scraping Images

# Declare and define function
def featured_image(browser):

    # Visit URL
    url = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
    browser.visit(url)

    # Find and click the full image button
    full_image_elem = browser.find_by_id('full_image')
    full_image_elem.click()

    # Find the more info button by searching for text and click it
    browser.is_element_present_by_text('more info', wait_time=1)
    more_info_elem = browser.links.find_by_partial_text('more info')
    more_info_elem.click()

    # Parse the resulting html with soup
    html = browser.html
    img_soup = BeautifulSoup(html, 'html.parser')

    try:
        # Find the relative image url
        img_url_rel = img_soup.select_one('figure.lede a img').get("src")
        # tell BeautifulSoup to look inside the <figure class=”lede” /> tag for an <a /> tag, and then look within
        # that <a /> tag for an <img /> tag.
        # Pull the link of the image by pointing BeautifulSoup to where the image will be, instead of grabbing the URL
        # directly. This way, when NASA updates its image page, the code will still pull the most recent image.

    except AttributeError:
        return None

    # Use the base URL to create an absolute URL
    img_url = f'https://www.jpl.nasa.gov{img_url_rel}'

    return img_url

# Mars Facts
def mars_facts():

    try:
        # Scrape HTML table and store in new df
        # The Pandas function read_html() specifically searches for and returns a list of tables found in the HTML.
        # By specifying an index of 0, we’re telling Pandas to pull only the first table it encounters.
        df = pd.read_html('http://space-facts.com/mars/')[0]

    except BaseException:
        return None

    # Assign columns to the new DataFrame for additional clarity
    df.columns=['Description', 'Mars']

    # Turn the Description column into the DataFrame’s index. inplace=True means that the updated index will remain
    # in place, without having to reassign the DataFrame to a new variable.
    df.set_index('Description', inplace=True)

    # Convert stored df back into HTML format so it can be added to a website
    return df.to_html(classes="table table -striped")

# CHALLENGE
# Reviewed speed run for assistance with function creation

# Store Mars Hemisphere Image links
def mars_hemisphere_images(browser):

    #create list
    hemisphere_image_urls = []

    #Assign mars image website to url variable
    url = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
    #visit site
    browser.visit(url)

    #retrieve list of hemisphere links
    #links = browser.find_by_css('a.product-item h3', wait_time=1)

    #loop through links
    for index in range (4):

        #find element link and click
        browser.find_by_css('a.product-item h3')[index].click()
        # Call scrape_hemisphere_images function and store results
        hemisphere_data = scrape_hemisphere_images(browser.html)
        #add image and title to list
        hemisphere_image_urls.append(hemisphere_data)

        #navigate back for next image link
        browser.back()

    return hemisphere_image_urls

#scrape hemisphere images
def scrape_hemisphere_images(html_text):

    #parse html text
    hemispheres_soup = BeautifulSoup(html_text, "html.parser")

    #Try to scrape image and title
    try:
        hemisphere_title = hemispheres_soup.find("h2", class_="title").get_text()
        image_link = hemispheres_soup.find("a", text="Sample").get("href")
    #return nothing if error occcurs
    except AttributeError:
        hemisphere_title = None
        image_link = None

    #create dictionary with stored image and title
    hemispheres = {
        "title": hemisphere_title,
        "image_url": image_link
    }

    return hemispheres

# Tell Flask to run
if __name__ == "__main__":
    # If running as script, print scraped data
    print(scrape_all())


from mailbox import Maildir
from django.shortcuts import render, redirect
from .models import Usuario

def home(request):
    usuarios = Usuario.objects.all()
    return render(request, 'registro.html', {"usuarios" : usuarios})

def registrarmensaje(request):
    nombre = request.POST['txtnombre']
    mail = request.POST['txtmail']
    consulta = request.POST['txtconsulta']

    consulta = Usuario.objects.create (
        nombre = nombre, mail = mail, consulta = consulta
    )
    return redirect("/")

def edicionMensaje(request, nombre):
    usuario = Usuario.objects.get(nombre=nombre)
    return render(request, "edicionMensaje.html", {"usuario": usuario})

def editarMensaje(request):
    nombre = request.POST['txtnombre']
    mail = request.POST['txtmail']
    consulta = request.POST['txtconsulta']

    usuario = Usuario.objects.get(nombre=nombre)

    usuario.mail = mail
    usuario.consulta = consulta

    usuario.save()
    return redirect("/")

def eliminarmensaje(request, nombre):
    usuario = Usuario.objects.get(nombre=nombre)
    usuario.delete()
    return redirect("/")